Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat: custom labels for connection points (#495) (#568)
Pouzor - Rémy Jardient69d7ebaabd1a
diff --git a/backend/app/api/routes/nodes.py b/backend/app/api/routes/nodes.pyindex d25c736..c47f165 100644--- a/backend/app/api/routes/nodes.py+++ b/backend/app/api/routes/nodes.py@@ -12,6 +12,7 @@ from app.schemas.utils import (SIDES,handle_count_field,handle_id,+ prune_port_labels,removed_handle_ids,side_default,)@@ -221,6 +222,11 @@ async def update_node(await _remap_shrunk_handles(db, node, sent)for field, value in node_columns(sent).items():setattr(node, field, value)+ # Only now are both the labels and the counts final: a shrink drops the+ # labels of the points it removed, whichever of the two the update sent.+ node.port_labels = prune_port_labels(+ node.port_labels, {side: getattr(node, handle_count_field(side)) for side in SIDES}+ )# The user edited the device, not just its drawing: push the facts down.# Only what was sent counts — an omitted field must not clear the row, and# lists are replaced only when the client actually sent them.diff --git a/backend/app/db/database.py b/backend/app/db/database.pyindex a46833d..d4aec06 100644--- a/backend/app/db/database.py+++ b/backend/app/db/database.py@@ -578,6 +578,9 @@ async def init_db() -> None:# A zone or a group describes no device, so it has no inventory row to# keep its text on. Furniture keeps it here instead — see `Node.description`.("nodes.description", "ALTER TABLE nodes ADD COLUMN description TEXT"),+ # The device's own port numbering, per connection point (#495). Added+ # before `_drop_legacy_node_columns`, whose rebuild copies it across.+ ("nodes.port_labels", "ALTER TABLE nodes ADD COLUMN port_labels JSON"),):await _try_migrate(conn, sql, label=label)# 3.3.x — the inventory row owns the device's rack modelisation: the@@ -659,6 +662,7 @@ _NODE_COLUMNS_SQL = ("custom_icon VARCHAR,""description TEXT,""show_port_numbers BOOLEAN,"+ "port_labels JSON,""width FLOAT,""height FLOAT,""bottom_handles INTEGER,"@@ -671,8 +675,8 @@ _NODE_COLUMNS_SQL = (_NODE_KEPT = ("id, type, label, design_id, device_id, display_view, pos_x, pos_y, parent_id, container_mode, "- "custom_colors, custom_icon, description, show_port_numbers, width, height, bottom_handles, "- "top_handles, left_handles, right_handles, created_at, updated_at"+ "custom_colors, custom_icon, description, show_port_numbers, port_labels, width, height, "+ "bottom_handles, top_handles, left_handles, right_handles, created_at, updated_at")diff --git a/backend/app/db/models.py b/backend/app/db/models.pyindex 5c6896c..20ebb86 100644--- a/backend/app/db/models.py+++ b/backend/app/db/models.py@@ -70,6 +70,10 @@ class Node(Base):# node that does draw a device: its notes belong to the inventory row.description: Mapped[str | None] = mapped_column(Text, nullable=True)show_port_numbers: Mapped[bool] = mapped_column(Boolean, default=False)+ # Text printed in place of a connection point's 1..N number, keyed by source+ # handle ID ('top', 'bottom-3'…), so a node can carry the device's own port+ # numbering (#495). NULL when every point shows its number.+ port_labels: Mapped[dict[str, str] | None] = mapped_column(JSON, nullable=True)width: Mapped[float | None] = mapped_column(Float, nullable=True)height: Mapped[float | None] = mapped_column(Float, nullable=True)bottom_handles: Mapped[int] = mapped_column(Integer, default=1)diff --git a/backend/app/schemas/canvas.py b/backend/app/schemas/canvas.pyindex 739d72a..c82cce8 100644--- a/backend/app/schemas/canvas.py+++ b/backend/app/schemas/canvas.py@@ -4,7 +4,14 @@ from pydantic import BaseModel, ValidationInfo, field_validator, model_validatorfrom app.schemas.edges import EdgeResponsefrom app.schemas.nodes import NodeResponse-from app.schemas.utils import clamp_handles, normalize_animated, normalize_marker+from app.schemas.utils import (+ SIDES,+ clamp_handles,+ normalize_animated,+ normalize_marker,+ normalize_port_labels,+ prune_port_labels,+)class NodeSave(BaseModel):@@ -44,6 +51,7 @@ class NodeSave(BaseModel):disk_gb: float | None = Noneshow_hardware: bool = Falseshow_port_numbers: bool = False+ port_labels: dict[str, str] | None = Noneproperties: list[Any] = []width: float | None = Noneheight: float | None = None@@ -64,6 +72,18 @@ class NodeSave(BaseModel):side = (info.field_name or '').removesuffix('_handles')return clamp_handles(side, v)+ @field_validator('port_labels', mode='before')+ @classmethod+ def clean_port_labels(cls, v: object) -> object:+ return normalize_port_labels(v)++ @model_validator(mode="after")+ def drop_unreachable_port_labels(self) -> "NodeSave":+ """Same pruning as `NodeBase`: no label outlives its connection point."""+ counts = {side: getattr(self, f"{side}_handles") for side in SIDES}+ self.port_labels = prune_port_labels(self.port_labels, counts)+ return self+@model_validator(mode="after")def drop_self_parent(self) -> "NodeSave":"""A node can never be its own parent.diff --git a/backend/app/schemas/nodes.py b/backend/app/schemas/nodes.pyindex a58afb8..1bbb23d 100644--- a/backend/app/schemas/nodes.py+++ b/backend/app/schemas/nodes.py@@ -1,9 +1,9 @@from datetime import datetimefrom typing import Any-from pydantic import BaseModel, ValidationInfo, field_validator+from pydantic import BaseModel, ValidationInfo, field_validator, model_validator-from app.schemas.utils import clamp_handles+from app.schemas.utils import SIDES, clamp_handles, normalize_port_labels, prune_port_labelsclass NodeBase(BaseModel):@@ -33,6 +33,8 @@ class NodeBase(BaseModel):disk_gb: float | None = Noneshow_hardware: bool = Falseshow_port_numbers: bool = False+ # Text shown in place of a connection point's number, keyed by handle ID.+ port_labels: dict[str, str] | None = Noneproperties: list[dict[str, Any]] = []width: float | None = Noneheight: float | None = None@@ -53,6 +55,18 @@ class NodeBase(BaseModel):side = (info.field_name or '').removesuffix('_handles')return clamp_handles(side, v)+ @field_validator('port_labels', mode='before')+ @classmethod+ def clean_port_labels(cls, v: object) -> object:+ return normalize_port_labels(v)++ @model_validator(mode="after")+ def drop_unreachable_port_labels(self) -> "NodeBase":+ """A label for a connection point the counts no longer draw is dead weight."""+ counts = {side: getattr(self, f"{side}_handles") for side in SIDES}+ self.port_labels = prune_port_labels(self.port_labels, counts)+ return self+class NodeCreate(NodeBase):# Override pos_x/pos_y so callers can omit them; None signals "auto-place".@@ -91,6 +105,7 @@ class NodeUpdate(BaseModel):disk_gb: float | None = Noneshow_hardware: bool | None = Noneshow_port_numbers: bool | None = None+ port_labels: dict[str, str] | None = Noneproperties: list[dict[str, Any]] | None = Nonewidth: float | None = Noneheight: float | None = None@@ -111,6 +126,13 @@ class NodeUpdate(BaseModel):side = (info.field_name or '').removesuffix('_handles')return clamp_handles(side, v)+ # Pruning against the counts needs the stored ones too, so a partial update+ # leaves it to the route (`update_node`).+ @field_validator('port_labels', mode='before')+ @classmethod+ def clean_port_labels(cls, v: object) -> object:+ return normalize_port_labels(v)+class NodeResponse(NodeBase):id: strdiff --git a/backend/app/schemas/utils.py b/backend/app/schemas/utils.pyindex 54d8ff9..7a2dd1d 100644--- a/backend/app/schemas/utils.py+++ b/backend/app/schemas/utils.py@@ -1,5 +1,6 @@import mathimport re+from collections.abc import Mappingdef normalize_animated(v: object) -> str:@@ -110,3 +111,57 @@ def parse_side_handle(handle: str) -> tuple[str, int] | None:return side, 0idx = int(slot) - 1return side, (idx if idx >= 1 else -1)+++# ---------------------------------------------------------------------------+# Port labels+# ---------------------------------------------------------------------------+# The text printed next to a connection point in place of its 1..N number, so a+# node can carry the numbering of the real device (#495). Keyed by source handle+# ID. Mirrors normalizePortLabels / prunePortLabels in handleUtils.ts.++MAX_PORT_LABEL_LENGTH = 8+++def normalize_port_labels(v: object) -> dict[str, str] | None:+ """Keep the well-formed labels: a source-form handle ID → trimmed, non-empty text.++ Text is cut to MAX_PORT_LABEL_LENGTH, the most the card has room for. A bad+ entry is dropped rather than rejected, like the handle-count clamp: it must+ not cost the user a whole canvas save. None when nothing is left.+ """+ if not isinstance(v, dict):+ return None+ out: dict[str, str] = {}+ for key, label in v.items():+ if not isinstance(key, str) or not isinstance(label, str):+ continue+ parsed = parse_side_handle(key)+ # The round trip rejects the '-t' target form and padded slots ('top-02').+ if parsed is None or not 0 <= parsed[1] < MAX_HANDLES or handle_id(*parsed) != key:+ continue+ text = label.strip()[:MAX_PORT_LABEL_LENGTH]+ if text:+ out[key] = text+ return out or None+++def prune_port_labels(+ labels: dict[str, str] | None, counts: Mapping[str, int | None]+) -> dict[str, str] | None:+ """Drop the labels of connection points a side's count no longer reaches.++ A side with no count falls back to its default, as everywhere else.+ """+ if not labels:+ return None+ kept: dict[str, str] = {}+ for key, text in labels.items():+ parsed = parse_side_handle(key)+ if parsed is None:+ continue+ side, idx = parsed+ count = counts.get(side)+ if idx < (side_default(side) if count is None else count):+ kept[key] = text+ return kept or Nonediff --git a/backend/tests/test_port_labels.py b/backend/tests/test_port_labels.pynew file mode 100644index 0000000..30427c2--- /dev/null+++ b/backend/tests/test_port_labels.py@@ -0,0 +1,131 @@+"""Per-connection-point labels (#495): the device's own port numbering on a node."""++import uuid++from httpx import AsyncClient++from app.db.database import _NODE_COLUMNS_SQL, _NODE_KEPT+from app.db.models import Node+from app.schemas.utils import MAX_PORT_LABEL_LENGTH, normalize_port_labels, prune_port_labels+++def node_payload(**kwargs):+ return {"id": str(uuid.uuid4()), "type": "switch", "label": "sw", "status": "unknown", "pos_x": 0, "pos_y": 0, **kwargs}+++async def _save_and_load(client: AsyncClient, headers: dict, node: dict) -> dict:+ res = await client.post("/api/v1/canvas/save", json={"nodes": [node], "edges": [], "viewport": {}}, headers=headers)+ assert res.status_code == 200+ canvas = (await client.get("/api/v1/canvas", headers=headers)).json()+ return canvas["nodes"][0]+++# ── normalize / prune ─────────────────────────────────────────────────────────++def test_normalize_keeps_trimmed_labels_on_source_handles():+ assert normalize_port_labels({"top": " 8 ", "bottom-3": "SFP1"}) == {"top": "8", "bottom-3": "SFP1"}+++def test_normalize_drops_bad_keys_values_and_blanks():+ raw = {+ "top-t": "a", "bottom-1": "b", "left-02": "c", "cluster-left": "d", "right-65": "e",+ "top": " ", "bottom": 8, "left": "ok",+ }+ assert normalize_port_labels(raw) == {"left": "ok"}+++def test_normalize_truncates_and_handles_non_dicts():+ assert normalize_port_labels({"top": "x" * 20}) == {"top": "x" * MAX_PORT_LABEL_LENGTH}+ assert normalize_port_labels(None) is None+ assert normalize_port_labels(["top"]) is None+ assert normalize_port_labels({}) is None+++def test_prune_drops_points_beyond_the_count_and_falls_back_to_defaults():+ labels = {"top": "8", "bottom-3": "3", "left": "x"}+ assert prune_port_labels(labels, {"top": 1, "bottom": 2, "left": None}) == {"top": "8"}+ assert prune_port_labels(labels, {"top": 0, "bottom": 0, "left": 0}) is None+ assert prune_port_labels(None, {}) is None+++# ── canvas save ───────────────────────────────────────────────────────────────++async def test_save_canvas_persists_port_labels(client: AsyncClient, headers: dict):+ node = await _save_and_load(+ client, headers,+ node_payload(bottom_handles=7, show_port_numbers=True, port_labels={"top": "8", "bottom-7": "7"}),+ )+ assert node["port_labels"] == {"top": "8", "bottom-7": "7"}+++async def test_save_canvas_port_labels_default_to_null(client: AsyncClient, headers: dict):+ node = await _save_and_load(client, headers, node_payload())+ assert node["port_labels"] is None+++async def test_save_canvas_cleans_and_prunes_port_labels(client: AsyncClient, headers: dict):+ # A bad entry is dropped, never a 422: it must not cost the whole save.+ node = await _save_and_load(+ client, headers,+ node_payload(bottom_handles=2, port_labels={"top": " 8 ", "bottom-t": "x", "bottom-5": "5", "left": "L"}),+ )+ assert node["port_labels"] == {"top": "8"}+++# ── node routes ───────────────────────────────────────────────────────────────++async def test_create_node_with_port_labels(client: AsyncClient, headers: dict):+ res = await client.post(+ "/api/v1/nodes",+ json={"type": "switch", "label": "sw1", "bottom_handles": 3, "port_labels": {"top": "8", "bottom-9": "9"}},+ headers=headers,+ )+ assert res.status_code == 201+ assert res.json()["port_labels"] == {"top": "8"}+++async def test_patch_shrink_drops_the_removed_points_labels(client: AsyncClient, headers: dict):+ node_id = (+ await client.post(+ "/api/v1/nodes",+ json={"type": "switch", "label": "sw1", "bottom_handles": 4,+ "port_labels": {"top": "8", "bottom-2": "2", "bottom-4": "4"}},+ headers=headers,+ )+ ).json()["id"]++ res = await client.patch(f"/api/v1/nodes/{node_id}", json={"bottom_handles": 2}, headers=headers)+ assert res.json()["port_labels"] == {"top": "8", "bottom-2": "2"}++ res = await client.patch(f"/api/v1/nodes/{node_id}", json={"top_handles": 0, "bottom_handles": 1}, headers=headers)+ assert res.json()["port_labels"] is None+++async def test_patch_labels_are_pruned_against_the_stored_counts(client: AsyncClient, headers: dict):+ node_id = (+ await client.post("/api/v1/nodes", json={"type": "switch", "label": "sw1", "bottom_handles": 2}, headers=headers)+ ).json()["id"]+ res = await client.patch(+ f"/api/v1/nodes/{node_id}", json={"port_labels": {"bottom-2": "2", "bottom-3": "3"}}, headers=headers+ )+ assert res.json()["port_labels"] == {"bottom-2": "2"}+++async def test_patch_without_labels_keeps_them(client: AsyncClient, headers: dict):+ node_id = (+ await client.post("/api/v1/nodes", json={"type": "switch", "label": "sw1", "port_labels": {"top": "8"}}, headers=headers)+ ).json()["id"]+ res = await client.patch(f"/api/v1/nodes/{node_id}", json={"label": "sw2"}, headers=headers)+ assert res.json()["port_labels"] == {"top": "8"}+++# ── migration ─────────────────────────────────────────────────────────────────++def test_nodes_rebuild_keeps_every_mapped_column():+ # The 3.3.0 legacy-column drop rebuilds `nodes` from an explicit column list;+ # a column missing from it would be silently lost on an upgraded database.+ kept = {c.strip() for c in _NODE_KEPT.split(",")}+ declared = {d.split()[0] for d in _NODE_COLUMNS_SQL.split(",")}+ for column in Node.__table__.columns:+ assert column.name in kept, f"{column.name} missing from _NODE_KEPT"+ assert column.name in declared, f"{column.name} missing from _NODE_COLUMNS_SQL"diff --git a/frontend/src/components/canvas/nodes/SideHandles.tsx b/frontend/src/components/canvas/nodes/SideHandles.tsxindex 98c4592..6c433c5 100644--- a/frontend/src/components/canvas/nodes/SideHandles.tsx+++ b/frontend/src/components/canvas/nodes/SideHandles.tsx@@ -25,7 +25,10 @@ interface SideHandlesProps {labelColor: string/** Which sides to render. Defaults to all four. */sides?: readonly Side[]- /** When true, render port-number labels if data.show_port_numbers is set. */+ /**+ * When true, render port-number labels if data.show_port_numbers is set: the+ * point's data.port_labels entry, else its 1-based slot on the side.+ */showLabels?: boolean}@@ -60,7 +63,7 @@ export function SideHandles({className="absolute font-mono leading-none pointer-events-none select-none"style={{ ...labelStyle, fontSize: 7, color: labelColor }}>- {idx + 1}+ {data.port_labels?.[sourceId] ?? idx + 1}</span>)}<Handlediff --git a/frontend/src/components/canvas/nodes/__tests__/SideHandles.test.tsx b/frontend/src/components/canvas/nodes/__tests__/SideHandles.test.tsxindex a0f5114..039b965 100644--- a/frontend/src/components/canvas/nodes/__tests__/SideHandles.test.tsx+++ b/frontend/src/components/canvas/nodes/__tests__/SideHandles.test.tsx@@ -4,7 +4,7 @@ import { ReactFlowProvider } from '@xyflow/react'import { SideHandles } from '../SideHandles'import type { NodeData } from '@/types'-function renderHandles(data: Partial<NodeData> = {}) {+function renderHandles(data: Partial<NodeData> = {}, showLabels = false) {const full: NodeData = { label: 'n', type: 'server', status: 'online', services: [], ...data }return render(<ReactFlowProvider>@@ -13,6 +13,7 @@ function renderHandles(data: Partial<NodeData> = {}) {handleBackground="#30363d"handleBorder="#30363d"labelColor="#8b949e"+ showLabels={showLabels}/></ReactFlowProvider>)@@ -38,4 +39,23 @@ describe('SideHandles', () => {const { container } = renderHandles({ top_handles: 2, left_handles: 3, right_handles: 1, bottom_handles: 1 })expect(container.querySelectorAll('.react-flow__handle.source').length).toBe(7)})++ describe('port labels (#495)', () => {+ const labelTexts = (container: HTMLElement) =>+ Array.from(container.querySelectorAll('span.font-mono')).map((el) => el.textContent)++ it('prints a custom label in place of the number, the rest keep theirs', () => {+ const { container } = renderHandles(+ { top_handles: 1, bottom_handles: 3, show_port_numbers: true, port_labels: { top: '8', 'bottom-3': 'SFP' } },+ true,+ )+ // SIDES order: top, then bottom.+ expect(labelTexts(container)).toEqual(['8', '1', '2', 'SFP'])+ })++ it('ignores labels while show_port_numbers is off', () => {+ const { container } = renderHandles({ port_labels: { top: '8' } }, true)+ expect(labelTexts(container)).toEqual([])+ })+ })})diff --git a/frontend/src/components/modals/NodeModal.tsx b/frontend/src/components/modals/NodeModal.tsxindex 7172ed2..131cfb9 100644--- a/frontend/src/components/modals/NodeModal.tsx+++ b/frontend/src/components/modals/NodeModal.tsx@@ -12,7 +12,7 @@ import { useThemeStore } from '@/stores/themeStore'import { resolveNodeColors } from '@/utils/nodeColors'import { ICON_REGISTRY, NODE_TYPE_DEFAULT_ICONS, isBrandIconKey, brandIconSlug, brandIconUrl } from '@/utils/nodeIcons'import { IconPickerPanel } from './IconPickerPanel'-import { MAX_HANDLES, MIN_HANDLES, clampHandles, sideDefault, handleCountField, type Side } from '@/utils/handleUtils'+import { MAX_HANDLES, MAX_PORT_LABEL_LENGTH, MIN_HANDLES, SIDES, clampHandles, handleId, normalizePortLabels, sideDefault, handleCountField, type Side } from '@/utils/handleUtils'import { isValidParentNode } from '@/utils/virtualEdgeParent'import { NODE_TYPE_GROUPS, isFurnitureType } from '@/utils/nodeTypeGroups'@@ -126,6 +126,46 @@ interface NodeModalProps {onEditTypeStyle?: (type: NodeType) => void}+const SIDE_LABELS: Record<Side, string> = { top: 'Top', bottom: 'Bottom', left: 'Left', right: 'Right' }++/**+ * One short text field per connection point, grouped by side, for the label the+ * card prints in place of the point's number — the device's own port numbering+ * (#495). An empty field keeps the number, shown as its placeholder.+ */+function PortLabelFields({ counts, labels, onChange }: {+ counts: Record<Side, number>+ labels: Record<string, string> | undefined+ onChange: (id: string, value: string) => void+}) {+ return (+ <div className="flex flex-col gap-1.5">+ {SIDES.filter((side) => counts[side] > 0).map((side) => (+ <div key={side} className="flex items-start gap-2">+ <span className="w-11 shrink-0 pt-1.5 text-[10px] text-muted-foreground/80">{SIDE_LABELS[side]}</span>+ <div className="flex flex-wrap gap-1">+ {Array.from({ length: counts[side] }, (_, idx) => {+ const id = handleId(side, idx)+ return (+ <input+ key={id}+ type="text"+ value={labels?.[id] ?? ''}+ placeholder={String(idx + 1)}+ maxLength={MAX_PORT_LABEL_LENGTH}+ aria-label={`${SIDE_LABELS[side]} port ${idx + 1} label`}+ onChange={(e) => onChange(id, e.target.value)}+ className="w-10 h-6 rounded border border-[#30363d] bg-[#0d1117] text-center text-xs font-mono text-foreground outline-none placeholder:text-muted-foreground/40 focus:border-[#ff6e00]"+ />+ )+ })}+ </div>+ </div>+ ))}+ </div>+ )+}+// NodeModal is always mounted with a key that changes on open/edit, so useState// initial value is enough - no need for a reset effect.export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node', parentCandidates = [], currentNodeId, onEditTypeStyle }: NodeModalProps) {@@ -183,6 +223,8 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'left_handles: sideValue('left'),right_handles: sideValue('right'),}),+ // Blank fields fall back to the number, so they are not stored.+ port_labels: normalizePortLabels(form.port_labels),parent_id: safeParentId,container_mode: canUseContainerMode ? !!form.container_mode : false,})@@ -592,6 +634,13 @@ export function NodeModal({ open, onClose, onSubmit, initial, title = 'Add Node'/></button></div>+ {form.show_port_numbers && (+ <PortLabelFields+ counts={{ top: sideValue('top'), bottom: sideValue('bottom'), left: sideValue('left'), right: sideValue('right') }}+ labels={form.port_labels}+ onChange={(id, value) => setForm((f) => ({ ...f, port_labels: { ...f.port_labels, [id]: value } }))}+ />+ )}</div>)}diff --git a/frontend/src/components/modals/__tests__/NodeModal.test.tsx b/frontend/src/components/modals/__tests__/NodeModal.test.tsxindex b22a622..699fda9 100644--- a/frontend/src/components/modals/__tests__/NodeModal.test.tsx+++ b/frontend/src/components/modals/__tests__/NodeModal.test.tsx@@ -594,6 +594,42 @@ describe('NodeModal', () => {expect((onSubmit.mock.calls[0][0] as Partial<NodeData>).show_port_numbers).toBe(true)})+ describe('port labels (#495)', () => {+ it('shows one field per connection point only while port numbers are on', () => {+ renderModal({ initial: { ...BASE, top_handles: 1, bottom_handles: 7 } })+ expect(screen.queryByLabelText('Top port 1 label')).toBeNull()+ fireEvent.click(screen.getByLabelText('Toggle port numbers'))+ expect(screen.getByLabelText('Top port 1 label')).toBeDefined()+ expect(screen.getByLabelText('Bottom port 7 label')).toBeDefined()+ expect(screen.queryByLabelText('Bottom port 8 label')).toBeNull()+ expect(screen.queryByLabelText('Left port 1 label')).toBeNull()+ })++ it('uses the port number as the placeholder and caps the length', () => {+ renderModal({ initial: { ...BASE, bottom_handles: 3, show_port_numbers: true } })+ const field = screen.getByLabelText('Bottom port 3 label') as HTMLInputElement+ expect(field.placeholder).toBe('3')+ expect(field.maxLength).toBe(8)+ })++ it('submits the typed labels, without the blank ones', () => {+ const { onSubmit } = renderModal({ initial: { ...BASE, bottom_handles: 7, show_port_numbers: true } })+ fireEvent.change(screen.getByLabelText('Top port 1 label'), { target: { value: '8' } })+ fireEvent.change(screen.getByLabelText('Bottom port 1 label'), { target: { value: ' ' } })+ fireEvent.click(screen.getByRole('button', { name: 'Add' }))+ expect((onSubmit.mock.calls[0][0] as Partial<NodeData>).port_labels).toEqual({ top: '8' })+ })++ it('pre-fills existing labels and submits undefined once they are all cleared', () => {+ const { onSubmit } = renderModal({ initial: { ...BASE, show_port_numbers: true, port_labels: { top: '8' } } })+ const field = screen.getByLabelText('Top port 1 label') as HTMLInputElement+ expect(field.value).toBe('8')+ fireEvent.change(field, { target: { value: '' } })+ fireEvent.click(screen.getByRole('button', { name: 'Add' }))+ expect((onSubmit.mock.calls[0][0] as Partial<NodeData>).port_labels).toBeUndefined()+ })+ })+// ── Zigbee nodes ──────────────────────────────────────────────────────const zigbeeTypes = ['zigbee_coordinator', 'zigbee_router', 'zigbee_enddevice'] as constdiff --git a/frontend/src/stores/__tests__/canvasStore/portLabels.test.ts b/frontend/src/stores/__tests__/canvasStore/portLabels.test.tsnew file mode 100644index 0000000..54e1d68--- /dev/null+++ b/frontend/src/stores/__tests__/canvasStore/portLabels.test.ts@@ -0,0 +1,55 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useCanvasStore } from '@/stores/canvasStore'+import { makeNode } from '@/test/factories'++function resetStore() {+ useCanvasStore.setState({+ nodes: [],+ edges: [],+ hasUnsavedChanges: false,+ editSeq: 0,+ selectedNodeId: null,+ selectedNodeIds: [],+ editingGroupRectId: null,+ editingTextId: null,+ past: [],+ future: [],+ clipboard: { nodes: [], edges: [] },+ serviceStatuses: {},+ floorMap: null,+ })+}++const labelsOf = (id: string) => useCanvasStore.getState().nodes.find((n) => n.id === id)!.data.port_labels++describe('canvasStore — port labels (#495)', () => {+ beforeEach(resetStore)++ it('stores labels sent through updateNode', () => {+ useCanvasStore.setState({ nodes: [makeNode('sw', { bottom_handles: 8 })] })+ useCanvasStore.getState().updateNode('sw', { port_labels: { top: '8', 'bottom-2': '2' } })+ expect(labelsOf('sw')).toEqual({ top: '8', 'bottom-2': '2' })+ })++ it('drops the labels of points a shrink removes, so a later grow starts blank', () => {+ useCanvasStore.setState({+ nodes: [makeNode('sw', { bottom_handles: 4, port_labels: { top: '8', 'bottom-3': '3', 'bottom-4': '4' } })],+ })+ useCanvasStore.getState().updateNode('sw', { bottom_handles: 2 })+ expect(labelsOf('sw')).toEqual({ top: '8' })+ useCanvasStore.getState().updateNode('sw', { bottom_handles: 4 })+ expect(labelsOf('sw')).toEqual({ top: '8' })+ })++ it('clears the field when the last label goes', () => {+ useCanvasStore.setState({ nodes: [makeNode('sw', { port_labels: { top: '8' } })] })+ useCanvasStore.getState().updateNode('sw', { top_handles: 0 })+ expect(labelsOf('sw')).toBeUndefined()+ })++ it('leaves an unlabelled node untouched', () => {+ useCanvasStore.setState({ nodes: [makeNode('sw', { bottom_handles: 4 })] })+ useCanvasStore.getState().updateNode('sw', { bottom_handles: 2 })+ expect(labelsOf('sw')).toBeUndefined()+ })+})diff --git a/frontend/src/stores/canvasStore.ts b/frontend/src/stores/canvasStore.tsindex 7918fba..eb6c22d 100644--- a/frontend/src/stores/canvasStore.ts+++ b/frontend/src/stores/canvasStore.ts@@ -12,7 +12,7 @@ import {} from '@xyflow/react'import type { NodeData, EdgeData, NodeType, EdgeType, NodeTypeStyle, EdgeTypeStyle, CustomStyleDef, ServiceStatus, FloorMapConfig } from '@/types'import { generateUUID } from '@/utils/uuid'-import { normalizeHandle, removedHandleIds, handleCountField, sideDefault, handleId, SIDES } from '@/utils/handleUtils'+import { normalizeHandle, removedHandleIds, handleCountField, sideDefault, handleId, prunePortLabels, SIDES } from '@/utils/handleUtils'import { applyOpacity } from '@/utils/colorUtils'import { readHideIp, writeHideIp } from '@/utils/ipDisplay'import { isValidCidr, isZoneSubnetCandidate } from '@/utils/subnet'@@ -647,6 +647,11 @@ export const useCanvasStore = create<CanvasState>((rawSet, get) => {let nodes = state.nodes.map((n) => {if (n.id !== id) return nconst updated: Node<NodeData> = { ...n, data: { ...n.data, ...data } }+ // A shrink takes its connection points' labels with it, so a later+ // grow does not resurrect a stale one on the new point.+ if (updated.data.port_labels) {+ updated.data = { ...updated.data, port_labels: prunePortLabels(updated.data) }+ }// When properties change, clear stored height so the node auto-sizes to fit new content.// A container-mode host (vm/lxc/docker_host) keeps a manually-set height: resetting it// snaps the container back to auto-fit size and scrambles its nested children (#278).diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 03e5dc6..17a8410 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -265,6 +265,11 @@ export interface NodeData extends Record<string, unknown> {right_handles?: number/** Show a port number (1..N) next to each connection point. */show_port_numbers?: boolean+ /**+ * Text shown in place of a connection point's number, keyed by source handle+ * ID ('top', 'bottom-3'…). A point without one keeps its 1..N number (#495).+ */+ port_labels?: Record<string, string>/** Text node content (type === 'text') */text_content?: string}diff --git a/frontend/src/types/yaml.ts b/frontend/src/types/yaml.tsindex 8e1e78e..ddd002d 100644--- a/frontend/src/types/yaml.ts+++ b/frontend/src/types/yaml.ts@@ -37,4 +37,7 @@ export interface YamlNode {// Whether port-number labels are shown next to connection points. Only written// when enabled so the toggle round-trips through export/import (issue #272).showPortNumbers?: boolean+ // The device's own numbering per connection point, keyed by handle ID — only+ // written when at least one point carries a label (#495).+ portLabels?: Record<string, string>}diff --git a/frontend/src/utils/__tests__/canvasSerializer.test.ts b/frontend/src/utils/__tests__/canvasSerializer.test.tsindex d9ad18c..8a3c3bc 100644--- a/frontend/src/utils/__tests__/canvasSerializer.test.ts+++ b/frontend/src/utils/__tests__/canvasSerializer.test.ts@@ -691,3 +691,27 @@ describe('furniture descriptions', () => {expect(node.data.description).toBe('Three Proxmox boxes.')})})++describe('port labels (#495)', () => {+ it('serializes labels, dropping blanks and points the counts no longer draw', () => {+ const node = makeRfNode({+ data: {+ label: 'sw', type: 'switch', status: 'online', services: [],+ bottom_handles: 2,+ port_labels: { top: '8', bottom: ' ', 'bottom-2': '2', 'bottom-5': '5' },+ },+ })+ expect(serializeNode(node).port_labels).toEqual({ top: '8', 'bottom-2': '2' })+ })++ it('serializes null when the node carries no label', () => {+ expect(serializeNode(makeRfNode()).port_labels).toBeNull()+ })++ it('deserializes labels and maps the API null to unset', () => {+ const withLabels = deserializeApiNode(makeApiNode({ port_labels: { top: '8' } }), new Map())+ expect(withLabels.data.port_labels).toEqual({ top: '8' })+ const without = deserializeApiNode(makeApiNode({ port_labels: null }), new Map())+ expect(without.data.port_labels).toBeUndefined()+ })+})diff --git a/frontend/src/utils/__tests__/exportYaml.test.ts b/frontend/src/utils/__tests__/exportYaml.test.tsindex c87afa6..be5fb4e 100644--- a/frontend/src/utils/__tests__/exportYaml.test.ts+++ b/frontend/src/utils/__tests__/exportYaml.test.ts@@ -216,4 +216,13 @@ describe('exportCanvasToYaml', () => {const off = (yaml.load(exportCanvasToYaml([makeNode({ label: 'Off', type: 'server', show_port_numbers: false })], [])) as Record<string, unknown>[])[0]expect(off).not.toHaveProperty('showPortNumbers')})++ it('exports portLabels only when a point carries one (#495)', () => {+ const labelled = (yaml.load(exportCanvasToYaml([makeNode({+ label: 'Sw', type: 'switch', show_port_numbers: true, port_labels: { top: '8', 'bottom-9': 'gone' },+ })], [])) as Record<string, unknown>[])[0]+ expect(labelled.portLabels).toEqual({ top: '8' })+ const plain = (yaml.load(exportCanvasToYaml([makeNode({ label: 'Plain', type: 'switch' })], [])) as Record<string, unknown>[])[0]+ expect(plain).not.toHaveProperty('portLabels')+ })})diff --git a/frontend/src/utils/__tests__/handleUtils.test.ts b/frontend/src/utils/__tests__/handleUtils.test.tsindex e674b71..ac60248 100644--- a/frontend/src/utils/__tests__/handleUtils.test.ts+++ b/frontend/src/utils/__tests__/handleUtils.test.ts@@ -18,7 +18,11 @@ import {handleCountField,isVerticalSide,SIDES,+ MAX_PORT_LABEL_LENGTH,+ normalizePortLabels,+ prunePortLabels,} from '../handleUtils'+import type { NodeData } from '@/types'describe('bottomHandleId', () => {it('first id is always "bottom" for backward compatibility', () => {@@ -341,3 +345,52 @@ describe('zero connection points on top/bottom (issue: min was 1)', () => {expect(removedHandleIds('top', 2, 0)).toEqual(new Set(['top', 'top-2']))})})++describe('normalizePortLabels (#495)', () => {+ it('keeps trimmed labels keyed by source handle ID', () => {+ expect(normalizePortLabels({ top: ' 8 ', 'bottom-3': 'SFP1' })).toEqual({ top: '8', 'bottom-3': 'SFP1' })+ })++ it('drops blank labels and returns undefined when none are left', () => {+ expect(normalizePortLabels({ top: ' ', bottom: '' })).toBeUndefined()+ })++ it('drops keys that are not source handle IDs', () => {+ const labels = { 'top-t': 'a', 'bottom-1': 'b', 'left-02': 'c', 'cluster-left': 'd', 'right-65': 'e', front: 'f', left: 'ok' }+ expect(normalizePortLabels(labels)).toEqual({ left: 'ok' })+ })++ it('drops non-string values', () => {+ expect(normalizePortLabels({ top: 8, bottom: null, left: 'x' })).toEqual({ left: 'x' })+ })++ it('truncates to MAX_PORT_LABEL_LENGTH', () => {+ expect(normalizePortLabels({ top: 'x'.repeat(20) })).toEqual({ top: 'x'.repeat(MAX_PORT_LABEL_LENGTH) })+ })++ it('returns undefined for anything that is not a plain object', () => {+ expect(normalizePortLabels(undefined)).toBeUndefined()+ expect(normalizePortLabels(null)).toBeUndefined()+ expect(normalizePortLabels('top')).toBeUndefined()+ expect(normalizePortLabels(['top'])).toBeUndefined()+ })+})++describe('prunePortLabels (#495)', () => {+ const base: NodeData = { label: 'sw', type: 'switch', status: 'online', services: [] }++ it('drops labels of points beyond the side count', () => {+ const data = { ...base, bottom_handles: 2, port_labels: { bottom: '1', 'bottom-2': '2', 'bottom-3': '3' } }+ expect(prunePortLabels(data)).toEqual({ bottom: '1', 'bottom-2': '2' })+ })++ it('uses side defaults when a count is unset (left/right → 0)', () => {+ const data = { ...base, port_labels: { top: '8', left: 'x' } }+ expect(prunePortLabels(data)).toEqual({ top: '8' })+ })++ it('returns undefined when nothing survives', () => {+ expect(prunePortLabels({ ...base, top_handles: 0, port_labels: { top: '8' } })).toBeUndefined()+ expect(prunePortLabels(base)).toBeUndefined()+ })+})diff --git a/frontend/src/utils/__tests__/importYaml.test.ts b/frontend/src/utils/__tests__/importYaml.test.tsindex 346e801..f90219c 100644--- a/frontend/src/utils/__tests__/importYaml.test.ts+++ b/frontend/src/utils/__tests__/importYaml.test.ts@@ -445,4 +445,29 @@ describe('parseYamlToCanvas', () => {expect(nodes.find((n) => n.data.label === 'On')!.data.show_port_numbers).toBe(true)expect(nodes.find((n) => n.data.label === 'Off')!.data.show_port_numbers).toBeUndefined()})++ it('round-trips port labels through export → import (#495)', () => {+ const sw: Node<NodeData> = {+ id: 'sw', type: 'switch', position: { x: 0, y: 0 },+ data: {+ label: 'Sw', type: 'switch', status: 'online', services: [],+ bottom_handles: 7, show_port_numbers: true, port_labels: { top: '8', 'bottom-7': '7' },+ },+ }+ const { nodes } = parseYamlToCanvas(exportCanvasToYaml([sw], []), empty, emptyEdges)+ expect(nodes[0].data.port_labels).toEqual({ top: '8', 'bottom-7': '7' })+ })++ it('drops malformed port labels on import (#495)', () => {+ const yamlStr = `+- nodeType: switch+ label: "Sw"+ portLabels:+ top: "8"+ top-t: "x"+ bottom: " "+`+ const { nodes } = parseYamlToCanvas(yamlStr, empty, emptyEdges)+ expect(nodes[0].data.port_labels).toEqual({ top: '8' })+ })})diff --git a/frontend/src/utils/canvasSerializer.ts b/frontend/src/utils/canvasSerializer.tsindex 290e908..9f453d6 100644--- a/frontend/src/utils/canvasSerializer.ts+++ b/frontend/src/utils/canvasSerializer.ts@@ -1,6 +1,6 @@import type { Node, Edge } from '@xyflow/react'import type { NodeData, EdgeData, Waypoint } from '@/types'-import { normalizeHandle, clampHandles, handleId, handleCountField, type Side } from '@/utils/handleUtils'+import { normalizeHandle, clampHandles, handleId, handleCountField, normalizePortLabels, prunePortLabels, type Side } from '@/utils/handleUtils'import { normalizeMarker } from '@/utils/edgeMarkers'import { changedFactFields, type FactsBaseline } from '@/utils/deviceFacts'@@ -41,6 +41,7 @@ export interface ApiNode extends Record<string, unknown> {left_handles?: numberright_handles?: numbershow_port_numbers?: boolean+ port_labels?: Record<string, string> | null}export interface ApiEdge {@@ -167,6 +168,7 @@ export function serializeNode(left_handles: clampHandles('left', n.data.left_handles ?? 0),right_handles: clampHandles('right', n.data.right_handles ?? 0),show_port_numbers: n.data.show_port_numbers ?? false,+ port_labels: prunePortLabels(n.data) ?? null,pos_x: n.position.x,pos_y: n.position.y,}@@ -245,6 +247,8 @@ export function deserializeApiNode(bottom_handles: clampHandles('bottom', n.bottom_handles ?? 1),left_handles: clampHandles('left', n.left_handles ?? 0),right_handles: clampHandles('right', n.right_handles ?? 0),+ // The API reports NULL for "no labels"; the canvas leaves the field unset.+ port_labels: normalizePortLabels(n.port_labels),collapsed: Boolean(n.custom_colors?.collapsed),} as unknown as NodeData,...(n.parent_id && parentIsZonediff --git a/frontend/src/utils/exportYaml.ts b/frontend/src/utils/exportYaml.tsindex 423d2a0..75c0693 100644--- a/frontend/src/utils/exportYaml.ts+++ b/frontend/src/utils/exportYaml.ts@@ -1,7 +1,7 @@import type { Node, Edge } from '@xyflow/react'import type { NodeData, EdgeData, EdgeType } from '@/types'import type { YamlNode, YamlNodeConnection } from '@/types/yaml'-import { SIDES, sideDefault, sideHandleCount } from '@/utils/handleUtils'+import { SIDES, prunePortLabels, sideDefault, sideHandleCount } from '@/utils/handleUtils'import yaml from 'js-yaml'/** Build a map of node id → label for edge resolution */@@ -94,6 +94,8 @@ export function exportCanvasToYaml(nodes: Node<NodeData>[], edges: Edge<EdgeData// Preserve the port-number toggle so it survives a round-trip (issue #272).if (d.show_port_numbers) entry.showPortNumbers = true+ const portLabels = prunePortLabels(d)+ if (portLabels) entry.portLabels = portLabels// Parent relationship: if this node has a parentId in React Flow,// encode it as a 'parent' connection using any virtual edge between them.diff --git a/frontend/src/utils/handleUtils.ts b/frontend/src/utils/handleUtils.tsindex ad653fc..2e86608 100644--- a/frontend/src/utils/handleUtils.ts+++ b/frontend/src/utils/handleUtils.ts@@ -112,6 +112,55 @@ export function removedHandleIds(side: Side, oldCount: number, newCount: number)return removed}+// ---------------------------------------------------------------------------+// Port labels — text shown in place of a connection point's 1..N number, so a+// node can carry the real device's numbering (#495). Keyed by source handle ID.+// Mirrors normalize_port_labels / prune_port_labels in backend/app/schemas/utils.py.+// ---------------------------------------------------------------------------++/** The most a label can hold: the card prints it at 7px beside the handle. */+export const MAX_PORT_LABEL_LENGTH = 8++/** Splits a source handle ID into side and slot, or null when it is not one. */+function parseSourceHandle(id: string): { side: Side; idx: number } | null {+ const m = id.match(/^(top|bottom|left|right)(?:-(\d+))?$/)+ if (!m) return null+ const side = m[1] as Side+ const idx = m[2] === undefined ? 0 : Number(m[2]) - 1+ // The round trip rejects the forms the canvas never emits ('top-1', 'top-02').+ if (idx < 0 || idx >= MAX_HANDLES || handleId(side, idx) !== id) return null+ return { side, idx }+}++/**+ * Keep the well-formed labels: a source handle ID → trimmed, non-empty text of+ * at most MAX_PORT_LABEL_LENGTH characters. Undefined when nothing is left, so+ * an emptied form clears the field instead of storing `{}`.+ */+export function normalizePortLabels(labels: unknown): Record<string, string> | undefined {+ if (!labels || typeof labels !== 'object' || Array.isArray(labels)) return undefined+ const out: Record<string, string> = {}+ for (const [id, text] of Object.entries(labels)) {+ if (typeof text !== 'string' || !parseSourceHandle(id)) continue+ const trimmed = text.trim().slice(0, MAX_PORT_LABEL_LENGTH)+ if (trimmed) out[id] = trimmed+ }+ return Object.keys(out).length ? out : undefined+}++/** The node's labels minus those of connection points its counts no longer draw. */+export function prunePortLabels(data: NodeData): Record<string, string> | undefined {+ const labels = normalizePortLabels(data.port_labels)+ if (!labels) return undefined+ const kept = Object.fromEntries(+ Object.entries(labels).filter(([id]) => {+ const parsed = parseSourceHandle(id)+ return parsed !== null && parsed.idx < sideHandleCount(data, parsed.side)+ }),+ )+ return Object.keys(kept).length ? kept : undefined+}+// ---------------------------------------------------------------------------// Deprecated bottom-only aliases — kept so existing call sites don't churn.// Prefer the side-generic functions above.diff --git a/frontend/src/utils/importYaml.ts b/frontend/src/utils/importYaml.tsindex 7153d28..f7d4f6c 100644--- a/frontend/src/utils/importYaml.ts+++ b/frontend/src/utils/importYaml.ts@@ -5,6 +5,7 @@ import type { YamlNode, YamlNodeConnection } from '@/types/yaml'import { generateUUID } from '@/utils/uuid'import { applyDagreLayout } from '@/utils/layout'import { migrateClusterHandles } from '@/utils/canvasSerializer'+import { normalizePortLabels } from '@/utils/handleUtils'/*** Hardware specs as canvas properties.@@ -74,6 +75,8 @@ export function parseYamlToCanvas(labelToId.set(yn.label, id)const hardware = hardwareProperties(yn)+ // The per-point labels, minus any entry the file mangled (#495).+ const portLabels = normalizePortLabels(yn.portLabels)const data: NodeData = {label: yn.label,@@ -103,6 +106,7 @@ export function parseYamlToCanvas(...(typeof yn.rightHandles === 'number' ? { right_handles: yn.rightHandles } : {}),// Restore the port-number toggle (issue #272)....(yn.showPortNumbers ? { show_port_numbers: true } : {}),+ ...(portLabels ? { port_labels: portLabels } : {}),}newNodes.push({diff --git a/mcp/app/tools.py b/mcp/app/tools.pyindex 4142bf6..3d1500d 100644--- a/mcp/app/tools.py+++ b/mcp/app/tools.py@@ -73,6 +73,15 @@ _NODE_FIELDS = {"left_handles": {"type": "integer", "minimum": 0, "maximum": 64, "description": "Connection points on the left side (default 0). Their IDs are 'left', 'left-2', 'left-3', ..."},"right_handles": {"type": "integer", "minimum": 0, "maximum": 64, "description": "Connection points on the right side (default 0). Their IDs are 'right', 'right-2', 'right-3', ..."},"show_port_numbers": {"type": "boolean", "description": "Number each connection point on the node card."},+ "port_labels": {+ "type": "object",+ "description": (+ "Text shown in place of a connection point's number when show_port_numbers is on, "+ "keyed by handle ID — e.g. {\"top\": \"8\"} for an uplink printed as port 8. "+ "At most 8 characters; a point without a label keeps its number."+ ),+ "additionalProperties": {"type": "string", "maxLength": 8},+ },"properties": {"type": "array","description": "Key/value metadata shown on the node. `key` is the identity: two properties sharing one are the same property.",diff --git a/mcp/tests/test_tools.py b/mcp/tests/test_tools.pyindex 6157100..ad9019c 100644--- a/mcp/tests/test_tools.py+++ b/mcp/tests/test_tools.py@@ -707,6 +707,14 @@ def test_node_schemas_expose_the_handle_counts(tool_name):assert "show_port_numbers" in props+def test_node_schemas_expose_port_labels():+ # The device's own port numbering per connection point (#495).+ for tool_name in ("create_node", "update_node"):+ props = _tool_schema(tool_name)+ assert props["port_labels"]["type"] == "object"+ assert props["port_labels"]["additionalProperties"] == {"type": "string", "maxLength": 8}++def test_edge_schemas_expose_the_connection_points():for tool_name in ("create_edge", "update_edge"):props = _tool_schema(tool_name)