Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(edges): reject an edge endpoint the node has no connection point for
Pouzor08d85a40c172
diff --git a/backend/app/api/routes/edges.py b/backend/app/api/routes/edges.pyindex 1255d9c..272ee3d 100644--- a/backend/app/api/routes/edges.py+++ b/backend/app/api/routes/edges.py@@ -6,6 +6,7 @@ from app.api.deps import get_current_userfrom app.db.database import get_dbfrom app.db.models import Design, Edge, Nodefrom app.schemas.edges import EdgeCreate, EdgeResponse, EdgeUpdate+from app.schemas.utils import SIDES, clamp_handles, handle_count_field, parse_side_handlerouter = APIRouter()@@ -55,6 +56,74 @@ async def _auto_handles(return "top", "bottom-t"+# ---------------------------------------------------------------------------+# Connection-point guards+# ---------------------------------------------------------------------------+++def _side_count(node: Node, side: str) -> int:+ """A node's clamped connection-point count for one side."""+ return clamp_handles(side, getattr(node, handle_count_field(side), None))+++async def _reject_missing_handle(db: AsyncSession, node_id: str, handle: str | None, role: str) -> None:+ """422 when an endpoint names a connection point its node does not have.++ React Flow draws nothing for an edge whose handle ID resolves to no element,+ so such an edge would persist and be invisible on the canvas with no error+ anywhere — the same failure `_remap_shrunk_handles` prevents when a count is+ lowered. Callers that supply no handle are auto-assigned one instead and+ never reach this.+ """+ if handle is None:+ return+ parsed = parse_side_handle(handle)+ if parsed is None:+ # Not a per-side handle ('cluster-right' and friends): its own renderer+ # owns it, and no count here describes it.+ return+ side, idx = parsed+ node = await db.get(Node, node_id)+ if node is None:+ # An unknown node is not this guard's error to report; the edge routes+ # have never checked that either endpoint exists.+ return+ count = _side_count(node, side)+ if 0 <= idx < count:+ return+ raise HTTPException(+ status_code=422,+ detail=(+ f"{role}_handle '{handle}' does not exist: node {node_id} has {count} "+ f"connection point(s) on its {side} side."+ ),+ )+++async def _existing_handle(db: AsyncSession, node_id: str, handle: str) -> str:+ """Keep an auto-assigned handle, or swap it for one the node actually has.++ The auto-assignment below always names a top/bottom slot 0, which a node that+ opted out of those sides no longer draws. The server picked it, not the+ caller, so this corrects it silently rather than raising. A node with no+ connection point at all keeps the original: there is nothing better to use,+ and refusing to create the edge would lose more than it saves.+ """+ node = await db.get(Node, node_id)+ if node is None:+ return handle+ parsed = parse_side_handle(handle)+ if parsed is not None:+ side, idx = parsed+ if 0 <= idx < _side_count(node, side):+ return handle+ suffix = "-t" if handle.endswith("-t") else ""+ for side in SIDES:+ if _side_count(node, side) > 0:+ return f"{side}{suffix}"+ return handle++@router.get("", response_model=list[EdgeResponse])async def list_edges(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[Edge]:result = await db.execute(select(Edge))@@ -75,12 +144,15 @@ async def create_edge(body: EdgeCreate, db: AsyncSession = Depends(get_db), _: s# Compares the canvas Y positions of both nodes so that the edge always exits# the upstream node's bottom and enters the downstream node's top (or vice versa# for reverse flows), matching the UI convention for top-to-bottom topologies.+ await _reject_missing_handle(db, data["source"], data.get("source_handle"), "source")+ await _reject_missing_handle(db, data["target"], data.get("target_handle"), "target")+if data.get("source_handle") is None or data.get("target_handle") is None:auto_src, auto_tgt = await _auto_handles(db, data["source"], data["target"])if data.get("source_handle") is None:- data["source_handle"] = auto_src+ data["source_handle"] = await _existing_handle(db, data["source"], auto_src)if data.get("target_handle") is None:- data["target_handle"] = auto_tgt+ data["target_handle"] = await _existing_handle(db, data["target"], auto_tgt)edge = Edge(**data)db.add(edge)@@ -105,7 +177,10 @@ async def update_edge(edge = await db.get(Edge, edge_id)if not edge:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Edge not found")- for field, value in body.model_dump(exclude_unset=True).items():+ sent = body.model_dump(exclude_unset=True)+ await _reject_missing_handle(db, edge.source, sent.get("source_handle"), "source")+ await _reject_missing_handle(db, edge.target, sent.get("target_handle"), "target")+ for field, value in sent.items():setattr(edge, field, value)await db.commit()await db.refresh(edge)diff --git a/backend/app/schemas/utils.py b/backend/app/schemas/utils.pyindex 9e7ebbc..54d8ff9 100644--- a/backend/app/schemas/utils.py+++ b/backend/app/schemas/utils.py@@ -1,4 +1,5 @@import math+import redef normalize_animated(v: object) -> str:@@ -83,3 +84,29 @@ def handle_id(side: str, idx: int) -> str:def removed_handle_ids(side: str, old_count: int, new_count: int) -> set[str]:"""The source handle IDs dropped when a side shrinks from old to new count."""return {handle_id(side, i) for i in range(new_count, old_count)}+++# A side handle ID, in either the source form ('left', 'left-3') or the+# invisible target form the frontend renders alongside it ('left-t', 'left-3-t').+_SIDE_HANDLE_RE = re.compile(r'^(top|bottom|left|right)(?:-(\d+))?(?:-t)?$')+++def parse_side_handle(handle: str) -> tuple[str, int] | None:+ """Split a side handle ID into (side, slot index), or None when it isn't one.++ A handle outside this vocabulary is left for its owner to interpret — the+ 'cluster-*' IDs a specialized node renderer draws are not per-side handles+ and must not be validated against a side's count.++ The numbered form is 2-based, because slot 0 keeps the bare side name: an+ ID ending in '-0' or '-1' is therefore one the canvas never emits, and is+ reported as slot -1 so that no count can satisfy it.+ """+ m = _SIDE_HANDLE_RE.match(handle)+ if m is None:+ return None+ side, slot = m.group(1), m.group(2)+ if slot is None:+ return side, 0+ idx = int(slot) - 1+ return side, (idx if idx >= 1 else -1)diff --git a/backend/tests/test_edges.py b/backend/tests/test_edges.pyindex 4110291..9feca2b 100644--- a/backend/tests/test_edges.py+++ b/backend/tests/test_edges.py@@ -330,3 +330,154 @@ async def test_create_edge_child_node_abs_y_resolved_through_parent(client: Asyndata = res.json()assert data["source_handle"] == "bottom"assert data["target_handle"] == "top-t"+++# ---------------------------------------------------------------------------+# Connection-point guards (#435)+# ---------------------------------------------------------------------------+# An edge whose handle ID resolves to no element is dropped by React Flow: it+# persists in the DB and is simply invisible. Handles became settable over the+# MCP, so the endpoints now check them.+++async def test_create_edge_rejects_a_handle_the_node_does_not_have(client: AsyncClient, headers: dict, two_nodes):+ src, tgt = two_nodes+ res = await client.post(+ "/api/v1/edges",+ json={"source": src, "target": tgt, "source_handle": "right-3", "target_handle": "top"},+ headers=headers,+ )+ assert res.status_code == 422+ assert "right-3" in res.json()["detail"]+ assert (await client.get("/api/v1/edges", headers=headers)).json() == []+++async def test_create_edge_rejects_a_side_the_node_opted_out_of(client: AsyncClient, headers: dict):+ # left/right default to zero connection points, so even slot 0 is absent.+ src = (await client.post("/api/v1/nodes", json={"type": "router", "label": "R1"}, headers=headers)).json()["id"]+ tgt = (await client.post("/api/v1/nodes", json={"type": "nas", "label": "N1"}, headers=headers)).json()["id"]++ res = await client.post(+ "/api/v1/edges", json={"source": src, "target": tgt, "source_handle": "left"}, headers=headers+ )++ assert res.status_code == 422+++async def test_create_edge_accepts_a_handle_the_node_opted_into(client: AsyncClient, headers: dict):+ src = (+ await client.post(+ "/api/v1/nodes", json={"type": "proxmox", "label": "pve1", "right_handles": 1}, headers=headers+ )+ ).json()["id"]+ tgt = (+ await client.post(+ "/api/v1/nodes", json={"type": "proxmox", "label": "pve2", "left_handles": 1}, headers=headers+ )+ ).json()["id"]++ res = await client.post(+ "/api/v1/edges",+ json={"source": src, "target": tgt, "type": "cluster", "source_handle": "right", "target_handle": "left"},+ headers=headers,+ )++ assert res.status_code == 201+ assert res.json()["source_handle"] == "right"+++async def test_create_edge_accepts_the_target_form_of_a_handle(client: AsyncClient, headers: dict):+ # '<side>-t' is the invisible target twin the canvas renders beside slot 0;+ # the auto-assignment stores exactly that, so it must validate.+ src = (await client.post("/api/v1/nodes", json={"type": "router", "label": "R1"}, headers=headers)).json()["id"]+ tgt = (+ await client.post("/api/v1/nodes", json={"type": "nas", "label": "N1", "top_handles": 2}, headers=headers)+ ).json()["id"]++ res = await client.post(+ "/api/v1/edges",+ json={"source": src, "target": tgt, "source_handle": "bottom", "target_handle": "top-2-t"},+ headers=headers,+ )++ assert res.status_code == 201+ assert res.json()["target_handle"] == "top-2-t"+++async def test_create_edge_leaves_a_foreign_handle_namespace_alone(client: AsyncClient, headers: dict, two_nodes):+ # 'cluster-right' is not a per-side handle; no count here describes it, so+ # the guard must not judge it.+ src, tgt = two_nodes+ res = await client.post(+ "/api/v1/edges",+ json={"source": src, "target": tgt, "type": "cluster", "source_handle": "cluster-right"},+ headers=headers,+ )+ assert res.status_code == 201+++async def test_update_edge_rejects_a_handle_the_node_does_not_have(client: AsyncClient, headers: dict, two_nodes):+ src, tgt = two_nodes+ edge_id = (+ await client.post("/api/v1/edges", json={"source": src, "target": tgt}, headers=headers)+ ).json()["id"]++ res = await client.patch(f"/api/v1/edges/{edge_id}", json={"source_handle": "bottom-9"}, headers=headers)++ assert res.status_code == 422+ edge = (await client.get("/api/v1/edges", headers=headers)).json()[0]+ assert edge["source_handle"] == "bottom"+++async def test_update_edge_accepts_a_handle_the_node_has(client: AsyncClient, headers: dict):+ src = (+ await client.post(+ "/api/v1/nodes", json={"type": "switch", "label": "sw1", "bottom_handles": 4}, headers=headers+ )+ ).json()["id"]+ tgt = (await client.post("/api/v1/nodes", json={"type": "nas", "label": "N1"}, headers=headers)).json()["id"]+ edge_id = (+ await client.post("/api/v1/edges", json={"source": src, "target": tgt}, headers=headers)+ ).json()["id"]++ res = await client.patch(f"/api/v1/edges/{edge_id}", json={"source_handle": "bottom-4"}, headers=headers)++ assert res.status_code == 200+ assert res.json()["source_handle"] == "bottom-4"+++async def test_auto_assignment_avoids_a_side_with_no_connection_point(client: AsyncClient, headers: dict):+ # The caller supplied no handle, so the server corrects its own pick rather+ # than raising: bottom is gone, and the node's remaining side is used.+ src = (+ await client.post(+ "/api/v1/nodes",+ json={"type": "switch", "label": "sw1", "bottom_handles": 0, "top_handles": 0, "right_handles": 2},+ headers=headers,+ )+ ).json()["id"]+ tgt = (await client.post("/api/v1/nodes", json={"type": "nas", "label": "N1"}, headers=headers)).json()["id"]++ res = await client.post("/api/v1/edges", json={"source": src, "target": tgt}, headers=headers)++ assert res.status_code == 201+ assert res.json()["source_handle"] == "right"+ assert res.json()["target_handle"] == "top-t"+++async def test_auto_assignment_keeps_its_pick_when_the_node_has_nothing(client: AsyncClient, headers: dict):+ # Every side is empty: there is no better handle to reach for, and refusing+ # the edge would lose more than it saves.+ src = (+ await client.post(+ "/api/v1/nodes",+ json={"type": "switch", "label": "sw1", "top_handles": 0, "bottom_handles": 0},+ headers=headers,+ )+ ).json()["id"]+ tgt = (await client.post("/api/v1/nodes", json={"type": "nas", "label": "N1"}, headers=headers)).json()["id"]++ res = await client.post("/api/v1/edges", json={"source": src, "target": tgt}, headers=headers)++ assert res.status_code == 201+ assert res.json()["source_handle"] == "bottom"diff --git a/backend/tests/test_handle_utils.py b/backend/tests/test_handle_utils.pynew file mode 100644index 0000000..9af88bc--- /dev/null+++ b/backend/tests/test_handle_utils.py@@ -0,0 +1,84 @@+"""Unit tests for the per-side connection-point vocabulary.++Mirrors frontend/src/utils/handleUtils.ts — the two must agree, or the server+stores handles the canvas cannot draw.+"""++import pytest++from app.schemas.utils import (+ MAX_HANDLES,+ clamp_handles,+ handle_count_field,+ handle_id,+ parse_side_handle,+ removed_handle_ids,+ side_default,+)++[email protected](("side", "expected"), [("top", 1), ("bottom", 1), ("left", 0), ("right", 0)])+def test_side_default(side: str, expected: int) -> None:+ assert side_default(side) == expected+++def test_handle_count_field() -> None:+ assert handle_count_field("left") == "left_handles"++[email protected](("raw", "expected"), [(0, 0), (3, 3), (64, 64), (65, 64), (5000, MAX_HANDLES), (-1, 0)])+def test_clamp_handles_bounds(raw: int, expected: int) -> None:+ assert clamp_handles("bottom", raw) == expected++[email protected]("raw", [None, "4", float("nan"), float("inf"), True])+def test_clamp_handles_falls_back_to_the_side_default(raw: object) -> None:+ # A missing or corrupt count still yields the historical number, per side.+ assert clamp_handles("bottom", raw) == 1+ assert clamp_handles("left", raw) == 0+++def test_clamp_handles_truncates_a_fraction() -> None:+ assert clamp_handles("bottom", 3.9) == 3+++def test_handle_id_keeps_the_bare_side_name_for_slot_zero() -> None:+ # Slot 0 stays 'bottom' so edges saved before the multi-handle expansion+ # keep resolving.+ assert handle_id("bottom", 0) == "bottom"+ assert handle_id("bottom", 1) == "bottom-2"+ assert handle_id("left", 3) == "left-4"+++def test_removed_handle_ids() -> None:+ assert removed_handle_ids("bottom", 4, 2) == {"bottom-3", "bottom-4"}+ assert removed_handle_ids("bottom", 2, 2) == set()+ assert removed_handle_ids("bottom", 1, 4) == set()+++ ("handle", "expected"),+ [+ ("top", ("top", 0)),+ ("bottom-2", ("bottom", 1)),+ ("left-4", ("left", 3)),+ # The invisible target twin resolves to the same slot as its source.+ ("right-t", ("right", 0)),+ ("bottom-3-t", ("bottom", 2)),+ ],+)+def test_parse_side_handle(handle: str, expected: tuple[str, int]) -> None:+ assert parse_side_handle(handle) == expected++[email protected]("handle", ["cluster-right", "", "middle", "top-left", "bottom-x"])+def test_parse_side_handle_ignores_a_foreign_namespace(handle: str) -> None:+ # Not a per-side handle: whoever owns it interprets it, not the side counts.+ assert parse_side_handle(handle) is None++[email protected]("handle", ["bottom-0", "bottom-1"])+def test_parse_side_handle_reports_an_impossible_slot(handle: str) -> None:+ # The numbered form is 2-based, so these are IDs the canvas never emits;+ # slot -1 means no count can satisfy them.+ assert parse_side_handle(handle) == ("bottom", -1)diff --git a/mcp/app/tools.py b/mcp/app/tools.pyindex cf75796..dfcc75f 100644--- a/mcp/app/tools.py+++ b/mcp/app/tools.py@@ -103,9 +103,12 @@ _ZONE_COLOR_FIELDS = {# per-side handle IDs (see the *_handles fields above): 'bottom', 'bottom-2',# 'left-3', ... Omit both on create and the backend picks them from the two nodes'# relative positions (_auto_handles in backend/app/api/routes/edges.py).+#+# The node must already have the connection point — left/right default to none —+# or the backend answers 422 rather than storing an edge the canvas cannot draw._EDGE_HANDLE_FIELDS = {- "source_handle": {"type": "string", "description": "Connection point on the source node, e.g. 'bottom' or 'right-2'. Omit to let the server pick."},- "target_handle": {"type": "string", "description": "Connection point on the target node, e.g. 'top' or 'left-3'. Omit to let the server pick."},+ "source_handle": {"type": "string", "description": "Connection point on the source node, e.g. 'bottom' or 'right-2'. The node must have it already — raise that side's *_handles first, or the call is rejected. Omit to let the server pick."},+ "target_handle": {"type": "string", "description": "Connection point on the target node, e.g. 'top' or 'left-3'. The node must have it already — raise that side's *_handles first, or the call is rejected. Omit to let the server pick."},}# Optional design/canvas selector. The backend attaches nodes/edges to the first