Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(rack): stop a clamped size from shrinking the device everywhere
Pouzorcaaa40861811
diff --git a/backend/app/api/routes/racks.py b/backend/app/api/routes/racks.pyindex 1dd3df9..387fcf9 100644--- a/backend/app/api/routes/racks.py+++ b/backend/app/api/routes/racks.py@@ -1,3 +1,4 @@+from collections.abc import Sequencefrom datetime import datetime, timezonefrom typing import Any, TypeVar@@ -143,15 +144,52 @@ def _rack_model(device: InventoryDevice) -> dict[str, Any] | None:}+# A mount's footprint in the rack grid: (u_start, u_height, col_start, col_span).+_Box = tuple[int, int, int, int]+++def _height_fits(u_start: int, u_height: int | None, rack_u_height: int | None) -> bool:+ """Whether a mount of that height, starting there, stays under the top rail."""+ if not u_height:+ return False+ return rack_u_height is None or u_start + u_height - 1 <= rack_u_height+++def _span_fits(col_start: int, col_span: int | None) -> bool:+ """Whether a mount of that width, starting there, stays inside the grid."""+ if not col_span:+ return False+ return col_start + col_span <= RACK_COLUMNS+++def _overlaps(box: _Box, others: Sequence[_Box]) -> bool:+ """Whether a footprint (u_start, u_height, col_start, col_span) hits any other."""+ u_start, u_height, col_start, col_span = box+ return any(+ u_start < o_u + o_uh+ and o_u < u_start + u_height+ and col_start < o_c + o_cs+ and o_c < col_start + col_span+ for o_u, o_uh, o_c, o_cs in others+ )++def _with_model(- device: RackDevice, model: dict[str, Any] | None, rack_u_height: int | None+ device: RackDevice,+ model: dict[str, Any] | None,+ rack_u_height: int | None,+ neighbours: Sequence[_Box] = (),) -> RackDeviceResponse:"""Overlay the inventory's rack modelisation onto a mount for the response.Geometry is global, but a rack is not: a device grown to 4U in one rack may nolonger fit where it sits in another. Height and width are therefore applied- only when they still fit at the mount's own `u_start` / `col_start`; the plate,- its colour and its ports always are, since none of them can overflow a rail.+ only when they still fit at the mount's own `u_start` / `col_start` *and* the+ bigger footprint lands on no neighbour — the placement rule the canvas itself+ enforces, and one a plain rail check misses: a 4U model overlaid on a mount+ with a device one U above it would draw two plates on the same U, and save+ back in that state. The plate, its colour and its ports always are, since+ none of them can overflow anything."""row = RackDeviceResponse.model_validate(device)if model is None:@@ -161,12 +199,16 @@ def _with_model("ports": model["ports"],"color": model["color"],}- u_height = model["u_height"]- if u_height and (rack_u_height is None or row.u_start + u_height - 1 <= rack_u_height):+ u_height = row.u_height+ if _height_fits(row.u_start, model["u_height"], rack_u_height) and not _overlaps(+ (row.u_start, model["u_height"], row.col_start, row.col_span), neighbours+ ):+ u_height = model["u_height"]patch["u_height"] = u_height- col_span = model["col_span"]- if col_span and row.col_start + col_span <= RACK_COLUMNS:- patch["col_span"] = col_span+ if _span_fits(row.col_start, model["col_span"]) and not _overlaps(+ (row.u_start, u_height, row.col_start, model["col_span"]), neighbours+ ):+ patch["col_span"] = model["col_span"]return row.model_copy(update=patch)@@ -226,12 +268,27 @@ async def load_racks(models[row.id] = modelheights = {r.id: r.u_height for r in racks}+ # An overlaid size must not land on the mount above. Footprints start as+ # persisted and are replaced by what the overlay actually applied, so a rack+ # of devices that all grew elsewhere resolves in one deterministic pass+ # instead of each one being measured against stale neighbours.+ boxes: dict[str, _Box] = {+ d.id: (d.u_start, d.u_height, d.col_start, d.col_span) for d in devices+ }+ mounted: list[RackDeviceResponse] = []+ for d in devices:+ placed = _with_model(+ d,+ models.get(d.device_id or ""),+ heights.get(d.rack_id),+ [boxes[o.id] for o in devices if o.id != d.id and o.rack_id == d.rack_id],+ )+ boxes[d.id] = (placed.u_start, placed.u_height, placed.col_start, placed.col_span)+ mounted.append(placed)+return RackStateResponse(racks=[RackResponse.model_validate(r) for r in racks],- devices=[- _with_model(d, models.get(d.device_id or ""), heights.get(d.rack_id))- for d in devices- ],+ devices=mounted,cables=[RackCableResponse.model_validate(c) for c in cables],viewport=state.viewport if state else {"x": 0, "y": 0, "zoom": 1},)@@ -292,6 +349,9 @@ async def save_racks(payload = device_data.model_dump()payload["design_id"] = body.design_iddb_device = await _owned(db, RackDevice, device_data.id, body.design_id)+ # The size this mount held before the save, to tell a real resize from an+ # echo of what the load handed out. See the write-through below.+ was = (db_device.u_height, db_device.col_span) if db_device else Noneif db_device:for field, value in payload.items():setattr(db_device, field, value)@@ -305,10 +365,17 @@ async def save_racks(entry = await db.get(InventoryDevice, device_data.device_id)if entry is not None:entry.rack_faceplate_id = device_data.faceplate_id- entry.rack_u_height = device_data.u_height- entry.rack_col_span = device_data.col_spanentry.rack_color = device_data.colorentry.rack_ports = [p for p in device_data.ports if isinstance(p, dict)]+ # Size, unlike the plate, is not written back blind. The load+ # overlays it only where it still fits this rack, so a mount can+ # legitimately hold less than the row does — and saving that back+ # would shrink the device in every other rack. Only a size this+ # save actually changes travels; an unchanged one is an echo.+ if was is None or device_data.u_height != was[0]:+ entry.rack_u_height = device_data.u_height+ if was is None or device_data.col_span != was[1]:+ entry.rack_col_span = device_data.col_spanawait db.flush() # devices must exist before cables point at themfor cable_data in body.cables:diff --git a/backend/app/schemas/racks.py b/backend/app/schemas/racks.pyindex 6db81cd..e4177fc 100644--- a/backend/app/schemas/racks.py+++ b/backend/app/schemas/racks.py@@ -161,6 +161,33 @@ class RackSaveRequest(BaseModel):)return self+ @model_validator(mode="after")+ def _devices_do_not_overlap(self) -> "RackSaveRequest":+ """Two mounts may not claim the same square of a rack.++ The canvas already refuses such a drop (`canPlace`), so this is the same+ rule stated where the state is persisted rather than where it is dragged+ — a stale tab, a hand-built payload or a bug upstream would otherwise+ store two plates drawn on top of each other, with no way to grab the one+ underneath.+ """+ by_rack: dict[str, list[RackDeviceSave]] = {}+ for device in self.devices:+ by_rack.setdefault(device.rack_id, []).append(device)+ for mounts in by_rack.values():+ for i, a in enumerate(mounts):+ for b in mounts[i + 1 :]:+ if (+ a.u_start < b.u_start + b.u_height+ and b.u_start < a.u_start + a.u_height+ and a.col_start < b.col_start + b.col_span+ and b.col_start < a.col_start + a.col_span+ ):+ raise ValueError(+ f"Devices {a.id} and {b.id} overlap in rack {a.rack_id}"+ )+ return self+class RackResponse(BaseModel):id: strdiff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.pyindex b4af8b4..6722d22 100644--- a/backend/tests/test_racks.py+++ b/backend/tests/test_racks.py@@ -214,6 +214,88 @@ class TestDeviceRackModel:assert item["rack_faceplate_id"] is Noneassert item["rack_ports"] == []+ async def test_a_clamped_size_is_not_written_back_over_the_model(+ self, client: AsyncClient, headers, db_session+ ):+ # The mount is served 1U because 4U no longer fits above U 10. Saving the+ # canvas then echoes that 1U back — and must not shrink the device in the+ # rack where it really is 4U.+ design_id = await self._mounted(client, headers, db_session)+ entry = await db_session.get(InventoryDevice, "inv-sw")+ entry.rack_u_height = 4+ entry.rack_col_span = 12+ await db_session.commit()++ served = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["devices"][0]+ assert served["u_height"] == 1+ state = _state(design_id, cables=[])+ state["devices"] = [{**state["devices"][0], "device_id": "inv-sw", "u_height": 1}]+ res = await client.post("/api/v1/racks/save", json=state, headers=headers)+ assert res.status_code == 200, res.text++ await db_session.refresh(entry)+ assert entry.rack_u_height == 4++ async def test_a_real_resize_still_reaches_the_model(+ self, client: AsyncClient, headers, db_session+ ):+ design_id = await self._mounted(client, headers, db_session)+ entry = await db_session.get(InventoryDevice, "inv-sw")+ entry.rack_u_height = 1+ await db_session.commit()++ state = _state(design_id, cables=[])+ state["devices"] = [+ {**state["devices"][0], "device_id": "inv-sw", "u_start": 8, "u_height": 3}+ ]+ res = await client.post("/api/v1/racks/save", json=state, headers=headers)+ assert res.status_code == 200, res.text++ await db_session.refresh(entry)+ assert entry.rack_u_height == 3++ async def test_load_does_not_inflate_a_mount_onto_its_neighbour(+ self, client: AsyncClient, headers, db_session+ ):+ # A 4U model fits the rails at U 1 of a 12U rack, but another device sits+ # at U 2. Two plates drawn on the same U is not a state the canvas can+ # produce, so the load must not invent it.+ design_id = await _design(client, headers)+ db_session.add(InventoryDevice(id="inv-sw", ip="192.168.1.10", suggested_type="switch"))+ await db_session.commit()+ state = _state(design_id, cables=[])+ state["devices"] = [+ {**state["devices"][0], "device_id": "inv-sw", "u_start": 1, "u_height": 1},+ {**state["devices"][1], "u_start": 2, "u_height": 1},+ ]+ assert (+ await client.post("/api/v1/racks/save", json=state, headers=headers)+ ).status_code == 200+ entry = await db_session.get(InventoryDevice, "inv-sw")+ entry.rack_u_height = 4+ await db_session.commit()++ devices = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["devices"]+ assert next(d for d in devices if d["id"] == "dev-sw")["u_height"] == 1++ async def test_load_inflates_a_mount_that_has_the_room(+ self, client: AsyncClient, headers, db_session+ ):+ design_id = await self._mounted(client, headers, db_session, u_start=1, u_height=1)+ entry = await db_session.get(InventoryDevice, "inv-sw")+ entry.rack_u_height = 4+ await db_session.commit()++ device = (+ await client.get(f"/api/v1/racks?design_id={design_id}", headers=headers)+ ).json()["devices"][0]+ assert device["u_height"] == 4++class TestSaveAndLoad:async def test_round_trips_the_full_state(self, client: AsyncClient, headers):@@ -924,3 +1006,35 @@ class TestDesignLifecycle:copied_ids = {d["id"] for d in loaded["devices"]}assert loaded["cables"][0]["from_device_id"] in copied_idsassert loaded["cables"][0]["to_device_id"] in copied_ids+++class TestOverlappingMounts:+ async def test_rejects_two_mounts_claiming_the_same_u(self, client: AsyncClient, headers):+ design_id = await _design(client, headers)+ state = _state(design_id, cables=[])+ state["devices"][1]["u_start"] = 10 # straight onto dev-sw++ res = await client.post("/api/v1/racks/save", json=state, headers=headers)+ assert res.status_code == 422+ assert "overlap" in res.text++ async def test_accepts_two_mounts_sharing_a_u_side_by_side(+ self, client: AsyncClient, headers+ ):+ # Half-width plates on the same U are the whole point of the column grid.+ design_id = await _design(client, headers)+ state = _state(design_id, cables=[])+ state["devices"][0].update(col_start=0, col_span=6)+ state["devices"][1].update(u_start=10, u_height=1, col_start=6, col_span=6)++ res = await client.post("/api/v1/racks/save", json=state, headers=headers)+ assert res.status_code == 200, res.text++ async def test_lets_two_racks_use_the_same_u(self, client: AsyncClient, headers):+ design_id = await _design(client, headers)+ state = _state(design_id, cables=[])+ state["racks"].append({**state["racks"][0], "id": "rack-2", "name": "Second"})+ state["devices"][1].update(rack_id="rack-2", u_start=10, u_height=1)++ res = await client.post("/api/v1/racks/save", json=state, headers=headers)+ assert res.status_code == 200, res.textdiff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.mdindex dc16d72..e2d1417 100644--- a/frontend/src/rack/README.md+++ b/frontend/src/rack/README.md@@ -23,7 +23,7 @@ Create one from **New Canvas → Kind → Rack**.| 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, 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 — geometry is global, a rack is not. 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 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. || 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. |diff --git a/frontend/src/rack/__tests__/store.test.ts b/frontend/src/rack/__tests__/store.test.tsindex 43e87ea..e15d269 100644--- a/frontend/src/rack/__tests__/store.test.ts+++ b/frontend/src/rack/__tests__/store.test.ts@@ -242,6 +242,60 @@ describe('mounting', () => {expect(entry.rackModel!.ports).toEqual(ports)})+ it('keeps the model size when an edit did not touch it', () => {+ // The mount may be drawn smaller than the row says: the backend applies a+ // size only where it still fits this rack. Editing anything else must not+ // mirror that clamped size back and shrink the device everywhere.+ const device = store().devices.find((d) => d.id === 'dev-pve1')!+ useRackStore.setState({+ inventory: store().inventory.map((item) =>+ item.id === device.deviceId+ ? {+ ...item,+ rackModel: {+ faceplateId: device.faceplateId,+ uHeight: 4,+ colSpan: RACK_COLUMNS,+ color: null,+ ports: device.ports,+ },+ }+ : item,+ ),+ })++ store().updateDevice('dev-pve1', { color: '#ff6e00' })++ const entry = store().inventory.find((i) => i.id === device.deviceId)!+ expect(entry.rackModel).toMatchObject({ uHeight: 4, color: '#ff6e00' })+ })++ it('keeps the model size when only the ports change', () => {+ const device = store().devices.find((d) => d.id === 'dev-pve1')!+ useRackStore.setState({+ inventory: store().inventory.map((item) =>+ item.id === device.deviceId+ ? {+ ...item,+ rackModel: {+ faceplateId: device.faceplateId,+ uHeight: 4,+ colSpan: RACK_COLUMNS,+ color: null,+ ports: device.ports,+ },+ }+ : item,+ ),+ })++ store().setPorts('dev-pve1', [{ id: 'p-x', label: 'wan', type: 'rj45' as const, x: 0.1, y: 0.6 }])++ const entry = store().inventory.find((i) => i.id === device.deviceId)!+ expect(entry.rackModel!.uHeight).toBe(4)+ expect(entry.rackModel!.ports.map((p) => p.id)).toEqual(['p-x'])+ })+it('leaves the inventory alone for an accessory, which stands for no device', () => {const id = store().mountAccessory('shelf-1u', 'rack-main', { uStart: 6 })!const before = store().inventorydiff --git a/frontend/src/rack/store.ts b/frontend/src/rack/store.tsindex edd8237..16f3052 100644--- a/frontend/src/rack/store.ts+++ b/frontend/src/rack/store.ts@@ -298,27 +298,35 @@ function withRackedFlags(inventory: InventoryDevice[], devices: RackDevice[]): I* mount from stale data. The backend does the same write-through on save; this* keeps the open session consistent in the meantime.*+ * Size is the exception: the backend applies the row's height and width to a+ * mount only where they still fit that rack, so a mount can legitimately show+ * less than the row holds. Mirroring an unchanged size back would shrink the+ * device everywhere else, so only a size this edit actually changed travels —+ * `before` is the mount as it stood, and equal means untouched.+ ** Standalone has no inventory row to own anything, so ports stay per mount there.*/function withDeviceModel(inventory: InventoryDevice[],device: RackDevice | undefined,+ before?: RackDevice,): InventoryDevice[] {if (STANDALONE || !device?.deviceId) return inventory- return inventory.map((item) =>- item.id === device.deviceId- ? {- ...item,- rackModel: {- faceplateId: device.faceplateId,- uHeight: device.uHeight,- colSpan: device.colSpan,- color: device.color ?? null,- ports: device.ports,- },- }- : item,- )+ return inventory.map((item) => {+ if (item.id !== device.deviceId) return item+ const resized = !before || before.uHeight !== device.uHeight+ const rewidened = !before || before.colSpan !== device.colSpan+ return {+ ...item,+ rackModel: {+ faceplateId: device.faceplateId,+ uHeight: resized ? device.uHeight : item.rackModel?.uHeight ?? device.uHeight,+ colSpan: rewidened ? device.colSpan : item.rackModel?.colSpan ?? device.colSpan,+ color: device.color ?? null,+ ports: device.ports,+ },+ }+ })}export const useRackStore = create<RackState>((set, get) => {@@ -642,7 +650,7 @@ export const useRackStore = create<RackState>((set, get) => {}edit((s) => {const devicesNext = s.devices.map((d) => (d.id === id ? next : d))- return { devices: devicesNext, inventory: withDeviceModel(s.inventory, next) }+ return { devices: devicesNext, inventory: withDeviceModel(s.inventory, next, device) }})return true},@@ -789,7 +797,11 @@ export const useRackStore = create<RackState>((set, get) => {const devicesNext = s.devices.map((d) => (d.id === deviceId ? { ...d, ports: next } : d))return {devices: devicesNext,- inventory: withDeviceModel(s.inventory, devicesNext.find((d) => d.id === deviceId)),+ inventory: withDeviceModel(+ s.inventory,+ devicesNext.find((d) => d.id === deviceId),+ s.devices.find((d) => d.id === deviceId),+ ),cables: s.cables.filter((c) =>!(c.from.deviceId === deviceId && !kept.has(c.from.portId)) &&