Преглед изворни кода

feat(rack): physical rack canvas with auto-cabling (labs) (#1123)

Phase 1 + phase 2 core of the physical rack view, kept under the labs badge.

- Rack canvas with realistic 19-inch proportions: drag devices from the picker (fleet routers, switches, servers, CCTV) or click to place; a placement dialog asks the U height and the patch panel port count. Drops snap to the nearest free slot, never overlapping.
- Faceplates show the device name, the detected port count and the ports themselves (lucide ethernet-port icons, uniform size), seeded from real polled ports for fleet routers.
- Auto-cabling from detection: Import links reads the FDB and draws cables where MACs are actually learned (single-MAC ports only), including router-to-router uplinks between mounted fleet members. Idempotent by construction, with a per-cable audit status.
- Racks, mounts and cables persist in SQLite with server-side overlap validation; an atomic per-rack layout save. i18n ES/EN.

Related: #1108
Nacho пре 2 месеци
родитељ
комит
7df5226ac4

+ 177 - 0
app/package-lock.json

@@ -35,6 +35,7 @@
         "@radix-ui/react-toggle": "^1.1.10",
         "@radix-ui/react-toggle-group": "^1.1.11",
         "@radix-ui/react-tooltip": "^1.2.8",
+        "@xyflow/react": "^12.12.0",
         "class-variance-authority": "^0.7.1",
         "clsx": "^2.1.1",
         "cmdk": "^1.1.1",
@@ -4500,6 +4501,15 @@
       "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
       "license": "MIT"
     },
+    "node_modules/@types/d3-drag": {
+      "version": "3.0.7",
+      "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
+      "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@types/d3-selection": "*"
+      }
+    },
     "node_modules/@types/d3-ease": {
       "version": "3.0.2",
       "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
@@ -4530,6 +4540,12 @@
         "@types/d3-time": "*"
       }
     },
+    "node_modules/@types/d3-selection": {
+      "version": "3.0.12",
+      "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.12.tgz",
+      "integrity": "sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw==",
+      "license": "MIT"
+    },
     "node_modules/@types/d3-shape": {
       "version": "3.1.8",
       "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",
@@ -4551,6 +4567,25 @@
       "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
       "license": "MIT"
     },
+    "node_modules/@types/d3-transition": {
+      "version": "3.0.9",
+      "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
+      "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
+      "license": "MIT",
+      "dependencies": {
+        "@types/d3-selection": "*"
+      }
+    },
+    "node_modules/@types/d3-zoom": {
+      "version": "3.0.9",
+      "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.9.tgz",
+      "integrity": "sha512-0sE1406XBYJGiqD3AusTl9ZqC//2mIXix51tbom25gDCA8ri4xnSZg28CaSE8Srl6FClqABUKfsn0qghgdepMA==",
+      "license": "MIT",
+      "dependencies": {
+        "@types/d3-interpolate": "*",
+        "@types/d3-selection": "*"
+      }
+    },
     "node_modules/@types/esrecurse": {
       "version": "4.3.1",
       "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
@@ -5283,6 +5318,48 @@
         }
       }
     },
+    "node_modules/@xyflow/react": {
+      "version": "12.12.0",
+      "resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.12.0.tgz",
+      "integrity": "sha512-74oXI0Rgm1Eu33cHQAd74J6oVgCH9mbFyTVQbsGgp2kmWwh0HdtBr2VP04z8mbPD+M/xO69nqG5dDEt7/EN2rQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@xyflow/system": "0.0.83",
+        "classcat": "^5.0.3",
+        "zustand": "^4.4.0"
+      },
+      "peerDependencies": {
+        "@types/react": ">=17",
+        "@types/react-dom": ">=17",
+        "react": ">=17",
+        "react-dom": ">=17"
+      },
+      "peerDependenciesMeta": {
+        "@types/react": {
+          "optional": true
+        },
+        "@types/react-dom": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@xyflow/system": {
+      "version": "0.0.83",
+      "resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.83.tgz",
+      "integrity": "sha512-a//eDjez3WZF47aaPTfVUDD0OINOq+WVwBZCRTqG+m0a5euX8EwlJ4jMY1Wxz0Ocj4xOeekJ70V22Pq0ll8RJw==",
+      "license": "MIT",
+      "dependencies": {
+        "@types/d3-drag": "^3.0.7",
+        "@types/d3-interpolate": "^3.0.4",
+        "@types/d3-selection": "^3.0.10",
+        "@types/d3-transition": "^3.0.8",
+        "@types/d3-zoom": "^3.0.8",
+        "d3-drag": "^3.0.0",
+        "d3-interpolate": "^3.0.1",
+        "d3-selection": "^3.0.0",
+        "d3-zoom": "^3.0.0"
+      }
+    },
     "node_modules/acorn": {
       "version": "8.18.0",
       "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
@@ -5656,6 +5733,12 @@
         "url": "https://polar.sh/cva"
       }
     },
+    "node_modules/classcat": {
+      "version": "5.0.5",
+      "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",
+      "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",
+      "license": "MIT"
+    },
     "node_modules/clsx": {
       "version": "2.1.1",
       "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@@ -5766,6 +5849,28 @@
         "node": ">=12"
       }
     },
+    "node_modules/d3-dispatch": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
+      "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
+      "license": "ISC",
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/d3-drag": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
+      "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
+      "license": "ISC",
+      "dependencies": {
+        "d3-dispatch": "1 - 3",
+        "d3-selection": "3"
+      },
+      "engines": {
+        "node": ">=12"
+      }
+    },
     "node_modules/d3-ease": {
       "version": "3.0.1",
       "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
@@ -5821,6 +5926,15 @@
         "node": ">=12"
       }
     },
+    "node_modules/d3-selection": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
+      "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
+      "license": "ISC",
+      "engines": {
+        "node": ">=12"
+      }
+    },
     "node_modules/d3-shape": {
       "version": "3.2.0",
       "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
@@ -5866,6 +5980,41 @@
         "node": ">=12"
       }
     },
+    "node_modules/d3-transition": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
+      "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
+      "license": "ISC",
+      "dependencies": {
+        "d3-color": "1 - 3",
+        "d3-dispatch": "1 - 3",
+        "d3-ease": "1 - 3",
+        "d3-interpolate": "1 - 3",
+        "d3-timer": "1 - 3"
+      },
+      "engines": {
+        "node": ">=12"
+      },
+      "peerDependencies": {
+        "d3-selection": "2 - 3"
+      }
+    },
+    "node_modules/d3-zoom": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
+      "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
+      "license": "ISC",
+      "dependencies": {
+        "d3-dispatch": "1 - 3",
+        "d3-drag": "2 - 3",
+        "d3-interpolate": "1 - 3",
+        "d3-selection": "2 - 3",
+        "d3-transition": "2 - 3"
+      },
+      "engines": {
+        "node": ">=12"
+      }
+    },
     "node_modules/data-view-buffer": {
       "version": "1.0.2",
       "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
@@ -10555,6 +10704,34 @@
       "peerDependencies": {
         "zod": "^3.25.0 || ^4.0.0"
       }
+    },
+    "node_modules/zustand": {
+      "version": "4.5.7",
+      "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
+      "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
+      "license": "MIT",
+      "dependencies": {
+        "use-sync-external-store": "^1.2.2"
+      },
+      "engines": {
+        "node": ">=12.7.0"
+      },
+      "peerDependencies": {
+        "@types/react": ">=16.8",
+        "immer": ">=9.0.6",
+        "react": ">=16.8"
+      },
+      "peerDependenciesMeta": {
+        "@types/react": {
+          "optional": true
+        },
+        "immer": {
+          "optional": true
+        },
+        "react": {
+          "optional": true
+        }
+      }
     }
   }
 }

+ 1 - 0
app/package.json

@@ -37,6 +37,7 @@
     "@radix-ui/react-toggle": "^1.1.10",
     "@radix-ui/react-toggle-group": "^1.1.11",
     "@radix-ui/react-tooltip": "^1.2.8",
+    "@xyflow/react": "^12.12.0",
     "class-variance-authority": "^0.7.1",
     "clsx": "^2.1.1",
     "cmdk": "^1.1.1",

+ 71 - 1
app/public/locales/en/translation.json

@@ -619,7 +619,8 @@
     "orchestration": "Orchestration",
     "channelPlan": "Channels",
     "firmwareUpgrades": "Firmware upgrades",
-    "help": "Help"
+    "help": "Help",
+    "rack": "Rack"
   },
   "roaming": {
     "subtitle": "Roaming and WiFi mesh status",
@@ -2479,5 +2480,74 @@
   },
   "app": {
     "title": "NetPulse - Your network at a glance"
+  },
+  "rack": {
+    "title": "Rack",
+    "subtitle": "Your physical hardware, placed and patched.",
+    "addRack": "Add rack",
+    "deleteRack": "Delete rack",
+    "deleteRackConfirm": "Delete this rack and everything mounted on it?",
+    "rackDeleted": "Rack deleted",
+    "save": "Save",
+    "saving": "Saving…",
+    "saved": "Rack saved",
+    "saveFailed": "Could not save",
+    "unsaved": "unsaved changes",
+    "patch": "Patch",
+    "visibility": "Cables",
+    "visibilityHover": "On hover",
+    "visibilityAlways": "Always",
+    "visibilityHidden": "Hidden",
+    "noSpace": "No free slot fits it",
+    "patchBusy": "That port already has all its cables",
+    "cableDeleted": "Cable unplugged",
+    "drafting": "From {{port}}: pick the target port (Esc cancels)",
+    "empty": "No racks yet",
+    "emptyHint": "Create a rack first",
+    "pickHint": "Drag onto a rack (or click) to mount into the active rack (the cyan one). Then drag to adjust the slot.",
+    "pickFleet": "Routers",
+    "pickDevice": "Devices",
+    "pickAccessory": "Accessories",
+    "plates": {
+      "server-1u": "1U server",
+      "server-2u": "2U server",
+      "switch": "Switch",
+      "router": "Router",
+      "nas-tower": "NAS tower",
+      "patch-panel-1u": "24-port patch panel",
+      "pdu-1u": "PDU",
+      "ups-4u": "4U UPS",
+      "shelf-1u": "Shelf",
+      "blank-1u": "1U blank",
+      "blank-half-1u": "Half-U blank",
+      "patch-panel-12p": "12-port patch panel",
+      "patch-panel-48p": "48-port patch panel"
+    },
+    "createTitle": "New rack",
+    "createName": "Name",
+    "createU": "Height (U)",
+    "createSubmit": "Create",
+    "createCancel": "Cancel",
+    "deleteTitle": "Delete rack?",
+    "deleteDesc": "This will delete «{{name}}» along with everything mounted on it. This cannot be undone.",
+    "deleteConfirm": "Delete",
+    "deleteCancel": "Cancel",
+    "unmounted": "Device unmounted from the rack",
+    "editRack": "Edit rack",
+    "editTitle": "Edit rack",
+    "editSubmit": "Save changes",
+    "rackUpdated": "Rack updated",
+    "createLocation": "Location",
+    "locationPlaceholder": "e.g. Office, Living room, Garage…",
+    "import": "Import links",
+    "importResult": "Import: {{created}} created · {{skipped}} skipped · {{noFree}} no free port",
+    "askTitle": "Place “{{name}}”",
+    "askTitlePatch": "Place patch panel",
+    "askHeight": "Height (U)",
+    "askPorts": "Ports",
+    "askPlace": "Place",
+    "dropNoRack": "Drop it inside a rack",
+    "portCount": "detected ports",
+    "importNeedsSave": "Save the rack changes before importing links"
   }
 }

+ 71 - 1
app/public/locales/es/translation.json

@@ -619,7 +619,8 @@
     "orchestration": "Orquestación",
     "channelPlan": "Canales",
     "firmwareUpgrades": "Actualizaciones",
-    "help": "Ayuda"
+    "help": "Ayuda",
+    "rack": "Rack"
   },
   "roaming": {
     "subtitle": "Estado de la itinerancia WiFi y la malla WiFi",
@@ -2479,5 +2480,74 @@
   },
   "app": {
     "title": "NetPulse - Tu red, de un vistazo"
+  },
+  "rack": {
+    "title": "Rack",
+    "subtitle": "Tu hardware físico, colocado y cableado.",
+    "addRack": "Añadir rack",
+    "deleteRack": "Eliminar rack",
+    "deleteRackConfirm": "¿Eliminar el rack y todo lo que tiene montado?",
+    "rackDeleted": "Rack eliminado",
+    "save": "Guardar",
+    "saving": "Guardando…",
+    "saved": "Rack guardado",
+    "saveFailed": "No se pudo guardar",
+    "unsaved": "cambios sin guardar",
+    "patch": "Cablear",
+    "visibility": "Cables",
+    "visibilityHover": "Al pasar",
+    "visibilityAlways": "Siempre",
+    "visibilityHidden": "Ocultos",
+    "noSpace": "No cabe en ningún hueco libre del rack",
+    "patchBusy": "Ese puerto ya tiene todos sus cables",
+    "cableDeleted": "Cable desconectado",
+    "drafting": "Desde {{port}}: elige el puerto de destino (Esc cancela)",
+    "empty": "Todavía no hay ningún rack",
+    "emptyHint": "Crea primero un rack",
+    "pickHint": "Arrastra al rack (o haz clic) para montar en el rack activo (el resaltado en cyan). Luego arrastra para ajustar el hueco.",
+    "pickFleet": "Routers",
+    "pickDevice": "Dispositivos",
+    "pickAccessory": "Accesorios",
+    "plates": {
+      "server-1u": "Servidor 1U",
+      "server-2u": "Servidor 2U",
+      "switch": "Switch",
+      "router": "Router",
+      "nas-tower": "NAS torre",
+      "patch-panel-1u": "Patch panel 24p",
+      "pdu-1u": "PDU",
+      "ups-4u": "SAI 4U",
+      "shelf-1u": "Bandeja",
+      "blank-1u": "Tapeta 1U",
+      "blank-half-1u": "Tapeta 1/2U",
+      "patch-panel-12p": "Patch panel 12p",
+      "patch-panel-48p": "Patch panel 48p"
+    },
+    "createTitle": "Nuevo rack",
+    "createName": "Nombre",
+    "createU": "Altura (U)",
+    "createSubmit": "Crear",
+    "createCancel": "Cancelar",
+    "deleteTitle": "¿Eliminar rack?",
+    "deleteDesc": "Se eliminará «{{name}}» con todo lo que tiene montado. No se puede deshacer.",
+    "deleteConfirm": "Eliminar",
+    "deleteCancel": "Cancelar",
+    "unmounted": "Equipo desmontado del rack",
+    "editRack": "Editar rack",
+    "editTitle": "Editar rack",
+    "editSubmit": "Guardar cambios",
+    "rackUpdated": "Rack actualizado",
+    "createLocation": "Ubicación",
+    "locationPlaceholder": "p. ej. Despacho, Salón, Garaje…",
+    "import": "Importar enlaces",
+    "importResult": "Importación: {{created}} creados · {{skipped}} saltados · {{noFree}} sin puerto libre",
+    "askTitle": "Colocar «{{name}}»",
+    "askTitlePatch": "Colocar patch panel",
+    "askHeight": "Altura (U)",
+    "askPorts": "Puertos",
+    "askPlace": "Colocar",
+    "dropNoRack": "Suéltalo dentro de un rack",
+    "portCount": "bocas detectadas",
+    "importNeedsSave": "Guarda los cambios del rack antes de importar enlaces"
   }
 }

+ 88 - 0
app/scripts/rack-catalog-check.mjs

@@ -0,0 +1,88 @@
+// rack-catalog-check.mjs - verificación ejecutable del catálogo de faceplates
+// (gates A1-A3). Corre con Node >= 23 (type stripping), sin dependencias.
+
+const mod = await import('../src/lib/rackFaceplates.ts')
+const { FACEPLATES, seedPorts, suggestFaceplate, applyFaceplate, getFaceplate } = mod
+
+let failed = false
+const bad = (msg) => {
+  failed = true
+  console.error('FAIL:', msg)
+}
+
+// A1: >= 9 plantillas, bandas no solapadas, puertos dentro de 0..1.
+if (FACEPLATES.length < 9) bad(`solo ${FACEPLATES.length} plantillas (min 9)`)
+for (const p of FACEPLATES) {
+  if (![3, 4, 6, 12].includes(p.colSpan)) bad(`${p.id}: colSpan ${p.colSpan} fuera de {3,4,6,12}`)
+  if (p.uHeight < 1) bad(`${p.id}: uHeight ${p.uHeight}`)
+  // r = semi-extensión vertical (fracción del alto): validamos el eje Y y
+  // que el centro X quede a la izquierda de la labelBox (banda fija LED,
+  // luego labelBox: nunca se tocan).
+  if (p.led.y - p.led.r < 0 || p.led.y + p.led.r > 1) bad(`${p.id}: led fuera del eje Y`)
+  if (p.led.x < 0 || p.led.x > 1) bad(`${p.id}: led fuera del eje X`)
+  const lb = p.labelBox
+  if (lb.x < 0 || lb.y < 0 || lb.x + lb.w > 1 || lb.y + lb.h > 1) bad(`${p.id}: labelBox fuera de 0..1`)
+  if (p.led.x >= lb.x) bad(`${p.id}: led debe quedar a la izquierda de la labelBox`)
+  for (const row of p.rows) {
+    if (row.count < 1) bad(`${p.id}: fila vacía`)
+    if (row.xStart < 0 || row.xEnd > 1 || row.y < 0 || row.y > 1) bad(`${p.id}: fila fuera de 0..1`)
+  }
+}
+const ids = new Set(FACEPLATES.map((p) => p.id))
+if (ids.size !== FACEPLATES.length) bad('IDs de plantilla duplicados')
+console.log(failed ? '' : 'CATALOG OK')
+
+// A2: suggest para los tipos canónicos del clasificador.
+const expected = [
+  ['router', 'router'],
+  ['ap', 'router'],
+  ['switch', 'switch'],
+  ['servidor', 'server-1u'],
+  ['ordenador', 'server-1u'],
+  ['nas', 'nas-tower'],
+  ['ups', 'ups-4u'],
+  ['pdu', 'pdu-1u'],
+  ['desconocido', undefined],
+  ['iot', undefined],
+  ['', undefined],
+]
+for (const [typ, want] of expected) {
+  const got = suggestFaceplate(typ)
+  const gotId = got ? got.id : undefined
+  if (gotId !== want) bad(`suggest("${typ}") = ${gotId}; want ${want}`)
+}
+console.log(failed ? '' : 'SUGGEST OK')
+
+// A3: seed estable y applyFaceplate.
+const sw = getFaceplate('switch')
+const p1 = seedPorts(sw)
+const p2 = seedPorts(sw)
+if (JSON.stringify(p1) !== JSON.stringify(p2)) bad('seedPorts no es estable')
+if (p1.length !== 28) bad(`switch: ${p1.length} puertos; want 28 (24 rj45 + 4 sfp+)`)
+const kinds = p1.reduce((m, p) => ((m[p.kind] = (m[p.kind] || 0) + 1), m), {})
+if (kinds.rj45 !== 24 || kinds['sfp+'] !== 4) bad(`switch kinds: ${JSON.stringify(kinds)}`)
+const idsStable = p1.map((p) => p.id).join(',')
+if (idsStable !== p1.map((_, i) => 'p' + String(i + 1).padStart(2, '0')).join(',')) bad('IDs de puerto inestables')
+for (const p of p1) {
+  if (p.x < 0 || p.x > 1 || p.y < 0 || p.y > 1) bad(`puerto ${p.id} fuera de 0..1`)
+}
+const applied = applyFaceplate('switch')
+if (!applied || applied.plate.id !== 'switch' || applied.ports.length !== 28) bad('applyFaceplate(switch) roto')
+// A4b: layoutPhysicalPorts determinista y con ids reales preservados.
+const { layoutPhysicalPorts } = mod
+const phys = layoutPhysicalPorts([
+  ...Array.from({ length: 5 }, (_, i) => ({ id: 'lan' + (i + 1), kind: 'rj45' })),
+  { id: 'eth1', kind: 'sfp+' },
+])
+if (phys.length !== 6) bad(`layoutPhysicalPorts: ${phys.length}; want 6`)
+if (phys[5].id !== 'eth1' || phys[5].x < 0.7) bad('sfp+ no queda a la derecha')
+if (phys[0].id !== 'lan1') bad('ids reales no preservados')
+for (const p of phys) if (p.x < 0 || p.x > 1 || p.y < 0 || p.y > 1) bad(`puerto físico ${p.id} fuera de 0..1`)
+console.log(failed ? '' : 'LAYOUT OK')
+
+const appliedBad = applyFaceplate('iot')
+if (appliedBad !== undefined) bad('applyFaceplate(iot) debería ser undefined')
+console.log(failed ? '' : 'SEED OK')
+
+console.log(failed ? 'CHECK FAILED' : 'ALL CHECKS PASS')
+process.exit(failed ? 1 : 0)

+ 2 - 0
app/src/App.tsx

@@ -15,6 +15,7 @@ import Alerts from '@/pages/Alerts'
 import Roaming from '@/pages/Roaming'
 import ChannelPlan from '@/pages/ChannelPlan'
 import Reports from '@/pages/Reports'
+import Rack from '@/pages/Rack'
 import Orchestration from '@/pages/Orchestration'
 import FirmwareUpgrades from '@/pages/FirmwareUpgrades'
 import Settings from '@/pages/Settings'
@@ -54,6 +55,7 @@ export default function App() {
         <Route path="agents" element={<Navigate to="/routers" replace />} />
         <Route path="devices" element={<Devices />} />
         <Route path="topology" element={<Topology />} />
+        <Route path="rack" element={<Rack />} />
         <Route path="alerts" element={<Alerts />} />
         <Route path="roaming" element={<Roaming />} />
         <Route path="wifi/channel-plan" element={<ChannelPlan />} />

+ 2 - 2
app/src/components/Layout.tsx

@@ -23,8 +23,7 @@ import {
   Settings,
   Waypoints,
   Wifi,
-  Wrench,
-} from 'lucide-react'
+  Wrench, Server } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import { useNetPulse } from '@/data/DataProvider'
 import { DashboardProvider, useDashboard } from '@/hooks/useDashboard'
@@ -59,6 +58,7 @@ const NAV_ITEMS: NavItem[] = [
   { to: '/routers', labelKey: 'nav.routers', icon: RouterIcon },
   { to: '/devices', labelKey: 'nav.devices', icon: MonitorSmartphone },
   { to: '/topology', labelKey: 'nav.topology', icon: Waypoints },
+  { to: '/rack', labelKey: 'nav.rack', icon: Server, badge: 'labs' },
   { to: '/roaming', labelKey: 'nav.roaming', icon: Wifi },
   { to: '/wifi/channel-plan', labelKey: 'nav.channelPlan', icon: Wifi },
   { to: '/firmware-upgrades', labelKey: 'nav.firmwareUpgrades', icon: Cpu, adminOnly: true },

+ 136 - 0
app/src/components/rack/Faceplate.tsx

@@ -0,0 +1,136 @@
+// Faceplate.tsx - renderer de la cara frontal del equipo. Diseño plano y
+// limpio: LED de estado en punto nítido (HTML), un único nombre que escala
+// con la altura U y nunca invade la zona de bocas, y bocas con el icono
+// EthernetPort de Lucide (SFP = ranura rectangular). Un nombre, un LED,
+// las bocas.
+import { useTranslation } from 'react-i18next'
+import { EthernetPort } from 'lucide-react'
+import type { FaceplateTemplate, FaceplatePort } from '@/lib/rackFaceplates'
+
+export interface PortState {
+  /** el puerto tiene al menos un cable */
+  cabled: boolean
+  /** es el origen del draft de patch */
+  drafting: boolean
+  /** puede pincharse ahora (modo patch) */
+  interactive: boolean
+}
+
+export function Faceplate({
+  plate,
+  ports,
+  label,
+  color,
+  status,
+  patchFacing,
+  portsVisible,
+  portState,
+  onPortClick,
+  onPortEnter,
+  onPortLeave,
+}: {
+  plate: FaceplateTemplate
+  ports: FaceplatePort[]
+  label: string
+  color?: string
+  status: 'online' | 'offline' | 'unknown'
+  /** true = puertos siempre visibles (equipos patch-facing) */
+  patchFacing: boolean
+  /** false = puertos ocultos salvo cable (modo no-patch, no hover) */
+  portsVisible: boolean
+  portState: (portId: string) => PortState
+  onPortClick?: (portId: string) => void
+  onPortEnter?: (portId: string) => void
+  onPortLeave?: (portId: string) => void
+}) {
+  const { t } = useTranslation()
+  const minPortX = ports.length > 0 ? Math.min(...ports.map((p) => p.x)) : 1
+  const ledColor =
+    status === 'online'
+      ? 'bg-emerald-400'
+      : status === 'offline'
+        ? 'bg-red-400'
+        : 'bg-zinc-500'
+  const bg = color || 'rgb(var(--elevated))'
+
+  return (
+    <div
+      className="relative h-full w-full overflow-hidden rounded-[2px] border border-black/30"
+      style={{ background: bg, containerType: 'size' }}
+      data-faceplate={plate.id}
+    >
+      {/* LED de estado: punto nítido de tamaño fijo */}
+      <div
+        className={'absolute rounded-full ' + ledColor}
+        style={{
+          left: 'max(6px, 3%)',
+          top: `${plate.led.y * 100}%`,
+          width: 8,
+          height: 8,
+          transform: 'translateY(-50%)',
+        }}
+        aria-hidden
+      />
+
+      {/* Nombre + conteo de bocas: la banda termina antes de la primera
+          boca real, así nunca se montan unos sobre otros. */}
+      <div
+        className="absolute flex items-center gap-[0.6em] overflow-hidden whitespace-nowrap font-semibold leading-none"
+        style={{
+          left: 'max(18px, 9%)',
+          top: `${plate.labelBox.y * 100}%`,
+          height: `${plate.labelBox.h * 100}%`,
+          width: `${Math.max(0.12, minPortX - plate.labelBox.x - 0.06) * 100}%`,
+          fontSize: 'min(17cqh, 12px)',
+          color: 'rgb(var(--text-secondary))',
+        }}
+      >
+        <span className="truncate">{label || t(plate.nameKey)}</span>
+        {ports.length > 0 && (
+          <span style={{ fontSize: '0.72em', color: 'rgb(var(--text-muted))' }} title={t('rack.portCount')}>
+            ×{ports.length}
+          </span>
+        )}
+      </div>
+
+      {/* Bocas: siluetas planas sobre las coords 0..1 de la plantilla */}
+      {(patchFacing || portsVisible) &&
+        ports.map((p) => {
+          const st = portState(p.id)
+          const visible = patchFacing || portsVisible || st.cabled || st.drafting
+          if (!visible) return null
+          const sfp = p.kind !== 'rj45'
+          const tone = st.drafting
+            ? 'text-amber-400'
+            : st.cabled
+              ? 'text-emerald-500 hover:text-emerald-400'
+              : st.interactive
+                ? 'text-zinc-500 hover:text-accent'
+                : 'text-zinc-600'
+          return (
+            <button
+              key={p.id}
+              type="button"
+              tabIndex={st.interactive ? 0 : -1}
+              aria-label={p.id}
+              title={`${p.id} · ${p.kind}`}
+              onClick={(e) => {
+                e.stopPropagation()
+                if (st.interactive) onPortClick?.(p.id)
+              }}
+              onMouseEnter={() => onPortEnter?.(p.id)}
+              onMouseLeave={() => onPortLeave?.(p.id)}
+              className={'nodrag absolute flex -translate-x-1/2 -translate-y-1/2 items-center justify-center ' + tone}
+              style={{ left: `${p.x * 100}%`, top: `${p.y * 100}%` }}
+            >
+              {sfp ? (
+                <span className="block rounded-[1px] bg-current" style={{ width: 18, height: 6 }} aria-hidden />
+              ) : (
+                <EthernetPort size={16} strokeWidth={2} aria-hidden />
+              )}
+            </button>
+          )
+        })}
+    </div>
+  )
+}

+ 71 - 0
app/src/components/rack/MountNode.tsx

@@ -0,0 +1,71 @@
+// MountNode.tsx - nodo montaje: faceplate SVG + selección. Los puertos
+// viven en la Faceplate; los eventos llegan vía node.data.
+import { memo } from 'react'
+import type { NodeProps, Node } from '@xyflow/react'
+import { X } from 'lucide-react'
+import { Faceplate, type PortState } from './Faceplate'
+import type { FaceplateTemplate, FaceplatePort } from '@/lib/rackFaceplates'
+
+export type MountNodeData = {
+  plate: FaceplateTemplate
+  ports: FaceplatePort[]
+  label: string
+  color?: string
+  status: 'online' | 'offline' | 'unknown'
+  patchFacing: boolean
+  portsVisible: boolean
+  selected: boolean
+  /** disponible para admin: botón desmontar en la esquina */
+  onUnmount?: () => void
+  /** clic en el montaje: selección propia (elementsSelectable off) */
+  onSelect?: () => void
+  portState: (portId: string) => PortState
+  onPortClick?: (portId: string) => void
+  onPortEnter?: (portId: string) => void
+  onPortLeave?: (portId: string) => void
+}
+
+export type MountNodeType = Node<MountNodeData, 'mount'>
+
+export const MountNode = memo(function MountNode({ data }: NodeProps<MountNodeType>) {
+  // selected viene de nuestro modelo (data.selected): el rebuild de nodos
+  // reemplaza los objetos y pisaría el estado de selección de React Flow.
+  return (
+    <div
+      className={'h-full w-full transition-shadow ' + (data.selected ? 'rounded-[2px] ring-2 ring-accent' : '')}
+      data-testid="mount-node"
+      onClick={(e) => {
+        e.stopPropagation()
+        data.onSelect?.()
+      }}
+    >
+      {data.selected && data.onUnmount && (
+        <button
+          type="button"
+          aria-label="unmount"
+          title="unmount"
+          onClick={(e) => {
+            e.stopPropagation()
+            data.onUnmount?.()
+          }}
+          className="nodrag absolute -right-1.5 -top-1.5 z-10 flex h-5 w-5 items-center justify-center rounded-full bg-danger text-white shadow hover:bg-danger/90"
+        >
+          <X size={12} />
+        </button>
+      )}
+      <Faceplate
+        plate={data.plate}
+        ports={data.ports}
+        label={data.label}
+        color={data.color}
+        status={data.status}
+        patchFacing={data.patchFacing}
+        portsVisible={data.portsVisible}
+        portState={data.portState}
+        onPortClick={data.onPortClick}
+        onPortEnter={data.onPortEnter}
+        onPortLeave={data.onPortLeave}
+      />
+    </div>
+  )
+})

+ 108 - 0
app/src/components/rack/RackNode.tsx

@@ -0,0 +1,108 @@
+// RackNode.tsx - nodo rack: cabecera con nombre, raíles con numeración U
+// (bottom-up por defecto; la opción numbering solo cambia etiquetas, nunca
+// la geometría), interior con rejilla y ghost de drop.
+import { memo } from 'react'
+import type { NodeProps, Node } from '@xyflow/react'
+import { COL_PX, U_PX, RAIL_PX, interiorWidthPx } from './layout'
+import type { GhostState } from './types'
+
+export type RackNodeData = {
+  name: string
+  location?: string
+  uHeight: number
+  numbering: string
+  selected: boolean
+  ghost: GhostState | null
+  onSelect?: () => void
+}
+
+export type RackNodeType = Node<RackNodeData, 'rack'>
+
+export const RackNode = memo(function RackNode({ data }: NodeProps<RackNodeType>) {
+  const { name, uHeight, numbering, selected, ghost } = data
+  const interiorW = interiorWidthPx()
+  const topDown = numbering === 'top-down'
+
+  return (
+    <div
+      className={
+        'relative rounded-md border-2 bg-surface ' +
+        (selected ? 'border-accent' : 'border-border')
+      }
+      style={{ width: RAIL_PX * 2 + interiorW, height: 24 + uHeight * U_PX + 4 }}
+      onClick={(e) => {
+        e.stopPropagation()
+        data.onSelect?.()
+      }}
+    >
+      {/* Cabecera: nombre del rack (+ ubicación) */}
+      <div className="flex h-[24px] items-center justify-center gap-1.5 truncate px-2 text-[11px] font-semibold text-text-secondary">
+        <span className="truncate">{name}</span>
+        {data.location && <span className="truncate text-[10px] font-normal text-text-muted">· {data.location}</span>}
+      </div>
+
+      {/* Raíl izquierdo: números de U. La U 1 está abajo siempre. */}
+      <div className="absolute left-0 top-[24px] bottom-[4px] w-[18px]">
+        {Array.from({ length: uHeight }, (_, i) => {
+          const labelU = topDown ? i + 1 : uHeight - i
+          return (
+            <div
+              key={i}
+              className="flex items-center justify-end pr-[3px] text-[11px] font-medium leading-none text-text-secondary"
+              style={{ height: U_PX, marginTop: 0 }}
+            >
+              {labelU}
+            </div>
+          )
+        })}
+      </div>
+      {/* Raíl derecho (simétrico, sin números) */}
+      <div className="absolute right-0 top-[24px] bottom-[4px] w-[18px] border-l border-border/40" />
+
+      {/* Interior con rejilla: línea por U + separadores de fracciones */}
+      <div
+        className="absolute border border-border/60"
+        style={{
+          left: RAIL_PX,
+          top: 24,
+          width: interiorW,
+          height: uHeight * U_PX,
+          backgroundImage:
+            'repeating-linear-gradient(to bottom, transparent 0, transparent ' +
+            (U_PX - 1) +
+            'px, rgb(var(--border)) ' +
+            (U_PX - 1) +
+            'px, rgb(var(--border)) ' +
+            U_PX +
+            'px)',
+          backgroundSize: '100% ' + U_PX + 'px',
+        }}
+      >
+        {/* marcas de fracciones de ancho: 1/2, 1/3, 1/4 */}
+        {[1 / 2, 1 / 3, 2 / 3, 1 / 4, 3 / 4].map((f) => (
+          <div
+            key={f}
+            className="absolute top-0 h-full w-px bg-border/30"
+            style={{ left: f * interiorW }}
+          />
+        ))}
+
+        {/* Ghost de drop: verde = encaja, rojo = imposible */}
+        {ghost && (
+          <div
+            className={
+              'pointer-events-none absolute rounded-[3px] border-2 ' +
+              (ghost.valid ? 'border-emerald-400 bg-emerald-400/10' : 'border-red-400 bg-red-400/10')
+            }
+            style={{
+              left: ghost.colStart * COL_PX,
+              top: (uHeight - ghost.uStart - ghost.uHeight + 1) * U_PX,
+              width: ghost.colSpan * COL_PX,
+              height: ghost.uHeight * U_PX,
+            }}
+          />
+        )}
+      </div>
+    </div>
+  )
+})

+ 58 - 0
app/src/components/rack/layout.ts

@@ -0,0 +1,58 @@
+// layout.ts - constantes y conversiones grid <-> píxeles del rack canvas.
+// U 1-based desde el rail inferior (RF y crece hacia abajo: la U 1 va abajo
+// del todo). Columnas 0-based.
+
+export const U_PX = 48
+/** Proporción real de un rack 19": ancho útil entre raíles (482,6 mm) /
+ * alto de 1U (44,45 mm) ≈ 10,86. El interior mide 10,86 U de ancho. */
+export const RACK19_RATIO = 10.86
+/** Ancho de columna derivado: interior = 12 columnas = U_PX * RACK19_RATIO. */
+export const COL_PX = (U_PX * RACK19_RATIO) / 12
+export const RAIL_PX = 18
+export const RACK_HEADER_PX = 24
+
+/** Ancho interior útil de un rack de ancho completo. */
+export function interiorWidthPx(): number {
+  return 12 * COL_PX
+}
+
+/** Alto total del nodo rack. */
+export function rackHeightPx(uHeight: number): number {
+  return RACK_HEADER_PX + uHeight * U_PX + 4
+}
+
+/** Ancho total del nodo rack. */
+export function rackWidthPx(): number {
+  return RAIL_PX * 2 + interiorWidthPx()
+}
+
+/**
+ * Posición RELATIVA al nodo rack de un montaje (RF nested nodes). Interior
+ * empieza tras el rail izquierdo y bajo la cabecera.
+ */
+export function mountRelPos(
+  rackUHeight: number,
+  uStart: number,
+  uHeight: number,
+  colStart: number,
+): { x: number; y: number } {
+  return {
+    x: RAIL_PX + colStart * COL_PX,
+    y: RACK_HEADER_PX + (rackUHeight - uStart - uHeight + 1) * U_PX,
+  }
+}
+
+/**
+ * Celda de grid correspondiente a una posición relativa suelta (inversa de
+ * mountRelPos, redondeando al hueco más cercano).
+ */
+export function relPosToCell(
+  rackUHeight: number,
+  x: number,
+  y: number,
+  uHeight: number,
+): { uStart: number; colStart: number } {
+  const colStart = Math.round((x - RAIL_PX) / COL_PX)
+  const uTop = Math.round((y - RACK_HEADER_PX) / U_PX)
+  return { uStart: rackUHeight - uTop - uHeight + 1, colStart }
+}

+ 9 - 0
app/src/components/rack/types.ts

@@ -0,0 +1,9 @@
+// types.ts - estado compartido entre la página y los nodos del canvas.
+import type { Footprint } from '@/lib/rackGeometry'
+
+/** Ghost de drop durante el drag de un montaje. */
+export interface GhostState extends Footprint {
+  valid: boolean
+}
+
+export type CableVisibility = 'hover' | 'always' | 'hidden'

+ 132 - 0
app/src/lib/rackApi.ts

@@ -0,0 +1,132 @@
+// rackApi.ts - tipos del wire (snake_case, espejo del contrato Go) y
+// llamadas al API del rack canvas.
+
+export interface RackDTO {
+  id: string
+  name: string
+  u_height: number
+  width_standard: string
+  numbering: string
+  style: string
+  location?: string
+  position_x: number
+  position_y: number
+}
+
+export interface MountDTO {
+  id: string
+  rack_id: string
+  device_mac?: string
+  faceplate_id: string
+  u_start: number
+  u_height: number
+  col_start: number
+  col_span: number
+  label?: string
+  status_pin: string
+  port_visibility: string
+}
+
+export interface CableDTO {
+  id: string
+  from_mount: string
+  from_port: string
+  to_mount: string
+  to_port: string
+  type: string
+  label?: string
+  properties?: string
+  origin: string
+  created_at: number
+}
+
+export type RackPortKindWire = 'rj45' | 'sfp' | 'sfp+'
+
+export interface ProfilePortDTO {
+  id: string
+  kind: RackPortKindWire
+  x: number
+  y: number
+}
+
+export interface ProfileDTO {
+  mac: string
+  faceplate_id: string
+  u_height: number
+  col_span: number
+  color: string
+  ports: ProfilePortDTO[]
+}
+
+export interface RackBundle {
+  racks: RackDTO[]
+  mounts: MountDTO[]
+  cables: CableDTO[]
+  profiles: ProfileDTO[]
+  /** estado de auditoría por cable: confirmed | manual-only | detected */
+  audit: Record<string, string>
+}
+
+async function req<T>(input: string, init?: RequestInit): Promise<T> {
+  const res = await fetch(input, init)
+  if (!res.ok) {
+    let msg = `HTTP ${res.status}`
+    try {
+      const body = await res.json()
+      if (body?.message) msg = body.message
+    } catch {
+      /* mensaje por defecto */
+    }
+    throw new Error(msg)
+  }
+  return res.json() as Promise<T>
+}
+
+const json = (method: string, body: unknown): RequestInit => ({
+  method,
+  headers: { 'Content-Type': 'application/json' },
+  body: JSON.stringify(body),
+})
+
+export function fetchRackBundle(): Promise<RackBundle> {
+  return req<RackBundle>('/api/racks')
+}
+
+export function createRack(body: Partial<RackDTO>): Promise<RackDTO> {
+  return req<RackDTO>('/api/racks', json('POST', body))
+}
+
+export function saveRack(rack: RackDTO): Promise<{ ok: boolean }> {
+  return req<{ ok: boolean }>(`/api/racks/${rack.id}`, json('PUT', rack))
+}
+
+export function deleteRack(id: string): Promise<{ ok: boolean }> {
+  return req<{ ok: boolean }>(`/api/racks/${id}`, { method: 'DELETE' })
+}
+
+export function saveLayout(body: { rack_id: string; upsert: MountDTO[]; delete: string[] }): Promise<{ ok: boolean }> {
+  return req<{ ok: boolean }>('/api/racks/layout', json('PUT', body))
+}
+
+export function addCable(body: Partial<CableDTO>): Promise<CableDTO> {
+  return req<CableDTO>('/api/racks/cables', json('POST', body))
+}
+
+export function deleteCable(id: string): Promise<{ ok: boolean }> {
+  return req<{ ok: boolean }>(`/api/racks/cables/${id}`, { method: 'DELETE' })
+}
+
+export function upsertProfile(mac: string, body: Omit<ProfileDTO, 'mac'>): Promise<ProfileDTO> {
+  return req<ProfileDTO>(`/api/racks/profiles/${encodeURIComponent(mac)}`, json('PUT', body))
+}
+
+export interface ImportResultDTO {
+  hints: number
+  created: number
+  skipped: number
+  noFreePort: number
+}
+
+export function importCables(): Promise<ImportResultDTO> {
+  return req<ImportResultDTO>('/api/racks/import-cables', { method: 'POST' })
+}

+ 356 - 0
app/src/lib/rackFaceplates.ts

@@ -0,0 +1,356 @@
+// rackFaceplates.ts - catálogo declarativo de faceplates del rack canvas.
+// Dominio puro, SIN dependencias de runtime: importable desde el canvas, el
+// picker y scripts node (type stripping). Las plantillas se expresan en
+// coordenadas de unidad 0..1 del faceplate: el puerto mantiene su sitio a
+// cualquier zoom y con cualquier altura de U.
+//
+// Bandas no solapadas por construcción (el renderer las dibuja en este
+// orden): LED de estado fijo a la izquierda, labelBox (nombre, clipped),
+// artwork del equipo y, a la derecha, los puertos.
+
+export type RackPortKind = 'rj45' | 'sfp' | 'sfp+'
+
+export interface FaceplatePort {
+  id: string
+  kind: RackPortKind
+  x: number
+  y: number
+}
+
+export interface PortRow {
+  kind: RackPortKind
+  count: number
+}
+
+/** Zona horizontal de las bocas RJ45 (0..1); los SFP van en columna a su
+ * derecha. La disposición concreta (filas de hasta 24, reparto uniforme)
+ * la calcula layoutPortZone: sirve para 4 bocas como para 48+4. */
+export interface PortZone {
+  xStart: number
+  xEnd: number
+}
+
+export interface FaceplateTemplate {
+  id: string
+  /** clave i18n del nombre en el picker (rack.plates.<id>) */
+  nameKey: string
+  group: 'device' | 'accessory'
+  /** artwork que dibuja el renderer (server, switch, router, panel, pdu...) */
+  artwork: string
+  uHeight: number
+  /** 12 = ancho completo, 6 = mitad, 4 = tercio, 3 = cuarto */
+  colSpan: number
+  /** LED de estado: centro en fracciones 0..1; r queda como referencia
+   * vertical (el renderer dibuja un punto de tamaño fijo) */
+  led: { x: number; y: number; r: number }
+  labelBox: { x: number; y: number; w: number; h: number }
+  rows: PortRow[]
+  portZone?: PortZone
+  /** los puertos de un patch panel son pass-through: admite 2 cables */
+  passThrough?: boolean
+}
+
+const fullWidth = 12
+
+export const FACEPLATES: FaceplateTemplate[] = [
+  {
+    id: 'server-1u',
+    nameKey: 'rack.plates.server-1u',
+    group: 'device',
+    artwork: 'server',
+    uHeight: 1,
+    colSpan: fullWidth,
+    led: { x: 0.035, y: 0.5, r: 0.16 },
+    labelBox: { x: 0.07, y: 0.28, w: 0.5, h: 0.44 },
+    portZone: { xStart: 0.52, xEnd: 0.94 },
+    rows: [
+      { kind: 'rj45', count: 2 },
+      { kind: 'sfp+', count: 2 },
+    ],
+  },
+  {
+    id: 'server-2u',
+    nameKey: 'rack.plates.server-2u',
+    group: 'device',
+    artwork: 'server',
+    uHeight: 2,
+    colSpan: fullWidth,
+    led: { x: 0.035, y: 0.25, r: 0.08 },
+    labelBox: { x: 0.07, y: 0.14, w: 0.45, h: 0.22 },
+    portZone: { xStart: 0.5, xEnd: 0.94 },
+    rows: [
+      { kind: 'rj45', count: 4 },
+      { kind: 'sfp+', count: 2 },
+      { kind: 'rj45', count: 2 },
+    ],
+  },
+  {
+    id: 'switch',
+    nameKey: 'rack.plates.switch',
+    group: 'device',
+    artwork: 'switch',
+    uHeight: 1,
+    colSpan: fullWidth,
+    led: { x: 0.03, y: 0.5, r: 0.16 },
+    labelBox: { x: 0.06, y: 0.3, w: 0.16, h: 0.4 },
+    portZone: { xStart: 0.24, xEnd: 0.8 },
+    rows: [
+      { kind: 'rj45', count: 12 },
+      { kind: 'rj45', count: 12 },
+      { kind: 'sfp+', count: 4 },
+    ],
+  },
+  {
+    id: 'router',
+    nameKey: 'rack.plates.router',
+    group: 'device',
+    artwork: 'router',
+    uHeight: 1,
+    colSpan: fullWidth,
+    led: { x: 0.035, y: 0.5, r: 0.16 },
+    labelBox: { x: 0.07, y: 0.3, w: 0.3, h: 0.4 },
+    portZone: { xStart: 0.44, xEnd: 0.88 },
+    rows: [
+      { kind: 'rj45', count: 5 },
+      { kind: 'sfp+', count: 1 },
+      { kind: 'rj45', count: 1 },
+    ],
+  },
+  {
+    id: 'nas-tower',
+    nameKey: 'rack.plates.nas-tower',
+    group: 'device',
+    artwork: 'nas',
+    uHeight: 4,
+    colSpan: 6,
+    led: { x: 0.07, y: 0.06, r: 0.02 },
+    labelBox: { x: 0.14, y: 0.04, w: 0.6, h: 0.05 },
+    portZone: { xStart: 0.4, xEnd: 0.94 },
+    rows: [{ kind: 'rj45', count: 2 }],
+  },
+  {
+    id: 'patch-panel-1u',
+    nameKey: 'rack.plates.patch-panel-1u',
+    group: 'accessory',
+    artwork: 'panel',
+    uHeight: 1,
+    colSpan: fullWidth,
+    led: { x: 0.03, y: 0.5, r: 0.16 },
+    labelBox: { x: 0.06, y: 0.3, w: 0.12, h: 0.4 },
+    portZone: { xStart: 0.2, xEnd: 0.96 },
+    rows: [
+      { kind: 'rj45', count: 12 },
+      { kind: 'rj45', count: 12 },
+    ],
+    passThrough: true,
+  },
+  {
+    id: 'patch-panel-12p',
+    nameKey: 'rack.plates.patch-panel-12p',
+    group: 'accessory',
+    artwork: 'panel',
+    uHeight: 1,
+    colSpan: 12,
+    led: { x: 0.03, y: 0.5, r: 0.16 },
+    labelBox: { x: 0.06, y: 0.3, w: 0.12, h: 0.4 },
+    portZone: { xStart: 0.2, xEnd: 0.96 },
+    rows: [{ kind: 'rj45', count: 12 }],
+    passThrough: true,
+  },
+  {
+    id: 'patch-panel-48p',
+    nameKey: 'rack.plates.patch-panel-48p',
+    group: 'accessory',
+    artwork: 'panel',
+    uHeight: 2,
+    colSpan: 12,
+    led: { x: 0.03, y: 0.25, r: 0.08 },
+    labelBox: { x: 0.06, y: 0.14, w: 0.14, h: 0.22 },
+    portZone: { xStart: 0.2, xEnd: 0.96 },
+    rows: [
+      { kind: 'rj45', count: 24 },
+      { kind: 'rj45', count: 24 },
+    ],
+    passThrough: true,
+  },
+  {
+    id: 'pdu-1u',
+    nameKey: 'rack.plates.pdu-1u',
+    group: 'accessory',
+    artwork: 'pdu',
+    uHeight: 1,
+    colSpan: fullWidth,
+    led: { x: 0.03, y: 0.5, r: 0.16 },
+    labelBox: { x: 0.06, y: 0.3, w: 0.5, h: 0.4 },
+    rows: [],
+  },
+  {
+    id: 'ups-4u',
+    nameKey: 'rack.plates.ups-4u',
+    group: 'device',
+    artwork: 'ups',
+    uHeight: 4,
+    colSpan: fullWidth,
+    led: { x: 0.03, y: 0.08, r: 0.04 },
+    labelBox: { x: 0.06, y: 0.05, w: 0.5, h: 0.07 },
+    portZone: { xStart: 0.7, xEnd: 0.94 },
+    rows: [{ kind: 'rj45', count: 1 }],
+  },
+  {
+    id: 'shelf-1u',
+    nameKey: 'rack.plates.shelf-1u',
+    group: 'accessory',
+    artwork: 'shelf',
+    uHeight: 1,
+    colSpan: fullWidth,
+    led: { x: 0.03, y: 0.5, r: 0.16 },
+    labelBox: { x: 0.06, y: 0.3, w: 0.6, h: 0.4 },
+    rows: [],
+  },
+  {
+    id: 'blank-1u',
+    nameKey: 'rack.plates.blank-1u',
+    group: 'accessory',
+    artwork: 'blank',
+    uHeight: 1,
+    colSpan: fullWidth,
+    led: { x: 0.03, y: 0.5, r: 0.16 },
+    labelBox: { x: 0.06, y: 0.3, w: 0.88, h: 0.4 },
+    rows: [],
+  },
+  {
+    id: 'blank-half-1u',
+    nameKey: 'rack.plates.blank-half-1u',
+    group: 'accessory',
+    artwork: 'blank',
+    uHeight: 1,
+    colSpan: 6,
+    led: { x: 0.06, y: 0.5, r: 0.16 },
+    labelBox: { x: 0.12, y: 0.3, w: 0.76, h: 0.4 },
+    rows: [],
+  },
+]
+
+const byId = new Map(FACEPLATES.map((p) => [p.id, p]))
+
+export function getFaceplate(id: string): FaceplateTemplate | undefined {
+  return byId.get(id)
+}
+
+/**
+ * seedPorts expande las filas declarativas en puertos con IDs estables
+ * ("p01", "p02", ...) y posiciones 0..1. Aplicar una plantilla siembra los
+ * puertos; el usuario los edita después.
+ */
+export function seedPorts(plate: FaceplateTemplate): FaceplatePort[] {
+  const counts: Partial<Record<RackPortKind, number>> = {}
+  for (const row of plate.rows) counts[row.kind] = (counts[row.kind] ?? 0) + row.count
+  return layoutPortZone(counts, plate.portZone ?? { xStart: 0.24, xEnd: 0.94 })
+}
+
+/**
+ * layoutPortZone: disposición uniforme de bocas en la zona, pensada para el
+ * peor caso real (48 RJ45 + 4 SFP+ en 1U): RJ45 en filas de hasta 24 (reparto
+ * equitativo con la zona entera: 4 bocas la ocupan completa con hueco
+ * garantizado entre ellas, igual que 24) y SFP/SFP+ en columna a la derecha
+ * de la zona. Mismo criterio para el KP-9000 (9) que para rt2 (4).
+ */
+export function layoutPortZone(
+  counts: Partial<Record<RackPortKind, number>>,
+  zone: PortZone,
+): FaceplatePort[] {
+  const out: FaceplatePort[] = []
+  const rj45 = counts.rj45 ?? 0
+  const sfp = counts.sfp ?? 0
+  const sfpPlus = counts['sfp+'] ?? 0
+  const sfps = sfp + sfpPlus
+  const rjEnd = sfps > 0 ? Math.max(zone.xStart + 0.1, zone.xEnd - 0.08) : zone.xEnd - 0.02
+  if (rj45 > 0) {
+    const rows = Math.max(1, Math.ceil(rj45 / 24))
+    const perRow = Math.ceil(rj45 / rows)
+    let n = 0
+    for (let row = 0; row < rows; row++) {
+      const inRow = Math.min(perRow, rj45 - row * perRow)
+      const y = rows === 1 ? 0.5 : 0.26 + (0.74 - 0.26) * (row / (rows - 1))
+      for (let i = 0; i < inRow; i++) {
+        n++
+        out.push({
+          id: 'p' + String(n).padStart(2, '0'),
+          kind: 'rj45',
+          x: inRow === 1 ? (zone.xStart + rjEnd) / 2 : zone.xStart + (rjEnd - zone.xStart) * (i / (inRow - 1)),
+          y,
+        })
+      }
+    }
+  }
+  for (let i = 0; i < sfps; i++) {
+    out.push({
+      id: 'p' + String(out.length + 1).padStart(2, '0'),
+      kind: i < sfpPlus ? 'sfp+' : 'sfp',
+      x: zone.xEnd - 0.02,
+      y: sfps === 1 ? 0.5 : 0.26 + (0.74 - 0.26) * (i / (sfps - 1)),
+    })
+  }
+  return out
+}
+
+/**
+ * layoutPhysicalPorts dispone puertos físicos reales (id = ifName) con el
+ * mismo algoritmo de zona, preservando los ids en el orden de disposición.
+ */
+export function layoutPhysicalPorts(
+  ports: { id: string; kind: RackPortKind }[],
+  zone?: { xStart: number; xEnd: number },
+): FaceplatePort[] {
+  const counts: Partial<Record<RackPortKind, number>> = {}
+  for (const p of ports) counts[p.kind] = (counts[p.kind] ?? 0) + 1
+  const laid = layoutPortZone(counts, zone ?? { xStart: 0.24, xEnd: 0.94 })
+  const byKind: Record<string, string[]> = {}
+  for (const p of ports) {
+    ;(byKind[p.kind] = byKind[p.kind] ?? []).push(p.id)
+  }
+  const used: Record<string, number> = {}
+  return laid.map((slot) => {
+    const ids = byKind[slot.kind] ?? []
+    const idx = Math.min(used[slot.kind] ?? 0, ids.length - 1)
+    used[slot.kind] = (used[slot.kind] ?? 0) + 1
+    return { ...slot, id: ids[idx] ?? slot.id }
+  })
+}
+
+/**
+ * suggestFaceplate sugiere plantilla desde el tipo detectado por NetPulse
+ * (clasificador interno, valores canónicos en español con alias en inglés).
+ * Tipos sin faceplate propio devuelven undefined y el caller decide.
+ */
+export function suggestFaceplate(deviceType: string): FaceplateTemplate | undefined {
+  switch (deviceType.toLowerCase().trim()) {
+    case 'router':
+    case 'ap': // los AP van montados como cualquier equipo de red pequeño
+    case 'punto de acceso':
+      return byId.get('router')
+    case 'switch':
+      return byId.get('switch')
+    case 'servidor':
+    case 'ordenador':
+    case 'server':
+    case 'desktop':
+      return byId.get('server-1u')
+    case 'nas':
+      return byId.get('nas-tower')
+    case 'ups':
+    case 'sai':
+      return byId.get('ups-4u')
+    case 'pdu':
+      return byId.get('pdu-1u')
+    default:
+      return undefined
+  }
+}
+
+/** applyFaceplate combina suggest + seed para un tipo detectado. */
+export function applyFaceplate(deviceType: string): { plate: FaceplateTemplate; ports: FaceplatePort[] } | undefined {
+  const plate = suggestFaceplate(deviceType)
+  if (!plate) return undefined
+  return { plate, ports: seedPorts(plate) }
+}

+ 60 - 0
app/src/lib/rackGeometry.ts

@@ -0,0 +1,60 @@
+// rackGeometry.ts - port del dominio Go (internal/rack/geometry.go), misma
+// semántica: U 1-based desde el rail inferior, 12 columnas por U, snap que
+// busca primero la U de destino y luego camina hacia fuera, con la columna
+// deseada primero y barrido izquierda-derecha. Módulo puro (node-testeable).
+
+export const RACK_COLUMNS = 12
+
+export interface Footprint {
+  uStart: number
+  uHeight: number
+  colStart: number
+  colSpan: number
+}
+
+export function overlaps(a: Footprint, b: Footprint): boolean {
+  return a.uStart < b.uStart + b.uHeight && b.uStart < a.uStart + a.uHeight &&
+    a.colStart < b.colStart + b.colSpan && b.colStart < a.colStart + a.colSpan
+}
+
+export function fitsRack(rackUHeight: number, f: Footprint): boolean {
+  return f.uStart >= 1 && f.uHeight >= 1 && f.uStart + f.uHeight - 1 <= rackUHeight &&
+    f.colStart >= 0 && f.colSpan >= 1 && f.colStart + f.colSpan <= RACK_COLUMNS
+}
+
+/** existing debe EXCLUIR la huella del montaje que se está moviendo. */
+export function canPlace(rackUHeight: number, existing: Footprint[], cand: Footprint): boolean {
+  if (!fitsRack(rackUHeight, cand)) return false
+  return !existing.some((e) => overlaps(e, cand))
+}
+
+function tryAt(rackUHeight: number, existing: Footprint[], u: number, c: number, uHeight: number, colSpan: number): Footprint | null {
+  const f: Footprint = { uStart: u, uHeight, colStart: c, colSpan }
+  return canPlace(rackUHeight, existing, f) ? f : null
+}
+
+/** Snap del drop: U destino primero, luego hacia fuera; columna deseada
+ * (clampada) primero, barrido izq→der. null = drop imposible (preview rojo,
+ * nunca colisión silenciosa). */
+export function findSlot(rackUHeight: number, existing: Footprint[], dropU: number, dropCol: number, uHeight: number, colSpan: number): Footprint | null {
+  if (uHeight < 1 || colSpan < 1) return null
+  const maxU = rackUHeight - uHeight + 1
+  const maxCol = RACK_COLUMNS - colSpan
+  if (maxU < 1 || maxCol < 0) return null
+  const col = Math.min(Math.max(dropCol, 0), maxCol)
+  const targetU = Math.min(Math.max(dropU, 1), maxU)
+  for (let offset = 0; offset < rackUHeight; offset++) {
+    const us = offset === 0 ? [targetU] : [targetU - offset, targetU + offset]
+    for (const u of us) {
+      if (u < 1 || u > maxU) continue
+      const first = tryAt(rackUHeight, existing, u, col, uHeight, colSpan)
+      if (first) return first
+      for (let c = 0; c <= maxCol; c++) {
+        if (c === col) continue
+        const f = tryAt(rackUHeight, existing, u, c, uHeight, colSpan)
+        if (f) return f
+      }
+    }
+  }
+  return null
+}

+ 1500 - 0
app/src/pages/Rack.tsx

@@ -0,0 +1,1500 @@
+/**
+ * NetPulse - Página Rack `/rack` (rack canvas, fase 1).
+ * Canvas con racks y montajes (snap al grid, save explícito), patch de
+ * cables port-to-port y visibilidad de cables. Dominio en lib/rackGeometry
+ * + lib/rackFaceplates; wire en lib/rackApi (snake_case).
+ */
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+  ReactFlow,
+  ReactFlowProvider,
+  ViewportPortal,
+  useNodesState,
+  useReactFlow,
+  Background,
+  BackgroundVariant,
+} from '@xyflow/react'
+import '@xyflow/react/dist/style.css'
+import { Cable, Cctv, Link2, Monitor, Network, Pencil, Plus, Router as RouterIcon, Save, Server, Trash2 } from 'lucide-react'
+import { toast } from 'sonner'
+import { SectionHeader } from '@/components/SectionHeader'
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
+import { SegmentedControl } from '@/components/SegmentedControl'
+import { RackNode, type RackNodeType } from '@/components/rack/RackNode'
+import { MountNode, type MountNodeType } from '@/components/rack/MountNode'
+import { COL_PX, U_PX, mountRelPos, rackHeightPx, rackWidthPx, relPosToCell } from '@/components/rack/layout'
+import type { CableVisibility, GhostState } from '@/components/rack/types'
+import { findSlot, type Footprint } from '@/lib/rackGeometry'
+import { FACEPLATES, getFaceplate, layoutPhysicalPorts, seedPorts, suggestFaceplate, type RackPortKind } from '@/lib/rackFaceplates'
+import * as api from '@/lib/rackApi'
+import type { CableDTO, MountDTO, ProfileDTO, RackDTO } from '@/lib/rackApi'
+import type { Router } from '@/data/types'
+import { useNetPulse } from '@/data/DataProvider'
+import { useAuth } from '@/data/AuthContext'
+
+const nodeTypes = { rack: RackNode, mount: MountNode }
+
+interface Working {
+  racks: RackDTO[]
+  mounts: MountDTO[]
+  cables: CableDTO[]
+  profiles: Map<string, ProfileDTO>
+  audit: Record<string, string>
+}
+
+let localSeq = 0
+const localId = (p: string) => `${p}-local-${++localSeq}`
+
+function RackCanvas() {
+  const { t } = useTranslation()
+  const np = useNetPulse()
+  const auth = useAuth()
+  const isAdmin = auth?.role === 'admin'
+
+  const [working, setWorking] = useState<Working>({ racks: [], mounts: [], cables: [], profiles: new Map(), audit: {} })
+  const [loaded, setLoaded] = useState(false)
+  const [activeRackId, setActiveRackId] = useState<string | null>(null)
+  const [patchMode, setPatchMode] = useState(false)
+  const [draft, setDraft] = useState<{ mountId: string; portId: string } | null>(null)
+  const [visibility, setVisibility] = useState<CableVisibility>('always')
+  const [hoverMountId, setHoverMountId] = useState<string | null>(null)
+  const [selectedCableId, setSelectedCableId] = useState<string | null>(null)
+  const [saving, setSaving] = useState(false)
+  const [addOpen, setAddOpen] = useState(false)
+  const [editOpen, setEditOpen] = useState(false)
+  const [editName, setEditName] = useState('')
+  const [editU, setEditU] = useState('12')
+  const [editLocation, setEditLocation] = useState('')
+  const [addName, setAddName] = useState('')
+  const [addU, setAddU] = useState('12')
+  const [addLocation, setAddLocation] = useState('')
+  const [deleteRackOpen, setDeleteRackOpen] = useState(false)
+  const [selectedMountId, setSelectedMountId] = useState<string | null>(null)
+  // Diálogo de colocación: se pregunta SIEMPRE (altura U; puertos si es
+  // patch panel), venga del picker por clic o por drag & drop.
+  const [mountAsk, setMountAsk] = useState<{
+    rackId: string
+    mac?: string
+    deviceType: string
+    label: string
+    faceplateId?: string
+    physicalPorts?: { id: string; kind: RackPortKind }[]
+    defaultU: number
+    isPatch: boolean
+    /** punto de drop en coords relativas al rack (coloca donde se soltó) */
+    dropRel?: { x: number; y: number }
+  } | null>(null)
+  const [askU, setAskU] = useState('1')
+  const [askPorts, setAskPorts] = useState('24')
+
+  // Dirty tracking (todo lo que Save debe persistir).
+  const [newMountIds, setNewMountIds] = useState<Set<string>>(new Set())
+  const [movedMountIds, setMovedMountIds] = useState<Set<string>>(new Set())
+  const [deletedMounts, setDeletedMounts] = useState<{ id: string; rackId: string }[]>([])
+  const [newCables, setNewCables] = useState<Set<string>>(new Set())
+  const [deletedCables, setDeletedCables] = useState<Set<string>>(new Set())
+  const [profileChanges, setProfileChanges] = useState<Map<string, ProfileDTO>>(new Map())
+  const [rackMoves, setRackMoves] = useState<Map<string, { x: number; y: number }>>(new Map())
+
+  const dirty =
+    newMountIds.size > 0 ||
+    movedMountIds.size > 0 ||
+    deletedMounts.length > 0 ||
+    newCables.size > 0 ||
+    deletedCables.size > 0 ||
+    profileChanges.size > 0 ||
+    rackMoves.size > 0
+
+  const draggingRef = useRef(false)
+  const { setViewport, screenToFlowPosition } = useReactFlow()
+
+  // Altura restante real de la ventana para el canvas: el contenido superior
+  // (header, toolbar, banner de avisos) es variable, un calc fijo se queda corto.
+  const canvasWrapRef = useRef<HTMLDivElement>(null)
+  const [canvasH, setCanvasH] = useState(560)
+  useEffect(() => {
+    const el = canvasWrapRef.current
+    if (!el) return
+    const update = () => setCanvasH(Math.max(320, window.innerHeight - el.getBoundingClientRect().top - 12))
+    update()
+    const t = setTimeout(update, 400)
+    window.addEventListener('resize', update)
+    return () => {
+      clearTimeout(t)
+      window.removeEventListener('resize', update)
+    }
+  }, [loaded, working.racks.length])
+
+  const fitCanvas = useCallback(() => {
+    const row = canvasWrapRef.current
+    if (!row || working.racks.length === 0) return
+    const W = row.clientWidth - 268 // aside w-64 + gap-3
+    const H = canvasH
+    let minX = Infinity
+    let minY = Infinity
+    let maxX = -Infinity
+    let maxY = -Infinity
+    for (const r of working.racks) {
+      const move = rackMoves.get(r.id)
+      const x = move?.x ?? r.position_x
+      const y = move?.y ?? r.position_y
+      minX = Math.min(minX, x)
+      minY = Math.min(minY, y)
+      maxX = Math.max(maxX, x + rackWidthPx())
+      maxY = Math.max(maxY, y + rackHeightPx(r.u_height))
+    }
+    const pad = 48
+    const bw = Math.max(1, maxX - minX)
+    const bh = Math.max(1, maxY - minY)
+    const zoom = Math.min(1, (W - pad) / bw, (H - pad) / bh)
+    setViewport({
+      x: (W - bw * zoom) / 2 - minX * zoom,
+      y: (H - bh * zoom) / 2 - minY * zoom,
+      zoom,
+    })
+  }, [working.racks, rackMoves, canvasH, setViewport])
+
+  // RF v12 añade la clase light/dark propia; sin colorMode el canvas cae en
+  // el tema claro y pisaría los tokens del app. Ligamos al tema real.
+  const [lightTheme, setLightTheme] = useState(() => document.documentElement.classList.contains('light'))
+  useEffect(() => {
+    const obs = new MutationObserver(() => setLightTheme(document.documentElement.classList.contains('light')))
+    obs.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] })
+    return () => obs.disconnect()
+  }, [])
+  const [nodes, setNodes, onNodesChange] = useNodesState<RackNodeType | MountNodeType>([])
+  const cancelRef = useRef(0)
+  // Última posición de drag (RF puede disparar dragStop con posición previa).
+  const dragPosRef = useRef<{ x: number; y: number } | null>(null)
+  // Posiciones actuales de los nodos rack (para hit-testing de drops y drags).
+  const rackPosRef = useRef<Map<string, { x: number; y: number }>>(new Map())
+  useEffect(() => {
+    const m = new Map<string, { x: number; y: number }>()
+    for (const n of nodes) {
+      if (n.type === 'rack') m.set(n.id.replace('rack-', ''), n.position)
+    }
+    rackPosRef.current = m
+  }, [nodes])
+
+  /** Rack cuyo rect contiene el punto (flow coords), con el punto relativo. */
+  const rackAtPoint = useCallback((x: number, y: number): { rack: RackDTO; relX: number; relY: number } | null => {
+    for (const r of working.racks) {
+      const pos = rackPosRef.current.get(r.id) ?? { x: r.position_x, y: r.position_y }
+      if (x >= pos.x && x <= pos.x + rackWidthPx() && y >= pos.y && y <= pos.y + rackHeightPx(r.u_height)) {
+        return { rack: r, relX: x - pos.x, relY: y - pos.y }
+      }
+    }
+    return null
+  }, [working.racks])
+  // Los nodos cargan asíncronos: fitView de init no los ve. Reenfocamos cada
+  // vez que cambia el número de nodos, con margen y sin pasar de escala 1.
+  // Encuadre determinista: calculamos el viewport desde el MODELO (posiciones
+  // de rack y tamaños conocidos), sin depender de la medición de RF ni de
+  // fitView con nodos asíncronos (race conocida: encuadres a escala 0.3).
+  useEffect(() => {
+    if (nodes.length === 0) return
+    const t1 = requestAnimationFrame(() => {
+      cancelRef.current = requestAnimationFrame(() => fitCanvas())
+    })
+    cancelRef.current = t1
+    return () => cancelAnimationFrame(cancelRef.current)
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [nodes.length, canvasH])
+
+
+  const reload = useCallback(async () => {
+    const b = await api.fetchRackBundle()
+    setWorking({
+      racks: b.racks,
+      mounts: b.mounts,
+      cables: b.cables,
+      profiles: new Map(b.profiles.map((p) => [p.mac, p])),
+      audit: b.audit ?? {},
+    })
+    setNewMountIds(new Set())
+    setMovedMountIds(new Set())
+    setDeletedMounts([])
+    setNewCables(new Set())
+    setDeletedCables(new Set())
+    setProfileChanges(new Map())
+    setRackMoves(new Map())
+    setDraft(null)
+    setSelectedCableId(null)
+    setLoaded(true)
+    // Rack activo por defecto: descubrible el botón Eliminar y el destino de
+    // los montajes del picker sin necesidad de un clic previo.
+    setActiveRackId((cur) => (cur && b.racks.some((r) => r.id === cur) ? cur : b.racks[0]?.id ?? null))
+  }, [])
+
+  useEffect(() => {
+    reload().catch((e) => toast.error(String(e)))
+  }, [reload])
+
+  // --- Modelo derivado ---
+  const deviceByMac = useMemo(() => new Map(np.devices.map((d) => [d.mac.toLowerCase(), d])), [np.devices])
+  const rackById = useMemo(() => new Map(working.racks.map((r) => [r.id, r])), [working.racks])
+  const mountById = useMemo(() => new Map(working.mounts.map((m) => [m.id, m])), [working.mounts])
+
+  const plateFor = useCallback(
+    (m: MountDTO) => {
+      if (m.device_mac) {
+        const prof = working.profiles.get(m.device_mac)
+        const plate = getFaceplate(prof?.faceplate_id || m.faceplate_id || '')
+        if (plate) return plate
+        // Perfil placeholder/vacío: sugerimos por el tipo detectado del
+        // dispositivo (un switch nunca debe quedarse sin bocas LAN).
+        const devType = deviceByMac.get(m.device_mac.toLowerCase())?.type ?? ''
+        return suggestFaceplate(devType) ?? getFaceplate('blank-1u')!
+      }
+      return getFaceplate(m.faceplate_id || 'blank-1u') || getFaceplate('blank-1u')!
+    },
+    [working.profiles, deviceByMac],
+  )
+
+  const portsFor = useCallback(
+    (m: MountDTO) => {
+      const plate = plateFor(m)
+      if (m.device_mac) {
+        const declared = working.profiles.get(m.device_mac)?.ports
+        if (declared && declared.length > 0) {
+          // Sanado de layouts legacy: si las bocas declaradas invaden la
+          // zona de la etiqueta de su plantilla, se re-disponen con la zona
+          // correcta (p. ej. perfiles creados antes de la zona por plantilla).
+          const zone = plate.portZone ?? { xStart: 0.24, xEnd: 0.94 }
+          const minX = Math.min(...declared.map((p) => p.x))
+          if (minX < zone.xStart - 0.02) {
+            return layoutPhysicalPorts(
+              declared.map((p) => ({ id: p.id, kind: p.kind as RackPortKind })),
+              zone,
+            )
+          }
+          return declared
+        }
+        return seedPorts(plate)
+      }
+      return seedPorts(plate)
+    },
+    [working.profiles, plateFor],
+  )
+
+
+  const statusFor = useCallback(
+    (m: MountDTO): 'online' | 'offline' | 'unknown' => {
+      if (m.status_pin && m.status_pin !== 'auto') return m.status_pin as 'online' | 'offline' | 'unknown'
+      if (!m.device_mac) return 'unknown'
+      const d = deviceByMac.get(m.device_mac.toLowerCase())
+      if (!d) return 'unknown'
+      return d.online ? 'online' : 'offline'
+    },
+    [deviceByMac],
+  )
+
+  const footprintsOfRack = useCallback(
+    (rackId: string, excludeMountId?: string): Footprint[] =>
+      working.mounts
+        .filter((m) => m.rack_id === rackId && m.id !== excludeMountId)
+        .map((m) => ({ uStart: m.u_start, uHeight: m.u_height, colStart: m.col_start, colSpan: m.col_span })),
+    [working.mounts],
+  )
+
+  const capacityFor = useCallback(
+    (m: MountDTO) => (plateFor(m).passThrough ? 2 : 1),
+    [plateFor],
+  )
+
+  const cablesOnPort = useCallback(
+    (mountId: string, portId: string) =>
+      working.cables.filter(
+        (c) =>
+          !deletedCables.has(c.id) &&
+          ((c.from_mount === mountId && c.from_port === portId) || (c.to_mount === mountId && c.to_port === portId)),
+      ),
+    [working.cables, deletedCables],
+  )
+
+  // --- Nodos ---
+  useEffect(() => {
+    if (!loaded) return
+    const ghostByRack = new Map<string, GhostState | null>()
+    const next: (RackNodeType | MountNodeType)[] = []
+    for (const r of working.racks) {
+      const move = rackMoves.get(r.id)
+      next.push({
+        id: `rack-${r.id}`,
+        type: 'rack',
+        position: move ?? { x: r.position_x, y: r.position_y },
+        draggable: true,
+        data: {
+          name: r.name,
+          location: r.location ?? '',
+          uHeight: r.u_height,
+          numbering: r.numbering,
+          selected: activeRackId === r.id,
+          ghost: ghostByRack.get(r.id) ?? null,
+          onSelect: () => {
+            setActiveRackId(r.id)
+            setSelectedMountId(null)
+            setSelectedCableId(null)
+          },
+        },
+      })
+    }
+    for (const m of working.mounts) {
+      const rack = rackById.get(m.rack_id)
+      if (!rack) continue
+      const plate = plateFor(m)
+      next.push({
+        id: `mount-${m.id}`,
+        type: 'mount',
+        parentId: `rack-${m.rack_id}`,
+        position: mountRelPos(rack.u_height, m.u_start, m.u_height, m.col_start),
+        draggable: true,
+        selectable: true,
+        style: { width: m.col_span * COL_PX, height: m.u_height * U_PX },
+        data: {
+          plate,
+          ports: portsFor(m),
+          label: m.label || deviceByMac.get(m.device_mac?.toLowerCase() ?? '')?.name || '',
+          color: m.device_mac ? working.profiles.get(m.device_mac)?.color || undefined : undefined,
+          status: statusFor(m),
+          selected: selectedMountId === m.id,
+          onSelect: () => setSelectedMountId((cur) => (cur === m.id ? null : m.id)),
+          onUnmount: isAdmin ? () => unmount(m.id) : undefined,
+          patchFacing:
+            plate.passThrough === true ||
+            plate.artwork === 'switch' ||
+            plate.artwork === 'router' ||
+            plate.artwork === 'panel' ||
+            plate.rows.reduce((n, r) => n + r.count, 0) >= 8,
+          portsVisible: patchMode || hoverMountId === m.id,
+          portState: (portId: string) => {
+            const cabled = cablesOnPort(m.id, portId).length > 0
+            const drafting = draft?.mountId === m.id && draft?.portId === portId
+            return { cabled, drafting, interactive: patchMode }
+          },
+          onPortClick: (portId: string) => handlePortClick(m.id, portId),
+          onPortEnter: () => setHoverMountId(m.id),
+          onPortLeave: () => setHoverMountId((h) => (h === m.id ? null : h)),
+        },
+      })
+    }
+    if (!draggingRef.current) setNodes(next)
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [loaded, working, activeRackId, patchMode, draft, rackMoves, deletedCables, hoverMountId, selectedMountId, isAdmin])
+
+  // handlePortClick se declara después; referencia estable vía ref.
+  const portClickRef = useRef<(mountId: string, portId: string) => void>(() => {})
+  const handlePortClick = useCallback(
+    (mountId: string, portId: string) => portClickRef.current(mountId, portId),
+    [],
+  )
+  useEffect(() => {
+    portClickRef.current = (mountId: string, portId: string) => {
+      if (!patchMode) return
+      if (!draft) {
+        setDraft({ mountId, portId })
+        return
+      }
+      if (draft.mountId === mountId && draft.portId === portId) {
+        setDraft(null)
+        return
+      }
+      const target = mountById.get(mountId)
+      if (!target) return
+      const busy = cablesOnPort(mountId, portId).length
+      if (busy >= capacityFor(target)) {
+        toast.error(t('rack.patchBusy'))
+        return
+      }
+      const c: CableDTO = {
+        id: localId('cable'),
+        from_mount: draft.mountId,
+        from_port: draft.portId,
+        to_mount: mountId,
+        to_port: portId,
+        type: 'ethernet',
+        origin: 'manual',
+        created_at: Date.now(),
+      }
+      setWorking((w) => ({ ...w, cables: [...w.cables, c] }))
+      setNewCables((s) => new Set(s).add(c.id))
+      setDraft(null)
+    }
+  }, [patchMode, draft, mountById, cablesOnPort, capacityFor, t])
+
+  // --- Drag & snap ---
+  const onNodeDrag = useCallback(
+    (_: unknown, node: (typeof nodes)[number]) => {
+      if (node.type !== 'mount') return
+      const mountId = node.id.replace('mount-', '')
+      const m = mountById.get(mountId)
+      const origRack = m && rackById.get(m.rack_id)
+      if (!m || !origRack) return
+      const origPos = rackPosRef.current.get(origRack.id) ?? { x: origRack.position_x, y: origRack.position_y }
+      dragPosRef.current = node.position
+      // El rack destino se decide por el CENTRO del montaje (el top-left
+      // puede quedar 6px fuera del rect con agarres centrales).
+      const absX = origPos.x + node.position.x
+      const absY = origPos.y + node.position.y
+      const absCx = absX + (m.col_span * COL_PX) / 2
+      const absCy = absY + (m.u_height * U_PX) / 2
+      const hit = rackAtPoint(absCx, absCy) ?? { rack: origRack, relX: node.position.x, relY: node.position.y }
+      const cell = relPosToCell(hit.rack.u_height, hit.relX, hit.relY, m.u_height)
+      const fp = findSlot(hit.rack.u_height, footprintsOfRack(hit.rack.id, mountId), cell.uStart, cell.colStart, m.u_height, m.col_span)
+      const ghost: GhostState | null = fp
+        ? { ...fp, valid: true }
+        : {
+            uStart: Math.min(Math.max(cell.uStart, 1), hit.rack.u_height - m.u_height + 1),
+            uHeight: m.u_height,
+            colStart: Math.min(Math.max(cell.colStart, 0), 12 - m.col_span),
+            colSpan: m.col_span,
+            valid: false,
+          }
+      setNodes((ns) =>
+        ns.map((n) =>
+          n.id === `rack-${hit.rack.id}` && n.type === 'rack'
+            ? { ...n, data: { ...n.data, ghost } }
+            : n,
+        ),
+      )
+    },
+    [mountById, rackById, footprintsOfRack, rackAtPoint, setNodes],
+  )
+
+  const onNodeDragStop = useCallback(
+    (_: unknown, node: (typeof nodes)[number]) => {
+      draggingRef.current = false
+      if (node.type === 'rack') {
+        const id = node.id.replace('rack-', '')
+        setRackMoves((m) => new Map(m).set(id, node.position))
+        return
+      }
+      if (node.type !== 'mount') return
+      const mountId = node.id.replace('mount-', '')
+      const m = mountById.get(mountId)
+      const origRack = m && rackById.get(m.rack_id)
+      if (!m || !origRack) return
+      const origPos = rackPosRef.current.get(origRack.id) ?? { x: origRack.position_x, y: origRack.position_y }
+      const pos = dragPosRef.current ?? node.position
+      dragPosRef.current = null
+      const absX = origPos.x + pos.x
+      const absY = origPos.y + pos.y
+      const absCx = absX + (m.col_span * COL_PX) / 2
+      const absCy = absY + (m.u_height * U_PX) / 2
+      const hit = rackAtPoint(absCx, absCy) ?? { rack: origRack, relX: pos.x, relY: pos.y }
+      const cell = relPosToCell(hit.rack.u_height, hit.relX, hit.relY, m.u_height)
+      const fp = findSlot(hit.rack.u_height, footprintsOfRack(hit.rack.id, mountId), cell.uStart, cell.colStart, m.u_height, m.col_span)
+      setNodes((ns) =>
+        ns.map((n) =>
+          n.id === `rack-${hit.rack.id}` && n.type === 'rack' ? { ...n, data: { ...n.data, ghost: null } } : n,
+        ),
+      )
+      if (!fp) {
+        toast.error(t('rack.noSpace'))
+        return
+      }
+      if (fp.uStart === m.u_start && fp.colStart === m.col_start && hit.rack.id === m.rack_id) return
+      // Entre racks el upsert MUEVE la fila (ON CONFLICT rack_id): los
+      // cables del montaje sobreviven; no hay delete en el origen.
+      setWorking((w) => ({
+        ...w,
+        mounts: w.mounts.map((mm) =>
+          mm.id === mountId ? { ...mm, rack_id: hit.rack.id, u_start: fp.uStart, col_start: fp.colStart } : mm,
+        ),
+      }))
+      if (!newMountIds.has(mountId)) setMovedMountIds((s) => new Set(s).add(mountId))
+    },
+    [mountById, rackById, footprintsOfRack, rackAtPoint, newMountIds, setNodes, t],
+  )
+
+  // --- Montar desde el picker ---
+  const mountAt = useCallback(
+    (rackId: string, fp: Footprint, partial: Omit<MountDTO, 'id' | 'rack_id' | 'u_start' | 'col_start' | 'status_pin' | 'port_visibility'>) => {
+      const m: MountDTO = {
+        ...partial,
+        id: localId('mount'),
+        rack_id: rackId,
+        u_start: fp.uStart,
+        col_start: fp.colStart,
+        status_pin: 'auto',
+        port_visibility: 'auto',
+      }
+      setWorking((w) => ({ ...w, mounts: [...w.mounts, m] }))
+      setNewMountIds((s) => new Set(s).add(m.id))
+      setActiveRackId(rackId)
+    },
+    [],
+  )
+
+  const prepareDeviceMount = useCallback(
+    (
+      mac: string,
+      deviceType: string,
+      label: string,
+      physicalPorts?: { id: string; kind: RackPortKind }[],
+      rackId?: string,
+      dropRel?: { x: number; y: number },
+    ) => {
+      const rid = rackId ?? activeRackId ?? working.racks[0]?.id
+      if (!rid || !rackById.get(rid)) {
+        toast.error(t('rack.emptyHint'))
+        return
+      }
+      const existing = working.profiles.get(mac)
+      // Sin sugerencia para el tipo detectado: faceplate genérico 1U (el
+      // usuario lo afina después); mejor eso que un placeholder sin puertos
+      // por el que el auto-cableado no puede parchar. Un perfil placeholder
+      // (faceplate vacío) también se sustituye por la sugerencia.
+      const plate =
+        (existing ? getFaceplate(existing.faceplate_id) : undefined) ??
+        suggestFaceplate(deviceType) ??
+        getFaceplate('server-1u')
+      const defU = existing?.u_height ?? plate?.uHeight ?? 1
+      setMountAsk({
+        rackId: rid,
+        mac,
+        deviceType,
+        label,
+        physicalPorts,
+        faceplateId: plate?.id ?? 'server-1u',
+        defaultU: defU,
+        isPatch: false,
+        dropRel,
+      })
+      setAskU(String(defU))
+    },
+    [activeRackId, working.racks, rackById, working.profiles, t],
+  )
+
+  const prepareAccessoryMount = useCallback(
+    (faceplateId: string, rackId?: string, dropRel?: { x: number; y: number }) => {
+      const rid = rackId ?? activeRackId ?? working.racks[0]?.id
+      const rack = rid ? rackById.get(rid) : undefined
+      const plate = getFaceplate(faceplateId)
+      if (!rack || !plate) {
+        toast.error(t('rack.emptyHint'))
+        return
+      }
+      const isPatch = plate.passThrough === true
+      setMountAsk({ rackId: rid!, deviceType: '', label: '', faceplateId, defaultU: plate.uHeight, isPatch, dropRel })
+      setAskU(String(plate.uHeight))
+      setAskPorts(faceplateId === 'patch-panel-12p' ? '12' : faceplateId === 'patch-panel-48p' ? '48' : '24')
+    },
+    [activeRackId, working.racks, rackById, t],
+  )
+
+  // Confirmación del diálogo: hueco final según la altura elegida y staging.
+  const commitMount = useCallback(() => {
+    const ask = mountAsk
+    if (!ask) return
+    const rack = rackById.get(ask.rackId)
+    if (!rack) return
+    // Patch panel: el nº de puertos elegido decide la variante del catálogo.
+    let faceplateId = ask.faceplateId ?? ''
+    let uHeight = Math.min(45, Math.max(1, parseInt(askU, 10) || ask.defaultU))
+    if (ask.isPatch) {
+      faceplateId = askPorts === '12' ? 'patch-panel-12p' : askPorts === '48' ? 'patch-panel-48p' : 'patch-panel-1u'
+      // La altura la impone la variante (48p = 2U).
+      uHeight = getFaceplate(faceplateId)?.uHeight ?? uHeight
+    }
+    const plate = getFaceplate(faceplateId)
+    const colSpan = plate?.colSpan ?? 12
+    // Coloca donde se soltó (snap al hueco libre más cercano a ese punto);
+    // sin punto de drop, el primer hueco libre desde abajo.
+    let dropU = 1
+    let dropCol = 0
+    if (ask.dropRel) {
+      const cell = relPosToCell(rack.u_height, ask.dropRel.x, ask.dropRel.y, uHeight)
+      dropU = cell.uStart
+      dropCol = cell.colStart
+    }
+    const fp = findSlot(rack.u_height, footprintsOfRack(rack.id), dropU, dropCol, uHeight, colSpan)
+    if (!fp) {
+      toast.error(t('rack.noSpace'))
+      return
+    }
+    if (ask.mac) {
+      const existing = working.profiles.get(ask.mac)
+      if (plate && (!existing || (existing.ports.length === 0 && !existing.faceplate_id) || existing.u_height !== uHeight)) {
+        const prof: ProfileDTO = {
+          mac: ask.mac,
+          faceplate_id: plate.id,
+          u_height: uHeight,
+          col_span: colSpan,
+          color: '',
+          // Bocas físicas reales cuando el poller las conoce (flota);
+          // si no, la plantilla siembra las típicas. La zona horizontal
+          // viene de la plantilla para no pisar la etiqueta.
+          ports:
+            ask.physicalPorts && ask.physicalPorts.length > 0
+              ? layoutPhysicalPorts(ask.physicalPorts, plate.portZone)
+              : seedPorts(plate),
+        }
+        setProfileChanges((pm) => new Map(pm).set(ask.mac!, prof))
+        setWorking((w) => ({ ...w, profiles: new Map(w.profiles).set(ask.mac!, prof) }))
+      }
+    }
+    mountAt(rack.id, fp, {
+      device_mac: ask.mac ?? '',
+      faceplate_id: faceplateId,
+      u_height: uHeight,
+      col_span: colSpan,
+      label: ask.label,
+    })
+    setMountAsk(null)
+  }, [mountAsk, askU, askPorts, rackById, footprintsOfRack, working.profiles, mountAt, t])
+
+  // Los routers de flota traen sus bocas reales del poller (extras.ethPorts).
+  const mountRouter = useCallback(
+    async (router: { id: string; mac?: string; name: string }, rackId?: string, dropRel?: { x: number; y: number }) => {
+      if (!router.mac) return
+      let physical: { id: string; kind: RackPortKind }[] | undefined
+      try {
+        const res = await fetch(`/api/routers/${encodeURIComponent(router.id)}`)
+        if (res.ok) {
+          const detail = await res.json()
+          const eth: { id?: string; iface?: string; name?: string }[] = detail?.extras?.ethPorts ?? []
+          physical = eth
+            .map((p) => p.id || p.iface || p.name || '')
+            .filter((id) => id && !id.startsWith('wlan'))
+            .map((id) => {
+              const k = /sfp\+|10g|fiber|fibre/i.test(id) ? 'sfp+' : /sfp/i.test(id) ? 'sfp' : 'rj45'
+              return { id, kind: k as RackPortKind }
+            })
+        }
+      } catch {
+        physical = undefined
+      }
+      prepareDeviceMount(router.mac, 'router', router.name, physical, rackId, dropRel)
+    },
+    [prepareDeviceMount],
+  )
+
+  // --- Rack ops ---
+  const openAddRack = useCallback(() => {
+    setAddName(`Rack ${working.racks.length + 1}`)
+    setAddU('12')
+    setAddLocation('')
+    setAddOpen(true)
+  }, [working.racks.length])
+
+  const submitAddRack = useCallback(async () => {
+    // A la derecha del último rack para que nazcan separados visualmente.
+    const maxX = working.racks.reduce((acc, r) => Math.max(acc, (rackMoves.get(r.id)?.x ?? r.position_x) + rackWidthPx()), 0)
+    try {
+      const r = await api.createRack({
+        name: addName.trim() || 'Rack',
+        u_height: Math.min(45, Math.max(1, parseInt(addU, 10) || 12)),
+        location: addLocation.trim(),
+        position_x: working.racks.length === 0 ? 40 : maxX + 40,
+        position_y: 40,
+      })
+      setWorking((w) => ({ ...w, racks: [...w.racks, r] }))
+      setActiveRackId(r.id)
+      setAddOpen(false)
+    } catch (e) {
+      toast.error(String(e))
+    }
+  }, [working.racks, rackMoves, addName, addU, addLocation])
+
+  const openEditRack = useCallback(() => {
+    const r = activeRackId ? rackById.get(activeRackId) : undefined
+    if (!r) return
+    setEditName(r.name)
+    setEditU(String(r.u_height))
+    setEditLocation(r.location ?? '')
+    setEditOpen(true)
+  }, [activeRackId, rackById])
+
+  const submitEditRack = useCallback(async () => {
+    const r = activeRackId ? rackById.get(activeRackId) : undefined
+    if (!r) return
+    try {
+      await api.saveRack({
+        ...r,
+        name: editName.trim() || r.name,
+        u_height: Math.min(45, Math.max(1, parseInt(editU, 10) || r.u_height)),
+        location: editLocation.trim(),
+      })
+      toast.success(t('rack.rackUpdated'))
+      setEditOpen(false)
+      await reload()
+    } catch (e) {
+      toast.error(String(e))
+    }
+  }, [activeRackId, rackById, editName, editU, editLocation, reload, t])
+
+  const confirmDeleteRack = useCallback(async () => {
+    const rackId = activeRackId
+    if (!rackId) return
+    try {
+      await api.deleteRack(rackId)
+      toast.success(t('rack.rackDeleted'))
+      setDeleteRackOpen(false)
+      await reload()
+    } catch (e) {
+      toast.error(String(e))
+    }
+  }, [activeRackId, reload, t])
+
+  // --- Save explícito: nada persiste sin Save ---
+  const save = useCallback(async () => {
+    setSaving(true)
+    try {
+      for (const [id, pos] of rackMoves) {
+        const r = rackById.get(id)
+        if (r) await api.saveRack({ ...r, position_x: pos.x, position_y: pos.y })
+      }
+      const rackIds = new Set<string>()
+      for (const m of working.mounts) {
+        if (newMountIds.has(m.id) || movedMountIds.has(m.id)) rackIds.add(m.rack_id)
+      }
+      for (const d of deletedMounts) rackIds.add(d.rackId)
+      for (const rid of rackIds) {
+        const upsert = working.mounts.filter((m) => m.rack_id === rid && (newMountIds.has(m.id) || movedMountIds.has(m.id)))
+        const del = deletedMounts.filter((d) => d.rackId === rid).map((d) => d.id)
+        await api.saveLayout({ rack_id: rid, upsert, delete: del })
+      }
+      for (const [mac, prof] of profileChanges) {
+        await api.upsertProfile(mac, {
+          faceplate_id: prof.faceplate_id,
+          u_height: prof.u_height,
+          col_span: prof.col_span,
+          color: prof.color,
+          ports: prof.ports,
+        })
+      }
+      // Un cable persistido que toca un montaje borrado no se borra a pie:
+      // la cascada del layout (ON DELETE CASCADE) ya se lo llevó.
+      const deletedMountIds = new Set(deletedMounts.map((d) => d.id))
+      for (const cid of deletedCables) {
+        if (newCables.has(cid)) continue
+        const c = working.cables.find((cc) => cc.id === cid)
+        if (c && (deletedMountIds.has(c.from_mount) || deletedMountIds.has(c.to_mount))) continue
+        await api.deleteCable(cid).catch(() => undefined)
+      }
+      for (const c of working.cables) {
+        if (!newCables.has(c.id)) continue
+        if (deletedMountIds.has(c.from_mount) || deletedMountIds.has(c.to_mount)) continue
+        const created = await api.addCable({
+          from_mount: c.from_mount,
+          from_port: c.from_port,
+          to_mount: c.to_mount,
+          to_port: c.to_port,
+          type: c.type,
+          label: c.label,
+          properties: c.properties,
+          origin: c.origin,
+        })
+        setWorking((w) => ({ ...w, cables: w.cables.map((cc) => (cc.id === c.id ? created : cc)) }))
+      }
+      toast.success(t('rack.saved'))
+      await reload()
+      np.refresh()
+    } catch (e) {
+      toast.error(`${t('rack.saveFailed')}: ${String(e)}`)
+    } finally {
+      setSaving(false)
+    }
+  }, [working, rackById, rackMoves, newMountIds, movedMountIds, deletedMounts, profileChanges, deletedCables, newCables, reload, np, t])
+
+  // api.saveRack no existe aún: lo añadimos (UpdateRack endpoint ya existe en Go).
+  // Desmontar: el montaje sale del rack (staging); sus cables se descartan
+  // del working copy (al guardar, el layout borra el montaje y la cascada
+  // del server se lleva los cables).
+  // Refs para que el compiler pueda estabilizar el callback (deps de maps/sets).
+  const mountByIdRef = useRef<Map<string, MountDTO>>(new Map())
+  useEffect(() => {
+    mountByIdRef.current = mountById
+  }, [mountById])
+  const newMountIdsRef = useRef<Set<string>>(new Set())
+  useEffect(() => {
+    newMountIdsRef.current = newMountIds
+  }, [newMountIds])
+
+  // Función plana (no useCallback): el compiler no logra preservar su
+  // memoización manual por las lecturas de ref; los consumidores usan ref.
+  const unmount = (mountId: string) => {
+      const m = mountByIdRef.current.get(mountId)
+      if (!m) return
+      setWorking((w) => ({
+        ...w,
+        mounts: w.mounts.filter((mm) => mm.id !== mountId),
+        cables: w.cables.filter((c) => c.from_mount !== mountId && c.to_mount !== mountId),
+      }))
+      if (newMountIdsRef.current.has(mountId)) {
+        setNewMountIds((prev) => {
+          const n = new Set(prev)
+          n.delete(mountId)
+          return n
+        })
+      } else {
+        setDeletedMounts((d) => [...d, { id: mountId, rackId: m.rack_id }])
+        setMovedMountIds((prev) => {
+          const n = new Set(prev)
+          n.delete(mountId)
+          return n
+        })
+      }
+      setSelectedMountId(null)
+      toast.success(t('rack.unmounted'))
+  }
+  const unmountRef = useRef(unmount)
+  useEffect(() => {
+    unmountRef.current = unmount
+  })
+
+  const runImport = useCallback(async () => {
+    if (dirty) {
+      toast.error(t('rack.importNeedsSave'))
+      return
+    }
+    try {
+      const res = await api.importCables()
+      toast.success(
+        t('rack.importResult', { created: res.created, skipped: res.skipped, noFree: res.noFreePort }),
+      )
+      await reload()
+    } catch (e) {
+      toast.error(String(e))
+    }
+  }, [dirty, reload, t])
+
+  // Drop desde el picker: punto en coords de flow, rack destino y diálogo
+  // de colocación (mismo flujo que el clic).
+  const onPickerDrop = useCallback(
+    (e: React.DragEvent) => {
+      e.preventDefault()
+      const raw = e.dataTransfer.getData(DND_MIME)
+      if (!raw) return
+      let payload: PickerDragPayload
+      try {
+        payload = JSON.parse(raw)
+      } catch {
+        return
+      }
+      const flow = screenToFlowPosition({ x: e.clientX, y: e.clientY })
+      const hit = rackAtPoint(flow.x, flow.y)
+      if (!hit) {
+        toast.error(t('rack.dropNoRack'))
+        return
+      }
+      const dropRel = { x: hit.relX, y: hit.relY }
+      if (payload.type === 'accessory' && payload.faceplateId) {
+        prepareAccessoryMount(payload.faceplateId, hit.rack.id, dropRel)
+      } else if (payload.type === 'router' && payload.routerId && payload.mac) {
+        void mountRouter({ id: payload.routerId, mac: payload.mac, name: payload.label ?? '' }, hit.rack.id, dropRel)
+      } else if (payload.type === 'device' && payload.mac) {
+        prepareDeviceMount(payload.mac, payload.deviceType ?? '', payload.label ?? '', undefined, hit.rack.id, dropRel)
+      }
+    },
+    [screenToFlowPosition, rackAtPoint, prepareAccessoryMount, mountRouter, prepareDeviceMount, t],
+  )
+
+  // --- Selección: montajes vía onSelectionChange; Delete gestiona cable o montaje ---
+  useEffect(() => {
+    const onKey = (e: KeyboardEvent) => {
+      if (e.key === 'Escape') {
+        setDraft(null)
+        setSelectedCableId(null)
+        setSelectedMountId(null)
+      }
+      if (e.key === 'Delete' || e.key === 'Backspace') {
+        if (selectedCableId) {
+          setDeletedCables((s) => new Set(s).add(selectedCableId))
+          setWorking((w) => ({ ...w, cables: w.cables.filter((c) => c.id !== selectedCableId) }))
+          setSelectedCableId(null)
+          toast.success(t('rack.cableDeleted'))
+        } else if (selectedMountId) {
+          unmountRef.current(selectedMountId)
+        }
+      }
+    }
+    window.addEventListener('keydown', onKey)
+    return () => window.removeEventListener('keydown', onKey)
+  }, [selectedCableId, selectedMountId, t])
+
+  // --- Cables: posiciones de puerto absolutas (flow coords) ---
+  const absPort = useCallback(
+    (mountId: string, portId: string): { x: number; y: number } | null => {
+      const m = mountById.get(mountId)
+      const rack = m && rackById.get(m.rack_id)
+      const rackNode = nodes.find((n) => n.id === `rack-${m?.rack_id}`)
+      if (!m || !rack || !rackNode) return null
+      const rel = mountRelPos(rack.u_height, m.u_start, m.u_height, m.col_start)
+      const p = portsFor(m).find((pp) => pp.id === portId)
+      if (!p) return null
+      return {
+        x: rackNode.position.x + rel.x + p.x * m.col_span * COL_PX,
+        y: rackNode.position.y + rel.y + p.y * m.u_height * U_PX,
+      }
+    },
+    [mountById, rackById, nodes, portsFor],
+  )
+
+  const cableVisible = useCallback(
+    (c: CableDTO) => {
+      if (c.id === selectedCableId) return true
+      if (patchMode || visibility === 'always') return true
+      if (visibility === 'hidden') return false
+      return c.from_mount === hoverMountId || c.to_mount === hoverMountId
+    },
+    [selectedCableId, patchMode, visibility, hoverMountId],
+  )
+
+  // --- Picker data ---
+  const mountedMacs = useMemo(
+    () => new Set(working.mounts.map((m) => m.device_mac?.toLowerCase() ?? '')),
+    [working.mounts],
+  )
+  // Solo cableados: el rack es físico; WiFi (2.4/5/6/60 GHz) queda fuera.
+  const unmountedDevices = useMemo(
+    () =>
+      // El rack es hardware de red: switches, servidores, ordenadores de
+      // torre y CCTV. Fuera TVs, altavoces, IoT y resto que no tenga sentido.
+      np.devices.filter(
+        (d) =>
+          !mountedMacs.has(d.mac.toLowerCase()) &&
+          (d.band === 'cable' || d.band === '—') &&
+          d.infra !== 'ct' &&
+          d.infra !== 'vm' &&
+          (['switch', 'servidor', 'ordenador', 'camara'].includes(d.type) ||
+            (d.type === 'desconocido' && d.name.toLowerCase() !== d.mac.toLowerCase())),
+      ),
+    [np.devices, mountedMacs],
+  )
+  const unmountedRouters = useMemo(
+    () => np.routers.filter((r) => r.mac && !mountedMacs.has(r.mac.toLowerCase())),
+    [np.routers, mountedMacs],
+  )
+  const accessoryPlates = useMemo(() => FACEPLATES.filter((p) => p.group === 'accessory'), [])
+
+  return (
+    <div className="flex h-full flex-col">
+      <SectionHeader title={t('rack.title')}>
+        <p className="mt-0.5 text-sm text-text-secondary">{t('rack.subtitle')}</p>
+      </SectionHeader>
+
+      {/* Toolbar */}
+      <div className="mt-3 flex flex-wrap items-center gap-2">
+        <button
+          type="button"
+          onClick={openAddRack}
+          disabled={!isAdmin}
+          className="flex h-9 items-center gap-1.5 rounded-xl border border-border bg-surface px-3 text-[13px] font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent disabled:opacity-50"
+        >
+          <Plus size={15} /> {t('rack.addRack')}
+        </button>
+        <button
+          type="button"
+          onClick={() => setPatchMode((p) => !p)}
+          disabled={!isAdmin}
+          aria-pressed={patchMode}
+          className={
+            'flex h-9 items-center gap-1.5 rounded-xl border px-3 text-[13px] font-medium transition-colors disabled:opacity-50 ' +
+            (patchMode ? 'border-accent/60 bg-accent/10 text-accent' : 'border-border bg-surface text-text-secondary hover:border-accent/40 hover:text-accent')
+          }
+        >
+          <Cable size={15} /> {t('rack.patch')}
+        </button>
+        <SegmentedControl<CableVisibility>
+          ariaLabel={t('rack.visibility')}
+          options={[
+            { value: 'hover', label: t('rack.visibilityHover') },
+            { value: 'always', label: t('rack.visibilityAlways') },
+            { value: 'hidden', label: t('rack.visibilityHidden') },
+          ]}
+          value={visibility}
+          onChange={setVisibility}
+          size="sm"
+        />
+        <button
+          type="button"
+          onClick={() => void runImport()}
+          disabled={!isAdmin}
+          className="flex h-9 items-center gap-1.5 rounded-xl border border-border bg-surface px-3 text-[13px] font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent disabled:opacity-50"
+        >
+          <Link2 size={15} /> {t('rack.import')}
+        </button>
+        <div className="ml-auto flex items-center gap-2">
+          {activeRackId && (
+            <button
+              type="button"
+              onClick={openEditRack}
+              disabled={!isAdmin}
+              className="flex h-9 items-center gap-1.5 rounded-xl border border-border bg-surface px-3 text-[13px] font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent disabled:opacity-50"
+            >
+              <Pencil size={15} /> {t('rack.editRack')}
+            </button>
+          )}
+          {activeRackId && (
+            <button
+              type="button"
+              onClick={() => setDeleteRackOpen(true)}
+              disabled={!isAdmin}
+              className="flex h-9 items-center gap-1.5 rounded-xl border border-border bg-surface px-3 text-[13px] font-medium text-text-secondary transition-colors hover:border-danger/50 hover:text-danger disabled:opacity-50"
+            >
+              <Trash2 size={15} /> {t('rack.deleteRack')}
+            </button>
+          )}
+          <button
+            type="button"
+            onClick={save}
+            disabled={!dirty || saving || !isAdmin}
+            className="flex h-9 items-center gap-1.5 rounded-xl bg-accent px-4 text-[13px] font-semibold text-black transition-opacity disabled:opacity-40"
+          >
+            <Save size={15} /> {saving ? t('rack.saving') : t('rack.save')}
+            {dirty && <span className="ml-0.5 inline-block h-1.5 w-1.5 rounded-full bg-black/70" aria-label={t('rack.unsaved')} />}
+          </button>
+        </div>
+      </div>
+
+      <div ref={canvasWrapRef} className="mt-3 flex gap-3" style={{ height: canvasH }}>
+        {/* Picker (izquierda, arrastrable al canvas) */}
+        <RackPicker
+          isAdmin={isAdmin}
+          unmountedRouters={unmountedRouters}
+          unmountedDevices={unmountedDevices}
+          accessoryPlates={accessoryPlates}
+          onRouter={(r) => void mountRouter(r)}
+          onDevice={(d) => prepareDeviceMount(d.mac, d.type, d.name)}
+          onAccessory={(id) => prepareAccessoryMount(id)}
+        />
+
+        {/* Canvas */}
+        <div className="relative min-w-0 flex-1 overflow-hidden rounded-xl border border-border bg-canvas">
+          {!loaded ? null : working.racks.length === 0 ? (
+            <div className="flex h-full flex-col items-center justify-center gap-3 text-text-secondary">
+              <Server size={32} className="opacity-40" />
+              <p className="text-sm">{t('rack.empty')}</p>
+              {isAdmin && (
+                <button
+                  type="button"
+                  onClick={openAddRack}
+                  className="flex h-9 items-center gap-1.5 rounded-xl bg-accent px-4 text-[13px] font-semibold text-black"
+                >
+                  <Plus size={15} /> {t('rack.addRack')}
+                </button>
+              )}
+            </div>
+          ) : (
+            <ReactFlow
+              nodes={nodes}
+              onNodesChange={onNodesChange}
+              onNodeDragStart={() => {
+                draggingRef.current = true
+              }}
+              onNodeDrag={onNodeDrag}
+              onNodeDragStop={onNodeDragStop}
+              nodeTypes={nodeTypes}
+              deleteKeyCode={null}
+              nodesConnectable={false}
+              elementsSelectable={false}
+              onPaneClick={() => {
+                setSelectedMountId(null)
+                setSelectedCableId(null)
+              }}
+              onDragOver={(e) => {
+                e.preventDefault()
+                e.dataTransfer.dropEffect = 'copy'
+              }}
+              onDrop={onPickerDrop}
+              minZoom={0.25}
+              maxZoom={2.5}
+              colorMode={lightTheme ? 'light' : 'dark'}
+              proOptions={{ hideAttribution: true }}
+            >
+              <Background variant={BackgroundVariant.Dots} gap={24} size={1} />
+              <ViewportPortal>
+                <svg
+                  data-testid="cables-layer"
+                  style={{ position: 'absolute', left: -10000, top: -10000, width: 20000, height: 20000, overflow: 'visible', pointerEvents: 'none' }}
+                >
+                  <g transform="translate(10000, 10000)" style={{ pointerEvents: 'all' }}>
+                  {working.cables.map((c) => {
+                    if (!cableVisible(c)) return null
+                    const a = absPort(c.from_mount, c.from_port)
+                    const b = absPort(c.to_mount, c.to_port)
+                    if (!a || !b) return null
+                    const sel = c.id === selectedCableId
+                    const audit = working.audit[c.id] ?? (c.origin === 'manual' ? 'manual-only' : 'detected')
+                    const manualOnly = audit === 'manual-only'
+                    const stroke = sel
+                      ? 'rgb(var(--accent))'
+                      : manualOnly
+                        ? 'rgb(var(--warn))'
+                        : c.type === 'fiber'
+                          ? 'rgb(var(--tunnel))'
+                          : 'rgb(var(--text-muted))'
+                    const mx = (a.x + b.x) / 2
+                    const my = (a.y + b.y) / 2
+                    return (
+                      <g key={c.id} data-cable-id={c.id} data-selected={sel} onClick={(e) => { e.stopPropagation(); setSelectedCableId(sel ? null : c.id) }} style={{ cursor: 'pointer' }}>
+                        <line x1={a.x} y1={a.y} x2={b.x} y2={b.y} stroke="transparent" strokeWidth={12} />
+                        <line
+                          x1={a.x}
+                          y1={a.y}
+                          x2={b.x}
+                          y2={b.y}
+                          stroke={stroke}
+                          strokeWidth={sel ? 2.5 : 1.5}
+                          strokeDasharray={manualOnly ? '6 4' : undefined}
+                        />
+                        {/* badge de auditoría: verde = confirmado por detección */}
+                        {audit === 'confirmed' && <circle cx={mx} cy={my} r={3} fill="rgb(var(--ok))" />}
+                      </g>
+                    )
+                  })}
+                  </g>
+                </svg>
+              </ViewportPortal>
+            </ReactFlow>
+          )}
+          {draft && (
+            <div className="pointer-events-none absolute bottom-3 left-1/2 -translate-x-1/2 rounded-lg border border-border bg-surface px-3 py-1.5 text-[12px] text-text-secondary">
+              {t('rack.drafting', { port: draft.portId })}
+            </div>
+          )}
+        </div>
+
+      </div>
+
+      {/* Diálogo de creación: nombre + altura U (los racks nuevos nacen a la
+          derecha del último, separados visualmente). */}
+      <Dialog open={addOpen} onOpenChange={setAddOpen}>
+        <DialogContent className="sm:max-w-sm">
+          <DialogHeader>
+            <DialogTitle>{t('rack.createTitle')}</DialogTitle>
+          </DialogHeader>
+          <div className="flex flex-col gap-3 py-2">
+            <div className="flex flex-col gap-1.5">
+              <Label htmlFor="rack-name">{t('rack.createName')}</Label>
+              <Input id="rack-name" value={addName} onChange={(e) => setAddName(e.target.value)} maxLength={40} />
+            </div>
+            <div className="flex flex-col gap-1.5">
+              <Label htmlFor="rack-u">{t('rack.createU')}</Label>
+              <Select value={addU} onValueChange={setAddU}>
+                <SelectTrigger id="rack-u" className="w-full">
+                  <SelectValue />
+                </SelectTrigger>
+                <SelectContent>
+                  {['6', '9', '12', '18', '24', '42'].map((u) => (
+                    <SelectItem key={u} value={u}>
+                      {u}U
+                    </SelectItem>
+                  ))}
+                </SelectContent>
+              </Select>
+            </div>
+            <div className="flex flex-col gap-1.5">
+              <Label htmlFor="rack-location">{t('rack.createLocation')}</Label>
+              <Input id="rack-location" value={addLocation} onChange={(e) => setAddLocation(e.target.value)} maxLength={60} placeholder={t('rack.locationPlaceholder')} />
+            </div>
+          </div>
+          <DialogFooter>
+            <button
+              type="button"
+              onClick={() => setAddOpen(false)}
+              className="h-9 rounded-xl border border-border px-4 text-[13px] font-medium text-text-secondary transition-colors hover:text-text-primary"
+            >
+              {t('rack.createCancel')}
+            </button>
+            <button
+              type="button"
+              onClick={() => void submitAddRack()}
+              className="h-9 rounded-xl bg-accent px-4 text-[13px] font-semibold text-black"
+            >
+              {t('rack.createSubmit')}
+            </button>
+          </DialogFooter>
+        </DialogContent>
+      </Dialog>
+
+      {/* Diálogo de colocación: altura U (y puertos en patch panels). */}
+      <Dialog open={mountAsk !== null} onOpenChange={(o) => !o && setMountAsk(null)}>
+        <DialogContent className="sm:max-w-sm">
+          <DialogHeader>
+            <DialogTitle>
+              {mountAsk?.isPatch ? t('rack.askTitlePatch') : t('rack.askTitle', { name: mountAsk?.label || t(getFaceplate(mountAsk?.faceplateId ?? '')?.nameKey ?? '') })}
+            </DialogTitle>
+          </DialogHeader>
+          <div className="flex flex-col gap-3 py-2">
+            {mountAsk?.isPatch && (
+              <div className="flex flex-col gap-1.5">
+                <Label htmlFor="ask-ports">{t('rack.askPorts')}</Label>
+                <Select
+                  value={askPorts}
+                  onValueChange={(v) => {
+                    setAskPorts(v)
+                    const variant = getFaceplate(v === '12' ? 'patch-panel-12p' : v === '48' ? 'patch-panel-48p' : 'patch-panel-1u')
+                    if (variant) setAskU(String(variant.uHeight))
+                  }}
+                >
+                  <SelectTrigger id="ask-ports" className="w-full">
+                    <SelectValue />
+                  </SelectTrigger>
+                  <SelectContent>
+                    {['12', '24', '48'].map((n) => (
+                      <SelectItem key={n} value={n}>
+                        {n}
+                      </SelectItem>
+                    ))}
+                  </SelectContent>
+                </Select>
+              </div>
+            )}
+            <div className="flex flex-col gap-1.5">
+              <Label htmlFor="ask-u">{t('rack.askHeight')}</Label>
+              <Input
+                id="ask-u"
+                type="number"
+                min={1}
+                max={45}
+                value={askU}
+                onChange={(e) => setAskU(e.target.value)}
+                className="w-full"
+              />
+            </div>
+          </div>
+          <DialogFooter>
+            <button
+              type="button"
+              onClick={() => setMountAsk(null)}
+              className="h-9 rounded-xl border border-border px-4 text-[13px] font-medium text-text-secondary transition-colors hover:text-text-primary"
+            >
+              {t('rack.createCancel')}
+            </button>
+            <button
+              type="button"
+              onClick={() => commitMount()}
+              className="h-9 rounded-xl bg-accent px-4 text-[13px] font-semibold text-black"
+            >
+              {t('rack.askPlace')}
+            </button>
+          </DialogFooter>
+        </DialogContent>
+      </Dialog>
+
+      {/* Edición de propiedades del rack activo (nombre + altura U). */}
+      <Dialog open={editOpen} onOpenChange={setEditOpen}>
+        <DialogContent className="sm:max-w-sm">
+          <DialogHeader>
+            <DialogTitle>{t('rack.editTitle')}</DialogTitle>
+          </DialogHeader>
+          <div className="flex flex-col gap-3 py-2">
+            <div className="flex flex-col gap-1.5">
+              <Label htmlFor="rack-edit-name">{t('rack.createName')}</Label>
+              <Input id="rack-edit-name" value={editName} onChange={(e) => setEditName(e.target.value)} maxLength={40} />
+            </div>
+            <div className="flex flex-col gap-1.5">
+              <Label htmlFor="rack-edit-u">{t('rack.createU')}</Label>
+              <Select value={editU} onValueChange={setEditU}>
+                <SelectTrigger id="rack-edit-u" className="w-full">
+                  <SelectValue />
+                </SelectTrigger>
+                <SelectContent>
+                  {['6', '9', '12', '18', '24', '42'].map((u) => (
+                    <SelectItem key={u} value={u}>
+                      {u}U
+                    </SelectItem>
+                  ))}
+                </SelectContent>
+              </Select>
+            </div>
+            <div className="flex flex-col gap-1.5">
+              <Label htmlFor="rack-edit-location">{t('rack.createLocation')}</Label>
+              <Input id="rack-edit-location" value={editLocation} onChange={(e) => setEditLocation(e.target.value)} maxLength={60} placeholder={t('rack.locationPlaceholder')} />
+            </div>
+          </div>
+          <DialogFooter>
+            <button
+              type="button"
+              onClick={() => setEditOpen(false)}
+              className="h-9 rounded-xl border border-border px-4 text-[13px] font-medium text-text-secondary transition-colors hover:text-text-primary"
+            >
+              {t('rack.createCancel')}
+            </button>
+            <button
+              type="button"
+              onClick={() => void submitEditRack()}
+              className="h-9 rounded-xl bg-accent px-4 text-[13px] font-semibold text-black"
+            >
+              {t('rack.editSubmit')}
+            </button>
+          </DialogFooter>
+        </DialogContent>
+      </Dialog>
+
+      {/* Confirmación in-app de borrado de rack (cascada incluida). */}
+      <AlertDialog open={deleteRackOpen} onOpenChange={setDeleteRackOpen}>
+        <AlertDialogContent>
+          <AlertDialogHeader>
+            <AlertDialogTitle>{t('rack.deleteTitle')}</AlertDialogTitle>
+            <AlertDialogDescription>{t('rack.deleteDesc', { name: rackById.get(activeRackId ?? '')?.name ?? '' })}</AlertDialogDescription>
+          </AlertDialogHeader>
+          <AlertDialogFooter>
+            <AlertDialogCancel>{t('rack.deleteCancel')}</AlertDialogCancel>
+            <AlertDialogAction onClick={() => void confirmDeleteRack()} className="bg-danger text-white hover:bg-danger/90">
+              {t('rack.deleteConfirm')}
+            </AlertDialogAction>
+          </AlertDialogFooter>
+        </AlertDialogContent>
+      </AlertDialog>
+    </div>
+  )
+}
+
+interface PickerDragPayload {
+  type: 'device' | 'router' | 'accessory'
+  mac?: string
+  routerId?: string
+  deviceType?: string
+  label?: string
+  faceplateId?: string
+}
+
+const DND_MIME = 'application/x-netpulse-rack'
+
+function RackPicker({
+  isAdmin,
+  unmountedRouters,
+  unmountedDevices,
+  accessoryPlates,
+  onRouter,
+  onDevice,
+  onAccessory,
+}: {
+  isAdmin: boolean
+  unmountedRouters: Router[]
+  unmountedDevices: { id: string; mac: string; type: string; name: string }[]
+  accessoryPlates: typeof FACEPLATES
+  onRouter: (r: Router) => void
+  onDevice: (d: { mac: string; type: string; name: string }) => void
+  onAccessory: (faceplateId: string) => void
+}) {
+  const { t } = useTranslation()
+  const dragStart = (payload: PickerDragPayload) => (e: React.DragEvent) => {
+    e.dataTransfer.setData(DND_MIME, JSON.stringify(payload))
+    e.dataTransfer.effectAllowed = 'copy'
+  }
+  return (
+    <aside className="hidden w-64 shrink-0 flex-col gap-4 overflow-y-auto rounded-xl border border-border bg-surface p-3 md:flex">
+      <p className="text-[12px] leading-snug text-text-secondary">{t('rack.pickHint')}</p>
+      <PickerGroup title={t('rack.pickFleet')}>
+        {unmountedRouters.map((r) => (
+          <PickerItem
+            key={r.id}
+            icon={<RouterIcon size={13} />}
+            label={r.name}
+            meta={r.modelShort || 'router'}
+            disabled={!isAdmin}
+            draggable={isAdmin}
+            onDragStart={dragStart({ type: 'router', routerId: r.id, mac: r.mac, label: r.name })}
+            onClick={() => onRouter(r)}
+          />
+        ))}
+      </PickerGroup>
+      <PickerGroup title={t('rack.pickDevice')}>
+        {unmountedDevices.length === 0 && <p className="text-[11px] text-text-muted">—</p>}
+        {unmountedDevices.slice(0, 60).map((d) => (
+          <PickerItem
+            key={d.id}
+            icon={<TypeIcon type={d.type} />}
+            label={d.name}
+            meta={d.type}
+            disabled={!isAdmin}
+            draggable={isAdmin}
+            onDragStart={dragStart({ type: 'device', mac: d.mac, deviceType: d.type, label: d.name })}
+            onClick={() => onDevice(d)}
+          />
+        ))}
+      </PickerGroup>
+      <PickerGroup title={t('rack.pickAccessory')}>
+        {accessoryPlates.map((p) => (
+          <PickerItem
+            key={p.id}
+            label={t(p.nameKey)}
+            meta={`${p.uHeight}U · ${p.colSpan}/12`}
+            disabled={!isAdmin}
+            draggable={isAdmin}
+            onDragStart={dragStart({ type: 'accessory', faceplateId: p.id })}
+            onClick={() => onAccessory(p.id)}
+          />
+        ))}
+      </PickerGroup>
+    </aside>
+  )
+}
+
+function TypeIcon({ type }: { type: string }) {
+  const cls = 'text-text-muted'
+  switch (type) {
+    case 'switch':
+      return <Network size={13} className={cls} aria-hidden />
+    case 'servidor':
+      return <Server size={13} className={cls} aria-hidden />
+    case 'ordenador':
+      return <Monitor size={13} className={cls} aria-hidden />
+    case 'camara':
+      return <Cctv size={13} className={cls} aria-hidden />
+    default:
+      return <Network size={13} className={cls} aria-hidden />
+  }
+}
+
+function PickerGroup({ title, children }: { title: string; children: React.ReactNode }) {
+  return (
+    <div>
+      <h3 className="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-text-muted">{title}</h3>
+      <div className="flex flex-col gap-1">{children}</div>
+    </div>
+  )
+}
+
+function PickerItem({
+  icon,
+  label,
+  meta,
+  onClick,
+  disabled,
+  draggable,
+  onDragStart,
+}: {
+  label: string
+  meta: string
+  onClick: () => void
+  disabled?: boolean
+  draggable?: boolean
+  onDragStart?: (e: React.DragEvent) => void
+  icon?: React.ReactNode
+}) {
+  return (
+    <button
+      type="button"
+      onClick={onClick}
+      disabled={disabled}
+      draggable={draggable}
+      onDragStart={onDragStart}
+      className="flex cursor-grab items-center justify-between gap-2 rounded-lg border border-border/60 px-2.5 py-1.5 text-left text-[13px] text-text-secondary transition-colors hover:border-accent/40 hover:text-accent active:cursor-grabbing disabled:opacity-50"
+    >
+      <span className="flex min-w-0 items-center gap-1.5">
+        {icon}
+        <span className="truncate">{label}</span>
+      </span>
+      <span className="shrink-0 text-[10px] uppercase text-text-muted">{meta}</span>
+    </button>
+  )
+}
+
+export default function Rack() {
+  return (
+    <ReactFlowProvider>
+      <RackCanvas />
+    </ReactFlowProvider>
+  )
+}

+ 1 - 0
app/vite.config.ts

@@ -54,6 +54,7 @@ export default defineConfig({
         ],
       },
       injectManifest: {
+      maximumFileSizeToCacheInBytes: 3.5 * 1024 * 1024,
         // App-shell precache (mismo glob que con generateSW: 16 entradas);
         // el fallback de navegación vive ahora en src/sw.ts (NavigationRoute)
         globPatterns: ['**/*.{js,css,html,svg,png,woff2}'],

+ 60 - 0
server-go/internal/db/db.go

@@ -400,6 +400,66 @@ CREATE TABLE IF NOT EXISTS alert_log (
 );
 CREATE INDEX IF NOT EXISTS idx_alert_log_ts ON alert_log(ts DESC);
 
+-- Rack canvas (fase 1): racks, montajes, cables y perfil físico por MAC.
+-- La identidad de dispositivo en NetPulse es la MAC (no hay tabla devices):
+-- rack_mounts.device_mac apunta a esa identidad y device_rack_profile guarda
+-- el modelo físico compartido (faceplate, altura U, span de columnas,
+-- color y puertos con posición). Los montajes con device_mac NULL son
+-- accesorios (blank, shelf, patch panel, PDU): su tamaño lo define el
+-- faceplate del catálogo.
+CREATE TABLE IF NOT EXISTS racks (
+  id TEXT PRIMARY KEY,
+  name TEXT NOT NULL,
+  u_height INTEGER NOT NULL,
+  width_standard TEXT NOT NULL DEFAULT '19',   -- '19' | '10'
+  numbering TEXT NOT NULL DEFAULT 'bottom-up', -- solo cambia etiquetas, nunca la geometría
+  style_json TEXT NOT NULL DEFAULT '{}',
+  location TEXT,
+  position_x REAL NOT NULL DEFAULT 0,
+  position_y REAL NOT NULL DEFAULT 0
+);
+
+CREATE TABLE IF NOT EXISTS device_rack_profile (
+  mac TEXT PRIMARY KEY,
+  faceplate_id TEXT NOT NULL DEFAULT '',
+  u_height INTEGER NOT NULL DEFAULT 1,
+  col_span INTEGER NOT NULL DEFAULT 12,
+  color TEXT NOT NULL DEFAULT '',
+  ports_json TEXT NOT NULL DEFAULT '[]'
+);
+
+CREATE TABLE IF NOT EXISTS rack_mounts (
+  id TEXT PRIMARY KEY,
+  rack_id TEXT NOT NULL REFERENCES racks(id) ON DELETE CASCADE,
+  device_mac TEXT REFERENCES device_rack_profile(mac) ON DELETE SET NULL, -- NULL = accesorio
+  faceplate_id TEXT NOT NULL DEFAULT '',  -- accesorios; el de dispositivos vive en device_rack_profile
+  u_start INTEGER NOT NULL,               -- 1-based, SIEMPRE contado desde el rail inferior
+  col_start INTEGER NOT NULL DEFAULT 0,   -- 0-based
+  label TEXT,
+  status_pin TEXT NOT NULL DEFAULT 'auto',      -- 'auto' → seguir el estado que conoce el poller
+  port_visibility TEXT NOT NULL DEFAULT 'auto'
+);
+CREATE INDEX IF NOT EXISTS idx_rack_mounts_rack ON rack_mounts(rack_id);
+
+-- Cables port-to-port (relación propia, no edges del canvas lógico).
+-- Pueden cruzar racks. Un puerto normal admite exactamente 1 cable; los
+-- patch panels (pass-through) admiten 2 (tirada de pared al rear + patch al
+-- switch al front). Cobre vs fibra se deriva del puerto de origen del patch.
+CREATE TABLE IF NOT EXISTS rack_cables (
+  id TEXT PRIMARY KEY,
+  from_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
+  from_port TEXT NOT NULL,
+  to_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
+  to_port TEXT NOT NULL,
+  type TEXT NOT NULL DEFAULT 'ethernet',       -- 'ethernet' | 'fiber'
+  label TEXT,
+  properties_json TEXT NOT NULL DEFAULT '{}',  -- key/value libre
+  origin TEXT NOT NULL DEFAULT 'manual',       -- 'manual' | 'imported' | 'detected'
+  created_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_rack_cables_from ON rack_cables(from_mount);
+CREATE INDEX IF NOT EXISTS idx_rack_cables_to ON rack_cables(to_mount);
+
 `
 
 // DB envuelve *sql.DB con los jobs y helpers de paridad.

+ 421 - 0
server-go/internal/httpapi/racks.go

@@ -0,0 +1,421 @@
+// racks.go — API REST del rack canvas bajo /api/racks (fase 1.5).
+//
+// Contrato wire en snake_case; el dominio (internal/rack) usa camelCase y el
+// mapper de este fichero es la frontera explícita entre ambos. Lecturas para
+// cualquier sesión (RequireAuth global); escrituras solo admin.
+package httpapi
+
+import (
+	"context"
+	"database/sql"
+	"errors"
+	"net/http"
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/rack"
+)
+
+func (s *server) registerRackRoutes(mux *http.ServeMux) {
+	if s.db == nil {
+		return
+	}
+	mux.HandleFunc("GET /api/racks", s.handleRacksGet)
+	mux.Handle("POST /api/racks", auth.RequireAdmin(http.HandlerFunc(s.handleRackCreate)))
+	mux.Handle("PUT /api/racks/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleRackUpdate)))
+	mux.Handle("DELETE /api/racks/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleRackDelete)))
+	mux.Handle("PUT /api/racks/layout", auth.RequireAdmin(http.HandlerFunc(s.handleRackLayoutPut)))
+	mux.Handle("POST /api/racks/cables", auth.RequireAdmin(http.HandlerFunc(s.handleRackCableAdd)))
+	mux.Handle("DELETE /api/racks/cables/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleRackCableDelete)))
+	mux.Handle("PUT /api/racks/profiles/{mac}", auth.RequireAdmin(http.HandlerFunc(s.handleRackProfilePut)))
+	mux.Handle("POST /api/racks/import-cables", auth.RequireAdmin(http.HandlerFunc(s.handleRackImportCables)))
+}
+
+// buildRackHints deriva candidatos de cable desde la DETECCIÓN (FDB): cada
+// dispositivo cableado cuya MAC y la de su router están montados genera un
+// hint con el puerto físico donde el bridge aprende su MAC. La fuente es el
+// descubrimiento, no el dibujo.
+func (s *server) buildRackHints(ctx context.Context, mounts []rack.MountRow) []rack.CableHint {
+	mounted := map[string]bool{}
+	for _, m := range mounts {
+		if m.DeviceMAC != "" {
+			mounted[strings.ToLower(m.DeviceMAC)] = true
+		}
+	}
+	routerMAC := map[string]string{}
+	routers := []adapters.Router{}
+	if ov := s.lastOv(); ov != nil {
+		for _, r := range ov.Routers {
+			if r.MAC != "" {
+				routerMAC[r.ID] = strings.ToLower(r.MAC)
+			}
+		}
+		routers = ov.Routers
+	}
+	// Honestidad de la inferencia: un puerto con VARIAS MACs aprendidas es un
+	// agregado (switch/bridge/hipervisor detrás); cablearlo a un dispositivo
+	// concreto sería inventar infraestructura. Solo los puertos de MAC única
+	// generan hint.
+	perPort := map[string]int{}
+	for _, d := range s.adapter.GetDevices(ctx) {
+		if d.Band != "cable" || d.MAC == "" || d.Port == "" {
+			continue
+		}
+		perPort[d.RouterID+"|"+d.Port]++
+	}
+	hints := []rack.CableHint{}
+	seen := map[string]bool{}
+	for _, d := range s.adapter.GetDevices(ctx) {
+		if d.Band != "cable" || d.MAC == "" || d.Port == "" {
+			continue
+		}
+		if perPort[d.RouterID+"|"+d.Port] != 1 {
+			continue
+		}
+		from, ok := routerMAC[d.RouterID]
+		if !ok || from == "" {
+			continue
+		}
+		to := strings.ToLower(d.MAC)
+		if !mounted[from] || !mounted[to] {
+			continue
+		}
+		if seen[from+"|"+to] {
+			continue
+		}
+		seen[from+"|"+to] = true
+		hints = append(hints, rack.CableHint{
+			FromDeviceID: from,
+			ToDeviceID:   to,
+			FromPortHint: d.Port,
+			Source:       "fdb",
+		})
+	}
+
+	// Uplinks entre miembros de flota montados: el FDB de cada router/switch
+	// aprende la MAC bridge de los demás miembros (rt3/rt4 en el switch,
+	// switch en el gateway). Es lo mismo que alimenta el mapa de topología.
+	for _, r := range routers {
+		if r.MAC == "" || !mounted[strings.ToLower(r.MAC)] {
+			continue
+		}
+		detail, err := s.adapter.GetRouterDetail(ctx, r.ID)
+		if err != nil {
+			continue
+		}
+		for _, ep := range detail.Ports {
+			peer := strings.ToLower(ep.DeviceMac)
+			if peer == "" || peer == strings.ToLower(r.MAC) || !mounted[peer] || peer == strings.ToLower(r.MAC) {
+				continue
+			}
+			if seen[strings.ToLower(r.MAC)+"|"+peer] || seen[peer+"|"+strings.ToLower(r.MAC)] {
+				continue
+			}
+			seen[strings.ToLower(r.MAC)+"|"+peer] = true
+			hints = append(hints, rack.CableHint{
+				FromDeviceID: strings.ToLower(r.MAC),
+				ToDeviceID:   peer,
+				FromPortHint: ep.Iface,
+				Source:       "fdb",
+			})
+		}
+	}
+	return hints
+}
+
+// --- DTOs (snake_case en el wire) ---
+
+type rackDTO struct {
+	ID            string  `json:"id"`
+	Name          string  `json:"name"`
+	UHeight       int     `json:"u_height"`
+	WidthStandard string  `json:"width_standard"`
+	Numbering     string  `json:"numbering"`
+	Style         string  `json:"style"`
+	Location      string  `json:"location,omitempty"`
+	PositionX     float64 `json:"position_x"`
+	PositionY     float64 `json:"position_y"`
+}
+
+type mountDTO struct {
+	ID             string `json:"id"`
+	RackID         string `json:"rack_id"`
+	DeviceMAC      string `json:"device_mac,omitempty"`
+	FaceplateID    string `json:"faceplate_id"`
+	UStart         int    `json:"u_start"`
+	UHeight        int    `json:"u_height"`
+	ColStart       int    `json:"col_start"`
+	ColSpan        int    `json:"col_span"`
+	Label          string `json:"label,omitempty"`
+	StatusPin      string `json:"status_pin"`
+	PortVisibility string `json:"port_visibility"`
+}
+
+type cableDTO struct {
+	ID         string `json:"id"`
+	FromMount  string `json:"from_mount"`
+	FromPort   string `json:"from_port"`
+	ToMount    string `json:"to_mount"`
+	ToPort     string `json:"to_port"`
+	Type       string `json:"type"`
+	Label      string `json:"label,omitempty"`
+	Properties string `json:"properties,omitempty"`
+	Origin     string `json:"origin"`
+	CreatedAt  int64  `json:"created_at"`
+}
+
+type profileDTO struct {
+	MAC         string      `json:"mac"`
+	FaceplateID string      `json:"faceplate_id"`
+	UHeight     int         `json:"u_height"`
+	ColSpan     int         `json:"col_span"`
+	Color       string      `json:"color"`
+	Ports       []rack.Port `json:"ports"`
+}
+
+func rackToDTO(r rack.Rack) rackDTO {
+	return rackDTO{
+		ID: r.ID, Name: r.Name, UHeight: r.UHeight, WidthStandard: r.WidthStandard,
+		Numbering: r.Numbering, Style: r.StyleJSON, Location: r.Location,
+		PositionX: r.PositionX, PositionY: r.PositionY,
+	}
+}
+
+func dtoToRack(d rackDTO) rack.Rack {
+	return rack.Rack{
+		ID: d.ID, Name: d.Name, UHeight: d.UHeight, WidthStandard: d.WidthStandard,
+		Numbering: d.Numbering, StyleJSON: d.Style, Location: d.Location,
+		PositionX: d.PositionX, PositionY: d.PositionY,
+	}
+}
+
+func mountRowToDTO(m rack.MountRow) mountDTO {
+	return mountDTO{
+		ID: m.ID, RackID: m.RackID, DeviceMAC: m.DeviceMAC, FaceplateID: m.FaceplateID,
+		UStart: m.UStart, UHeight: m.UHeight, ColStart: m.ColStart, ColSpan: m.ColSpan,
+		Label: m.Label, StatusPin: m.StatusPin, PortVisibility: m.PortVisibility,
+	}
+}
+
+func dtoToMount(d mountDTO) rack.Mount {
+	return rack.Mount{
+		ID: d.ID, RackID: d.RackID, DeviceMAC: d.DeviceMAC, FaceplateID: d.FaceplateID,
+		UStart: d.UStart, ColStart: d.ColStart,
+		Label: d.Label, StatusPin: d.StatusPin, PortVisibility: d.PortVisibility,
+	}
+}
+
+func cableToDTO(c rack.Cable) cableDTO {
+	return cableDTO{
+		ID: c.ID, FromMount: c.FromMount, FromPort: c.FromPort, ToMount: c.ToMount,
+		ToPort: c.ToPort, Type: c.Type, Label: c.Label, Properties: c.PropertiesJSON,
+		Origin: c.Origin, CreatedAt: c.CreatedAt,
+	}
+}
+
+func dtoToCable(d cableDTO) rack.Cable {
+	return rack.Cable{
+		ID: d.ID, FromMount: d.FromMount, FromPort: d.FromPort, ToMount: d.ToMount,
+		ToPort: d.ToPort, Type: d.Type, Label: d.Label, PropertiesJSON: d.Properties,
+		Origin: d.Origin, CreatedAt: d.CreatedAt,
+	}
+}
+
+func profileToDTO(p rack.DeviceProfile) profileDTO {
+	return profileDTO{
+		MAC: p.MAC, FaceplateID: p.FaceplateID, UHeight: p.UHeight,
+		ColSpan: p.ColSpan, Color: p.Color, Ports: p.Ports,
+	}
+}
+
+func dtoToProfile(d profileDTO) rack.DeviceProfile {
+	return rack.DeviceProfile{
+		MAC: d.MAC, FaceplateID: d.FaceplateID, UHeight: d.UHeight,
+		ColSpan: d.ColSpan, Color: d.Color, Ports: d.Ports,
+	}
+}
+
+// --- Handlers ---
+
+// handleRacksGet: bundle completo del canvas en una sola petición
+// (offline-first: racks + montajes con huella + cables + perfiles).
+func (s *server) handleRacksGet(w http.ResponseWriter, r *http.Request) {
+	racks, err := rack.ListRacks(s.db.DB)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "db_error", err.Error())
+		return
+	}
+	mounts, err := rack.ListMountRows(s.db.DB)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "db_error", err.Error())
+		return
+	}
+	cables, err := rack.ListCables(s.db.DB)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "db_error", err.Error())
+		return
+	}
+	profiles, err := rack.ListProfiles(s.db.DB)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "db_error", err.Error())
+		return
+	}
+	racksOut := make([]rackDTO, 0, len(racks))
+	for _, r := range racks {
+		racksOut = append(racksOut, rackToDTO(r))
+	}
+	mountsOut := make([]mountDTO, 0, len(mounts))
+	for _, m := range mounts {
+		mountsOut = append(mountsOut, mountRowToDTO(m))
+	}
+	cablesOut := make([]cableDTO, 0, len(cables))
+	for _, c := range cables {
+		cablesOut = append(cablesOut, cableToDTO(c))
+	}
+	profilesOut := make([]profileDTO, 0, len(profiles))
+	for _, p := range profiles {
+		profilesOut = append(profilesOut, profileToDTO(p))
+	}
+	// Auditoría dibujado vs detectado: cada cable lleva su estado.
+	hints := s.buildRackHints(r.Context(), mounts)
+	writeJSON(w, http.StatusOK, map[string]any{
+		"racks": racksOut, "mounts": mountsOut, "cables": cablesOut, "profiles": profilesOut,
+		"audit": rack.AuditCables(cables, hints, mounts),
+	})
+}
+
+// handleRackImportCables: siembra cables desde la topología detectada.
+// Idempotente por construcción: re-ejecutar solo hace la mitad útil.
+func (s *server) handleRackImportCables(w http.ResponseWriter, r *http.Request) {
+	mounts, err := rack.ListMountRows(s.db.DB)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "db_error", err.Error())
+		return
+	}
+	hints := s.buildRackHints(r.Context(), mounts)
+	res, err := rack.ImportCables(s.db.DB, hints)
+	if err != nil {
+		writeRackStoreError(w, err)
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{
+		"hints":      len(hints),
+		"created":    len(res.Created),
+		"skipped":    res.Skipped,
+		"noFreePort": len(res.NoFreePort),
+	})
+}
+
+func (s *server) handleRackCreate(w http.ResponseWriter, r *http.Request) {
+	var d rackDTO
+	if st := readJSONBody(w, r, &d); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	created, err := rack.CreateRack(s.db.DB, dtoToRack(d))
+	if err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_rack", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, rackToDTO(created))
+}
+
+func (s *server) handleRackUpdate(w http.ResponseWriter, r *http.Request) {
+	var d rackDTO
+	if st := readJSONBody(w, r, &d); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	d.ID = r.PathValue("id")
+	if err := rack.UpdateRack(s.db.DB, dtoToRack(d)); err != nil {
+		writeRackStoreError(w, err)
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+func (s *server) handleRackDelete(w http.ResponseWriter, r *http.Request) {
+	if err := rack.DeleteRack(s.db.DB, r.PathValue("id")); err != nil {
+		writeRackStoreError(w, err)
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+// handleRackLayoutPut: guardada atómica de montajes de un rack. Body:
+// {"rack_id": "...", "upsert": [mount...], "delete": ["id"...]}.
+func (s *server) handleRackLayoutPut(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		RackID string     `json:"rack_id"`
+		Upsert []mountDTO `json:"upsert"`
+		Delete []string   `json:"delete"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	if body.RackID == "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "rack_id is required")
+		return
+	}
+	change := rack.LayoutChange{RackID: body.RackID, Delete: body.Delete}
+	for _, d := range body.Upsert {
+		change.Upsert = append(change.Upsert, dtoToMount(d))
+	}
+	if err := rack.SaveLayout(s.db.DB, change); err != nil {
+		writeRackStoreError(w, err)
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+func (s *server) handleRackCableAdd(w http.ResponseWriter, r *http.Request) {
+	var d cableDTO
+	if st := readJSONBody(w, r, &d); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	created, err := rack.AddCable(s.db.DB, dtoToCable(d))
+	if err != nil {
+		writeRackStoreError(w, err)
+		return
+	}
+	writeJSON(w, http.StatusOK, cableToDTO(created))
+}
+
+func (s *server) handleRackCableDelete(w http.ResponseWriter, r *http.Request) {
+	if err := rack.DeleteCable(s.db.DB, r.PathValue("id")); err != nil {
+		writeRackStoreError(w, err)
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+func (s *server) handleRackProfilePut(w http.ResponseWriter, r *http.Request) {
+	var d profileDTO
+	if st := readJSONBody(w, r, &d); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	d.MAC = r.PathValue("mac")
+	if err := rack.UpsertProfile(s.db.DB, dtoToProfile(d)); err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_profile", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, profileToDTO(dtoToProfile(d)))
+}
+
+// writeRackStoreError mapea los errores del store a códigos HTTP estables.
+func writeRackStoreError(w http.ResponseWriter, err error) {
+	switch {
+	case errors.Is(err, rack.ErrOverlap), errors.Is(err, rack.ErrPortBusy):
+		writeError(w, http.StatusConflict, "conflict", err.Error())
+	case errors.Is(err, rack.ErrUnknownMount), errors.Is(err, sql.ErrNoRows):
+		writeError(w, http.StatusNotFound, "not_found", err.Error())
+	case errors.Is(err, rack.ErrUnknownPort):
+		writeError(w, http.StatusBadRequest, "unknown_port", err.Error())
+	default:
+		writeError(w, http.StatusInternalServerError, "db_error", err.Error())
+	}
+}

+ 3 - 0
server-go/internal/httpapi/server.go

@@ -538,6 +538,9 @@ func NewHandler(d Deps) http.Handler {
 	// --- Copias de seguridad (issue #158) ---
 	s.registerBackupRoutes(mux)
 
+	// --- Rack canvas (fase 1) ---
+	s.registerRackRoutes(mux)
+
 	// Avisos externos para todas las instancias (siempre: también en demo).
 	s.startAnnouncements()
 	s.registerAnnouncementRoutes(mux)

+ 39 - 0
server-go/internal/rack/faceplates.go

@@ -0,0 +1,39 @@
+package rack
+
+import "strings"
+
+// accessorySizes es el catálogo mínimo de accesorios (montajes sin
+// dispositivo): faceplate ID -> {altura U, span de columnas}. La fase 1.3
+// extenderá cada entrada a plantilla SVG con puertos sembrados; la
+// validación de montaje solo necesita tamaños. IDs desconocidos caen al
+// fallback 1U x ancho completo.
+var accessorySizes = map[string][2]int{
+	"blank-1u":         {1, 12},
+	"blank-2u":         {2, 12},
+	"blank-3u":         {3, 12},
+	"blank-half-1u":    {1, 6},
+	"shelf-1u":         {1, 12},
+	"cable-manager-1u": {1, 12},
+	"patch-panel-1u":   {1, 12},
+	"patch-panel-12p":  {1, 12},
+	"patch-panel-48p":  {2, 12},
+	"pdu-1u":           {1, 12},
+}
+
+// accessoryFallback: tamaño por defecto para faceplates ajenos al catálogo.
+var accessoryFallback = [2]int{1, 12}
+
+// AccessorySize devuelve la altura U y el span de columnas del accesorio.
+func AccessorySize(faceplateID string) (uHeight, colSpan int) {
+	if s, ok := accessorySizes[faceplateID]; ok {
+		return s[0], s[1]
+	}
+	return accessoryFallback[0], accessoryFallback[1]
+}
+
+// IsPassThrough marca los montajes pass-through (patch panels): su puerto
+// admite 2 cables (tirada de pared al rear + patch al switch al front) en
+// vez de 1.
+func IsPassThrough(faceplateID string) bool {
+	return strings.HasPrefix(faceplateID, "patch-panel")
+}

+ 100 - 0
server-go/internal/rack/geometry.go

@@ -0,0 +1,100 @@
+package rack
+
+// Footprint es la huella ocupada por un montaje en el grid del rack:
+// U 1-based desde el rail inferior, columnas 0-based.
+type Footprint struct {
+	UStart   int
+	UHeight  int
+	ColStart int
+	ColSpan  int
+}
+
+// Overlaps informa si dos huellas comparten alguna celda del grid.
+func Overlaps(a, b Footprint) bool {
+	return a.UStart < b.UStart+b.UHeight && b.UStart < a.UStart+a.UHeight &&
+		a.ColStart < b.ColStart+b.ColSpan && b.ColStart < a.ColStart+a.ColSpan
+}
+
+// FitsRack informa si la huella cabe dentro del grid del rack.
+func FitsRack(rackUHeight int, f Footprint) bool {
+	return f.UStart >= 1 && f.UHeight >= 1 && f.UStart+f.UHeight-1 <= rackUHeight &&
+		f.ColStart >= 0 && f.ColSpan >= 1 && f.ColStart+f.ColSpan <= RackColumns
+}
+
+// CanPlace informa si la huella candidata cabe en el rack y no se solapa con
+// ninguna huella existente. El servidor lo re-valida al guardar: dos montajes
+// solapados en el mismo rack nunca se persisten. existing debe EXCLUIR la
+// huella del montaje que se está moviendo (un drag sin cambio de sitio sigue
+// siendo válido).
+func CanPlace(rackUHeight int, existing []Footprint, cand Footprint) bool {
+	if !FitsRack(rackUHeight, cand) {
+		return false
+	}
+	for _, e := range existing {
+		if Overlaps(e, cand) {
+			return false
+		}
+	}
+	return true
+}
+
+// FindSlot aplica el snap del drop: busca primero en la U de destino y luego
+// camina hacia fuera (±1, ±2...). En cada U prueba primero la columna deseada
+// (clampada al grid) y luego el barrido de columnas de izquierda a derecha.
+// Si nada cabe, devuelve false y el caller muestra preview en rojo: un drop
+// imposible nunca colisiona en silencio.
+func FindSlot(rackUHeight int, existing []Footprint, dropU, dropCol, uHeight, colSpan int) (Footprint, bool) {
+	if uHeight < 1 || colSpan < 1 {
+		return Footprint{}, false
+	}
+	maxU := rackUHeight - uHeight + 1
+	maxCol := RackColumns - colSpan
+	if maxU < 1 || maxCol < 0 {
+		return Footprint{}, false
+	}
+	col := dropCol
+	if col < 0 {
+		col = 0
+	}
+	if col > maxCol {
+		col = maxCol
+	}
+	targetU := dropU
+	if targetU < 1 {
+		targetU = 1
+	}
+	if targetU > maxU {
+		targetU = maxU
+	}
+	for offset := 0; offset < rackUHeight; offset++ {
+		us := []int{targetU}
+		if offset > 0 {
+			us = []int{targetU - offset, targetU + offset}
+		}
+		for _, u := range us {
+			if u < 1 || u > maxU {
+				continue
+			}
+			if f, ok := tryAt(rackUHeight, existing, u, col, uHeight, colSpan); ok {
+				return f, true
+			}
+			for c := 0; c <= maxCol; c++ {
+				if c == col {
+					continue
+				}
+				if f, ok := tryAt(rackUHeight, existing, u, c, uHeight, colSpan); ok {
+					return f, true
+				}
+			}
+		}
+	}
+	return Footprint{}, false
+}
+
+func tryAt(rackUHeight int, existing []Footprint, u, c, uHeight, colSpan int) (Footprint, bool) {
+	f := Footprint{UStart: u, UHeight: uHeight, ColStart: c, ColSpan: colSpan}
+	if !CanPlace(rackUHeight, existing, f) {
+		return Footprint{}, false
+	}
+	return f, true
+}

+ 118 - 0
server-go/internal/rack/geometry_test.go

@@ -0,0 +1,118 @@
+package rack
+
+import "testing"
+
+func TestOverlaps(t *testing.T) {
+	full := Footprint{UStart: 5, UHeight: 1, ColStart: 0, ColSpan: 12}
+	cases := []struct {
+		name string
+		a, b Footprint
+		want bool
+	}{
+		{"idénticas", full, full, true},
+		{"U disjuntas", full, Footprint{UStart: 6, UHeight: 1, ColStart: 0, ColSpan: 12}, false},
+		{"columnas disjuntas misma U",
+			Footprint{UStart: 5, UHeight: 1, ColStart: 0, ColSpan: 6},
+			Footprint{UStart: 5, UHeight: 1, ColStart: 6, ColSpan: 6}, false},
+		{"solape parcial de columnas",
+			Footprint{UStart: 5, UHeight: 1, ColStart: 0, ColSpan: 6},
+			Footprint{UStart: 5, UHeight: 1, ColStart: 3, ColSpan: 6}, true},
+		{"adyacentes en U sin compartir celda",
+			Footprint{UStart: 5, UHeight: 2, ColStart: 0, ColSpan: 12},
+			Footprint{UStart: 7, UHeight: 1, ColStart: 0, ColSpan: 12}, false},
+	}
+	for _, tc := range cases {
+		if got := Overlaps(tc.a, tc.b); got != tc.want {
+			t.Errorf("%s: Overlaps = %v; want %v", tc.name, got, tc.want)
+		}
+	}
+}
+
+func TestCanPlace(t *testing.T) {
+	occupied := []Footprint{{UStart: 5, UHeight: 1, ColStart: 0, ColSpan: 6}}
+
+	if !CanPlace(42, nil, Footprint{UStart: 10, UHeight: 2, ColStart: 0, ColSpan: 12}) {
+		t.Error("colocación libre en rack vacío debe caber")
+	}
+	// Fuera del rack por arriba: U 42 + altura 2 en rack de 42U.
+	if CanPlace(42, nil, Footprint{UStart: 42, UHeight: 2, ColStart: 0, ColSpan: 12}) {
+		t.Error("huella que se sale por arriba del rack no debe caber")
+	}
+	// uStart 0 es inválido (1-based).
+	if CanPlace(42, nil, Footprint{UStart: 0, UHeight: 1, ColStart: 0, ColSpan: 12}) {
+		t.Error("uStart 0 no debe ser válido")
+	}
+	// Overflow de columnas.
+	if CanPlace(42, nil, Footprint{UStart: 1, UHeight: 1, ColStart: 6, ColSpan: 12}) {
+		t.Error("col_start 6 + span 12 excede las 12 columnas")
+	}
+	// Solape con la huella ocupada.
+	if CanPlace(42, occupied, Footprint{UStart: 5, UHeight: 1, ColStart: 3, ColSpan: 6}) {
+		t.Error("huella solapada con una existente no debe caber")
+	}
+	// La mitad libre de la U ocupada sí cabe.
+	if !CanPlace(42, occupied, Footprint{UStart: 5, UHeight: 1, ColStart: 6, ColSpan: 6}) {
+		t.Error("la mitad libre de una U compartida debe caber")
+	}
+}
+
+func TestFindSlot(t *testing.T) {
+	// Rack vacío: el drop cae en su sitio.
+	f, ok := FindSlot(42, nil, 10, 0, 1, 12)
+	if !ok || f.UStart != 10 || f.ColStart != 0 {
+		t.Errorf("rack vacío: got %+v ok=%v; want U10 col0", f, ok)
+	}
+
+	// Drop sobre la mitad ocupada de una U: snap a la mitad libre de la MISMA U.
+	occupied := []Footprint{{UStart: 10, UHeight: 1, ColStart: 0, ColSpan: 6}}
+	f, ok = FindSlot(42, occupied, 10, 0, 1, 6)
+	if !ok || f.UStart != 10 || f.ColStart != 6 {
+		t.Errorf("snap a mitad libre: got %+v ok=%v; want U10 col6", f, ok)
+	}
+
+	// U completamente ocupada: camina hacia fuera, primero hacia abajo.
+	occupied = []Footprint{{UStart: 10, UHeight: 1, ColStart: 0, ColSpan: 12}}
+	f, ok = FindSlot(42, occupied, 10, 0, 1, 12)
+	if !ok || f.UStart != 9 || f.ColStart != 0 {
+		t.Errorf("U ocupada: got %+v ok=%v; want U9 col0 (la más cercana)", f, ok)
+	}
+
+	// Drop fuera del grid: clamp a los límites del rack.
+	f, ok = FindSlot(42, nil, 99, 99, 1, 6)
+	if !ok || f.UStart != 42 || f.ColStart != 6 {
+		t.Errorf("clamp: got %+v ok=%v; want U42 col6", f, ok)
+	}
+
+	// Rack lleno: imposible, sin colisión silenciosa.
+	var full []Footprint
+	for u := 1; u <= 2; u++ {
+		full = append(full, Footprint{UStart: u, UHeight: 1, ColStart: 0, ColSpan: 12})
+	}
+	if _, ok := FindSlot(2, full, 1, 0, 1, 12); ok {
+		t.Error("rack lleno debe devolver ok=false")
+	}
+
+	// Dispositivo más alto que el rack.
+	if _, ok := FindSlot(1, nil, 1, 0, 2, 12); ok {
+		t.Error("dispositivo 2U en rack 1U debe devolver ok=false")
+	}
+}
+
+func TestRackValid(t *testing.T) {
+	valid := Rack{Name: "rack", UHeight: 12, WidthStandard: Width19, Numbering: NumBottomUp}
+	if !valid.Valid() {
+		t.Error("rack válido rechazado")
+	}
+	for _, mutate := range []func(*Rack){
+		func(r *Rack) { r.UHeight = 0 },
+		func(r *Rack) { r.Name = "" },
+		func(r *Rack) { r.WidthStandard = "24" },
+		func(r *Rack) { r.Numbering = "diagonal" },
+	} {
+		r := valid
+		mutate(&r)
+		if r.Valid() {
+			t.Errorf("rack inválido aceptado: %+v", r)
+		}
+	}
+}

+ 231 - 0
server-go/internal/rack/import.go

@@ -0,0 +1,231 @@
+// import.go - auto-cableado del rack desde la topología detectada (fase 2).
+//
+// La fuente es el descubrimiento (FDB/LLDP), no el dibujo: un CableHint
+// propone un cable entre dos dispositivos montados. ImportCables es
+// IDEMPOTENTE POR CONSTRUCCIÓN: un par de montajes ya cableado se salta (en
+// cualquier puerto); no hay flag "ya importado" que viva solo en memoria y
+// duplique cables tras un reload. Re-ejecutar tras montar más equipos hace
+// la mitad útil del trabajo.
+package rack
+
+import (
+	"database/sql"
+	"fmt"
+	"sort"
+	"strings"
+	"time"
+)
+
+// CableHint candidato de cable. From/To son MACs normalizadas; ambos
+// extremos deben estar montados para que el hint produzca cable.
+type CableHint struct {
+	FromDeviceID string
+	ToDeviceID   string
+	Medium       string // "ethernet" | "fiber" (vacío = se deriva del puerto)
+	FromPortHint string // ifName/ifDescr opcional (LLDP/SNMP)
+	ToPortHint   string
+	Source       string // "lldp" | "fdb" | "manual"
+}
+
+// ImportResult resume una pasada de importación.
+type ImportResult struct {
+	Created    []Cable
+	Skipped    int // par ya cableado o algún extremo no montado
+	NoFreePort []CableHint
+}
+
+// pairKey dedup por par NO ordenado: sort(a,b).join("|").
+func pairKey(a, b string) string {
+	p := []string{a, b}
+	sort.Strings(p)
+	return p[0] + "|" + p[1]
+}
+
+func normMac(m string) string { return strings.ToLower(strings.TrimSpace(m)) }
+
+// ImportCables crea cables para los hints cuyos extremos están montados.
+// Elección de puerto en dos niveles: primero uno libre cuyo tipo case con el
+// medio (fiber → sfp/sfp+, cobre → rj45); si no, cualquier puerto libre.
+// Sin puerto libre en algún extremo se reporta en NoFreePort (nunca se cae
+// en silencio). Todo en una transacción: fallo medio → ningún cable.
+func ImportCables(db *sql.DB, hints []CableHint) (ImportResult, error) {
+	mounts, err := ListMountRows(db)
+	if err != nil {
+		return ImportResult{}, err
+	}
+	mountByMac := map[string]MountRow{}
+	for _, m := range mounts {
+		if m.DeviceMAC != "" {
+			mountByMac[normMac(m.DeviceMAC)] = m
+		}
+	}
+	profiles := map[string]DeviceProfile{}
+	if profs, err := ListProfiles(db); err == nil {
+		for _, p := range profs {
+			profiles[normMac(p.MAC)] = p
+		}
+	}
+	existing, err := ListCables(db)
+	if err != nil {
+		return ImportResult{}, err
+	}
+
+	// Estado vivo: pares cableados y uso por puerto.
+	pairs := map[string]bool{}
+	usage := map[string]map[string]int{} // mountID -> portID -> cables
+	addUsage := func(mountID, portID string) {
+		if usage[mountID] == nil {
+			usage[mountID] = map[string]int{}
+		}
+		usage[mountID][portID]++
+	}
+	for _, c := range existing {
+		pairs[pairKey(c.FromMount, c.ToMount)] = true
+		addUsage(c.FromMount, c.FromPort)
+		addUsage(c.ToMount, c.ToPort)
+	}
+
+	capacity := func(m MountRow) int {
+		if m.DeviceMAC == "" && IsPassThrough(m.FaceplateID) {
+			return 2
+		}
+		return 1
+	}
+	free := func(m MountRow, portID string) bool {
+		return usage[m.ID][portID] < capacity(m)
+	}
+	mediumWantsFiber := func(medium string) bool { return medium == CableFiber }
+
+	// pickPort: 0) hint exacto libre (evidencia directa: LLDP/SNMP lo vio
+	// en ese puerto), 1) libre que case con el medio, 2) cualquier libre.
+	// hinted=true cuando ganó el hint exacto: el tipo de cable se deriva
+	// ENTONCES del puerto (la evidencia directa manda sobre el medio
+	// inferido).
+	pickPort := func(m MountRow, prof DeviceProfile, medium, hint string) (*Port, bool) {
+		ports := prof.Ports
+		if len(ports) == 0 {
+			return nil, false
+		}
+		if hint != "" {
+			for i := range ports {
+				if ports[i].ID == hint && free(m, ports[i].ID) {
+					return &ports[i], true
+				}
+			}
+		}
+		wantFiber := mediumWantsFiber(medium)
+		for i := range ports {
+			isFiber := ports[i].Kind != PortRJ45
+			if free(m, ports[i].ID) && isFiber == wantFiber {
+				return &ports[i], false
+			}
+		}
+		for i := range ports {
+			if free(m, ports[i].ID) {
+				return &ports[i], false
+			}
+		}
+		return nil, false
+	}
+
+	res := ImportResult{}
+	tx, err := db.Begin()
+	if err != nil {
+		return res, err
+	}
+	defer tx.Rollback()
+
+	for _, h := range hints {
+		ma, oka := mountByMac[normMac(h.FromDeviceID)]
+		mb, okb := mountByMac[normMac(h.ToDeviceID)]
+		if !oka || !okb || ma.ID == mb.ID {
+			res.Skipped++
+			continue
+		}
+		if pairs[pairKey(ma.ID, mb.ID)] {
+			res.Skipped++
+			continue
+		}
+		pa, hintedA := pickPort(ma, profiles[normMac(ma.DeviceMAC)], h.Medium, h.FromPortHint)
+		pb, _ := pickPort(mb, profiles[normMac(mb.DeviceMAC)], h.Medium, h.ToPortHint)
+		if pa == nil || pb == nil {
+			res.NoFreePort = append(res.NoFreePort, h)
+			continue
+		}
+		// Cobre vs fibra: si el puerto de origen salió de evidencia directa
+		// (hint), manda su tipo; si no, el medio declarado y por último el
+		// tipo del puerto de origen del patch.
+		medium := h.Medium
+		if hintedA || medium == "" {
+			medium = CableEthernet
+			if pa.Kind != PortRJ45 {
+				medium = CableFiber
+			}
+		}
+		origin := OriginDetected
+		if h.Source == OriginManual {
+			origin = OriginImported
+		}
+		c := Cable{
+			ID:        newID(),
+			FromMount: ma.ID,
+			FromPort:  pa.ID,
+			ToMount:   mb.ID,
+			ToPort:    pb.ID,
+			Type:      medium,
+			Origin:    origin,
+			CreatedAt: time.Now().UnixMilli(),
+		}
+		if _, err := tx.Exec(`INSERT INTO rack_cables (id, from_mount, from_port, to_mount, to_port, type, label, properties_json, origin, created_at)
+			VALUES (?, ?, ?, ?, ?, ?, NULL, '{}', ?, ?)`,
+			c.ID, c.FromMount, c.FromPort, c.ToMount, c.ToPort, c.Type, c.Origin, c.CreatedAt); err != nil {
+			return res, err
+		}
+		pairs[pairKey(ma.ID, mb.ID)] = true
+		addUsage(ma.ID, pa.ID)
+		addUsage(mb.ID, pb.ID)
+		res.Created = append(res.Created, c)
+	}
+	return res, tx.Commit()
+}
+
+// AuditStatus de un cable contra la detección actual.
+const (
+	AuditConfirmed  = "confirmed"   // detección actual confirma el par
+	AuditManualOnly = "manual-only" // dibujado a mano, sin evidencia
+	AuditDetected   = "detected"    // origin detectado/importado
+)
+
+// AuditCables marca cada cable: los origin!=manual son "detected"; los
+// "manual" cuyo par aparece en los hints actuales pasan a "confirmed"; el
+// resto queda "manual-only".
+func AuditCables(cables []Cable, hints []CableHint, mounts []MountRow) map[string]string {
+	mountByMac := map[string]MountRow{}
+	for _, m := range mounts {
+		if m.DeviceMAC != "" {
+			mountByMac[normMac(m.DeviceMAC)] = m
+		}
+	}
+	hintPairs := map[string]bool{}
+	for _, h := range hints {
+		ma, oka := mountByMac[normMac(h.FromDeviceID)]
+		mb, okb := mountByMac[normMac(h.ToDeviceID)]
+		if oka && okb {
+			hintPairs[pairKey(ma.ID, mb.ID)] = true
+		}
+	}
+	out := map[string]string{}
+	for _, c := range cables {
+		switch {
+		case c.Origin != OriginManual:
+			out[c.ID] = AuditDetected
+		case hintPairs[pairKey(c.FromMount, c.ToMount)]:
+			out[c.ID] = AuditConfirmed
+		default:
+			out[c.ID] = AuditManualOnly
+		}
+	}
+	return out
+}
+
+var _ = fmt.Sprintf // (placeholder si se añaden errores formateados)

+ 171 - 0
server-go/internal/rack/import_test.go

@@ -0,0 +1,171 @@
+package rack
+
+import (
+	"database/sql"
+	"testing"
+)
+
+// escenarioImport monta un switch (con sfps) y dos servidores, con un cable
+// manual previo entre switch y servidor1.
+func escenarioImport(t *testing.T, db *sql.DB) (MountRow, MountRow, MountRow) {
+	t.Helper()
+	rack := createTestRack(t, db)
+
+	sw := "aa:bb:cc:00:01:00"
+	s1 := "aa:bb:cc:00:01:01"
+	s2 := "aa:bb:cc:00:01:02"
+	if err := UpsertProfile(db, DeviceProfile{MAC: sw, FaceplateID: "switch", UHeight: 1, ColSpan: 12, Ports: []Port{
+		{ID: "lan1", Kind: PortRJ45}, {ID: "lan2", Kind: PortRJ45}, {ID: "sfp1", Kind: PortSFPPlus},
+	}}); err != nil {
+		t.Fatalf("UpsertProfile sw: %v", err)
+	}
+	for _, mac := range []string{s1, s2} {
+		if err := UpsertProfile(db, DeviceProfile{MAC: mac, FaceplateID: "server-1u", UHeight: 1, ColSpan: 12, Ports: []Port{
+			{ID: "eth0", Kind: PortRJ45}, {ID: "sfp0", Kind: PortSFPPlus},
+		}}); err != nil {
+			t.Fatalf("UpsertProfile %s: %v", mac, err)
+		}
+	}
+	err := SaveLayout(db, LayoutChange{RackID: rack.ID, Upsert: []Mount{
+		{DeviceMAC: sw, UStart: 1, ColStart: 0},
+		{DeviceMAC: s1, UStart: 2, ColStart: 0},
+		{DeviceMAC: s2, UStart: 3, ColStart: 0},
+	}})
+	if err != nil {
+		t.Fatalf("SaveLayout: %v", err)
+	}
+	mounts, err := ListMountRows(db)
+	if err != nil || len(mounts) != 3 {
+		t.Fatalf("ListMountRows: %v n=%d", err, len(mounts))
+	}
+	byMac := map[string]MountRow{}
+	for _, m := range mounts {
+		byMac[m.DeviceMAC] = m
+	}
+	return byMac[sw], byMac[s1], byMac[s2]
+}
+
+func TestImportCablesCreatesWithPortFallback(t *testing.T) {
+	db := openTestDB(t)
+	sw, s1, s2 := escenarioImport(t, db)
+
+	// Hint 1: evidencia directa (LLDP vio el puerto lan2, rj45): el port
+	// hint manda sobre el medio declarado "fiber" -> cable ETHERNET en lan2.
+	// Hint 2: fibra sin port hint: elige sfp1 (switch) y sfp0 (server).
+	res, err := ImportCables(db, []CableHint{
+		{FromDeviceID: sw.DeviceMAC, ToDeviceID: s1.DeviceMAC, Medium: CableFiber, FromPortHint: "lan2", Source: "lldp"},
+		{FromDeviceID: sw.DeviceMAC, ToDeviceID: s2.DeviceMAC, Medium: CableFiber, Source: "fdb"},
+	})
+	if err != nil {
+		t.Fatalf("ImportCables: %v", err)
+	}
+	if len(res.Created) != 2 || res.Skipped != 0 || len(res.NoFreePort) != 0 {
+		t.Fatalf("resultado: %+v", res)
+	}
+	ev := res.Created[0]
+	if ev.FromPort != "lan2" || ev.Type != CableEthernet {
+		t.Fatalf("el port hint (evidencia) debe mandar sobre el medio: %+v", ev)
+	}
+	fib := res.Created[1]
+	if fib.Type != CableFiber || fib.FromPort != "sfp1" || fib.ToPort != "sfp0" || fib.Origin != OriginDetected {
+		t.Fatalf("cable fibra: %+v", fib)
+	}
+	// Idempotencia por construcción: re-ejecutar salta los pares ya
+	// cableados (en cualquier puerto y en cualquier orden de hint).
+	res2, err := ImportCables(db, []CableHint{
+		{FromDeviceID: s1.DeviceMAC, ToDeviceID: sw.DeviceMAC, Source: "fdb"}, // orden invertido
+	})
+	if err != nil {
+		t.Fatalf("ImportCables 2: %v", err)
+	}
+	if len(res2.Created) != 0 || res2.Skipped != 1 {
+		t.Fatalf("no idempotente: %+v", res2)
+	}
+}
+
+func TestImportCablesNoFreePortAndUnmounted(t *testing.T) {
+	db := openTestDB(t)
+	sw, _, _ := escenarioImport(t, db)
+
+	// s3: un solo puerto, montado y agotado con un cable manual al switch.
+	s3 := "aa:bb:cc:00:01:03"
+	if err := UpsertProfile(db, DeviceProfile{MAC: s3, UHeight: 1, ColSpan: 12, Ports: []Port{{ID: "eth0", Kind: PortRJ45}}}); err != nil {
+		t.Fatalf("UpsertProfile s3: %v", err)
+	}
+	rackRows, err := ListMountRows(db)
+	if err != nil {
+		t.Fatalf("ListMountRows: %v", err)
+	}
+	rackID := rackRows[0].RackID
+	if err := SaveLayout(db, LayoutChange{RackID: rackID, Upsert: []Mount{{DeviceMAC: s3, UStart: 4, ColStart: 0}}}); err != nil {
+		t.Fatalf("SaveLayout s3: %v", err)
+	}
+	mS1 := mustMount(t, db, "aa:bb:cc:00:01:01")
+	mS3 := mustMount(t, db, s3)
+	// Agota el único puerto de s3 CONTRA OTRO PAR (s1): el par s3<->sw
+	// queda sin cable, pero s3 no tiene puerto libre -> NoFreePort.
+	if _, err := AddCable(db, Cable{FromMount: mS3.ID, FromPort: "eth0", ToMount: mS1.ID, ToPort: "eth0"}); err != nil {
+		t.Fatalf("AddCable: %v", err)
+	}
+
+	res, err := ImportCables(db, []CableHint{
+		{FromDeviceID: s3, ToDeviceID: sw.DeviceMAC, Source: "fdb"},                  // s3 sin puertos libres
+		{FromDeviceID: "cc:cc:cc:cc:cc:cc", ToDeviceID: sw.DeviceMAC, Source: "fdb"}, // no montado
+	})
+	if err != nil {
+		t.Fatalf("ImportCables: %v", err)
+	}
+	if len(res.NoFreePort) != 1 || res.Skipped != 1 || len(res.Created) != 0 {
+		t.Fatalf("esperaba 1 NoFreePort + 1 Skipped: %+v", res)
+	}
+}
+
+func mustMount(t *testing.T, db *sql.DB, mac string) MountRow {
+	t.Helper()
+	mounts, err := ListMountRows(db)
+	if err != nil {
+		t.Fatalf("ListMountRows: %v", err)
+	}
+	for _, m := range mounts {
+		if m.DeviceMAC == mac {
+			return m
+		}
+	}
+	t.Fatalf("montaje no encontrado para %s", mac)
+	return MountRow{}
+}
+
+func TestAuditCables(t *testing.T) {
+	db := openTestDB(t)
+	sw, s1, s2 := escenarioImport(t, db)
+	mSw, mS1 := mustMount(t, db, sw.DeviceMAC), mustMount(t, db, s1.DeviceMAC)
+
+	manual, err := AddCable(db, Cable{FromMount: mSw.ID, FromPort: "lan2", ToMount: mS1.ID, ToPort: "eth0"})
+	if err != nil {
+		t.Fatalf("AddCable: %v", err)
+	}
+	mounts, _ := ListMountRows(db)
+	cables, _ := ListCables(db)
+
+	// Sin hints: el manual es manual-only.
+	audit := AuditCables(cables, nil, mounts)
+	if audit[manual.ID] != AuditManualOnly {
+		t.Fatalf("sin hints: %v", audit[manual.ID])
+	}
+	// Con hint del par: pasa a confirmed.
+	audit = AuditCables(cables, []CableHint{{FromDeviceID: s1.DeviceMAC, ToDeviceID: sw.DeviceMAC, Source: "fdb"}}, mounts)
+	if audit[manual.ID] != AuditConfirmed {
+		t.Fatalf("con hint: %v", audit[manual.ID])
+	}
+	// Cable detectado: siempre detected. Y el par de s2 (sin cable) no
+	// afecta.
+	res, err := ImportCables(db, []CableHint{{FromDeviceID: s2.DeviceMAC, ToDeviceID: sw.DeviceMAC, Source: "fdb"}})
+	if err != nil || len(res.Created) != 1 {
+		t.Fatalf("import: %v %+v", err, res)
+	}
+	cables, _ = ListCables(db)
+	audit = AuditCables(cables, nil, mounts)
+	if audit[res.Created[0].ID] != AuditDetected || audit[manual.ID] != AuditManualOnly {
+		t.Fatalf("audit mixto: %+v", audit)
+	}
+}

+ 510 - 0
server-go/internal/rack/store.go

@@ -0,0 +1,510 @@
+// store.go — capa de persistencia del rack canvas sobre SQLite. Funciones
+// a nivel de paquete tomando *sql.DB (mismo patrón que topooverride).
+//
+// SaveLayout es la única escritura de montajes: atómica y con validación
+// anti-solape server-side sobre el estado final (el cliente valida para el
+// snap; el servidor es la última frontera: dos montajes solapados en el
+// mismo rack nunca se persisten).
+package rack
+
+import (
+	"crypto/rand"
+	"database/sql"
+	"encoding/hex"
+	"encoding/json"
+	"errors"
+	"fmt"
+)
+
+// ErrOverlap indica que el estado final del layout tiene dos montajes
+// solapados o fuera de rack.
+var ErrOverlap = errors.New("rack: montajes solapados o fuera de rack")
+
+// ErrPortBusy indica que el puerto ya tiene todos los cables que admite.
+var ErrPortBusy = errors.New("rack: puerto sin capacidad para otro cable")
+
+// ErrUnknownMount / ErrUnknownPort referencian montajes o puertos inexistentes.
+var ErrUnknownMount = errors.New("rack: montaje inexistente")
+
+// ErrUnknownPort indica un puerto que el dispositivo no declara en su perfil.
+var ErrUnknownPort = errors.New("rack: puerto no declarado por el dispositivo")
+
+func newID() string {
+	b := make([]byte, 8)
+	_, _ = rand.Read(b)
+	return hex.EncodeToString(b)
+}
+
+// --- Racks ---
+
+func ListRacks(db *sql.DB) ([]Rack, error) {
+	rows, err := db.Query(`SELECT id, name, u_height, width_standard, numbering, style_json, location, position_x, position_y
+		FROM racks ORDER BY position_y, position_x, name`)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	out := []Rack{}
+	for rows.Next() {
+		var r Rack
+		var loc sql.NullString
+		if err := rows.Scan(&r.ID, &r.Name, &r.UHeight, &r.WidthStandard, &r.Numbering, &r.StyleJSON, &loc, &r.PositionX, &r.PositionY); err != nil {
+			return nil, err
+		}
+		r.Location = loc.String
+		out = append(out, r)
+	}
+	return out, rows.Err()
+}
+
+// GetRack devuelve sql.ErrNoRows si no existe.
+func GetRack(db *sql.DB, id string) (Rack, error) {
+	var r Rack
+	var loc sql.NullString
+	err := db.QueryRow(`SELECT id, name, u_height, width_standard, numbering, style_json, location, position_x, position_y
+		FROM racks WHERE id = ?`, id).Scan(&r.ID, &r.Name, &r.UHeight, &r.WidthStandard, &r.Numbering, &r.StyleJSON, &loc, &r.PositionX, &r.PositionY)
+	r.Location = loc.String
+	return r, err
+}
+
+// CreateRack inserta un rack nuevo (id generado server-side) con defaults
+// aplicados y devuelve la fila creada.
+func CreateRack(db *sql.DB, in Rack) (Rack, error) {
+	in.ID = newID()
+	if in.WidthStandard == "" {
+		in.WidthStandard = Width19
+	}
+	if in.Numbering == "" {
+		in.Numbering = NumBottomUp
+	}
+	if in.StyleJSON == "" {
+		in.StyleJSON = "{}"
+	}
+	if !in.Valid() {
+		return Rack{}, fmt.Errorf("rack: rack inválido")
+	}
+	_, err := db.Exec(`INSERT INTO racks (id, name, u_height, width_standard, numbering, style_json, location, position_x, position_y)
+		VALUES (?, ?, ?, ?, ?, ?, NULLIF(?, ''), ?, ?)`,
+		in.ID, in.Name, in.UHeight, in.WidthStandard, in.Numbering, in.StyleJSON, in.Location, in.PositionX, in.PositionY)
+	return in, err
+}
+
+func UpdateRack(db *sql.DB, r Rack) error {
+	if !r.Valid() {
+		return fmt.Errorf("rack: rack inválido")
+	}
+	// Guarda: no reducir el rack por debajo de lo ya montado (la geometría
+	// quedaría fuera del grid; el anti-solape se valida al guardar layouts).
+	mounts, err := ListMountRowsByRack(db, r.ID)
+	if err != nil {
+		return err
+	}
+	for _, m := range mounts {
+		if bottom := m.UStart + m.UHeight - 1; bottom > r.UHeight {
+			return fmt.Errorf("%w: montaje %s ocupa hasta U%d (nuevo alto U%d)", ErrOverlap, m.ID, bottom, r.UHeight)
+		}
+	}
+	res, err := db.Exec(`UPDATE racks SET name = ?, u_height = ?, width_standard = ?, numbering = ?, style_json = ?, location = NULLIF(?, ''), position_x = ?, position_y = ? WHERE id = ?`,
+		r.Name, r.UHeight, r.WidthStandard, r.Numbering, r.StyleJSON, r.Location, r.PositionX, r.PositionY, r.ID)
+	if err != nil {
+		return err
+	}
+	return requireAffected(res)
+}
+
+// DeleteRack borra el rack; montajes y cables que cuelgan de ellos se van en
+// cascada (ON DELETE CASCADE).
+func DeleteRack(db *sql.DB, id string) error {
+	res, err := db.Exec(`DELETE FROM racks WHERE id = ?`, id)
+	if err != nil {
+		return err
+	}
+	return requireAffected(res)
+}
+
+// --- Perfiles físicos de dispositivo ---
+
+func ListProfiles(db *sql.DB) ([]DeviceProfile, error) {
+	rows, err := db.Query(`SELECT mac, faceplate_id, u_height, col_span, color, ports_json FROM device_rack_profile ORDER BY mac`)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	out := []DeviceProfile{}
+	for rows.Next() {
+		var p DeviceProfile
+		var ports string
+		if err := rows.Scan(&p.MAC, &p.FaceplateID, &p.UHeight, &p.ColSpan, &p.Color, &ports); err != nil {
+			return nil, err
+		}
+		p.Ports = parsePorts(ports)
+		out = append(out, p)
+	}
+	return out, rows.Err()
+}
+
+// GetProfile devuelve el perfil de una MAC; sql.ErrNoRows si no existe.
+func GetProfile(db *sql.DB, mac string) (DeviceProfile, error) {
+	var p DeviceProfile
+	var ports string
+	err := db.QueryRow(`SELECT mac, faceplate_id, u_height, col_span, color, ports_json FROM device_rack_profile WHERE mac = ?`, mac).
+		Scan(&p.MAC, &p.FaceplateID, &p.UHeight, &p.ColSpan, &p.Color, &ports)
+	if err != nil {
+		return DeviceProfile{}, err
+	}
+	p.Ports = parsePorts(ports)
+	return p, nil
+}
+
+// UpsertProfile crea o actualiza el modelo físico del dispositivo.
+func UpsertProfile(db *sql.DB, p DeviceProfile) error {
+	if p.MAC == "" {
+		return fmt.Errorf("rack: mac requerida")
+	}
+	if p.UHeight < 1 {
+		p.UHeight = 1
+	}
+	if p.ColSpan < 1 {
+		p.ColSpan = RackColumns
+	}
+	ports, err := json.Marshal(p.Ports)
+	if err != nil {
+		return err
+	}
+	_, err = db.Exec(`INSERT INTO device_rack_profile (mac, faceplate_id, u_height, col_span, color, ports_json)
+		VALUES (?, ?, ?, ?, ?, ?)
+		ON CONFLICT(mac) DO UPDATE SET faceplate_id = excluded.faceplate_id, u_height = excluded.u_height,
+			col_span = excluded.col_span, color = excluded.color, ports_json = excluded.ports_json`,
+		p.MAC, p.FaceplateID, p.UHeight, p.ColSpan, p.Color, string(ports))
+	return err
+}
+
+func parsePorts(s string) []Port {
+	if s == "" {
+		return []Port{}
+	}
+	var out []Port
+	if err := json.Unmarshal([]byte(s), &out); err != nil {
+		return []Port{}
+	}
+	if out == nil {
+		out = []Port{}
+	}
+	return out
+}
+
+// --- Montajes ---
+
+// MountRow es un montaje con su huella resuelta (del perfil del dispositivo
+// o del catálogo de accesorios). Es lo que el canvas necesita para dibujar.
+type MountRow struct {
+	Mount
+	UHeight int
+	ColSpan int
+}
+
+// Footprint devuelve la huella del montaje en el grid del rack.
+func (m MountRow) Footprint() Footprint {
+	return Footprint{UStart: m.UStart, UHeight: m.UHeight, ColStart: m.ColStart, ColSpan: m.ColSpan}
+}
+
+// ListMountRows devuelve todos los montajes de todos los racks con huella
+// resuelta.
+func ListMountRows(db *sql.DB) ([]MountRow, error) {
+	rows, err := db.Query(`SELECT m.id, m.rack_id, IFNULL(m.device_mac, ''), m.faceplate_id, m.u_start, m.col_start, m.label, m.status_pin, m.port_visibility,
+		p.u_height, p.col_span
+		FROM rack_mounts m LEFT JOIN device_rack_profile p ON p.mac = m.device_mac
+		ORDER BY m.rack_id, m.u_start DESC, m.col_start`)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	return scanMountRows(rows)
+}
+
+func ListMountRowsByRack(db *sql.DB, rackID string) ([]MountRow, error) {
+	rows, err := db.Query(`SELECT m.id, m.rack_id, IFNULL(m.device_mac, ''), m.faceplate_id, m.u_start, m.col_start, m.label, m.status_pin, m.port_visibility,
+		p.u_height, p.col_span
+		FROM rack_mounts m LEFT JOIN device_rack_profile p ON p.mac = m.device_mac
+		WHERE m.rack_id = ?
+		ORDER BY m.u_start DESC, m.col_start`, rackID)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	return scanMountRows(rows)
+}
+
+func scanMountRows(rows *sql.Rows) ([]MountRow, error) {
+	out := []MountRow{}
+	for rows.Next() {
+		var m MountRow
+		var devMAC, label sql.NullString
+		var profU, profC sql.NullInt64
+		if err := rows.Scan(&m.ID, &m.RackID, &devMAC, &m.FaceplateID, &m.UStart, &m.ColStart, &label, &m.StatusPin, &m.PortVisibility, &profU, &profC); err != nil {
+			return nil, err
+		}
+		m.DeviceMAC = devMAC.String
+		m.Label = label.String
+		if m.DeviceMAC != "" {
+			// Dispositivo: la huella la pone su perfil (la FK garantiza la
+			// fila; el COALESCE es defensa ante bajas directas).
+			m.UHeight, m.ColSpan = 1, RackColumns
+			if profU.Valid {
+				m.UHeight = int(profU.Int64)
+			}
+			if profC.Valid {
+				m.ColSpan = int(profC.Int64)
+			}
+		} else {
+			// Accesorio: la huella la pone el catálogo de faceplates.
+			m.UHeight, m.ColSpan = AccessorySize(m.FaceplateID)
+		}
+		out = append(out, m)
+	}
+	return out, rows.Err()
+}
+
+// LayoutChange es una guardada atómica de montajes de un rack: altas/cambios
+// por upsert + bajas por id. Todos los upserted quedan en RackID (un layout
+// se guarda por rack; mover a OTRO rack es un SaveLayout de destino).
+type LayoutChange struct {
+	RackID string
+	Upsert []Mount
+	Delete []string
+}
+
+// SaveLayout aplica el cambio en una transacción y valida el estado final:
+// cada montaje cabe en el rack y ningún par se solapa. Cualquier violación
+// revierte todo (ErrOverlap). Los montajes de dispositivo sin perfil crean
+// uno por defecto (1U x ancho completo) para satisfacer la FK.
+func SaveLayout(db *sql.DB, change LayoutChange) error {
+	if change.RackID == "" {
+		return fmt.Errorf("rack: rack_id requerido")
+	}
+	rack, err := GetRack(db, change.RackID)
+	if err != nil {
+		return err
+	}
+	tx, err := db.Begin()
+	if err != nil {
+		return err
+	}
+	defer tx.Rollback()
+
+	for _, id := range change.Delete {
+		if _, err := tx.Exec(`DELETE FROM rack_mounts WHERE id = ? AND rack_id = ?`, id, change.RackID); err != nil {
+			return err
+		}
+	}
+	for _, m := range change.Upsert {
+		m.RackID = change.RackID
+		if m.ID == "" {
+			m.ID = newID()
+		}
+		if m.StatusPin == "" {
+			m.StatusPin = StatusAuto
+		}
+		if m.PortVisibility == "" {
+			m.PortVisibility = "auto"
+		}
+		if m.DeviceMAC != "" {
+			// Perfil por defecto si el dispositivo aún no tiene: la FK lo exige.
+			if _, err := tx.Exec(`INSERT INTO device_rack_profile (mac) VALUES (?) ON CONFLICT(mac) DO NOTHING`, m.DeviceMAC); err != nil {
+				return err
+			}
+		}
+		if _, err := tx.Exec(`INSERT INTO rack_mounts (id, rack_id, device_mac, faceplate_id, u_start, col_start, label, status_pin, port_visibility)
+			VALUES (?, ?, NULLIF(?, ''), ?, ?, ?, NULLIF(?, ''), ?, ?)
+			ON CONFLICT(id) DO UPDATE SET rack_id = excluded.rack_id, device_mac = excluded.device_mac, faceplate_id = excluded.faceplate_id,
+				u_start = excluded.u_start, col_start = excluded.col_start, label = excluded.label,
+				status_pin = excluded.status_pin, port_visibility = excluded.port_visibility`,
+			m.ID, m.RackID, m.DeviceMAC, m.FaceplateID, m.UStart, m.ColStart, m.Label, m.StatusPin, m.PortVisibility); err != nil {
+			return err
+		}
+	}
+
+	// Validación del estado final: dentro de rack y sin solapes.
+	final, err := listMountRowsTx(tx, change.RackID)
+	if err != nil {
+		return err
+	}
+	if err := validateLayout(rack.UHeight, final); err != nil {
+		return err
+	}
+	return tx.Commit()
+}
+
+func listMountRowsTx(tx *sql.Tx, rackID string) ([]MountRow, error) {
+	rows, err := tx.Query(`SELECT m.id, m.rack_id, IFNULL(m.device_mac, ''), m.faceplate_id, m.u_start, m.col_start, m.label, m.status_pin, m.port_visibility,
+		p.u_height, p.col_span
+		FROM rack_mounts m LEFT JOIN device_rack_profile p ON p.mac = m.device_mac
+		WHERE m.rack_id = ?
+		ORDER BY m.u_start DESC, m.col_start`, rackID)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	return scanMountRows(rows)
+}
+
+// validateLayout comprueba que cada huella cabe en el rack y que ningún par
+// se solapa (O(n²) sobre ~docenas de montajes: sobra).
+func validateLayout(rackUHeight int, mounts []MountRow) error {
+	footprints := make([]Footprint, 0, len(mounts))
+	for _, m := range mounts {
+		f := m.Footprint()
+		if !FitsRack(rackUHeight, f) {
+			return fmt.Errorf("%w: montaje %s fuera de rack", ErrOverlap, m.ID)
+		}
+		footprints = append(footprints, f)
+	}
+	for i := range footprints {
+		for j := i + 1; j < len(footprints); j++ {
+			if Overlaps(footprints[i], footprints[j]) {
+				return fmt.Errorf("%w: montajes %s y %s", ErrOverlap, mounts[i].ID, mounts[j].ID)
+			}
+		}
+	}
+	return nil
+}
+
+// --- Cables ---
+
+func ListCables(db *sql.DB) ([]Cable, error) {
+	rows, err := db.Query(`SELECT id, from_mount, from_port, to_mount, to_port, type, label, properties_json, origin, created_at
+		FROM rack_cables ORDER BY created_at`)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	out := []Cable{}
+	for rows.Next() {
+		var c Cable
+		var label, props sql.NullString
+		if err := rows.Scan(&c.ID, &c.FromMount, &c.FromPort, &c.ToMount, &c.ToPort, &c.Type, &label, &props, &c.Origin, &c.CreatedAt); err != nil {
+			return nil, err
+		}
+		c.Label = label.String
+		c.PropertiesJSON = props.String
+		out = append(out, c)
+	}
+	return out, rows.Err()
+}
+
+// AddCable conecta dos puertos de dos montajes. Valida que los montajes
+// existan, que el puerto lo declare el dispositivo cuando su perfil tiene
+// puertos sembrados, y la capacidad del puerto: 1 cable (2 en pass-through
+// de patch panel).
+func AddCable(db *sql.DB, in Cable) (Cable, error) {
+	if in.FromMount == "" || in.ToMount == "" || in.FromPort == "" || in.ToPort == "" {
+		return Cable{}, fmt.Errorf("rack: from/to mount y port requeridos")
+	}
+	if in.Type == "" {
+		in.Type = CableEthernet
+	}
+	if in.Origin == "" {
+		in.Origin = OriginManual
+	}
+	if in.PropertiesJSON == "" {
+		in.PropertiesJSON = "{}"
+	}
+	if in.ID == "" {
+		in.ID = newID()
+	}
+	exists := func(id string) (bool, error) {
+		var n int
+		err := db.QueryRow(`SELECT COUNT(1) FROM rack_mounts WHERE id = ?`, id).Scan(&n)
+		return n > 0, err
+	}
+	ok, err := exists(in.FromMount)
+	if err != nil {
+		return Cable{}, err
+	}
+	if !ok {
+		return Cable{}, ErrUnknownMount
+	}
+	ok, err = exists(in.ToMount)
+	if err != nil {
+		return Cable{}, err
+	}
+	if !ok {
+		return Cable{}, ErrUnknownMount
+	}
+	for _, end := range [][2]string{{in.FromMount, in.FromPort}, {in.ToMount, in.ToPort}} {
+		if err := checkPortCapacity(db, end[0], end[1]); err != nil {
+			return Cable{}, err
+		}
+	}
+	_, err = db.Exec(`INSERT INTO rack_cables (id, from_mount, from_port, to_mount, to_port, type, label, properties_json, origin, created_at)
+		VALUES (?, ?, ?, ?, ?, ?, ?, NULLIF(?, ''), ?, ?)`,
+		in.ID, in.FromMount, in.FromPort, in.ToMount, in.ToPort, in.Type, in.Label, in.PropertiesJSON, in.Origin, in.CreatedAt)
+	return in, err
+}
+
+func DeleteCable(db *sql.DB, id string) error {
+	res, err := db.Exec(`DELETE FROM rack_cables WHERE id = ?`, id)
+	if err != nil {
+		return err
+	}
+	return requireAffected(res)
+}
+
+// checkPortCapacity valida que el puerto del montaje admita otro cable. Un
+// puerto normal admite exactamente 1; un puerto pass-through de patch panel
+// admite 2. Los dispositivos con puertos sembrados en su perfil rechazan IDs
+// de puerto que no declaren (los accesorios aún sin catálogo de puertos
+// aceptan cualquier ID).
+func checkPortCapacity(db *sql.DB, mountID, portID string) error {
+	var deviceMAC, faceplate sql.NullString
+	var ports string
+	err := db.QueryRow(`SELECT device_mac, faceplate_id,
+		COALESCE((SELECT ports_json FROM device_rack_profile p WHERE p.mac = m.device_mac), '')
+		FROM rack_mounts m WHERE m.id = ?`, mountID).Scan(&deviceMAC, &faceplate, &ports)
+	if err == sql.ErrNoRows {
+		return ErrUnknownMount
+	}
+	if err != nil {
+		return err
+	}
+	if deviceMAC.Valid {
+		declared := parsePorts(ports)
+		if len(declared) > 0 {
+			found := false
+			for _, p := range declared {
+				if p.ID == portID {
+					found = true
+					break
+				}
+			}
+			if !found {
+				return fmt.Errorf("%w: %s", ErrUnknownPort, portID)
+			}
+		}
+	}
+	capacity := 1
+	if faceplate.Valid && IsPassThrough(faceplate.String) {
+		capacity = 2
+	}
+	var n int
+	if err := db.QueryRow(`SELECT COUNT(1) FROM rack_cables
+		WHERE (from_mount = ? AND from_port = ?) OR (to_mount = ? AND to_port = ?)`,
+		mountID, portID, mountID, portID).Scan(&n); err != nil {
+		return err
+	}
+	if n+1 > capacity {
+		return fmt.Errorf("%w: %s/%s", ErrPortBusy, mountID, portID)
+	}
+	return nil
+}
+
+func requireAffected(res sql.Result) error {
+	n, err := res.RowsAffected()
+	if err != nil {
+		return err
+	}
+	if n == 0 {
+		return sql.ErrNoRows
+	}
+	return nil
+}

+ 286 - 0
server-go/internal/rack/store_test.go

@@ -0,0 +1,286 @@
+package rack
+
+import (
+	"database/sql"
+	"errors"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func openTestDB(t *testing.T) *sql.DB {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return d.DB
+}
+
+func createTestRack(t *testing.T, db *sql.DB) Rack {
+	t.Helper()
+	r, err := CreateRack(db, Rack{Name: "rack-test", UHeight: 12})
+	if err != nil {
+		t.Fatalf("CreateRack: %v", err)
+	}
+	return r
+}
+
+func TestRackCRUD(t *testing.T) {
+	db := openTestDB(t)
+
+	r, err := CreateRack(db, Rack{Name: "lab", UHeight: 24, WidthStandard: Width10, Numbering: NumTopDown, Location: "despacho"})
+	if err != nil {
+		t.Fatalf("CreateRack: %v", err)
+	}
+	if r.ID == "" || r.WidthStandard != Width10 {
+		t.Fatalf("rack creado incompleto: %+v", r)
+	}
+
+	got, err := GetRack(db, r.ID)
+	if err != nil || got.Name != "lab" || got.Location != "despacho" {
+		t.Fatalf("GetRack: %+v err=%v", got, err)
+	}
+
+	got.Name = "lab-2"
+	if err := UpdateRack(db, got); err != nil {
+		t.Fatalf("UpdateRack: %v", err)
+	}
+
+	list, err := ListRacks(db)
+	if err != nil || len(list) != 1 || list[0].Name != "lab-2" {
+		t.Fatalf("ListRacks: %+v err=%v", list, err)
+	}
+
+	if err := DeleteRack(db, r.ID); err != nil {
+		t.Fatalf("DeleteRack: %v", err)
+	}
+	if _, err := GetRack(db, r.ID); !errors.Is(err, sql.ErrNoRows) {
+		t.Fatalf("GetRack tras delete: err=%v", err)
+	}
+	// Update sobre id inexistente: ErrNoRows.
+	if err := UpdateRack(db, got); !errors.Is(err, sql.ErrNoRows) {
+		t.Fatalf("UpdateRack inexistente: err=%v", err)
+	}
+}
+
+func TestSaveLayoutAtomicAndOverlap(t *testing.T) {
+	db := openTestDB(t)
+	rack := createTestRack(t, db)
+
+	m1 := Mount{FaceplateID: "blank-half-1u", UStart: 1, ColStart: 0}
+	m2 := Mount{FaceplateID: "blank-half-1u", UStart: 1, ColStart: 6}
+	if err := SaveLayout(db, LayoutChange{RackID: rack.ID, Upsert: []Mount{m1, m2}}); err != nil {
+		t.Fatalf("SaveLayout mitades compartiendo U: %v", err)
+	}
+	rows, err := ListMountRows(db)
+	if err != nil || len(rows) != 2 {
+		t.Fatalf("ListMountRows: %d rows err=%v", len(rows), err)
+	}
+
+	// Tercera mitad en la misma U: solapa a una de las dos. Debe fallar y NO
+	// persistir nada (atomicidad).
+	m3 := Mount{UStart: 1, ColStart: 0, Label: "intruso"}
+	if err := SaveLayout(db, LayoutChange{RackID: rack.ID, Upsert: []Mount{m3}}); !errors.Is(err, ErrOverlap) {
+		t.Fatalf("SaveLayout solape: err=%v", err)
+	}
+	rows, _ = ListMountRows(db)
+	if len(rows) != 2 {
+		t.Fatalf("el layout rechazado persistió: %d rows", len(rows))
+	}
+
+	// Fuera del rack por arriba: perfil 2U en un rack de 12U con u_start 12.
+	tall := Mount{DeviceMAC: "aa:bb:cc:dd:ee:ff", UStart: 12, ColStart: 0}
+	if err := UpsertProfile(db, DeviceProfile{MAC: "aa:bb:cc:dd:ee:ff", UHeight: 2, ColSpan: 12}); err != nil {
+		t.Fatalf("UpsertProfile: %v", err)
+	}
+	if err := SaveLayout(db, LayoutChange{RackID: rack.ID, Upsert: []Mount{tall}}); !errors.Is(err, ErrOverlap) {
+		t.Fatalf("SaveLayout fuera de rack: err=%v", err)
+	}
+
+	// El montaje del dispositivo creó perfil por defecto; lo comprobamos con
+	// un dispositivo nuevo sin perfil.
+	noProfile := Mount{DeviceMAC: "11:22:33:44:55:66", UStart: 6, ColStart: 0}
+	if err := SaveLayout(db, LayoutChange{RackID: rack.ID, Upsert: []Mount{noProfile}}); err != nil {
+		t.Fatalf("SaveLayout dispositivo sin perfil: %v", err)
+	}
+	p, err := GetProfile(db, "11:22:33:44:55:66")
+	if err != nil || p.UHeight != 1 || p.ColSpan != 12 {
+		t.Fatalf("perfil por defecto no creado: %+v err=%v", p, err)
+	}
+
+	// Mover un montaje: upsert con id existente en otra posición.
+	rows, _ = ListMountRows(db)
+	var target string
+	for _, m := range rows {
+		if m.ColStart == 6 && m.UStart == 1 {
+			target = m.ID
+		}
+	}
+	if target == "" {
+		t.Fatal("montaje esperado no encontrado")
+	}
+	mv := Mount{ID: target, UStart: 3, ColStart: 0}
+	if err := SaveLayout(db, LayoutChange{RackID: rack.ID, Upsert: []Mount{mv}}); err != nil {
+		t.Fatalf("SaveLayout mover: %v", err)
+	}
+	rows, _ = ListMountRows(db)
+	moved := false
+	for _, m := range rows {
+		if m.ID == target && m.UStart == 3 {
+			moved = true
+		}
+	}
+	if !moved {
+		t.Fatal("el montaje no se movió")
+	}
+
+	// Borrado por id.
+	if err := SaveLayout(db, LayoutChange{RackID: rack.ID, Delete: []string{target}}); err != nil {
+		t.Fatalf("SaveLayout delete: %v", err)
+	}
+	rows, _ = ListMountRows(db)
+	if len(rows) != 2 {
+		t.Fatalf("tras delete hay %d rows; want 2", len(rows))
+	}
+}
+
+func TestUpdateRackGuardShrinkBelowMounted(t *testing.T) {
+	db := openTestDB(t)
+	rack := createTestRack(t, db)
+
+	// Montaje 2U con el fondo en U3.
+	m := Mount{DeviceMAC: "aa:bb:cc:dd:ee:f1", UStart: 2, ColStart: 0}
+	if err := UpsertProfile(db, DeviceProfile{MAC: "aa:bb:cc:dd:ee:f1", UHeight: 2, ColSpan: 12}); err != nil {
+		t.Fatalf("UpsertProfile: %v", err)
+	}
+	if err := SaveLayout(db, LayoutChange{RackID: rack.ID, Upsert: []Mount{m}}); err != nil {
+		t.Fatalf("SaveLayout: %v", err)
+	}
+
+	// Reducir a U2: el montaje llega hasta U3 -> debe rechazar.
+	rack.UHeight = 2
+	if err := UpdateRack(db, rack); !errors.Is(err, ErrOverlap) {
+		t.Fatalf("UpdateRack shrink: err=%v; want ErrOverlap", err)
+	}
+	// Ampliar a U24: válido.
+	rack.UHeight = 24
+	if err := UpdateRack(db, rack); err != nil {
+		t.Fatalf("UpdateRack grow: %v", err)
+	}
+}
+
+func TestProfileCRUD(t *testing.T) {
+	db := openTestDB(t)
+	p := DeviceProfile{
+		MAC: "aa:bb:cc:00:00:01", FaceplateID: "server-2u", UHeight: 2, ColSpan: 12,
+		Color: "#334455", Ports: []Port{{ID: "eth0", Kind: PortRJ45, X: 0.1, Y: 0.5}},
+	}
+	if err := UpsertProfile(db, p); err != nil {
+		t.Fatalf("UpsertProfile: %v", err)
+	}
+	got, err := GetProfile(db, p.MAC)
+	if err != nil {
+		t.Fatalf("GetProfile: %v", err)
+	}
+	if got.UHeight != 2 || len(got.Ports) != 1 || got.Ports[0].ID != "eth0" {
+		t.Fatalf("perfil redondeado mal: %+v", got)
+	}
+	// Upsert actualiza.
+	p.Color = "#000000"
+	if err := UpsertProfile(db, p); err != nil {
+		t.Fatalf("UpsertProfile update: %v", err)
+	}
+	got, _ = GetProfile(db, p.MAC)
+	if got.Color != "#000000" {
+		t.Fatalf("update no aplicado: %+v", got)
+	}
+	list, err := ListProfiles(db)
+	if err != nil || len(list) != 1 {
+		t.Fatalf("ListProfiles: %v err=%v", list, err)
+	}
+}
+
+func TestCablesCapacityAndCascade(t *testing.T) {
+	db := openTestDB(t)
+	rack := createTestRack(t, db)
+
+	// Dos switches con perfil con puertos sembrados.
+	sw1 := "aa:bb:cc:00:00:01"
+	sw2 := "aa:bb:cc:00:00:02"
+	for i, mac := range []string{sw1, sw2} {
+		if err := UpsertProfile(db, DeviceProfile{MAC: mac, UHeight: 1, ColSpan: 12,
+			Ports: []Port{{ID: "eth0", Kind: PortRJ45}, {ID: "eth1", Kind: PortRJ45}}}); err != nil {
+			t.Fatalf("UpsertProfile: %v", err)
+		}
+		if err := SaveLayout(db, LayoutChange{RackID: rack.ID, Upsert: []Mount{{DeviceMAC: mac, UStart: i + 1, ColStart: 0}}}); err != nil {
+			t.Fatalf("SaveLayout: %v", err)
+		}
+	}
+	// Un patch panel (accesorio pass-through).
+	if err := SaveLayout(db, LayoutChange{RackID: rack.ID, Upsert: []Mount{{FaceplateID: "patch-panel-1u", UStart: 3, ColStart: 0}}}); err != nil {
+		t.Fatalf("SaveLayout patch panel: %v", err)
+	}
+	rows, _ := ListMountRows(db)
+	var mSw1, mSw2, mPP string
+	for _, m := range rows {
+		switch {
+		case m.DeviceMAC == sw1:
+			mSw1 = m.ID
+		case m.DeviceMAC == sw2:
+			mSw2 = m.ID
+		case m.FaceplateID == "patch-panel-1u":
+			mPP = m.ID
+		}
+	}
+
+	// Cable válido sw1:eth0 -> sw2:eth0.
+	c, err := AddCable(db, Cable{FromMount: mSw1, FromPort: "eth0", ToMount: mSw2, ToPort: "eth0"})
+	if err != nil {
+		t.Fatalf("AddCable: %v", err)
+	}
+	// Segundo cable sobre el mismo puerto: capacidad 1.
+	if _, err := AddCable(db, Cable{FromMount: mSw1, FromPort: "eth0", ToMount: mSw2, ToPort: "eth1"}); !errors.Is(err, ErrPortBusy) {
+		t.Fatalf("puerto ocupado: err=%v", err)
+	}
+	// Puerto no declarado por el dispositivo.
+	if _, err := AddCable(db, Cable{FromMount: mSw1, FromPort: "eth9", ToMount: mSw2, ToPort: "eth1"}); !errors.Is(err, ErrUnknownPort) {
+		t.Fatalf("puerto no declarado: err=%v", err)
+	}
+	// Montaje inexistente.
+	if _, err := AddCable(db, Cable{FromMount: "nope", FromPort: "eth0", ToMount: mSw2, ToPort: "eth1"}); !errors.Is(err, ErrUnknownMount) {
+		t.Fatalf("montaje inexistente: err=%v", err)
+	}
+	// Patch panel: admite 2 cables en el mismo puerto.
+	if _, err := AddCable(db, Cable{FromMount: mSw1, FromPort: "eth1", ToMount: mPP, ToPort: "1"}); err != nil {
+		t.Fatalf("patch panel primer cable: %v", err)
+	}
+	if _, err := AddCable(db, Cable{FromMount: mSw2, FromPort: "eth1", ToMount: mPP, ToPort: "1"}); err != nil {
+		t.Fatalf("patch panel segundo cable: %v", err)
+	}
+	if _, err := AddCable(db, Cable{FromMount: mPP, FromPort: "1", ToMount: mPP, ToPort: "1"}); !errors.Is(err, ErrPortBusy) {
+		t.Fatalf("patch panel tercer cable: err=%v", err)
+	}
+
+	cables, err := ListCables(db)
+	if err != nil || len(cables) != 3 {
+		t.Fatalf("ListCables: %d err=%v", len(cables), err)
+	}
+	if err := DeleteCable(db, c.ID); err != nil {
+		t.Fatalf("DeleteCable: %v", err)
+	}
+
+	// Cascada: borrar el rack se lleva montajes y cables.
+	if err := DeleteRack(db, rack.ID); err != nil {
+		t.Fatalf("DeleteRack: %v", err)
+	}
+	cables, _ = ListCables(db)
+	if len(cables) != 0 {
+		t.Fatalf("cables huérfanos tras DeleteRack: %d", len(cables))
+	}
+	rows, _ = ListMountRows(db)
+	if len(rows) != 0 {
+		t.Fatalf("mounts huérfanos tras DeleteRack: %d", len(rows))
+	}
+}

+ 139 - 0
server-go/internal/rack/types.go

@@ -0,0 +1,139 @@
+// Package rack modela el rack canvas: racks, montajes, cables y el perfil
+// físico de los dispositivos. Dominio puro, sin dependencias de HTTP ni DB.
+//
+// Convenciones de geometría:
+//   - Las U son 1-based y se cuentan SIEMPRE desde el rail inferior. La
+//     opción Numbering solo cambia las etiquetas impresas, nunca la
+//     geometría interna.
+//   - Cada U tiene RackColumns columnas (12): ancho completo = 12, mitad =
+//     6, tercio = 4, cuarto = 3. ColStart es 0-based.
+//   - El modelo físico (faceplate, altura U, span, puertos) lo posee el
+//     dispositivo (DeviceProfile, clave MAC). El montaje solo guarda
+//     posición (rack, uStart, colStart), label y status pinneado.
+package rack
+
+// RackColumns es el número de columnas por U del grid horizontal.
+const RackColumns = 12
+
+// WidthStandard y Numbering validan los valores permitidos del rack.
+const (
+	Width19     = "19"
+	Width10     = "10"
+	NumBottomUp = "bottom-up"
+	NumTopDown  = "top-down"
+)
+
+// Cable types y origins.
+const (
+	CableEthernet = "ethernet"
+	CableFiber    = "fiber"
+
+	OriginManual   = "manual"
+	OriginImported = "imported"
+	OriginDetected = "detected"
+)
+
+// StatusPin: "" o "auto" siguen el estado que NetPulse ya conoce del
+// dispositivo (snapshot del poller); el resto pinnean a mano.
+const (
+	StatusAuto    = "auto"
+	StatusOnline  = "online"
+	StatusOffline = "offline"
+	StatusUnknown = "unknown"
+)
+
+// PortKind son los tipos de puerto de v1 (sin alimentación).
+type PortKind string
+
+const (
+	PortRJ45    PortKind = "rj45"
+	PortSFP     PortKind = "sfp"
+	PortSFPPlus PortKind = "sfp+"
+)
+
+// Port es un puerto del faceplate del dispositivo. X e Y son coordenadas
+// locales 0..1 del faceplate: el puerto mantiene su sitio a cualquier zoom
+// y con cualquier altura de U.
+type Port struct {
+	ID   string   `json:"id"`
+	Kind PortKind `json:"kind"`
+	X    float64  `json:"x"`
+	Y    float64  `json:"y"`
+}
+
+// DeviceProfile es el modelo físico compartido del dispositivo: la misma
+// cara frontal en todos los racks. Clave: MAC normalizada (minúsculas, ':').
+type DeviceProfile struct {
+	MAC         string `json:"mac"`
+	FaceplateID string `json:"faceplateId"`
+	UHeight     int    `json:"uHeight"`
+	ColSpan     int    `json:"colSpan"`
+	Color       string `json:"color"`
+	Ports       []Port `json:"ports"`
+}
+
+// Rack es un rack físico (19" o 10").
+type Rack struct {
+	ID            string  `json:"id"`
+	Name          string  `json:"name"`
+	UHeight       int     `json:"uHeight"`
+	WidthStandard string  `json:"widthStandard"`
+	Numbering     string  `json:"numbering"`
+	StyleJSON     string  `json:"style"`
+	Location      string  `json:"location,omitempty"`
+	PositionX     float64 `json:"positionX"`
+	PositionY     float64 `json:"positionY"`
+}
+
+// Mount es la colocación de un dispositivo (o accesorio) en un rack.
+// DeviceMAC == "" indica accesorio (blank, shelf, patch panel, PDU).
+type Mount struct {
+	ID             string `json:"id"`
+	RackID         string `json:"rackId"`
+	DeviceMAC      string `json:"deviceMac,omitempty"`
+	FaceplateID    string `json:"faceplateId"`
+	UStart         int    `json:"uStart"`
+	ColStart       int    `json:"colStart"`
+	Label          string `json:"label,omitempty"`
+	StatusPin      string `json:"statusPin"`
+	PortVisibility string `json:"portVisibility"`
+}
+
+// Cable conecta dos puertos de dos montajes (puede cruzar racks).
+type Cable struct {
+	ID             string `json:"id"`
+	FromMount      string `json:"fromMount"`
+	FromPort       string `json:"fromPort"`
+	ToMount        string `json:"toMount"`
+	ToPort         string `json:"toPort"`
+	Type           string `json:"type"`
+	Label          string `json:"label,omitempty"`
+	PropertiesJSON string `json:"properties,omitempty"`
+	Origin         string `json:"origin"`
+	CreatedAt      int64  `json:"createdAt"`
+}
+
+// Valid informa si el rack tiene valores de enumerado permitidos.
+func (r Rack) Valid() bool {
+	if r.UHeight < 1 || r.Name == "" {
+		return false
+	}
+	switch r.WidthStandard {
+	case Width19, Width10:
+	default:
+		return false
+	}
+	switch r.Numbering {
+	case NumBottomUp, NumTopDown:
+	default:
+		return false
+	}
+	return true
+}
+
+// Footprint devuelve la huella del montaje dado su tamaño resuelto (el
+// DeviceProfile para dispositivos, el faceplate del catálogo para
+// accesorios).
+func (m Mount) Footprint(uHeight, colSpan int) Footprint {
+	return Footprint{UStart: m.UStart, UHeight: uHeight, ColStart: m.ColStart, ColSpan: colSpan}
+}