Skip to content

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

feat(rack): pick a mount from the Device Inventory, filtered to rackable gear

Pouzorb129200929fb
diff --git a/backend/tests/test_rackable_sync.py b/backend/tests/test_rackable_sync.py
new file mode 100644
index 0000000..d773f25
--- /dev/null
+++ b/backend/tests/test_rackable_sync.py
@@ -0,0 +1,34 @@
+"""The rackable exclusion list is duplicated in the frontend — keep them equal.
+
+`GET /api/v1/racks/inventory` filters on `_UNRACKABLE_TYPES`, while the Device
+Inventory modal's "Rackable" filter (used as the rack picker's default) filters
+on `UNRACKABLE_TYPES` in `frontend/src/utils/rackable.ts`. If the two drift, the
+picker offers devices the rack side then refuses.
+"""
+import re
+from pathlib import Path
+
+from app.api.routes.racks import _UNRACKABLE_TYPES
+
+FRONTEND_FILE = (
+ Path(__file__).resolve().parents[2] / "frontend" / "src" / "utils" / "rackable.ts"
+)
+
+
+def _frontend_unrackable() -> set[str]:
+ src = FRONTEND_FILE.read_text()
+ match = re.search(r"export const UNRACKABLE_TYPES = new Set\(\[(.*?)\]\)", src, re.S)
+ assert match, (
+ "Could not locate UNRACKABLE_TYPES in frontend/src/utils/rackable.ts — "
+ "update this parser if the file's shape changed."
+ )
+ return set(re.findall(r"'([^']+)'", match.group(1)))
+
+
+def test_unrackable_types_in_sync_with_frontend():
+ frontend = _frontend_unrackable()
+ assert frontend == _UNRACKABLE_TYPES, (
+ "racks.py _UNRACKABLE_TYPES is out of sync with frontend rackable.ts.\n"
+ f"Missing from the backend: {sorted(frontend - _UNRACKABLE_TYPES)}\n"
+ f"Missing from the frontend: {sorted(_UNRACKABLE_TYPES - frontend)}"
+ )
diff --git a/frontend/src/components/modals/PendingDevicesModal.tsx b/frontend/src/components/modals/PendingDevicesModal.tsx
index a68c49e..ccf9984 100644
--- a/frontend/src/components/modals/PendingDevicesModal.tsx
+++ b/frontend/src/components/modals/PendingDevicesModal.tsx
@@ -19,6 +19,7 @@ import { buildMacProperty } from '@/utils/macProperty'
import { formatRelative, formatTimestamp } from '@/utils/timeFormat'
import { getCenteredPosition } from '@/utils/viewportCenter'
import { sourceBuckets, orderedSources, isRackDevice, SOURCE_META, type SourceBucket } from '@/utils/pendingSources'
+import { isRackable } from '@/utils/rackable'
interface PendingDevicesModalProps {
open: boolean
@@ -27,6 +28,14 @@ interface PendingDevicesModalProps {
initialStatus?: 'pending' | 'hidden'
/** Getting Started tour: render these canned devices and skip the backend fetch. */
demoDevices?: PendingDevice[]
+ /**
+ * Picker mode. Clicking a card hands the device back instead of opening its
+ * detail modal, so another feature (the rack canvas) can reuse this list —
+ * search, filters, badges and all — rather than reimplementing a `<select>`.
+ */
+ onPick?: (device: PendingDevice) => void
+ /** Start with the Rackable filter on (what the rack picker wants). */
+ initialRackableOnly?: boolean
}
const PORT_COLORS: Record<number, string> = {
@@ -115,7 +124,7 @@ function injectAutoEdges(edges: AutoEdge[] | undefined) {
}))
}
-export function PendingDevicesModal({ open, onClose, highlightId, initialStatus = 'pending', demoDevices }: PendingDevicesModalProps) {
+export function PendingDevicesModal({ open, onClose, highlightId, initialStatus = 'pending', demoDevices, onPick, initialRackableOnly = false }: PendingDevicesModalProps) {
const [devices, setDevices] = useState<PendingDevice[]>([])
const [loading, setLoading] = useState(false)
const [selected, setSelected] = useState<PendingDevice | null>(null)
@@ -129,6 +138,9 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
const [showOnCanvas, setShowOnCanvas] = useState(true)
// Optionally restrict to devices that have at least one detected service.
const [withServicesOnly, setWithServicesOnly] = useState(false)
+ // Hardware only — what a rack can hold. On by default when the rack canvas
+ // opens the inventory to pick a mount.
+ const [rackableOnly, setRackableOnly] = useState(initialRackableOnly)
const { addNode, scanEventTs } = useCanvasStore()
const setSelectedNode = useCanvasStore((s) => s.setSelectedNode)
const activeDesignId = useDesignStore((s) => s.activeDesignId)
@@ -162,8 +174,11 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
setSearch('')
} else {
setStatusFilter(initialStatus)
+ // Reopening from the rack picker must re-arm the filter even if the user
+ // turned it off during the previous visit.
+ setRackableOnly(initialRackableOnly)
}
- }, [open, initialStatus])
+ }, [open, initialStatus, initialRackableOnly])
const distinctTypes = useMemo(() => {
const set = new Set<string>()
@@ -179,6 +194,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
// Inventory-only: optionally hide devices already placed on a canvas.
if (statusFilter === 'pending' && !showOnCanvas && (d.canvas_count ?? 0) > 0) return false
if (withServicesOnly && (d.services?.length ?? 0) === 0) return false
+ if (rackableOnly && !isRackable(d)) return false
if (q) {
const hay = [
d.friendly_name, d.hostname, d.ip, d.mac, d.ieee_address, d.vendor, d.model,
@@ -188,7 +204,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
}
return true
})
- }, [devices, search, sourceFilter, typeFilter, statusFilter, showOnCanvas, withServicesOnly])
+ }, [devices, search, sourceFilter, typeFilter, statusFilter, showOnCanvas, withServicesOnly, rackableOnly])
useEffect(() => {
if (!highlightId || loading || !open) return
@@ -204,6 +220,9 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
}
const handleCardClick = (d: PendingDevice) => {
+ // Picker mode wins over everything else: the caller opened this list to get
+ // one device back, not to approve or hide anything.
+ if (onPick) { onPick(d); return }
if (selectMode) { toggleSelect(d.id); return }
if (statusFilter === 'hidden') { handleRestore(d); return }
setSelected(d)
@@ -459,6 +478,9 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
}
if (inField) return
if (e.key === '/') { e.preventDefault(); searchRef.current?.focus() }
+ // Bulk actions are meaningless in picker mode — the card click returns a
+ // device, so select mode must stay unreachable from the keyboard too.
+ else if (onPick) return
else if (e.key.toLowerCase() === 's') { e.preventDefault(); if (selectMode) exitSelectMode(); else enterSelectMode() }
else if (e.key.toLowerCase() === 'a' && selectMode) { e.preventDefault(); selectAllVisible() }
else if (e.key === 'Enter' && selectMode && selectedIds.size > 0) {
@@ -474,7 +496,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
// statusFilter is included so Enter dispatches the correct bulk action
// (approve vs restore) even if the device list doesn't change on switch.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [open, selectMode, selectedIds, filtered, statusFilter])
+ }, [open, selectMode, selectedIds, filtered, statusFilter, onPick])
return (
<>
@@ -486,7 +508,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
<DialogHeader className="px-4 py-3 border-b border-border shrink-0">
<div className="flex items-center justify-between gap-3">
<DialogTitle className="text-base font-semibold flex items-center gap-2">
- {statusFilter === 'pending' ? 'Device Inventory' : 'Hidden Devices'}
+ {onPick ? 'Pick a Device' : statusFilter === 'pending' ? 'Device Inventory' : 'Hidden Devices'}
<span className="text-muted-foreground font-normal text-xs">
({filtered.length}{filtered.length !== devices.length && ` of ${devices.length}`})
</span>
@@ -495,7 +517,8 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
<button onClick={load} className="text-muted-foreground hover:text-foreground p-1.5 rounded transition-colors" title="Refresh">
<RefreshCw size={14} />
</button>
- {statusFilter === 'pending' && devices.length > 0 && (
+ {/* Never offer a destructive bulk clear from a picker. */}
+ {!onPick && statusFilter === 'pending' && devices.length > 0 && (
<button
onClick={handleClearAll}
className="text-muted-foreground hover:text-[#f85149] p-1.5 rounded transition-colors"
@@ -615,6 +638,16 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
<ServerCog size={12} />
With services
</button>
+ <button
+ onClick={() => setRackableOnly((v) => !v)}
+ className={`flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded border transition-colors ${rackableOnly ? 'bg-[#39d353]/20 text-[#39d353] border-[#39d353]/50' : 'bg-[#0d1117] text-muted-foreground border-border hover:text-foreground'}`}
+ title="Only show hardware you could mount in a rack (no VMs, containers or mesh devices)"
+ aria-pressed={rackableOnly}
+ >
+ <Server size={12} />
+ Rackable
+ </button>
+ {!onPick && (
<button
onClick={() => selectMode ? exitSelectMode() : enterSelectMode()}
className={`text-xs px-2.5 py-1.5 rounded border transition-colors ${selectMode ? 'bg-[#00d4ff]/20 text-[#00d4ff] border-[#00d4ff]/50' : 'bg-[#0d1117] text-muted-foreground border-border hover:text-foreground'}`}
@@ -622,6 +655,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
>
{selectMode ? 'Exit select' : 'Select mode'}
</button>
+ )}
</div>
{/* Body */}
diff --git a/frontend/src/components/modals/__tests__/PendingDevicesModal.test.tsx b/frontend/src/components/modals/__tests__/PendingDevicesModal.test.tsx
index e470746..93c597c 100644
--- a/frontend/src/components/modals/__tests__/PendingDevicesModal.test.tsx
+++ b/frontend/src/components/modals/__tests__/PendingDevicesModal.test.tsx
@@ -121,6 +121,19 @@ const DEVICE_RACK = {
discovered_at: '2026-01-05T00:00:00Z',
}
+const DEVICE_VM = {
+ id: 'dev-vm',
+ ip: '192.168.1.55',
+ hostname: 'web-vm',
+ mac: null,
+ os: null,
+ services: [],
+ suggested_type: 'vm',
+ status: 'pending',
+ discovery_source: 'proxmox',
+ discovered_at: '2026-01-06T00:00:00Z',
+}
+
beforeEach(() => {
vi.clearAllMocks()
// Apply the selector when one is passed (setSelectedNode is read via a
@@ -603,6 +616,12 @@ describe('PendingDevicesModal', () => {
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('1 rack device'))
})
+ it('keeps rack gear in the rackable list — it is hardware', async () => {
+ render(<PendingDevicesModal {...baseProps} initialRackableOnly />)
+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-rack')).toBeInTheDocument())
+ expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument()
+ })
+
it('approves nothing when the whole selection is rack gear', async () => {
render(<PendingDevicesModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-rack')).toBeInTheDocument())
@@ -613,4 +632,64 @@ describe('PendingDevicesModal', () => {
await waitFor(() => expect(mockBulkApprove).not.toHaveBeenCalled())
})
})
+
+ // The rack canvas opens this modal to pick a mount, so it needs a hardware
+ // filter and a way to hand one device back instead of approving it.
+ describe('rackable filter and picker mode', () => {
+ beforeEach(() => {
+ mockPending.mockResolvedValue({ data: [DEVICE_IP, DEVICE_VM] })
+ })
+
+ it('drops virtual and mesh kinds when the filter is on', async () => {
+ render(<PendingDevicesModal {...baseProps} />)
+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-vm')).toBeInTheDocument())
+
+ fireEvent.click(screen.getByRole('button', { name: 'Rackable' }))
+ expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument()
+ expect(screen.queryByTestId('pending-card-dev-vm')).not.toBeInTheDocument()
+ })
+
+ it('starts filtered when the caller asks for it', async () => {
+ render(<PendingDevicesModal {...baseProps} initialRackableOnly />)
+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
+ expect(screen.queryByTestId('pending-card-dev-vm')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Rackable' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ )
+ })
+
+ it('re-arms the filter when reopened after the user turned it off', async () => {
+ const { rerender } = render(<PendingDevicesModal {...baseProps} initialRackableOnly />)
+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
+ fireEvent.click(screen.getByRole('button', { name: 'Rackable' }))
+ expect(screen.getByTestId('pending-card-dev-vm')).toBeInTheDocument()
+
+ rerender(<PendingDevicesModal {...baseProps} open={false} initialRackableOnly />)
+ rerender(<PendingDevicesModal {...baseProps} initialRackableOnly />)
+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
+ expect(screen.queryByTestId('pending-card-dev-vm')).not.toBeInTheDocument()
+ })
+
+ it('hands the card back instead of opening the approval modal', async () => {
+ const onPick = vi.fn()
+ render(<PendingDevicesModal {...baseProps} onPick={onPick} />)
+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
+
+ fireEvent.click(screen.getByTestId('pending-card-dev-a'))
+ expect(onPick).toHaveBeenCalledWith(expect.objectContaining({ id: 'dev-a' }))
+ expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument()
+ })
+
+ it('hides the bulk and clear controls a picker has no business offering', async () => {
+ render(<PendingDevicesModal {...baseProps} onPick={vi.fn()} />)
+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
+
+ expect(screen.queryByRole('button', { name: 'Select mode' })).not.toBeInTheDocument()
+ expect(screen.queryByTitle(/Clear all pending/)).not.toBeInTheDocument()
+ // …and the keyboard shortcut cannot bring select mode back either.
+ fireEvent.keyDown(window, { key: 's' })
+ expect(screen.queryByRole('button', { name: /Approve \(/ })).not.toBeInTheDocument()
+ })
+ })
})
diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.md
index 7ce29c3..46efe62 100644
--- a/frontend/src/rack/README.md
+++ b/frontend/src/rack/README.md
@@ -16,6 +16,7 @@ Create one from **New Canvas → Kind → Rack**.
| 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. |
+| 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. |
| 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. |
@@ -45,7 +46,7 @@ types in `@/types/rack`, narrowing every enum on the way in.
## Interactions
-- **+ Device** (left rail) → `RackDeviceModal`. Source is either an existing **Device Inventory** entry, a new device created here (which lands in the inventory too), or a rack-only accessory.
+- **+ Device** (left rail) → `RackDeviceModal`. Source is either an existing **Device Inventory** entry, a new device created here (which lands in the inventory too), or a rack-only accessory. Nothing is preselected: the entry is picked in the Device Inventory modal, which the field opens.
- Drag from the sidebar tray onto a rack → snaps to a free U.
- Drag a mounted device inside the rack → same snapping, own slot ignored.
- The **Faceplate** field previews the current plate; clicking it opens `FaceplatePicker`. Switching the source between device and accessory swaps the plate to a sane default of the other kind.
diff --git a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
index b157caa..f4f5aad 100644
--- a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
+++ b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
@@ -8,11 +8,18 @@ import { RackDeviceModal } from '../components/RackDeviceModal'
import { useRackStore } from '../store'
const createPending = vi.fn()
+const pendingList = vi.fn()
vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())
vi.mock('@/api/client', () => ({
racksApi: { load: vi.fn(), inventory: vi.fn(), save: vi.fn() },
- scanApi: { createPending: (...args: unknown[]) => createPending(...args) },
+ scanApi: {
+ createPending: (...args: unknown[]) => createPending(...args),
+ // The inventory entry is now picked in the Device Inventory modal, which
+ // reads `pending_devices` itself rather than the rack's mirrored list.
+ pending: (...args: unknown[]) => pendingList(...args),
+ hidden: vi.fn().mockResolvedValue({ data: [] }),
+ },
}))
const store = () => useRackStore.getState()
@@ -20,8 +27,36 @@ const store = () => useRackStore.getState()
beforeEach(() => {
vi.clearAllMocks()
store().loadDemo()
+ pendingList.mockResolvedValue({ data: [] })
})
+/** Shape the Device Inventory modal expects for one of the rack's entries. */
+function pendingRow(id: string, extra: Record<string, unknown> = {}) {
+ return {
+ id,
+ ip: null,
+ hostname: id,
+ mac: null,
+ os: null,
+ services: [],
+ suggested_type: 'server',
+ status: 'pending',
+ discovery_source: 'arp',
+ discovered_at: '2026-01-01T00:00:00Z',
+ ...extra,
+ }
+}
+
+/** Open the Device Inventory from the rack modal and click one of its cards. */
+async function pickFromInventory(id: string, extra: Record<string, unknown> = {}) {
+ pendingList.mockResolvedValue({ data: [pendingRow(id, extra)] })
+ fireEvent.click(screen.getByLabelText('Device Inventory entry'))
+ const card = await screen.findByTestId(`pending-card-${id}`)
+ await act(async () => {
+ fireEvent.click(card)
+ })
+}
+
function submit() {
fireEvent.click(screen.getByRole('button', { name: /^(Add|Save)$/ }))
}
@@ -45,9 +80,7 @@ describe('RackDeviceModal — adding', () => {
render(<RackDeviceModal />)
const unracked = store().inventory.find((i) => !i.racked)!
- fireEvent.change(screen.getByLabelText('Device Inventory entry'), {
- target: { value: unracked.id },
- })
+ await pickFromInventory(unracked.id)
submit()
await waitFor(() =>
@@ -58,7 +91,7 @@ describe('RackDeviceModal — adding', () => {
expect(store().deviceEditor).toBeNull()
})
- it('keeps the preselected entry status instead of saving unknown over it', async () => {
+ it('takes the picked entry status instead of saving unknown over it', async () => {
store().openDeviceEditor()
const first = store().inventory.find((i) => !i.racked)!
useRackStore.setState({
@@ -68,14 +101,43 @@ describe('RackDeviceModal — adding', () => {
})
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.
+ // Picking and submitting without touching the Status select is the common
+ // path — it used to commit `unknown` over the entry's live status.
+ await pickFromInventory(first.id)
submit()
await waitFor(() => expect(store().deviceEditor).toBeNull())
expect(store().devices.find((d) => d.deviceId === first.id)!.status).toBe('online')
})
+ it('refuses an entry already mounted in this design', async () => {
+ const { toast } = await import('sonner')
+ store().openDeviceEditor()
+ const racked = store().inventory.find((i) => i.racked)!
+ render(<RackDeviceModal />)
+
+ // The Device Inventory lists every device, racked or not — the rack side is
+ // what knows one is already mounted here, and one mount per entry is the rule.
+ await pickFromInventory(racked.id)
+
+ expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('already mounted'))
+ expect(screen.getByLabelText('Device Inventory entry')).toHaveAttribute('data-device-id', '')
+ })
+
+ it('refuses a device the rack inventory does not carry', async () => {
+ const { toast } = await import('sonner')
+ store().openDeviceEditor()
+ render(<RackDeviceModal />)
+
+ // The two lists come from different endpoints: a row can be in the Device
+ // Inventory and absent from the rack's (hidden there, or a kind no rack can
+ // hold). Refuse it rather than mount a ghost with no entry behind it.
+ await pickFromInventory('dev-ghost')
+
+ expect(toast.error).toHaveBeenCalledWith('That device cannot be mounted in a rack')
+ expect(screen.getByLabelText('Device Inventory entry')).toHaveAttribute('data-device-id', '')
+ })
+
it('creates nothing in the inventory when the rack has no room', async () => {
store().openDeviceEditor()
const rack = store().racks[0]
@@ -122,16 +184,14 @@ describe('RackDeviceModal — adding', () => {
const picked = store().inventory.find((i) => !i.racked)!
render(<RackDeviceModal />)
- fireEvent.change(screen.getByLabelText('Device Inventory entry'), {
- target: { value: picked.id },
- })
+ await pickFromInventory(picked.id)
// Racked from another modal, or purged from the inventory, while this one
// was open: the mount fails, and it used to read "No free slot in this rack".
act(() => {
useRackStore.setState({ inventory: store().inventory.filter((i) => i.id !== picked.id) })
})
- // The select drops back to its placeholder rather than holding a dead id…
- expect(screen.getByLabelText('Device Inventory entry')).toHaveValue('')
+ // The field drops back to its placeholder rather than holding a dead id…
+ expect(screen.getByLabelText('Device Inventory entry')).toHaveAttribute('data-device-id', '')
await act(async () => submit())
// …so the error names the real cause instead of the rack's capacity.
@@ -145,9 +205,7 @@ describe('RackDeviceModal — adding', () => {
const entry = store().inventory.find((i) => !i.racked)!
render(<RackDeviceModal />)
- fireEvent.change(screen.getByLabelText('Device Inventory entry'), {
- target: { value: entry.id },
- })
+ await pickFromInventory(entry.id)
// U 1 is taken in the demo rack, so the mount relocates. Patching the form's
// own geometry afterwards used to undo that, silently.
fireEvent.change(screen.getByLabelText('U position'), { target: { value: '1' } })
@@ -166,7 +224,7 @@ describe('RackDeviceModal — adding', () => {
}
})
- it('labels inventory options without repeating the IP', () => {
+ it('names the picked entry without repeating the IP', async () => {
store().openDeviceEditor()
useRackStore.setState({
inventory: [
@@ -180,25 +238,29 @@ describe('RackDeviceModal — adding', () => {
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 />)
+ await pickFromInventory('inv-ip')
// 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()
+ const field = screen.getByLabelText('Device Inventory entry')
+ expect(field).toHaveTextContent('192.168.1.63 · server')
+ expect(field).not.toHaveTextContent('192.168.1.63 · 192.168.1.63')
+ })
+
+ it('lays the form out in two columns inside a NodeModal-sized dialog', () => {
+ store().openDeviceEditor()
+ render(<RackDeviceModal />)
+
+ // Regression: a max-w-md dialog with one column pushed the port list — and
+ // the Add button — below the fold on a laptop screen.
+ expect(screen.getByRole('dialog')).toHaveClass('sm:max-w-3xl')
+ const columns = document.querySelector('.sm\\:grid-cols-2')!
+ expect(columns).not.toBeNull()
+ // Fields on the left, ports on the right, both inside the same grid.
+ expect(columns).toContainElement(screen.getByLabelText('Label'))
+ expect(columns).toContainElement(screen.getByRole('button', { name: 'Add port' }))
})
it('creates a brand new inventory entry from the canvas and mounts it', async () => {
diff --git a/frontend/src/rack/components/RackDeviceModal.tsx b/frontend/src/rack/components/RackDeviceModal.tsx
index 229ee1e..c4cb768 100644
--- a/frontend/src/rack/components/RackDeviceModal.tsx
+++ b/frontend/src/rack/components/RackDeviceModal.tsx
@@ -16,6 +16,8 @@ import { toast } from 'sonner'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
+import { PendingDevicesModal } from '@/components/modals/PendingDevicesModal'
+import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
import { useRackStore } from '../store'
import { FaceplatePicker } from './FaceplatePicker'
import { Faceplate } from './Faceplate'
@@ -31,6 +33,7 @@ import {
} from '@/types'
const DEFAULT_COLOR = '#2b323c'
+const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
type Source = 'inventory' | 'new' | 'accessory'
@@ -87,29 +90,25 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
const unracked = useMemo(() => inventory.filter((i) => !i.racked), [inventory])
const [source, setSource] = useState<Source>(unracked.length > 0 ? 'inventory' : 'new')
- const [inventoryId, setInventoryId] = useState(unracked[0]?.id ?? '')
+ // No preselection: the entry comes from the Device Inventory modal, which the
+ // user opens and picks from explicitly.
+ const [inventoryId, setInventoryId] = useState('')
const [newIp, setNewIp] = useState('')
const [rackId, setRackId] = useState(device?.rackId ?? racks[0]?.id ?? '')
const [label, setLabel] = useState(device?.label ?? '')
- const [faceplateId, setFaceplateId] = useState(
- device?.faceplateId ?? unracked[0]?.suggestedFaceplateId ?? 'server-1u',
- )
+ const [faceplateId, setFaceplateId] = useState(device?.faceplateId ?? 'server-1u')
const [uStart, setUStart] = useState(device?.uStart ?? 1)
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)
- // 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 [status, setStatus] = useState<DeviceStatus>(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() })),
)
const [plateChanged, setPlateChanged] = useState(false)
const [pickerOpen, setPickerOpen] = useState(false)
+ const [inventoryPickerOpen, setInventoryPickerOpen] = useState(false)
const [busy, setBusy] = useState(false)
// The inventory lives in the Device Inventory, which the user can edit from
@@ -154,15 +153,39 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
}
}
- function pickInventory(id: string) {
- setInventoryId(id)
- const item = inventory.find((i) => i.id === id)
- if (!item) return
+ function applyInventoryItem(item: InventoryDevice) {
+ setInventoryId(item.id)
if (!label.trim()) setLabel(item.label)
setStatus(item.status)
pickFaceplate(item.suggestedFaceplateId)
}
+ /**
+ * A device picked in the Device Inventory modal.
+ *
+ * That modal reads `pending_devices` directly, while the rack keeps its own
+ * rackable-and-flagged copy — so a row can be visible there and absent here
+ * (added since this form opened, or a kind no rack can hold). Refetch once
+ * before refusing, and never mount a device twice in the same design.
+ */
+ async function handlePickFromInventory(picked: PendingDevice) {
+ let entry = inventory.find((i) => i.id === picked.id)
+ if (!entry) {
+ await refreshInventory()
+ entry = useRackStore.getState().inventory.find((i) => i.id === picked.id)
+ }
+ if (!entry) {
+ toast.error('That device cannot be mounted in a rack')
+ return
+ }
+ if (entry.racked) {
+ toast.error(`${entry.label} is already mounted in this design`)
+ return
+ }
+ applyInventoryItem(entry)
+ setInventoryPickerOpen(false)
+ }
+
const geometry = { uStart, uHeight, colStart, colSpan }
async function handleSubmit(e: React.FormEvent) {
@@ -254,10 +277,13 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
}
const showInventoryPicker = !isEdit && source === 'inventory'
+ const selectedEntry = inventory.find((i) => i.id === inventoryId)
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
- <DialogContent className="max-w-md border-[#30363d] bg-[#161b22] text-foreground max-h-[85vh] overflow-y-auto">
+ {/* Same footprint as NodeModal — the form is two columns wide so a mount
+ fits on screen without scrolling. */}
+ <DialogContent className="border-[#30363d] bg-[#161b22] text-foreground max-w-[calc(100%-2rem)] sm:max-w-3xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-sm font-semibold">
{isEdit ? 'Edit Device' : 'Add Device'}
@@ -292,251 +318,297 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
</Field>
)}
- {showInventoryPicker && (
- <Field label="Device Inventory entry">
- <select
- className={inputClass}
- aria-label="Device Inventory entry"
- value={inventoryId}
- onChange={(e) => pickInventory(e.target.value)}
- >
- <option value="">Select a device…</option>
- {unracked.map((item) => (
- <option key={item.id} value={item.id}>
- {inventoryOption(item)}
- </option>
- ))}
- </select>
- {unracked.length === 0 && (
- <p className="text-[11px] text-muted-foreground">
- Everything in the inventory is already racked — create a new device instead.
- </p>
- )}
- </Field>
- )}
+ {/* Left column: what the device is and where it sits. Right column:
+ its ports, which is the list that used to push everything else
+ below the fold. */}
+ <div className="grid gap-x-4 gap-y-3 sm:grid-cols-2">
+ <div className="flex flex-col gap-3">
+ {showInventoryPicker && STANDALONE && (
+ /* No backend, so no Device Inventory modal to open (it reads
+ `pending_devices` over REST) — standalone keeps the flat list. */
+ <Field label="Device Inventory entry">
+ <select
+ className={inputClass}
+ aria-label="Device Inventory entry"
+ value={inventoryId}
+ onChange={(e) => {
+ const item = inventory.find((i) => i.id === e.target.value)
+ if (item) applyInventoryItem(item)
+ else setInventoryId('')
+ }}
+ >
+ <option value="">Select a device…</option>
+ {unracked.map((item) => (
+ <option key={item.id} value={item.id}>
+ {inventoryOption(item)}
+ </option>
+ ))}
+ </select>
+ </Field>
+ )}
- {!isEdit && source === 'new' && (
- <Field label="IP (optional)">
- <input
- className={`${inputClass} font-mono`}
- aria-label="IP"
- value={newIp}
- onChange={(e) => setNewIp(e.target.value)}
- placeholder="192.168.1.10"
- />
- </Field>
- )}
+ {showInventoryPicker && !STANDALONE && (
+ <Field label="Device Inventory entry">
+ {/* Opens the real Device Inventory rather than a flat <select>:
+ the user gets its search, source/type filters and the tech
+ detail on each card to tell look-alike hosts apart. */}
+ <button
+ type="button"
+ aria-label="Device Inventory entry"
+ data-device-id={inventoryId}
+ onClick={() => setInventoryPickerOpen(true)}
+ className="flex cursor-pointer flex-col items-start gap-0.5 rounded border border-[#30363d] bg-[#21262d] px-2 py-1.5 text-left hover:border-[#00d4ff]"
+ >
+ <span className="text-sm">
+ {selectedEntry ? inventoryOption(selectedEntry) : 'No device picked yet'}
+ </span>
+ <span className="text-[11px] text-[#00d4ff]">
+ {selectedEntry ? 'Change device…' : 'Browse the Device Inventory…'}
+ </span>
+ </button>
+ {unracked.length === 0 && (
+ <p className="text-[11px] text-muted-foreground">
+ Everything in the inventory is already racked — create a new device instead.
+ </p>
+ )}
+ {/* Rendered inside this DialogContent on purpose: an open Base UI
+ dialog marks outside content inert, so a sibling overlay would
+ be unclickable. */}
+ <PendingDevicesModal
+ open={inventoryPickerOpen}
+ onClose={() => setInventoryPickerOpen(false)}
+ onPick={(d) => void handlePickFromInventory(d)}
+ initialRackableOnly
+ />
+ </Field>
+ )}
- {!isEdit && racks.length > 1 && (
- <Field label="Rack">
- <select
- className={inputClass}
- aria-label="Rack"
- value={rackId}
- onChange={(e) => setRackId(e.target.value)}
- >
- {racks.map((r) => (
- <option key={r.id} value={r.id}>
- {r.name}
- </option>
- ))}
- </select>
- </Field>
- )}
+ {!isEdit && source === 'new' && (
+ <Field label="IP (optional)">
+ <input
+ className={`${inputClass} font-mono`}
+ aria-label="IP"
+ value={newIp}
+ onChange={(e) => setNewIp(e.target.value)}
+ placeholder="192.168.1.10"
+ />
+ </Field>
+ )}
- <Field label="Label">
- <input
- className={inputClass}
- aria-label="Label"
- value={label}
- onChange={(e) => setLabel(e.target.value)}
- placeholder={source === 'accessory' ? getFaceplate(faceplateId).label : 'Device name'}
- />
- </Field>
-
- <Field label="Faceplate">
- {/* The catalog is visual — the button previews the current plate and
- opens the picker rather than hiding drawings behind a name. */}
- <button
- type="button"
- aria-label="Faceplate"
- data-faceplate={faceplateId}
- onClick={() => setPickerOpen(true)}
- className="flex cursor-pointer items-center gap-3 rounded border border-[#30363d] bg-[#21262d] p-2 text-left hover:border-[#00d4ff]"
- >
- <Faceplate
- faceplateId={faceplateId}
- label={label || getFaceplate(faceplateId).label}
- status={status}
- ports={ports}
- width={(160 * colSpan) / RACK_COLUMNS}
- height={Math.min(uHeight, 4) * 18}
- colorOverride={color}
- revealed
- />
- <span className="flex flex-col">
- <span className="text-xs">{getFaceplate(faceplateId).label}</span>
- <span className="text-[11px] text-[#00d4ff]">Browse faceplates…</span>
- </span>
- </button>
- <FaceplatePicker
- open={pickerOpen}
- value={faceplateId}
- kind={!isEdit && source === 'accessory' ? 'accessory' : undefined}
- onPick={pickFaceplate}
- onClose={() => setPickerOpen(false)}
- />
- {plateChanged && isEdit && (
- <p className="text-[11px] text-[#e3b341]">
- Changing the plate replaces its ports and drops their patches.
- </p>
+ {!isEdit && racks.length > 1 && (
+ <Field label="Rack">
+ <select
+ className={inputClass}
+ aria-label="Rack"
+ value={rackId}
+ onChange={(e) => setRackId(e.target.value)}
+ >
+ {racks.map((r) => (
+ <option key={r.id} value={r.id}>
+ {r.name}
+ </option>
+ ))}
+ </select>
+ </Field>
)}
- </Field>
- <div className="grid grid-cols-2 gap-3">
- <Field label="U position">
- <input
- type="number"
- min={1}
- className={inputClass}
- aria-label="U position"
- value={uStart}
- onChange={(e) => setUStart(Number(e.target.value) || 1)}
- />
- </Field>
- <Field label="Height (U)">
+ <Field label="Label">
<input
- type="number"
- min={1}
- max={12}
className={inputClass}
- aria-label="Height (U)"
- value={uHeight}
- onChange={(e) => setUHeight(Number(e.target.value) || 1)}
+ aria-label="Label"
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ placeholder={source === 'accessory' ? getFaceplate(faceplateId).label : 'Device name'}
/>
</Field>
- <Field label="Column">
- <input
- type="number"
- min={0}
- max={RACK_COLUMNS - 1}
- className={inputClass}
- aria-label="Column"
- value={colStart}
- onChange={(e) => setColStart(Number(e.target.value) || 0)}
+
+ <Field label="Faceplate">
+ {/* The catalog is visual — the button previews the current plate and
+ opens the picker rather than hiding drawings behind a name. */}
+ <button
+ type="button"
+ aria-label="Faceplate"
+ data-faceplate={faceplateId}
+ onClick={() => setPickerOpen(true)}
+ className="flex cursor-pointer items-center gap-3 rounded border border-[#30363d] bg-[#21262d] p-2 text-left hover:border-[#00d4ff]"
+ >
+ <Faceplate
+ faceplateId={faceplateId}
+ label={label || getFaceplate(faceplateId).label}
+ status={status}
+ ports={ports}
+ width={(160 * colSpan) / RACK_COLUMNS}
+ height={Math.min(uHeight, 4) * 18}
+ colorOverride={color}
+ revealed
+ />
+ <span className="flex flex-col">
+ <span className="text-xs">{getFaceplate(faceplateId).label}</span>
+ <span className="text-[11px] text-[#00d4ff]">Browse faceplates…</span>
+ </span>
+ </button>
+ <FaceplatePicker
+ open={pickerOpen}
+ value={faceplateId}
+ kind={!isEdit && source === 'accessory' ? 'accessory' : undefined}
+ onPick={pickFaceplate}
+ onClose={() => setPickerOpen(false)}
/>
+ {plateChanged && isEdit && (
+ <p className="text-[11px] text-[#e3b341]">
+ Changing the plate replaces its ports and drops their patches.
+ </p>
+ )}
</Field>
- <Field label={`Width (/${RACK_COLUMNS})`}>
+
+ <div className="grid grid-cols-2 gap-3">
+ <Field label="U position">
+ <input
+ type="number"
+ min={1}
+ className={inputClass}
+ aria-label="U position"
+ value={uStart}
+ onChange={(e) => setUStart(Number(e.target.value) || 1)}
+ />
+ </Field>
+ <Field label="Height (U)">
+ <input
+ type="number"
+ min={1}
+ max={12}
+ className={inputClass}
+ aria-label="Height (U)"
+ value={uHeight}
+ onChange={(e) => setUHeight(Number(e.target.value) || 1)}
+ />
+ </Field>
+ <Field label="Column">
+ <input
+ type="number"
+ min={0}
+ max={RACK_COLUMNS - 1}
+ className={inputClass}
+ aria-label="Column"
+ value={colStart}
+ onChange={(e) => setColStart(Number(e.target.value) || 0)}
+ />
+ </Field>
+ <Field label={`Width (/${RACK_COLUMNS})`}>
+ <select
+ className={inputClass}
+ aria-label="Width"
+ value={colSpan}
+ onChange={(e) => setColSpan(Number(e.target.value))}
+ >
+ <option value={RACK_COLUMNS}>Full width</option>
+ <option value={RACK_COLUMNS / 2}>Half width</option>
+ <option value={RACK_COLUMNS / 3}>Third width</option>
+ <option value={RACK_COLUMNS / 4}>Quarter width</option>
+ </select>
+ </Field>
+ </div>
+
+ <Field label="Status">
<select
className={inputClass}
- aria-label="Width"
- value={colSpan}
- onChange={(e) => setColSpan(Number(e.target.value))}
+ aria-label="Status"
+ value={status}
+ onChange={(e) => setStatus(e.target.value as DeviceStatus)}
>
- <option value={RACK_COLUMNS}>Full width</option>
- <option value={RACK_COLUMNS / 2}>Half width</option>
- <option value={RACK_COLUMNS / 3}>Third width</option>
- <option value={RACK_COLUMNS / 4}>Quarter width</option>
+ <option value="online">Online</option>
+ <option value="offline">Offline</option>
+ <option value="unknown">Unknown</option>
</select>
</Field>
- </div>
- <Field label="Status">
- <select
- className={inputClass}
- aria-label="Status"
- value={status}
- onChange={(e) => setStatus(e.target.value as DeviceStatus)}
- >
- <option value="online">Online</option>
- <option value="offline">Offline</option>
- <option value="unknown">Unknown</option>
- </select>
- </Field>
-
- <Field label="Colour override">
- <div className="flex items-center gap-2">
- <input
- type="color"
- aria-label="Colour override"
- className="h-8 flex-1 cursor-pointer rounded border border-[#30363d] bg-[#21262d]"
- value={color ?? DEFAULT_COLOR}
- onChange={(e) => setColor(e.target.value)}
- />
- <button
- type="button"
- onClick={() => setColor(undefined)}
- className="rounded border border-[#30363d] px-2 py-1 text-[11px] text-muted-foreground hover:text-foreground cursor-pointer"
- >
- Reset
- </button>
- </div>
- </Field>
-
- <div className="flex items-center justify-between">
- <Label className={fieldLabel}>Ports ({ports.length})</Label>
- <button
- type="button"
- aria-label="Add port"
- className="cursor-pointer rounded border border-[#30363d] px-2 py-0.5 text-xs hover:border-[#00d4ff]"
- onClick={() =>
- setLocalPorts((p) => [
- ...p,
- { id: generateUUID(), label: `p${p.length + 1}`, type: 'rj45', x: 0.5, y: 0.5 },
- ])
- }
- >
- <Plus size={12} className="inline" /> Add
- </button>
- </div>
- <ul className="max-h-40 space-y-1 overflow-y-auto">
- {ports.map((port) => (
- <li key={port.id} className="flex items-center gap-1">
+ <Field label="Colour override">
+ <div className="flex items-center gap-2">
<input
- // `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) =>
- list.map((p) => (p.id === port.id ? { ...p, label: e.target.value } : p)),
- )
- }
+ type="color"
+ aria-label="Colour override"
+ className="h-8 flex-1 cursor-pointer rounded border border-[#30363d] bg-[#21262d]"
+ value={color ?? DEFAULT_COLOR}
+ onChange={(e) => setColor(e.target.value)}
/>
- <select
- className={`${inputBase} w-24 shrink-0`}
- aria-label={`Port ${port.label} type`}
- value={port.type}
- onChange={(e) =>
- setLocalPorts((list) =>
- list.map((p) =>
- p.id === port.id ? { ...p, type: e.target.value as PortType } : p,
- ),
- )
- }
+ <button
+ type="button"
+ onClick={() => setColor(undefined)}
+ className="rounded border border-[#30363d] px-2 py-1 text-[11px] text-muted-foreground hover:text-foreground cursor-pointer"
>
- {(['rj45', 'sfp', 'sfp+'] as PortType[]).map((t) => (
- <option key={t} value={t}>
- {t}
- </option>
- ))}
- </select>
+ Reset
+ </button>
+ </div>
+ </Field>
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <Label className={fieldLabel}>Ports ({ports.length})</Label>
<button
type="button"
- aria-label={`Remove port ${port.label}`}
- className="cursor-pointer px-1 text-xs text-muted-foreground hover:text-[#f85149]"
- onClick={() => setLocalPorts((list) => list.filter((p) => p.id !== port.id))}
+ aria-label="Add port"
+ className="cursor-pointer rounded border border-[#30363d] px-2 py-0.5 text-xs hover:border-[#00d4ff]"
+ onClick={() =>
+ setLocalPorts((p) => [
+ ...p,
+ { id: generateUUID(), label: `p${p.length + 1}`, type: 'rj45', x: 0.5, y: 0.5 },
+ ])
+ }
>
- <X size={12} />
+ <Plus size={12} className="inline" /> Add
</button>
- </li>
- ))}
- {ports.length === 0 && (
- <li className="text-[11px] text-muted-foreground">No port on this plate.</li>
- )}
- </ul>
+ </div>
+ <ul className="max-h-[26rem] space-y-1 overflow-y-auto">
+ {ports.map((port) => (
+ <li key={port.id} className="flex items-center gap-1">
+ <input
+ // `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) =>
+ list.map((p) => (p.id === port.id ? { ...p, label: e.target.value } : p)),
+ )
+ }
+ />
+ <select
+ className={`${inputBase} w-24 shrink-0`}
+ aria-label={`Port ${port.label} type`}
+ value={port.type}
+ onChange={(e) =>
+ setLocalPorts((list) =>
+ list.map((p) =>
+ p.id === port.id ? { ...p, type: e.target.value as PortType } : p,
+ ),
+ )
+ }
+ >
+ {(['rj45', 'sfp', 'sfp+'] as PortType[]).map((t) => (
+ <option key={t} value={t}>
+ {t}
+ </option>
+ ))}
+ </select>
+ <button
+ type="button"
+ aria-label={`Remove port ${port.label}`}
+ className="cursor-pointer px-1 text-xs text-muted-foreground hover:text-[#f85149]"
+ onClick={() => setLocalPorts((list) => list.filter((p) => p.id !== port.id))}
+ >
+ <X size={12} />
+ </button>
+ </li>
+ ))}
+ {ports.length === 0 && (
+ <li className="text-[11px] text-muted-foreground">No port on this plate.</li>
+ )}
+ </ul>
+ </div>
+ </div>
<div className="mt-1 flex items-center gap-2">
{isEdit && (
diff --git a/frontend/src/utils/__tests__/rackable.test.ts b/frontend/src/utils/__tests__/rackable.test.ts
new file mode 100644
index 0000000..3e81b30
--- /dev/null
+++ b/frontend/src/utils/__tests__/rackable.test.ts
@@ -0,0 +1,43 @@
+import { describe, it, expect } from 'vitest'
+import { isRackable, UNRACKABLE_TYPES } from '../rackable'
+import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+
+function device(suggested_type: string | null): PendingDevice {
+ return {
+ id: 'd1',
+ ip: null,
+ mac: null,
+ hostname: null,
+ os: null,
+ services: [],
+ suggested_type,
+ status: 'pending',
+ discovery_source: 'arp',
+ discovered_at: '2026-01-01T00:00:00Z',
+ }
+}
+
+describe('isRackable', () => {
+ it('takes hardware kinds', () => {
+ for (const type of ['server', 'switch', 'nas', 'proxmox', 'router', 'ups']) {
+ expect(isRackable(device(type))).toBe(true)
+ }
+ })
+
+ it('rejects virtual, mesh and annotation kinds', () => {
+ for (const type of ['vm', 'lxc', 'docker_container', 'zigbee_enddevice', 'text']) {
+ expect(isRackable(device(type))).toBe(false)
+ }
+ })
+
+ it('keeps an unclassified device — the scanner just has not named it', () => {
+ // A bare ARP hit has no suggested_type; hiding those would empty the picker
+ // on a freshly scanned network.
+ expect(isRackable(device(null))).toBe(true)
+ })
+
+ it('is an exclusion list, so a new hardware type is rackable by default', () => {
+ expect(isRackable(device('tape_library'))).toBe(true)
+ expect(UNRACKABLE_TYPES.has('tape_library')).toBe(false)
+ })
+})
diff --git a/frontend/src/utils/rackable.ts b/frontend/src/utils/rackable.ts
new file mode 100644
index 0000000..0f88bf8
--- /dev/null
+++ b/frontend/src/utils/rackable.ts
@@ -0,0 +1,40 @@
+/**
+ * "Rackable" — a Device Inventory entry that describes a piece of hardware you
+ * could screw into a rack, as opposed to something virtual, mesh-attached or
+ * purely a canvas annotation.
+ *
+ * An exclusion list, not an allow list: new hardware types should be rackable
+ * by default and only the obviously non-physical kinds opt out. A device with
+ * no `suggested_type` at all (a bare IP-scan hit) stays rackable — the scanner
+ * simply has not named it yet.
+ *
+ * Mirrors `_UNRACKABLE_TYPES` in `backend/app/api/routes/racks.py`, which is
+ * what `GET /api/v1/racks/inventory` filters on; `test_rackable_sync.py` fails
+ * the backend suite when the two drift. Keeping them equal is what makes the
+ * inventory modal's Rackable filter show exactly the rows the rack tray offers.
+ */
+import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+
+export const UNRACKABLE_TYPES = new Set([
+ 'vm',
+ 'lxc',
+ 'docker_container',
+ 'mobile',
+ 'laptop',
+ 'light',
+ 'socket',
+ 'load',
+ 'groupRect',
+ 'group',
+ 'text',
+ 'zigbee_coordinator',
+ 'zigbee_router',
+ 'zigbee_enddevice',
+ 'zwave_coordinator',
+ 'zwave_router',
+ 'zwave_enddevice',
+])
+
+export function isRackable(device: PendingDevice): boolean {
+ return !device.suggested_type || !UNRACKABLE_TYPES.has(device.suggested_type)
+}