Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(rack): make Import links idempotent instead of one-shot
Pouzor06ccd354c54d
diff --git a/FEATURES.md b/FEATURES.mdindex 8a92aaf..7d84415 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -87,7 +87,7 @@ Here's what Homelable can do. One line on what each feature is, then how to swit- The **Faceplate** field opens a visual catalog — servers, switches, routers, patch panels, UPS and PDUs, desktop NAS towers, shelves and blanks — drawn as vector artwork that scales with the rack and follows your theme.- **Patch**: drag from one port to another (or click both in turn) to cable them, across racks if you need to. Click a cable to select it, then **Delete** or **Unplug**. A header select controls whether cables show on hover, always, or not at all.- **Status**: pin a mount's colour, or set **Check device** 🔒 so it follows the status check already configured on the matching diagram node.-- **Import links** 🔒 derives patches, once per canvas, from the physical links already drawn on your diagrams.+- **Import links** 🔒 derives patches from the physical links already drawn on your diagrams. Run it again after racking more gear — pairs already cabled are left alone.- Saving is explicit — **Save Rack** — like any other canvas.> **Full documentation:** [docs/rack-canvas.md](./docs/rack-canvas.md)diff --git a/docs/rack-canvas.md b/docs/rack-canvas.mdindex 4df92e6..cb6326a 100644--- a/docs/rack-canvas.md+++ b/docs/rack-canvas.md@@ -23,7 +23,7 @@ lands on.- **Ports & patching** — RJ45 and SFP ports per device, cabled port-to-port by dragging from one to the other, across racks if needed.- **Device Inventory** 🔒 — a mount points at a real inventory entry, so a rack shows the same devices your scans found, and gear you rack by hand joins that inventory.- **Live status** 🔒 — a mount can follow the status check already configured on the matching diagram node, and light its plate LED accordingly.-- **Import links** 🔒 — derive patches in one shot from the physical links already drawn on your diagrams.+- **Import links** 🔒 — derive patches from the physical links already drawn on your diagrams, as often as you like.---@@ -155,7 +155,9 @@ pan and zoom with the canvas and may run from one rack to another.**Import links** derives patches from the physical links (ethernet, fibre, vlan,cluster) already drawn on your diagrams, matching both ends to mounts that point-at those nodes. It runs **once per canvas** — afterwards, patch by hand.+at those nodes. Run it as often as you like: a pair of devices already cabled+is left alone, so a second run after racking more gear only adds what is+missing.---diff --git a/frontend/src/components/panels/RackToolbarActions.tsx b/frontend/src/components/panels/RackToolbarActions.tsxindex 7913468..137d0d8 100644--- a/frontend/src/components/panels/RackToolbarActions.tsx+++ b/frontend/src/components/panels/RackToolbarActions.tsx@@ -42,7 +42,6 @@ export function RackToolbarActions() {const selectedCableId = useRackStore((s) => s.selectedCableId)const removeSelectedCable = useRackStore((s) => s.removeSelectedCable)const importCables = useRackStore((s) => s.importCablesFromNetwork)- const networkImportDone = useRackStore((s) => s.networkImportDone)const designs = useDesignStore((s) => s.designs)const [importing, setImporting] = useState(false)@@ -123,7 +122,7 @@ export function RackToolbarActions() {size="sm"variant="ghost"className={ghost}- disabled={networkImportDone || importing}+ disabled={importing}onClick={() => void handleImport()}title="One-shot: derive patches from the links already drawn on the logical canvases">diff --git a/frontend/src/components/panels/__tests__/Sidebar.test.tsx b/frontend/src/components/panels/__tests__/Sidebar.test.tsxindex afbdf78..fb8d312 100644--- a/frontend/src/components/panels/__tests__/Sidebar.test.tsx+++ b/frontend/src/components/panels/__tests__/Sidebar.test.tsx@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'-import { render, screen, fireEvent, waitFor } from '@testing-library/react'+import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react'import { Sidebar } from '../Sidebar'import { useCanvasStore } from '@/stores/canvasStore'import { useAuthStore } from '@/stores/authStore'@@ -318,6 +318,90 @@ describe('Sidebar', () => {})})+// ── Rack canvas ────────────────────────────────────────────────────────────────+// Same component, a different half of it: the rack branch swaps the view label,+// the actions, the body and the footer. A mocked canvas store would happily hide+// all of that, so each branch is asserted rather than assumed.+describe('Sidebar (rack canvas)', () => {+ let restore: { designs: Design[]; activeDesignId: string | null; activeDesignType: string }++ beforeEach(async () => {+ mockStore()+ mockAuth()+ const { useDesignStore } = await import('@/stores/designStore')+ const { useRackStore } = await import('@/rack/store')+ const s = useDesignStore.getState()+ restore = { designs: s.designs, activeDesignId: s.activeDesignId, activeDesignType: s.activeDesignType }+ useDesignStore.setState({ activeDesignType: 'rack' })+ useRackStore.getState().loadDemo()+ })++ afterEach(async () => {+ cleanup()+ const { useDesignStore } = await import('@/stores/designStore')+ useDesignStore.setState(restore)+ })++ it('swaps the view and the actions for their rack equivalents', () => {+ render(<Sidebar {...defaultProps} />)+ expect(screen.getByText('Rack view')).toBeInTheDocument()+ expect(screen.getByText('Add Device')).toBeInTheDocument()+ expect(screen.getByText('Save Rack')).toBeInTheDocument()+ expect(screen.queryByText('Canvas')).not.toBeInTheDocument()+ expect(screen.queryByText('Add Node')).not.toBeInTheDocument()+ expect(screen.queryByText('Add Zone')).not.toBeInTheDocument()+ expect(screen.queryByText('Add Text')).not.toBeInTheDocument()+ })++ it('hides the logical-canvas discovery actions', () => {+ render(<Sidebar {...defaultProps} />)+ // Nothing here is scanned onto a rack — those actions belong to a diagram.+ expect(screen.queryByText('Scan Network')).not.toBeInTheDocument()+ expect(screen.queryByText('Zigbee Import')).not.toBeInTheDocument()+ expect(screen.queryByText('Z-Wave Import')).not.toBeInTheDocument()+ expect(screen.queryByText('Proxmox Import')).not.toBeInTheDocument()+ // The Device Inventory stays: a rack mounts what the scans found.+ expect(screen.getByText('Device Inventory')).toBeInTheDocument()+ })++ it('opens the device editor from + Device', async () => {+ const { useRackStore } = await import('@/rack/store')+ render(<Sidebar {...defaultProps} />)++ fireEvent.click(screen.getByText('Add Device'))+ expect(useRackStore.getState().deviceEditor).toEqual({ deviceId: null })+ })++ it('counts capacity instead of reachability', async () => {+ const { useRackStore } = await import('@/rack/store')+ const { freeUnits } = await import('@/rack/layout')+ const { racks, devices, cables } = useRackStore.getState()+ const free = racks.reduce((sum, r) => sum + freeUnits(r, devices), 0)+ const total = racks.reduce((sum, r) => sum + r.uHeight, 0)++ render(<Sidebar {...defaultProps} />)++ expect(screen.getByText('Racks').nextElementSibling).toHaveTextContent(String(racks.length))+ expect(screen.getByText('Mounted').nextElementSibling).toHaveTextContent(String(devices.length))+ expect(screen.getByText('Cables').nextElementSibling).toHaveTextContent(String(cables.length))+ expect(screen.getByText(`${free}U / ${total}U`)).toBeInTheDocument()+ expect(screen.queryByText('Online')).not.toBeInTheDocument()+ })++ it('tracks the rack store for the unsaved badge, not the canvas store', async () => {+ const { useRackStore } = await import('@/rack/store')+ useRackStore.setState({ hasUnsavedChanges: true })+ // The canvas store — mocked clean — must not be what answers here.+ const { container } = render(<Sidebar {...defaultProps} />)+ expect(container.querySelector('.bg-\\[\\#e3b341\\]')).toBeInTheDocument()++ cleanup()+ useRackStore.setState({ hasUnsavedChanges: false })+ const { container: clean } = render(<Sidebar {...defaultProps} />)+ expect(clean.querySelector('.bg-\\[\\#e3b341\\]')).toBeNull()+ })+})+// ── Standalone mode ────────────────────────────────────────────────────────────// VITE_STANDALONE is read at module load, so re-import Sidebar after stubbing it.// The hoisted vi.mock auto-mocks re-apply on re-import; configure the fresh mockdiff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.mdindex c3b2214..ce314eb 100644--- a/frontend/src/rack/README.md+++ b/frontend/src/rack/README.md@@ -55,7 +55,7 @@ types in `@/types/rack`, narrowing every enum on the way in.- Double-click empty rack chrome → `RackSettingsModal` (name, location, U height, 19"/10", numbering direction, frame/rail/interior colours, U numbers, enclosed, delete).- Growing a device — by hand or by picking a taller plate — relocates it to the nearest slot that takes the new size. Only a rack with no such slot rejects the edit, and says so.- **Patch mode**: drag from port A to port B to cable them — a dashed rubber band follows the pointer, exactly like dragging an edge on the logical canvas. Clicking A then B still works; Escape drops a half-drawn patch. Click a cable to select it (it gets an accent halo), then press Delete/Backspace — or the header's Unplug button — to remove it; Escape or a pane click deselects. Rack dragging is disabled while in patch mode.-- **Import links**: one shot per canvas, guarded by `networkImportDone`. Reads the physical edges (ethernet/fibre/vlan/cluster) of every non-rack design and matches them on `nodeId`.+- **Import links**: reads the physical edges (ethernet/fibre/vlan/cluster) of every non-rack design and matches them on `nodeId`. Idempotent — a device pair already cabled is skipped, whichever ports carry it, so a re-run after racking more gear adds only what is missing. There is no "done" flag: one lived in memory only, and a reload re-armed the import onto the next free ports.- **New device**: the modal's *New device* source adds a Device Inventory entry (tagged `rack`), for gear no scan will ever discover. The left-rail tray only carries accessories, as a drag source.## Panel behaviour in rack modediff --git a/frontend/src/rack/__tests__/store.test.ts b/frontend/src/rack/__tests__/store.test.tsindex 55ffb0e..86652c1 100644--- a/frontend/src/rack/__tests__/store.test.ts+++ b/frontend/src/rack/__tests__/store.test.ts@@ -415,25 +415,67 @@ describe('cables', () => {expect(store().cableVisibility).toBe('always')})- it('imports links from the network canvas once', () => {+ it('imports links from the network canvas', () => {// Mount the inventory item the hints reference; the other end is racked already.store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 4 })const first = store().importCablesFromNetwork(demoNetworkLinks())expect(first).toBeGreaterThan(0)+ })++ it('re-running the import adds nothing to a pair already patched', () => {+ // The guard used to be an in-memory flag, so a reload re-armed the import and+ // every link came back on the next free pair of ports. The pair itself is the+ // guard now, and it survives a reload because the cables do.+ store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 4 })+ const created = store().importCablesFromNetwork(demoNetworkLinks())+ const after = store().cables.length+expect(store().importCablesFromNetwork(demoNetworkLinks())).toBe(0)+ expect(store().cables).toHaveLength(after)+ expect(created).toBeGreaterThan(0)})- it('stays available after an import that matched nothing', () => {- // Nothing racked for these hints yet: the run creates nothing, and the user- // is told to rack the devices first — so the button has to survive it.+ it('imports what is newly rackable after a run that matched nothing', () => {+ // Import before racking anything: nothing matches, and the toast tells the+ // user to rack the devices first. That retry has to still work.expect(store().importCablesFromNetwork([{ from: 'node-nowhere-a', to: 'node-nowhere-b', type: 'ethernet' },])).toBe(0)- expect(store().networkImportDone).toBe(false)store().mountFromInventory('inv-sw8', 'rack-main', { uStart: 4 })expect(store().importCablesFromNetwork(demoNetworkLinks())).toBeGreaterThan(0)- expect(store().networkImportDone).toBe(true)+ })++ it('lands a fibre link on fibre ports when both plates have a free one', () => {+ const used = new Set(+ store().cables.flatMap((c) => [+ `${c.from.deviceId}:${c.from.portId}`,+ `${c.to.deviceId}:${c.to.portId}`,+ ]),+ )+ // Devices that carry both kinds of free port, so the first free one is copper+ // and picking the fibre one is a real choice rather than the only option.+ const mixed = store().devices.filter((d) => {+ const free = d.ports.filter((p) => !used.has(`${d.id}:${p.id}`))+ return d.nodeId && free.some((p) => p.type === 'rj45') && free.some((p) => p.type !== 'rj45')+ })+ const patched = new Set(+ store().cables.map((c) => [c.from.deviceId, c.to.deviceId].sort().join('|')),+ )+ const pair = mixed.flatMap((x, i) =>+ mixed.slice(i + 1).map((y) => [x, y] as const),+ ).find(([x, y]) => !patched.has([x.id, y.id].sort().join('|')))+ expect(pair).toBeDefined()+ const [a, b] = pair!+ const before = new Set(store().cables.map((c) => c.id))++ store().importCablesFromNetwork([{ from: a.nodeId!, to: b.nodeId!, type: 'fiber' }])++ const cable = store().cables.find((c) => !before.has(c.id))!+ const portOf = (deviceId: string, portId: string) =>+ store().devices.find((d) => d.id === deviceId)!.ports.find((p) => p.id === portId)!+ expect(portOf(cable.from.deviceId, cable.from.portId).type).not.toBe('rj45')+ expect(portOf(cable.to.deviceId, cable.to.portId).type).not.toBe('rj45')})it('skips hints whose devices are not racked', () => {diff --git a/frontend/src/rack/store.ts b/frontend/src/rack/store.tsindex 6ad60ac..9d1bbd6 100644--- a/frontend/src/rack/store.ts+++ b/frontend/src/rack/store.ts@@ -175,9 +175,12 @@ interface RackState {) => string | nullupdateCable: (id: string, patch: Partial<Omit<Cable, 'id'>>) => voidremoveCable: (id: string) => void- /** One-shot seed from the logical canvas — offered at creation time only. */+ /**+ * Seed patches from the logical canvas. Idempotent: a device pair already+ * cabled is skipped, so re-running after racking more gear adds only what is+ * missing instead of doubling what is there.+ */importCablesFromNetwork: (hints: NetworkLinkHint[]) => number- networkImportDone: boolean// UI actionssetViewport: (v: Viewport) => void@@ -233,7 +236,6 @@ function emptyState() {cableMode: false,cableDraft: null,cableDrag: null,- networkImportDone: false,deviceEditor: null,rackEditorId: null,}@@ -647,22 +649,33 @@ export const useRackStore = create<RackState>((set, get) => {})),importCablesFromNetwork: (hints) => {- const { devices, networkImportDone } = get()- if (networkImportDone) return 0+ const { devices } = get()+ // Idempotent by construction rather than by a "done" flag: a flag lives in+ // memory only, so a reload re-armed the import and every logical link got+ // a second cable on the next free pair of ports. A pair already patched is+ // skipped instead, whichever ports carry it, which also makes a re-run+ // after racking more gear do the useful half of the work.+ const pairKey = (x: string, y: string) => [x, y].sort().join('|')+ const patched = new Set(get().cables.map((c) => pairKey(c.from.deviceId, c.to.deviceId)))let created = 0for (const hint of hints) {const a = devices.find((d) => d.nodeId === hint.from)const b = devices.find((d) => d.nodeId === hint.to)- if (!a || !b) continue+ if (!a || !b || patched.has(pairKey(a.id, b.id))) continueconst usedPorts = new Set(get().cables.flatMap((c) => [`${c.from.deviceId}:${c.from.portId}`,`${c.to.deviceId}:${c.to.portId}`,]),)- const freePort = (device: typeof a) =>- device.ports.find((p) => !usedPorts.has(`${device.id}:${p.id}`))+ // Prefer a port the cable could actually be plugged into: a fibre link+ // landing on two RJ45 jacks draws an amber run across copper ports. Any+ // free port still beats no patch at all when the plate has none.+ const freePort = (device: typeof a) => {+ const free = device.ports.filter((p) => !usedPorts.has(`${device.id}:${p.id}`))+ return free.find((p) => PORT_CABLE_TYPE[p.type] === hint.type) ?? free[0]+ }const pa = freePort(a)const pb = freePort(b)if (!pa || !pb) continue@@ -671,12 +684,11 @@ export const useRackStore = create<RackState>((set, get) => {{ deviceId: b.id, portId: pb.id },{ type: hint.type, label: hint.label },)- if (id) created+++ if (id) {+ created+++ patched.add(pairKey(a.id, b.id))+ }}- // Only latch on success. An import run before anything is racked matches- // nothing and says so — disabling the button then would kill the retry the- // toast just asked for.- if (created > 0) set({ networkImportDone: true })return created},