Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(rack): follow a node's status check, and type rack-created gear
Pouzor3138cda3785c
diff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.pyindex 79db721..60f5d7c 100644--- a/backend/tests/test_racks.py+++ b/backend/tests/test_racks.py@@ -107,6 +107,22 @@ class TestSaveAndLoad:assert loaded["cables"][0]["from_port_id"] == "p1"assert loaded["viewport"] == {"x": 10, "y": 20, "zoom": 1.5}+ async def test_keeps_a_mount_that_follows_its_node_check(+ self, client: AsyncClient, headers+ ):+ # "Check device" is stored as `auto` on the mount: the rack has no+ # checker, it reads the linked node's live status at render time. The+ # status column is free-form, so this only guards it staying that way.+ design_id = await _design(client, headers)+ state = _state(design_id)+ state["devices"][0]["status"] = "auto"+ res = await client.post("/api/v1/racks/save", json=state, headers=headers)+ assert res.status_code == 200, res.text++ loaded = (await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)).json()+ mount = next(d for d in loaded["devices"] if d["id"] == "dev-sw")+ assert mount["status"] == "auto"+async def test_prunes_what_the_client_dropped(self, client: AsyncClient, headers):design_id = await _design(client, headers)await client.post("/api/v1/racks/save", json=_state(design_id), headers=headers)diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.mdindex 46efe62..5417e12 100644--- a/frontend/src/rack/README.md+++ b/frontend/src/rack/README.md@@ -15,9 +15,10 @@ Create one from **New Canvas → Kind → Rack**.| 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`. `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. |+| 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. Its `suggested_type` comes from the plate it wears (`deviceTypeForFaceplate`), since no scan is there to guess one: without it the row had no icon, no role badge and no place in the type filter. Passive gear uses the rack-only kinds `patch_panel` and `pdu` — the logical canvas has no node type for it, and `pdu` must not be `socket`, which is excluded from the rack inventory. || Picking one | The **Device Inventory entry** field opens the real Device Inventory modal (`PendingDevicesModal` in picker mode: a card click returns the device, bulk/clear controls are hidden) rather than a flat `<select>`, so the user gets its search, source/type filters and per-card detail. It opens with the **Rackable** filter armed — hardware only, `UNRACKABLE_TYPES` in `utils/rackable.ts` mirroring `_UNRACKABLE_TYPES` in `racks.py`, with `test_rackable_sync.py` failing on drift. The rack side still has the last word: a device missing from its own list, or already mounted in this design, is refused with a toast. Standalone keeps the `<select>` — no backend, no inventory modal. || 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. |+| Status | A mount stores a `MountStatus`: `online` / `offline` / `unknown` pinned by hand, or `auto` — "check device", i.e. follow the status check already configured on the matching canvas node (ping, http, ssh…). The rack runs no checker of its own; `auto` resolves through the inventory entry's `node_status` (`resolveDeviceStatus` in `deviceStatus.ts`) and falls back to `unknown` when nothing is behind it. The Status select offers `auto` only when the mount — or the entry being picked — resolves to a node, and drops back to `unknown` when that link is lost. `useAutoStatusRefresh` polls the inventory every 60 s while at least one mount is on `auto`, and only then; the refresh writes inventory only, so autosave stays quiet. || 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). || Ports | RJ45 and SFP/SFP+ only, drawn as real jack artwork at a fixed pixel size so plates of different U heights line up. Manual list per device. Power outlets are artwork, never a cable endpoint. || Port visibility | Patch-facing gear (switches, patch panels) shows its ports permanently. Everything else reveals them on hover, on selection, or when cables are on — a cable never ends on an invisible port. |diff --git a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx b/frontend/src/rack/__tests__/RackDeviceModal.test.tsxindex c776513..de21a63 100644--- a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx+++ b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx@@ -298,6 +298,26 @@ describe('RackDeviceModal — adding', () => {expect(store().inventory.some((i) => i.id === 'pending-1')).toBe(true)})+ it('types a canvas-created device from the plate it wears', async () => {+ createPending.mockResolvedValue({ data: { id: 'pending-pdu' } })+ store().openDeviceEditor()+ render(<RackDeviceModal />)++ fireEvent.click(screen.getByRole('button', { name: 'New device' }))+ fireEvent.change(screen.getByLabelText('Label'), { target: { value: 'pdu-a' } })+ pickFaceplate('PDU 1U — 8 outlets')+ submit()++ // Nothing discovered this device, so the plate is what says what it is —+ // the row used to land in the Device Inventory with no type at all.+ await waitFor(() => expect(createPending).toHaveBeenCalledTimes(1))+ expect(createPending).toHaveBeenCalledWith(+ expect.objectContaining({ suggested_type: 'pdu', discovery_source: 'rack' }),+ )+ await waitFor(() => expect(store().deviceEditor).toBeNull())+ expect(store().inventory.find((i) => i.id === 'pending-pdu')!.type).toBe('pdu')+ })+it('mounts an accessory without touching the inventory', async () => {const before = store().inventory.lengthstore().openDeviceEditor()@@ -329,6 +349,46 @@ describe('RackDeviceModal — adding', () => {fireEvent.click(screen.getByRole('button', { name: 'New device' }))expect(screen.getByLabelText('Faceplate')).toHaveAttribute('data-faceplate', 'server-1u')})++ it('offers "Check device" only once the pick resolves to a canvas node', async () => {+ store().openDeviceEditor()+ render(<RackDeviceModal />)++ // Nothing picked yet: there is no check to follow, so the option would lie.+ const select = screen.getByLabelText('Status')+ expect(select).not.toHaveTextContent('Check device')++ const linked = store().inventory.find((i) => !i.racked && i.nodeId)!+ await pickFromInventory(linked.id)+ expect(select).toHaveTextContent('Check device')+ })++ it('hides "Check device" for an entry with no canvas node behind it', async () => {+ store().openDeviceEditor()+ const orphan = store().inventory.find((i) => !i.racked)!+ useRackStore.setState({+ inventory: store().inventory.map((i) => (i.id === orphan.id ? { ...i, nodeId: null } : i)),+ })+ render(<RackDeviceModal />)++ await pickFromInventory(orphan.id)+ expect(screen.getByLabelText('Status')).not.toHaveTextContent('Check device')+ })++ it('mounts a device that follows its node check', async () => {+ store().openDeviceEditor()+ const linked = store().inventory.find((i) => !i.racked && i.nodeId)!+ render(<RackDeviceModal />)++ await pickFromInventory(linked.id)+ fireEvent.change(screen.getByLabelText('Status'), { target: { value: 'auto' } })+ submit()++ await waitFor(() => expect(store().deviceEditor).toBeNull())+ // The mount stores the intent, not a colour — the LED is resolved from the+ // inventory's live `node_status` at render time.+ expect(store().devices.find((d) => d.deviceId === linked.id)!.status).toBe('auto')+ })})describe('RackDeviceModal — editing', () => {@@ -482,4 +542,35 @@ describe('RackDeviceModal — editing', () => {expect(store().deviceEditor).not.toBeNull()expect(store().devices.find((d) => d.id === 'dev-pve1')!.uHeight).toBe(2)})++ it('keeps "Check device" for a mount already linked to a node', () => {+ store().openDeviceEditor('dev-pve1')+ render(<RackDeviceModal />)++ expect(store().devices.find((d) => d.id === 'dev-pve1')!.nodeId).toBeTruthy()+ expect(screen.getByLabelText('Status')).toHaveTextContent('Check device')+ })++ it('drops a mount off the node check when the link is gone', async () => {+ store().openDeviceEditor('dev-pve1')+ // The canvas node was deleted (`node_id` is ON DELETE SET NULL) and the+ // inventory entry no longer resolves to one: nothing left to follow.+ useRackStore.setState({+ devices: store().devices.map((d) =>+ d.id === 'dev-pve1' ? { ...d, nodeId: null, status: 'auto' as const } : d,+ ),+ inventory: store().inventory.map((i) =>+ i.id === 'inv-pve1' ? { ...i, nodeId: null } : i,+ ),+ })+ render(<RackDeviceModal />)++ const select = screen.getByLabelText('Status')+ expect(select).not.toHaveTextContent('Check device')+ expect(select).toHaveValue('unknown')++ submit()+ await waitFor(() => expect(store().deviceEditor).toBeNull())+ expect(store().devices.find((d) => d.id === 'dev-pve1')!.status).toBe('unknown')+ })})diff --git a/frontend/src/rack/__tests__/RackFlowNode.test.tsx b/frontend/src/rack/__tests__/RackFlowNode.test.tsxnew file mode 100644index 0000000..a743ed6--- /dev/null+++ b/frontend/src/rack/__tests__/RackFlowNode.test.tsx@@ -0,0 +1,75 @@+/**+ * The rack draws a colour, never a mode: a mount set to "check device" reads+ * its LED from the Device Inventory's live `node_status`.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { render, screen } from '@testing-library/react'+import { RackFlowNode } from '../components/RackFlowNode'+import { useRackStore } from '../store'+import { rackPalette } from '../rackTheme'+import { useThemeStore } from '@/stores/themeStore'+import { getFaceplate } from '../faceplates'+import type { NodeProps } from '@xyflow/react'++vi.mock('@xyflow/react', async () => {+ const { mockReactFlow } = await import('@/test/mocks')+ return mockReactFlow({ useReactFlow: () => ({ getZoom: () => 1 }) })+})++const store = () => useRackStore.getState()++beforeEach(() => {+ store().reset()+ store().loadDemo()+})++/** A mounted device whose plate actually draws a status LED. */+function ledDevice() {+ return store().devices.find((d) => d.deviceId && getFaceplate(d.faceplateId).statusLed)!+}++function renderRack() {+ const rackId = store().racks[0].id+ return render(<RackFlowNode {...({ id: rackId } as NodeProps)} />)+}++/** Whatever theme the app is on — the rack derives its colours from it. */+const palette = () => rackPalette(useThemeStore.getState().activeTheme)++/** The LED is the only circle the plate draws. */+function ledFill(label: string): string | null {+ const plate = screen.getByTitle(new RegExp(`^${label} ·`)).querySelector('svg')!+ return plate.querySelector('circle')!.getAttribute('fill')+}++describe('RackFlowNode status', () => {+ it('follows the inventory live status for an auto mount', () => {+ const device = ledDevice()+ useRackStore.setState({+ devices: store().devices.map((d) =>+ d.id === device.id ? { ...d, status: 'auto' as const } : d,+ ),+ inventory: store().inventory.map((i) =>+ i.id === device.deviceId ? { ...i, status: 'offline' as const } : i,+ ),+ })++ renderRack()+ expect(ledFill(device.label)).toBe(palette().status.offline)+ })++ it('keeps drawing a pinned status as-is', () => {+ const device = ledDevice()+ useRackStore.setState({+ devices: store().devices.map((d) =>+ d.id === device.id ? { ...d, status: 'online' as const } : d,+ ),+ inventory: store().inventory.map((i) =>+ i.id === device.deviceId ? { ...i, status: 'offline' as const } : i,+ ),+ })++ renderRack()+ expect(ledFill(device.label)).toBe(palette().status.online)+ })+})diff --git a/frontend/src/rack/__tests__/deviceStatus.test.ts b/frontend/src/rack/__tests__/deviceStatus.test.tsnew file mode 100644index 0000000..84a3f98--- /dev/null+++ b/frontend/src/rack/__tests__/deviceStatus.test.ts@@ -0,0 +1,54 @@+import { describe, it, expect } from 'vitest'+import { MOUNT_STATUSES, canFollowNode, resolveDeviceStatus } from '../deviceStatus'+import type { InventoryDevice } from '@/types'++function entry(over: Partial<InventoryDevice> = {}): InventoryDevice {+ return {+ id: 'inv-1',+ label: 'nas',+ type: 'nas',+ ip: '192.168.1.10',+ status: 'online',+ nodeId: 'node-1',+ racked: false,+ suggestedFaceplateId: 'server-1u',+ ...over,+ }+}++describe('canFollowNode', () => {+ it('needs an entry the backend matched to a canvas node', () => {+ expect(canFollowNode(entry())).toBe(true)+ expect(canFollowNode(entry({ nodeId: null }))).toBe(false)+ expect(canFollowNode(undefined)).toBe(false)+ })+})++describe('resolveDeviceStatus', () => {+ it('returns a pinned status untouched', () => {+ expect(resolveDeviceStatus({ status: 'offline', deviceId: 'inv-1' }, [entry()])).toBe('offline')+ })++ it('reads the inventory entry live status when the mount follows the node', () => {+ expect(resolveDeviceStatus({ status: 'auto', deviceId: 'inv-1' }, [entry()])).toBe('online')+ expect(+ resolveDeviceStatus({ status: 'auto', deviceId: 'inv-1' }, [entry({ status: 'offline' })]),+ ).toBe('offline')+ })++ it('falls back to unknown when there is nothing to read', () => {+ // Accessory (no entry), purged inventory, entry with no node behind it: the+ // rack has no checker of its own, so it must not invent a colour.+ expect(resolveDeviceStatus({ status: 'auto', deviceId: null }, [entry()])).toBe('unknown')+ expect(resolveDeviceStatus({ status: 'auto', deviceId: 'gone' }, [entry()])).toBe('unknown')+ expect(+ resolveDeviceStatus({ status: 'auto', deviceId: 'inv-1' }, [+ entry({ status: 'unknown', nodeId: null }),+ ]),+ ).toBe('unknown')+ })++ it('offers auto first in the Status select', () => {+ expect(MOUNT_STATUSES).toEqual(['auto', 'online', 'offline', 'unknown'])+ })+})diff --git a/frontend/src/rack/__tests__/faceplates.test.ts b/frontend/src/rack/__tests__/faceplates.test.tsindex 951434e..6ad837a 100644--- a/frontend/src/rack/__tests__/faceplates.test.ts+++ b/frontend/src/rack/__tests__/faceplates.test.ts@@ -1,5 +1,13 @@import { describe, it, expect } from 'vitest'-import { FACEPLATES, bank, faceplateGroups, getFaceplate } from '../faceplates'+import {+ FACEPLATES,+ bank,+ deviceTypeForFaceplate,+ faceplateGroups,+ getFaceplate,+ suggestFaceplate,+} from '../faceplates'+import { UNRACKABLE_TYPES } from '@/utils/rackable'import { RACK_COLUMNS, type PortType } from '@/types'const ALLOWED_PORT_TYPES: PortType[] = ['rj45', 'sfp', 'sfp+']@@ -136,6 +144,33 @@ describe('faceplate catalog', () => {expect(plate5.x + plate5.w).toBeLessThanOrEqual(1)})+ it('names the hardware behind every device plate', () => {+ // A device created from the rack canvas has no discovery behind it: the+ // plate is the only thing that says what it is, and a row with no type gets+ // no icon, no role badge and no place in the type filter.+ for (const plate of FACEPLATES.filter((f) => f.kind === 'device')) {+ expect(deviceTypeForFaceplate(plate.id), `${plate.id} has no device type`).toBeTruthy()+ }+ for (const plate of FACEPLATES.filter((f) => f.kind === 'accessory')) {+ expect(deviceTypeForFaceplate(plate.id)).toBeNull()+ }+ expect(deviceTypeForFaceplate('does-not-exist')).toBeNull()+ })++ it('keeps rack-only kinds rackable', () => {+ // Passive gear has no logical node type, so the rack invents two. They must+ // not collide with an excluded kind — a PDU typed `socket` would vanish from+ // the rack inventory the moment it was created.+ const rackOnly = ['patch_panel', 'pdu']+ for (const type of rackOnly) {+ expect(UNRACKABLE_TYPES.has(type)).toBe(false)+ // …and each still proposes a sane plate when re-mounted later.+ expect(getFaceplate(suggestFaceplate(type)).kind).toBe('device')+ }+ expect(suggestFaceplate('pdu')).toBe('pdu-1u')+ expect(suggestFaceplate('patch_panel')).toBe('patch-24')+ })+it('falls back to the first plate on an unknown id', () => {expect(getFaceplate('does-not-exist')).toBe(FACEPLATES[0])})diff --git a/frontend/src/rack/__tests__/useAutoStatusRefresh.test.ts b/frontend/src/rack/__tests__/useAutoStatusRefresh.test.tsnew file mode 100644index 0000000..9e0267b--- /dev/null+++ b/frontend/src/rack/__tests__/useAutoStatusRefresh.test.ts@@ -0,0 +1,69 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { renderHook } from '@testing-library/react'+import { useAutoStatusRefresh } from '../useAutoStatusRefresh'+import { useRackStore } from '../store'+import type { RackDevice } from '@/types'++vi.mock('@/api/client', () => ({+ racksApi: { load: vi.fn(), inventory: vi.fn(), save: vi.fn() },+ scanApi: { createPending: vi.fn(), pending: vi.fn(), hidden: vi.fn() },+}))++const refreshInventory = vi.fn().mockResolvedValue(undefined)++function mount(status: RackDevice['status']): RackDevice {+ return {+ id: 'd1',+ rackId: 'r1',+ deviceId: 'inv-1',+ nodeId: 'node-1',+ label: 'nas',+ uStart: 1,+ uHeight: 1,+ colStart: 0,+ colSpan: 12,+ faceplateId: 'server-1u',+ status,+ ports: [],+ }+}++beforeEach(() => {+ vi.clearAllMocks()+ vi.useFakeTimers()+ useRackStore.setState({ refreshInventory })+})++afterEach(() => {+ vi.useRealTimers()+})++describe('useAutoStatusRefresh', () => {+ it('polls the inventory while a mount follows its node', () => {+ useRackStore.setState({ devices: [mount('auto')] })+ renderHook(() => useAutoStatusRefresh(1000))++ vi.advanceTimersByTime(3000)+ expect(refreshInventory).toHaveBeenCalledTimes(3)+ })++ it('stays quiet when every mount pins its own status', () => {+ // Nothing to refresh for: the LEDs are what the user set, and a needless+ // poll would hit the backend on every rack canvas ever opened.+ useRackStore.setState({ devices: [mount('online'), mount('unknown')] })+ renderHook(() => useAutoStatusRefresh(1000))++ vi.advanceTimersByTime(5000)+ expect(refreshInventory).not.toHaveBeenCalled()+ })++ it('stops polling once unmounted', () => {+ useRackStore.setState({ devices: [mount('auto')] })+ const { unmount } = renderHook(() => useAutoStatusRefresh(1000))++ vi.advanceTimersByTime(1000)+ unmount()+ vi.advanceTimersByTime(5000)+ expect(refreshInventory).toHaveBeenCalledTimes(1)+ })+})diff --git a/frontend/src/rack/components/RackCanvas.tsx b/frontend/src/rack/components/RackCanvas.tsxindex bbda87a..6da7557 100644--- a/frontend/src/rack/components/RackCanvas.tsx+++ b/frontend/src/rack/components/RackCanvas.tsx@@ -19,6 +19,7 @@ import { Plus } from 'lucide-react'import { rackHeight, rackWidth } from '../layout'import { useRackStore } from '../store'import { useRackPalette } from '../rackTheme'+import { useAutoStatusRefresh } from '../useAutoStatusRefresh'import { CableLayer } from './CableLayer'import { RackDeviceModal } from './RackDeviceModal'import { RackFlowNode } from './RackFlowNode'@@ -42,6 +43,10 @@ export function RackCanvas() {const palette = useRackPalette()const { setViewport: applyViewport } = useReactFlow()+ // Mounts set to "check device" read their LED from the inventory's+ // `node_status`, which only a refetch moves.+ useAutoStatusRefresh()+// Restore the saved pan/zoom once per design, not on every viewport nudge.const restoredFor = useRef<string | null>(null)useEffect(() => {diff --git a/frontend/src/rack/components/RackDeviceModal.tsx b/frontend/src/rack/components/RackDeviceModal.tsxindex 7ff2833..3eefd0d 100644--- a/frontend/src/rack/components/RackDeviceModal.tsx+++ b/frontend/src/rack/components/RackDeviceModal.tsx@@ -21,13 +21,14 @@ import type { PendingDevice } from '@/components/modals/PendingDeviceModal'import { useRackStore } from '../store'import { FaceplatePicker } from './FaceplatePicker'import { Faceplate } from './Faceplate'-import { getFaceplate } from '../faceplates'+import { deviceTypeForFaceplate, getFaceplate } from '../faceplates'import { findSlot } from '../layout'+import { canFollowNode, resolveDeviceStatus } from '../deviceStatus'import { generateUUID } from '@/utils/uuid'import {RACK_COLUMNS,- type DeviceStatus,type InventoryDevice,+ type MountStatus,type Port,type PortType,} from '@/types'@@ -101,7 +102,7 @@ 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')+ const [status, setStatus] = useState<MountStatus>(device?.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() })),@@ -156,6 +157,8 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (function applyInventoryItem(item: InventoryDevice) {setInventoryId(item.id)if (!label.trim()) setLabel(item.label)+ // Seed the entry's current colour, not `auto`: following the node's check+ // is the user's call, made in the Status select.setStatus(item.status)pickFaceplate(item.suggestedFaceplateId)}@@ -186,6 +189,23 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (setInventoryPickerOpen(false)}+ /**+ * The Device Inventory row behind this mount: the entry being picked while+ * adding, the one the mount was created from while editing.+ */+ const selectedEntry = inventory.find((i) => i.id === inventoryId)+ const mountEntry = isEdit ? inventory.find((i) => i.id === device?.deviceId) : selectedEntry++ // "Check device" needs a canvas node to read a check from — one the mount+ // already carries, or one the picked entry resolves to.+ const canCheck = (isEdit && !!device?.nodeId) || canFollowNode(mountEntry)++ // Losing that link (another entry picked, node deleted) must not leave the+ // form on a status nothing can resolve.+ useEffect(() => {+ if (!canCheck) setStatus((s) => (s === 'auto' ? 'unknown' : s))+ }, [canCheck])+const geometry = { uStart, uHeight, colStart, colSpan }async function handleSubmit(e: React.FormEvent) {@@ -246,7 +266,13 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (// 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 })+ // Nothing discovered this device, so the plate is what says what it is —+ // otherwise the inventory row shows up with no type, no icon, no filter.+ const created = await createInventoryDevice({+ label: name,+ type: deviceTypeForFaceplate(faceplateId),+ ip: newIp.trim() || null,+ })if (!created) {toast.error('Could not add the device to the inventory')return null@@ -277,7 +303,11 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (}const showInventoryPicker = !isEdit && source === 'inventory'- const selectedEntry = inventory.find((i) => i.id === inventoryId)+ // The plate preview draws a colour, never the word `auto`.+ const previewStatus = resolveDeviceStatus(+ { status, deviceId: mountEntry?.id ?? null },+ inventory,+ )return (<Dialog open onOpenChange={(o) => !o && onClose()}>@@ -435,7 +465,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (<FaceplatefaceplateId={faceplateId}label={label || getFaceplate(faceplateId).label}- status={status}+ status={previewStatus}ports={ports}width={(160 * colSpan) / RACK_COLUMNS}height={Math.min(uHeight, 4) * 18}@@ -515,12 +545,20 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (className={inputClass}aria-label="Status"value={status}- onChange={(e) => setStatus(e.target.value as DeviceStatus)}+ onChange={(e) => setStatus(e.target.value as MountStatus)}>+ {/* Only offered when there is a node to read: the rack runs no+ check of its own. */}+ {canCheck && <option value="auto">Check device (live)</option>}<option value="online">Online</option><option value="offline">Offline</option><option value="unknown">Unknown</option></select>+ {status === 'auto' && (+ <p className="text-[11px] text-muted-foreground">+ Follows the status check configured on the matching canvas node.+ </p>+ )}</Field><Field label="Colour override">diff --git a/frontend/src/rack/components/RackFlowNode.tsx b/frontend/src/rack/components/RackFlowNode.tsxindex d304d55..1d359d4 100644--- a/frontend/src/rack/components/RackFlowNode.tsx+++ b/frontend/src/rack/components/RackFlowNode.tsx@@ -21,6 +21,7 @@ import {} from '../layout'import { useRackStore } from '../store'import { useRackPalette } from '../rackTheme'+import { resolveDeviceStatus } from '../deviceStatus'import { RACK_COLUMNS } from '@/types'import { Faceplate } from './Faceplate'import { endDrag, getDragPayload, parseDragPayload, startDrag } from './dragPayload'@@ -38,6 +39,7 @@ export function RackFlowNode({ id }: NodeProps) {const rack = useRackStore((s) => s.racks.find((r) => r.id === id))const devices = useRackStore((s) => s.devices)const cables = useRackStore((s) => s.cables)+ const inventory = useRackStore((s) => s.inventory)const selectedDeviceId = useRackStore((s) => s.selectedDeviceId)const selectedRackId = useRackStore((s) => s.selectedRackId)const hoveredDeviceId = useRackStore((s) => s.hoveredDeviceId)@@ -289,7 +291,7 @@ export function RackFlowNode({ id }: NodeProps) {<FaceplatefaceplateId={device.faceplateId}label={device.label}- status={device.status}+ status={resolveDeviceStatus(device, inventory)}ports={device.ports}width={box.width}height={box.height}diff --git a/frontend/src/rack/deviceStatus.ts b/frontend/src/rack/deviceStatus.tsnew file mode 100644index 0000000..aa03f38--- /dev/null+++ b/frontend/src/rack/deviceStatus.ts@@ -0,0 +1,32 @@+/**+ * Where a mount's status LED gets its colour.+ *+ * A mount stores a `MountStatus`: three states the user pins by hand, plus+ * `auto` — "check device". The rack has no status checker of its own; the one+ * that already runs is the node-level one on the logical canvas (ping, http,+ * ssh, …). The backend reports that node's live state on every Device Inventory+ * row (`node_status`), so `auto` resolves through the inventory entry the mount+ * points at, and falls back to `unknown` when there is no node behind it.+ */+import type { DeviceStatus, InventoryDevice, MountStatus, RackDevice } from '@/types'++/** Every value the Status select offers, `auto` first. */+export const MOUNT_STATUSES: MountStatus[] = ['auto', 'online', 'offline', 'unknown']++/**+ * Whether "check device" is worth offering: only an inventory entry the backend+ * matched to a canvas node carries a check to follow.+ */+export function canFollowNode(entry: InventoryDevice | undefined | null): boolean {+ return !!entry?.nodeId+}++/** The colour to draw, given what the mount stores and the current inventory. */+export function resolveDeviceStatus(+ device: Pick<RackDevice, 'status' | 'deviceId'>,+ inventory: InventoryDevice[],+): DeviceStatus {+ if (device.status !== 'auto') return device.status+ if (!device.deviceId) return 'unknown'+ return inventory.find((i) => i.id === device.deviceId)?.status ?? 'unknown'+}diff --git a/frontend/src/rack/faceplates.ts b/frontend/src/rack/faceplates.tsindex 44e7536..d4f5710 100644--- a/frontend/src/rack/faceplates.ts+++ b/frontend/src/rack/faceplates.ts@@ -500,6 +500,8 @@ const FACEPLATE_BY_DEVICE_TYPE: Record<string, string> = {computer: 'sff-half',docker_host: 'server-1u',ups: 'ups-2u',+ pdu: 'pdu-1u',+ patch_panel: 'patch-24',printer: 'shelf-1u',camera: 'mini-third',iot: 'mini-third',@@ -510,6 +512,45 @@ export function suggestFaceplate(deviceType: string | null | undefined): stringreturn (deviceType && FACEPLATE_BY_DEVICE_TYPE[deviceType]) || 'server-1u'}+/**+ * The other direction: what kind of hardware a plate represents.+ *+ * A device created from the rack canvas has no discovery behind it, so the only+ * thing that says what it is, is the plate the user picked. Without this the row+ * landed in the Device Inventory with no type at all — no icon, no role badge,+ * invisible to the type filter.+ *+ * `patch_panel` and `pdu` are rack-only kinds: the logical canvas has no node+ * type for passive gear, and rack devices are never approved onto one anyway+ * (`approve` returns 409). They must stay out of `UNRACKABLE_TYPES` — a PDU is+ * the most rackable thing there is, which is also why it is not `socket`.+ */+const DEVICE_TYPE_BY_FACEPLATE: Record<string, string> = {+ 'server-1u': 'server',+ 'server-1u-bays': 'server',+ 'server-2u-bays': 'server',+ 'server-4u-storage': 'server',+ 'sff-half': 'computer',+ 'mini-third': 'computer',+ 'switch-8': 'switch',+ 'switch-24': 'switch',+ 'switch-48': 'switch',+ 'router-1u': 'router',+ 'patch-24': 'patch_panel',+ 'patch-fiber-12': 'patch_panel',+ 'nas-2u': 'nas',+ 'nas-desktop-2': 'nas',+ 'nas-desktop-4': 'nas',+ 'nas-desktop-5': 'nas',+ 'ups-2u': 'ups',+ 'pdu-1u': 'pdu',+}++/** Null for accessories, which are rack furniture and never inventory rows. */+export function deviceTypeForFaceplate(faceplateId: string): string | null {+ return DEVICE_TYPE_BY_FACEPLATE[faceplateId] ?? null+}+/** Templates grouped for the picker, preserving catalog order. */export function faceplateGroups(): { group: string; items: FaceplateTemplate[] }[] {const groups: { group: string; items: FaceplateTemplate[] }[] = []diff --git a/frontend/src/rack/useAutoStatusRefresh.ts b/frontend/src/rack/useAutoStatusRefresh.tsnew file mode 100644index 0000000..17d717c--- /dev/null+++ b/frontend/src/rack/useAutoStatusRefresh.ts@@ -0,0 +1,26 @@+/**+ * Keeps "check device" mounts live.+ *+ * The status checker runs in the backend and reaches the rack only through the+ * Device Inventory (`node_status` on each row), which the rack fetches once on+ * load. A mount set to `auto` would therefore freeze on the state it had when+ * the canvas opened — so poll while at least one mount follows a node, and stop+ * as soon as none does. The refresh writes inventory only: it never dirties the+ * canvas, so autosave stays quiet.+ */+import { useEffect } from 'react'+import { useRackStore } from './store'++/** Matches the backend's default `STATUS_CHECKER_INTERVAL`. */+export const AUTO_STATUS_INTERVAL_MS = 60_000++export function useAutoStatusRefresh(intervalMs: number = AUTO_STATUS_INTERVAL_MS) {+ const refreshInventory = useRackStore((s) => s.refreshInventory)+ const following = useRackStore((s) => s.devices.some((d) => d.status === 'auto'))++ useEffect(() => {+ if (!following) return+ const timer = setInterval(() => void refreshInventory(), intervalMs)+ return () => clearInterval(timer)+ }, [following, intervalMs, refreshInventory])+}diff --git a/frontend/src/types/rack.ts b/frontend/src/types/rack.tsindex 8529cce..d7a486d 100644--- a/frontend/src/types/rack.ts+++ b/frontend/src/types/rack.ts@@ -124,6 +124,15 @@ export interface FaceplateTemplate {export type DeviceStatus = 'online' | 'offline' | 'unknown'+/**+ * What a mount's Status field holds: a state the user pinned by hand, or `auto`+ * — "check device", i.e. follow the status check already configured on the+ * matching logical-canvas node (ping / http / ssh…). The rack runs no checker+ * of its own, so `auto` only means anything for a mount whose inventory entry+ * resolves to a node; it renders as `unknown` otherwise.+ */+export type MountStatus = DeviceStatus | 'auto'+export interface RackDevice {id: stringrackId: string@@ -151,7 +160,8 @@ export interface RackDevice {faceplateId: string/** Overrides the faceplate panel fill when set. */color?: string- status: DeviceStatus+ /** Pinned state, or `auto` to follow the linked node's check. */+ status: MountStatusports: Port[]}diff --git a/frontend/src/utils/__tests__/rackSerializer.test.ts b/frontend/src/utils/__tests__/rackSerializer.test.tsindex ab46867..5fd569a 100644--- a/frontend/src/utils/__tests__/rackSerializer.test.ts+++ b/frontend/src/utils/__tests__/rackSerializer.test.ts@@ -110,6 +110,13 @@ describe('API → domain', () => {expect(toRackDevice({ ...apiDevice, status: 'exploded' }).status).toBe('unknown')})+ it('keeps a mount that follows its node check on auto', () => {+ // `auto` is a mount-only value — an inventory row never carries it, so only+ // the device mapper widens the narrowing.+ expect(toRackDevice({ ...apiDevice, status: 'auto' }).status).toBe('auto')+ expect(fromRackDevice(toRackDevice({ ...apiDevice, status: 'auto' })).status).toBe('auto')+ })+it('maps a cable into nested endpoints', () => {expect(toCable(apiCable)).toMatchObject({type: 'fiber',diff --git a/frontend/src/utils/rackSerializer.ts b/frontend/src/utils/rackSerializer.tsindex 744e47c..eb865a8 100644--- a/frontend/src/utils/rackSerializer.ts+++ b/frontend/src/utils/rackSerializer.ts@@ -12,6 +12,7 @@ import type {CableType,DeviceStatus,InventoryDevice,+ MountStatus,Port,PortType,Rack,@@ -111,6 +112,11 @@ function asStatus(v: string | null): DeviceStatus {return (DEVICE_STATUSES as (string | null)[]).includes(v) ? (v as DeviceStatus) : 'unknown'}+/** A mount may also store `auto` — it follows the linked node's check. */+function asMountStatus(v: string | null): MountStatus {+ return v === 'auto' ? 'auto' : asStatus(v)+}+/** Style is free-form JSON on the wire; fill any key the server never wrote. */function asStyle(raw: Record<string, unknown>): RackStyle {const pick = (key: keyof RackStyle) => raw[key]@@ -177,7 +183,7 @@ export function toRackDevice(api: ApiRackDevice): RackDevice {colSpan: api.col_span,faceplateId: api.faceplate_id,color: api.color ?? undefined,- status: asStatus(api.status),+ status: asMountStatus(api.status),ports: asPorts(api.ports ?? []),}}