Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(rack): let a mount say when it shows its ports, and never end a cable on hidden metal
Pouzor4ccad61e73c0
diff --git a/backend/app/db/database.py b/backend/app/db/database.pyindex 94a2fb2..02e14ac 100644--- a/backend/app/db/database.py+++ b/backend/app/db/database.py@@ -362,6 +362,18 @@ async def init_db() -> None:"UPDATE rack_cables SET properties = '[]' WHERE properties IS NULL")+ # A mount can override when its plate draws its sockets. Existing rows+ # keep the old behaviour, which is exactly what "auto" means.+ await _try_migrate(+ conn,+ "ALTER TABLE rack_devices ADD COLUMN port_visibility TEXT NOT NULL DEFAULT 'auto'",+ label="rack_devices.port_visibility",+ )+ with suppress(OperationalError):+ await conn.exec_driver_sql(+ "UPDATE rack_devices SET port_visibility = 'auto' WHERE port_visibility IS NULL"+ )+with suppress(OperationalError):await conn.exec_driver_sql("ALTER TABLE edges ADD COLUMN waypoints JSON")with suppress(OperationalError):diff --git a/backend/app/db/models.py b/backend/app/db/models.pyindex 05a62cb..d45d14c 100644--- a/backend/app/db/models.py+++ b/backend/app/db/models.py@@ -172,6 +172,9 @@ class RackDevice(Base):faceplate_id: Mapped[str] = mapped_column(String, nullable=False, default="blank-1u")color: Mapped[str | None] = mapped_column(String, nullable=True)status: Mapped[str] = mapped_column(String, default="unknown")+ # When the plate draws its sockets: "auto" (the faceplate decides), "always"+ # or "hover". A canvas display choice about the mount, not about the device.+ port_visibility: Mapped[str] = mapped_column(String, default="auto")# [{id, label, type, x, y}] — positions are unit coordinates on the plate.ports: Mapped[list[Any]] = mapped_column(JSON, default=list)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)diff --git a/backend/app/schemas/racks.py b/backend/app/schemas/racks.pyindex e4177fc..c633fbd 100644--- a/backend/app/schemas/racks.py+++ b/backend/app/schemas/racks.py@@ -7,6 +7,8 @@ from pydantic import BaseModel, field_validator, model_validatorWIDTH_STANDARDS = {"19", "10"}NUMBERINGS = {"bottom-up", "top-down"}CABLE_TYPES = {"ethernet", "fiber"}+# When a mount draws its ports; "auto" leaves the faceplate in charge.+PORT_VISIBILITIES = {"auto", "always", "hover"}# 12-column horizontal grid: full = 12, half = 6, third = 4, quarter = 3.RACK_COLUMNS = 12@@ -57,8 +59,15 @@ class RackDeviceSave(BaseModel):faceplate_id: str = "blank-1u"color: str | None = Nonestatus: str = "unknown"+ port_visibility: str = "auto"ports: list[Any] = []+ @field_validator("port_visibility", mode="before")+ @classmethod+ def _known_port_visibility(cls, v: Any) -> str:+ """Anything unknown — including the NULL of a pre-column row — is `auto`."""+ return str(v) if v in PORT_VISIBILITIES else "auto"+@field_validator("u_start", "u_height")@classmethoddef _positive(cls, v: int) -> int:@@ -223,8 +232,15 @@ class RackDeviceResponse(BaseModel):faceplate_id: strcolor: str | None = Nonestatus: str+ port_visibility: str = "auto"ports: list[Any] = []+ @field_validator("port_visibility", mode="before")+ @classmethod+ def _port_visibility_or_auto(cls, v: Any) -> str:+ """Rows written before the column existed read back as NULL."""+ return str(v) if v in PORT_VISIBILITIES else "auto"+@field_validator("ports", mode="before")@classmethoddef _coerce_ports(cls, v: Any) -> list[Any]:diff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.pyindex 6722d22..86ac86d 100644--- a/backend/tests/test_racks.py+++ b/backend/tests/test_racks.py@@ -312,6 +312,35 @@ class TestSaveAndLoad:assert loaded["cables"][0]["from_port_id"] == "p1"assert loaded["viewport"] == {"x": 10, "y": 20, "zoom": 1.5}+ async def test_round_trips_the_port_visibility_override(+ self, client: AsyncClient, headers+ ):+ # When a plate draws its sockets is a per-mount display choice, so it+ # rides on the mount and not on the inventory row behind it.+ design_id = await _design(client, headers)+ state = _state(design_id, cables=[])+ state["devices"][0]["port_visibility"] = "hover"+ state["devices"][1]["port_visibility"] = "always"+ 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()+ by_id = {d["id"]: d for d in loaded["devices"]}+ assert by_id["dev-sw"]["port_visibility"] == "hover"+ assert by_id["dev-nas"]["port_visibility"] == "always"++ async def test_defaults_port_visibility_to_auto(self, client: AsyncClient, headers):+ # A payload from before the field existed — and any unknown value —+ # keeps the old behaviour: the faceplate decides.+ design_id = await _design(client, headers)+ state = _state(design_id, cables=[])+ state["devices"][1]["port_visibility"] = "sometimes"+ 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()+ assert {d["port_visibility"] for d in loaded["devices"]} == {"auto"}+async def test_keeps_a_mount_that_follows_its_node_check(self, client: AsyncClient, headers):diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.mdindex e2d1417..7698344 100644--- a/frontend/src/rack/README.md+++ b/frontend/src/rack/README.md@@ -24,7 +24,7 @@ Create one from **New Canvas → Kind → Rack**.| 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, positioned by hand on the plate (`portLayout.ts` + `PortPositionEditor`). Accessories carry none. Power outlets are artwork, never a cable endpoint. || Port ownership | The **Device Inventory row owns the rack modelisation** — faceplate, U height, column span, colour override and the port list, positions included — not the mount. A device therefore wears the same front panel in every rack. Only placement (`rackId`, `uStart`, `colStart`), pinned status and label stay per canvas. Columns `device_inventory.rack_*`; `POST /racks/save` writes them through and `GET /racks` overlays them on load. Size is applied only where it still fits the mount's rack **and lands on no neighbour** — geometry is global, a rack is not, and an overlaid plate must obey the same placement rule as a dropped one. A mount can therefore hold less than its row does, so the write-through sends size back only when that save actually changed it; an unchanged size is an echo of the clamp and would shrink the device in every other rack. `POST /racks/save` also refuses two mounts that overlap in the same rack. Standalone has no inventory row to hang this on, so ports stay per mount there. Editable from both ends: a mount in `RackDeviceModal`, or the row itself in the Device Inventory detail modal (`DeviceFaceplateEditor`, shown only for a device already modelled), which writes the same columns through `PATCH /scan/pending/{id}`. |-| 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. |+| Port visibility | Per mount, `portVisibility`: `auto` (the default) leaves the faceplate in charge — patch-facing gear (switches, patch panels, `alwaysShowPorts`) shows its ports permanently, everything else reveals them on hover, on selection or in patch mode; `always` and `hover` override that plate rule either way. On top of the mode, a port a **drawn** cable ends on is always rendered, on both plates — hovering a switch lights the far sockets its runs land on, so a cable never ends on invisible metal. `cableVisibility.ts` owns that rule and `CableLayer` draws from the same answer. The mode is a canvas display choice: it lives on the rack mount, never on the inventory row. || Plate zones | Each template reserves three non-overlapping bands: status LED (fixed left), `labelBox` (name, clipped), then artwork and ports. A test asserts no port lands on the name band. `labelBox.y` (default 0.5) moves the name band *and* the LED off mid-height — desktop NAS boxes are drive doors over a badge strip at the bottom. || Cables | Port-to-port, a relation of their own — not React Flow edges. One cable per port. Drawn in a `ViewportPortal` so they pan/zoom with the canvas and can cross racks. || Cable visibility | Hidden by default; shown on hover/selection, or all-on via patch mode / the header. Plates stay opaque in every mode — fading them to 40 % showed the rails and the U grid through the gear. Copper vs fibre follows the port the patch starts from. A selected cable is drawn whatever the mode, `hidden` included — its panel is open on the right, so hiding the run it describes would read as a bug — but `hidden` reveals nothing else, not even on hover. |diff --git a/frontend/src/rack/__tests__/Faceplate.test.tsx b/frontend/src/rack/__tests__/Faceplate.test.tsxindex 903b8f0..17ae7cd 100644--- a/frontend/src/rack/__tests__/Faceplate.test.tsx+++ b/frontend/src/rack/__tests__/Faceplate.test.tsx@@ -86,3 +86,60 @@ describe('Faceplate — name band', () => {expect(text).toHaveAttribute('y', String(band * HEIGHT))})})++/** Ids of the ports the plate actually drew. */+function drawnPortIds(props: Partial<Parameters<typeof Faceplate>[0]>) {+ const ports = [+ { id: 'a', label: 'p1', type: 'rj45' as const, x: 0.3, y: 0.5 },+ { id: 'b', label: 'p2', type: 'rj45' as const, x: 0.5, y: 0.5 },+ ]+ const { container } = render(+ <Faceplate+ faceplateId="server-1u"+ label="box"+ status="online"+ ports={ports}+ width={200}+ height={24}+ {...props}+ />,+ )+ return Array.from(container.querySelectorAll('title'))+ .map((t) => t.textContent?.split(' ·')[0])+ .filter(Boolean)+}++describe('Faceplate — when ports are drawn', () => {+ it('hides the ports of non-patch gear until it is focused', () => {+ expect(drawnPortIds({})).toEqual([])+ expect(drawnPortIds({ revealed: true })).toEqual(['p1', 'p2'])+ })++ it('always draws a port a visible cable ends on, focused or not', () => {+ // The far end of a hovered device's run lands on a plate that is not+ // hovered — a cable must never end on an invisible socket.+ expect(drawnPortIds({ revealedPortIds: new Set(['b']) })).toEqual(['p2'])+ })++ it('honours an `always` override on gear the plate would hide', () => {+ expect(drawnPortIds({ portVisibility: 'always' })).toEqual(['p1', 'p2'])+ })++ it('honours a `hover` override on a switch the plate would always show', () => {+ const asSwitch = { faceplateId: 'switch-24' as const }+ expect(drawnPortIds({ ...asSwitch })).toEqual(['p1', 'p2'])+ expect(drawnPortIds({ ...asSwitch, portVisibility: 'hover' })).toEqual([])+ expect(drawnPortIds({ ...asSwitch, portVisibility: 'hover', revealed: true })).toEqual([+ 'p1',+ 'p2',+ ])+ })++ it('leaves `auto` on the faceplate to decide', () => {+ expect(drawnPortIds({ portVisibility: 'auto' })).toEqual([])+ expect(drawnPortIds({ portVisibility: 'auto', faceplateId: 'switch-24' })).toEqual([+ 'p1',+ 'p2',+ ])+ })+})diff --git a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx b/frontend/src/rack/__tests__/RackDeviceModal.test.tsxindex b165128..49be135 100644--- a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx+++ b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx@@ -415,6 +415,26 @@ describe('RackDeviceModal — editing', () => {expect(screen.getByText(`Ports (${device.ports.length})`)).toBeInTheDocument()})+ it('saves a port visibility override on the mount', async () => {+ store().openDeviceEditor('dev-pve1')+ render(<RackDeviceModal />)++ const select = screen.getByLabelText('Show ports on the canvas')+ expect(select).toHaveValue('auto')+ fireEvent.change(select, { target: { value: 'always' } })+ submit()++ await waitFor(() => expect(store().deviceEditor).toBeNull())+ expect(store().devices.find((d) => d.id === 'dev-pve1')!.portVisibility).toBe('always')+ })++ it('leaves the port visibility selector off an accessory', () => {+ // A shelf has no ports, so there is nothing to decide about.+ store().openDeviceEditor('dev-shelf')+ render(<RackDeviceModal />)+ expect(screen.queryByLabelText('Show ports on the canvas')).toBeNull()+ })+it('saves label, status and geometry in one go', async () => {store().openDeviceEditor('dev-shelf')render(<RackDeviceModal />)diff --git a/frontend/src/rack/__tests__/RackFlowNode.test.tsx b/frontend/src/rack/__tests__/RackFlowNode.test.tsxindex 8007b24..d4a1ce2 100644--- a/frontend/src/rack/__tests__/RackFlowNode.test.tsx+++ b/frontend/src/rack/__tests__/RackFlowNode.test.tsx@@ -155,3 +155,69 @@ describe('RackFlowNode patching', () => {expect(store().cables).toHaveLength(before + 1)})})++describe('RackFlowNode port visibility', () => {+ /** How many sockets the plate of `label` is currently drawing. */+ function drawnPorts(label: string) {+ const plate = screen.getByTitle(new RegExp(`^${label} ·`))+ return Array.from(plate.querySelectorAll('title')).length+ }++ /** A cable between a switch and a non-patch plate, and both its ends. */+ function crossCable() {+ const sw = store().devices.find((d) => d.faceplateId === 'switch-24')!+ const cable = store().cables.find(+ (c) => c.from.deviceId === sw.id || c.to.deviceId === sw.id,+ )!+ const farId = cable.from.deviceId === sw.id ? cable.to.deviceId : cable.from.deviceId+ return { sw, cable, far: store().devices.find((d) => d.id === farId)! }+ }++ it('hides the ports of non-patch gear until it is hovered', () => {+ const { far } = crossCable()+ renderRack()+ expect(drawnPorts(far.label)).toBe(0)++ fireEvent.mouseEnter(screen.getByTitle(new RegExp(`^${far.label} ·`)))+ expect(drawnPorts(far.label)).toBe(far.ports.length)+ })++ it('draws the far socket of a cable revealed by hovering the switch', () => {+ // The reported bug: hovering the switch drew its runs, but the ends landed+ // on plates that draw nothing — a cable stopping on blank metal.+ const { sw, far } = crossCable()+ renderRack()++ fireEvent.mouseEnter(screen.getByTitle(new RegExp(`^${sw.label} ·`)))+ expect(drawnPorts(far.label)).toBeGreaterThan(0)+ // Only the patched one: hovering a neighbour does not reveal the whole plate.+ expect(drawnPorts(far.label)).toBeLessThan(far.ports.length)+ })++ it('draws no socket at all while the cabling overlay is hidden', () => {+ const { sw, far } = crossCable()+ store().setCableVisibility('hidden')+ renderRack()++ fireEvent.mouseEnter(screen.getByTitle(new RegExp(`^${sw.label} ·`)))+ expect(drawnPorts(far.label)).toBe(0)+ })++ it('obeys a mount that overrides when its ports show', () => {+ const { sw, far } = crossCable()+ useRackStore.setState({+ devices: store().devices.map((d) =>+ d.id === far.id+ ? { ...d, portVisibility: 'always' as const }+ : d.id === sw.id+ ? { ...d, portVisibility: 'hover' as const }+ : d,+ ),+ })+ renderRack()++ expect(drawnPorts(far.label)).toBe(far.ports.length)+ // A switch set to `hover` keeps only what a drawn cable ends on.+ expect(drawnPorts(sw.label)).toBeLessThan(sw.ports.length)+ })+})diff --git a/frontend/src/rack/__tests__/cableVisibility.test.ts b/frontend/src/rack/__tests__/cableVisibility.test.tsnew file mode 100644index 0000000..d2ffcb6--- /dev/null+++ b/frontend/src/rack/__tests__/cableVisibility.test.ts@@ -0,0 +1,65 @@+/**+ * The rule two components share: which cables are on screen, and therefore+ * which sockets the plates must draw.+ */+import { describe, it, expect } from 'vitest'+import { patchedPortIds, visibleCables, type CableFocus } from '../cableVisibility'+import type { Cable } from '@/types'++const cable = (id: string, from: string, to: string): Cable => ({+ id,+ type: 'ethernet',+ color: '#39d353',+ from: { deviceId: from, portId: `${from}-out` },+ to: { deviceId: to, portId: `${to}-in` },+})++const CABLES = [cable('c1', 'sw', 'nas'), cable('c2', 'sw', 'pc'), cable('c3', 'nas', 'pc')]++const focus = (over: Partial<CableFocus> = {}): CableFocus => ({+ visibility: 'hover',+ cableMode: false,+ focusDeviceId: null,+ selectedCableId: null,+ ...over,+})++const ids = (f: CableFocus) => visibleCables(CABLES, f).map((c) => c.id)++describe('visibleCables', () => {+ it('draws everything when the overlay is on, or in patch mode', () => {+ expect(ids(focus({ visibility: 'always' }))).toEqual(['c1', 'c2', 'c3'])+ expect(ids(focus({ visibility: 'hidden', cableMode: true }))).toEqual(['c1', 'c2', 'c3'])+ })++ it('draws nothing in hover mode until a device is focused', () => {+ expect(ids(focus())).toEqual([])+ })++ it('draws both ends of the focused device runs', () => {+ expect(ids(focus({ focusDeviceId: 'sw' }))).toEqual(['c1', 'c2'])+ expect(ids(focus({ focusDeviceId: 'pc' }))).toEqual(['c2', 'c3'])+ })++ it('keeps a selected cable on screen even when everything is hidden', () => {+ // Its panel is open on the right; hiding the run it describes reads as a bug.+ expect(ids(focus({ visibility: 'hidden', selectedCableId: 'c2' }))).toEqual(['c2'])+ })++ it('reveals nothing extra on hover while hidden', () => {+ expect(ids(focus({ visibility: 'hidden', focusDeviceId: 'sw' }))).toEqual([])+ })+})++describe('patchedPortIds', () => {+ it('collects both endpoints of every drawn cable', () => {+ // Hovering the switch must light the sockets on the *far* plates too.+ expect(patchedPortIds(CABLES, focus({ focusDeviceId: 'sw' }))).toEqual(+ new Set(['sw-out', 'nas-in', 'pc-in']),+ )+ })++ it('is empty when no cable is drawn', () => {+ expect(patchedPortIds(CABLES, focus())).toEqual(new Set())+ })+})diff --git a/frontend/src/rack/cableVisibility.ts b/frontend/src/rack/cableVisibility.tsnew file mode 100644index 0000000..662d107--- /dev/null+++ b/frontend/src/rack/cableVisibility.ts@@ -0,0 +1,43 @@+/**+ * Which cables the canvas is currently drawing.+ *+ * Two components need the same answer and must not drift: `CableLayer` draws+ * the runs, and `RackFlowNode` reveals the sockets they end on — a cable that+ * lands on a plate with no port drawn reads as a rendering bug.+ */+import type { Cable, CableVisibility } from '@/types/rack'++export interface CableFocus {+ visibility: CableVisibility+ /** Patch mode shows everything, whatever the visibility setting. */+ cableMode: boolean+ /** Hovered device, else the selected one. */+ focusDeviceId: string | null+ /** The cable whose panel is open on the right. */+ selectedCableId: string | null+}++/** Cables drawn right now, in input order. */+export function visibleCables(cables: Cable[], focus: CableFocus): Cable[] {+ const showAll = focus.cableMode || focus.visibility === 'always'+ return cables.filter((cable) => {+ // A selected cable stays on screen whatever the visibility mode — its panel+ // is open on the right, so hiding the run it describes reads as a bug.+ if (showAll || cable.id === focus.selectedCableId) return true+ // `hidden` means hidden: hovering a plate reveals nothing extra, or the+ // selection would drag its neighbours back on screen with it.+ if (focus.visibility === 'hidden') return false+ if (!focus.focusDeviceId) return false+ return cable.from.deviceId === focus.focusDeviceId || cable.to.deviceId === focus.focusDeviceId+ })+}++/** Every port a drawn cable ends on. Those sockets must be rendered. */+export function patchedPortIds(cables: Cable[], focus: CableFocus): Set<string> {+ const ids = new Set<string>()+ for (const cable of visibleCables(cables, focus)) {+ ids.add(cable.from.portId)+ ids.add(cable.to.portId)+ }+ return ids+}diff --git a/frontend/src/rack/components/CableLayer.tsx b/frontend/src/rack/components/CableLayer.tsxindex 3074799..a464863 100644--- a/frontend/src/rack/components/CableLayer.tsx+++ b/frontend/src/rack/components/CableLayer.tsx@@ -6,6 +6,7 @@* one, and they attach to ports rather than to node handles.*/import { ViewportPortal } from '@xyflow/react'+import { visibleCables } from '../cableVisibility'import { portPosition } from '../layout'import { useRackPalette, type RackPalette } from '../rackTheme'import { useRackStore } from '../store'@@ -75,8 +76,8 @@ export function CableLayer() {const rackById = new Map<string, Rack>(racks.map((r) => [r.id, r]))const deviceById = new Map<string, RackDevice>(devices.map((d) => [d.id, d]))+ // Also what dims the runs that are on screen but not the focused device's.const focus = hoveredDeviceId ?? selectedDeviceId- const showAll = cableMode || visibility === 'always'const resolve = (deviceId: string, portId: string) => {const device = deviceById.get(deviceId)@@ -87,16 +88,13 @@ export function CableLayer() {}const visible: Resolved[] = []- for (const cable of cables) {- // A selected cable stays on screen whatever the visibility mode — its panel- // is open on the right, so hiding the run it describes reads as a bug.- if (!showAll && cable.id !== selectedCableId) {- // `hidden` means hidden: hovering a plate reveals nothing extra, or the- // selection would drag its neighbours back on screen with it.- if (visibility === 'hidden') continue- if (!focus) continue- if (cable.from.deviceId !== focus && cable.to.deviceId !== focus) continue- }+ // The same rule decides which sockets the plates draw — see `cableVisibility`.+ for (const cable of visibleCables(cables, {+ visibility,+ cableMode,+ focusDeviceId: focus,+ selectedCableId,+ })) {const from = resolve(cable.from.deviceId, cable.from.portId)const to = resolve(cable.to.deviceId, cable.to.portId)if (!from || !to) continuediff --git a/frontend/src/rack/components/Faceplate.tsx b/frontend/src/rack/components/Faceplate.tsxindex f3be95c..cf005d8 100644--- a/frontend/src/rack/components/Faceplate.tsx+++ b/frontend/src/rack/components/Faceplate.tsx@@ -9,7 +9,7 @@ import { memo, useId } from 'react'import { getFaceplate } from '../faceplates'import { U_PX } from '../layout'import { useRackPalette } from '../rackTheme'-import type { DeviceStatus, FaceplateElement, Port, PortType } from '@/types'+import type { DeviceStatus, FaceplateElement, Port, PortType, PortVisibility } from '@/types'const LED_X = 9const LED_R = 3@@ -162,6 +162,16 @@ interface Props {selected?: boolean/** Hover or selection: reveals the ports of non-patch gear. */revealed?: boolean+ /**+ * Per-mount override of the plate's own rule. Absent (or `auto`) leaves the+ * faceplate template in charge.+ */+ portVisibility?: PortVisibility+ /**+ * Ports a drawn cable ends on. Always rendered, whatever the plate and the+ * mode: a cable must never end on an invisible socket.+ */+ revealedPortIds?: Set<string>/** Ports take the pointer (patch mode). */interactivePorts?: boolean/**@@ -190,6 +200,8 @@ export const Faceplate = memo(function Faceplate({colorOverride,selected,revealed,+ portVisibility,+ revealedPortIds,interactivePorts,portScale,patchedPorts,@@ -203,7 +215,11 @@ export const Faceplate = memo(function Faceplate({const panel = template.elements.find((e) => e.kind === 'panel')const fill = colorOverride ?? (panel?.kind === 'panel' ? panel.fill : palette.plate)- const showPorts = template.alwaysShowPorts || revealed || interactivePorts+ // `always` and `hover` override the plate; `auto` (the default) keeps the+ // template's own rule — patch-facing gear on, everything else on focus.+ const plateAlwaysShows =+ portVisibility === 'always' || (portVisibility !== 'hover' && !!template.alwaysShowPorts)+ const showPorts = plateAlwaysShows || revealed || interactivePortsconst labelX = template.labelBox.x * widthconst labelW = template.labelBox.w * width@@ -264,8 +280,8 @@ export const Faceplate = memo(function Faceplate({</text>)}- {showPorts &&- ports.map((port) => {+ {ports.map((port) => {+ if (!showPorts && !revealedPortIds?.has(port.id)) return nullconst cx = port.x * widthconst cy = port.y * heightconst patchColor = patchedPorts?.get(port.id)diff --git a/frontend/src/rack/components/RackDeviceModal.tsx b/frontend/src/rack/components/RackDeviceModal.tsxindex 36e53f3..c533da6 100644--- a/frontend/src/rack/components/RackDeviceModal.tsx+++ b/frontend/src/rack/components/RackDeviceModal.tsx@@ -32,6 +32,7 @@ import {type InventoryDevice,type MountStatus,type Port,+ type PortVisibility,} from '@/types'const DEFAULT_COLOR = '#2b323c'@@ -106,6 +107,9 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (const [colSpan, setColSpan] = useState(device?.colSpan ?? getFaceplate(faceplateId).colSpan)const [status, setStatus] = useState<MountStatus>(device?.status ?? 'unknown')const [color, setColor] = useState<string | undefined>(device?.color)+ const [portVisibility, setPortVisibility] = useState<PortVisibility>(+ device?.portVisibility ?? 'auto',+ )const [ports, setLocalPorts] = useState<Port[]>(device?.ports ?? getFaceplate(faceplateId).ports.map((p) => ({ ...p, id: generateUUID() })),)@@ -266,7 +270,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (}}const name = label.trim() || device.label- if (!updateDevice(device.id, { ...geometry, label: name, status, color })) {+ if (!updateDevice(device.id, { ...geometry, label: name, status, color, portVisibility })) {toast.error('No room in the rack for that size')return null}@@ -285,7 +289,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (// fits, and patching it afterwards would drag the plate back off it.const id = mountAccessory(faceplateId, rackId, geometry)if (!id) return noRoom()- updateDevice(id, { label: name || getFaceplate(faceplateId).label, color })+ updateDevice(id, { label: name || getFaceplate(faceplateId).label, color, portVisibility })return id}@@ -321,7 +325,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (if (!id) return noRoom()// The mount takes its label and status from the inventory entry, and its// slot from `findSlot` — only patch what the form actually overrides.- updateDevice(id, { status, color, ...(name ? { label: name } : {}) })+ updateDevice(id, { status, color, portVisibility, ...(name ? { label: name } : {}) })return id}@@ -635,14 +639,32 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (<div className="flex flex-col gap-3">{!isAccessory && (- <PortListEditor- ports={ports}- onChange={setLocalPorts}- positioning={positioning}- onPositioningChange={setPositioning}- selectedPortId={selectedPortId}- onSelect={setSelectedPortId}- />+ <>+ <PortListEditor+ ports={ports}+ onChange={setLocalPorts}+ positioning={positioning}+ onPositioningChange={setPositioning}+ selectedPortId={selectedPortId}+ onSelect={setSelectedPortId}+ />++ {/* How the canvas draws these sockets — a display choice about+ this mount, not a fact about the hardware, so it stays on+ the mount and never reaches the inventory entry. */}+ <Field label="Show ports on the canvas">+ <select+ className="h-8 w-full rounded border border-[#30363d] bg-[#21262d] px-2 text-xs cursor-pointer"+ aria-label="Show ports on the canvas"+ value={portVisibility}+ onChange={(e) => setPortVisibility(e.target.value as PortVisibility)}+ >+ <option value="auto">Automatic (switches and patch panels)</option>+ <option value="always">Always</option>+ <option value="hover">On hover or selection</option>+ </select>+ </Field>+ </>)}{/* The column below the port list used to be dead space. A mountdiff --git a/frontend/src/rack/components/RackFlowNode.tsx b/frontend/src/rack/components/RackFlowNode.tsxindex 405eb42..0c77a48 100644--- a/frontend/src/rack/components/RackFlowNode.tsx+++ b/frontend/src/rack/components/RackFlowNode.tsx@@ -1,6 +1,7 @@/** One rack = one React Flow node. The U grid inside is rendered by hand. */import { useCallback, useState } from 'react'import { useReactFlow, type NodeProps } from '@xyflow/react'+import { patchedPortIds } from '../cableVisibility'import { getFaceplate } from '../faceplates'import {HEADER_PX,@@ -46,6 +47,7 @@ export function RackFlowNode({ id }: NodeProps) {const cableMode = useRackStore((s) => s.cableMode)const cableDraft = useRackStore((s) => s.cableDraft)const cableVisibility = useRackStore((s) => s.cableVisibility)+ const selectedCableId = useRackStore((s) => s.selectedCableId)const selectDevice = useRackStore((s) => s.selectDevice)const selectRack = useRackStore((s) => s.selectRack)@@ -150,8 +152,17 @@ export function RackFlowNode({ id }: NodeProps) {}const cablesOn = cableVisibility === 'always' || cableMode// Ports of non-patch gear stay hidden until the plate is focused, or until- // cables are on globally — a cable must never end on an invisible port.+ // cables are on globally.const revealAll = cablesOn+ // A cable must never end on an invisible port, and in `hover` mode the far+ // end of a focused device's run lands on a plate that is *not* focused — so+ // reveal the sockets of every cable actually being drawn, on both plates.+ const revealedPortIds = patchedPortIds(cables, {+ visibility: cableVisibility,+ cableMode,+ focusDeviceId: hoveredDeviceId ?? selectedDeviceId,+ selectedCableId,+ })return (<div@@ -299,6 +310,8 @@ export function RackFlowNode({ id }: NodeProps) {colorOverride={device.color}selected={selectedDeviceId === device.id}revealed={revealAll || focused}+ portVisibility={device.portVisibility}+ revealedPortIds={revealedPortIds}interactivePorts={cableMode}patchedPorts={patchedPorts}draftPortId={isDraftDevice ? cableDraft.portId : null}diff --git a/frontend/src/types/rack.ts b/frontend/src/types/rack.tsindex 39f706e..820790b 100644--- a/frontend/src/types/rack.ts+++ b/frontend/src/types/rack.ts@@ -184,9 +184,28 @@ export interface RackDevice {color?: string/** Pinned state, or `auto` to follow the linked node's check. */status: MountStatus+ /**+ * Per-mount override of when the plate draws its sockets. Absent means+ * `auto` — see `PortVisibility`.+ */+ portVisibility?: PortVisibilityports: Port[]}+/**+ * When a mount draws its ports.+ *+ * * `auto` — the faceplate decides: patch-facing gear (switches, patch panels,+ * `FaceplateTemplate.alwaysShowPorts`) always shows them, everything else+ * only on hover, selection or in patch mode. The default.+ * * `always` — always drawn, whatever the plate.+ * * `hover` — only on hover, selection or in patch mode, even for a switch.+ *+ * A display choice about this mount on this canvas, not a fact about the+ * hardware: it lives on the rack mount, never on the inventory entry.+ */+export type PortVisibility = 'auto' | 'always' | 'hover'+// ---------------------------------------------------------------------------// Cabling// ---------------------------------------------------------------------------diff --git a/frontend/src/utils/__tests__/rackSerializer.test.ts b/frontend/src/utils/__tests__/rackSerializer.test.tsindex f54f585..3b685d8 100644--- a/frontend/src/utils/__tests__/rackSerializer.test.ts+++ b/frontend/src/utils/__tests__/rackSerializer.test.ts@@ -120,6 +120,23 @@ describe('API → domain', () => {expect(fromRackDevice(toRackDevice({ ...apiDevice, status: 'auto' })).status).toBe('auto')})+ it('carries a port visibility override, and treats anything else as auto', () => {+ // The column is newer than the table: a legacy row reads back NULL, and+ // `auto` is the absence of an override rather than a stored value.+ expect(toRackDevice({ ...apiDevice, port_visibility: 'hover' }).portVisibility).toBe('hover')+ expect(toRackDevice({ ...apiDevice, port_visibility: 'always' }).portVisibility).toBe('always')+ expect(toRackDevice({ ...apiDevice, port_visibility: null }).portVisibility).toBeUndefined()+ expect(toRackDevice({ ...apiDevice, port_visibility: 'sometimes' }).portVisibility).toBeUndefined()+ expect(toRackDevice(apiDevice).portVisibility).toBeUndefined()+ })++ it('sends auto for a mount with no port visibility override', () => {+ expect(fromRackDevice(toRackDevice(apiDevice)).port_visibility).toBe('auto')+ expect(+ fromRackDevice(toRackDevice({ ...apiDevice, port_visibility: 'always' })).port_visibility,+ ).toBe('always')+ })+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 cd3fb38..a739cf7 100644--- a/frontend/src/utils/rackSerializer.ts+++ b/frontend/src/utils/rackSerializer.ts@@ -18,6 +18,7 @@ import type {MountStatus,Port,PortType,+ PortVisibility,Rack,RackDevice,RackModel,@@ -55,6 +56,8 @@ export interface ApiRackDevice {faceplate_id: stringcolor: string | nullstatus: string+ /** 'auto' | 'always' | 'hover'. Rows written before the column read NULL. */+ port_visibility?: string | nullports: unknown[]}@@ -147,6 +150,11 @@ function asMountStatus(v: string | null): MountStatus {return v === 'auto' ? 'auto' : asStatus(v)}+/** Absent, NULL or unknown all mean `auto`: let the faceplate decide. */+function asPortVisibility(v: string | null | undefined): PortVisibility | undefined {+ return v === 'always' || v === 'hover' ? v : undefined+}+/** 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]@@ -235,6 +243,7 @@ export function toRackDevice(api: ApiRackDevice): RackDevice {faceplateId: api.faceplate_id,color: api.color ?? undefined,status: asMountStatus(api.status),+ portVisibility: asPortVisibility(api.port_visibility),ports: asPorts(api.ports ?? []),}}@@ -356,6 +365,7 @@ export function fromRackDevice(device: RackDevice): Omit<ApiRackDevice, 'design_faceplate_id: device.faceplateId,color: device.color ?? null,status: device.status,+ port_visibility: device.portVisibility ?? 'auto',ports: device.ports,}}