Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(mcp): make connection points editable over MCP
Pouzore247483d9b75
diff --git a/backend/app/api/routes/nodes.py b/backend/app/api/routes/nodes.pyindex 4442c6c..a383402 100644--- a/backend/app/api/routes/nodes.py+++ b/backend/app/api/routes/nodes.py@@ -1,13 +1,20 @@from typing import Anyfrom fastapi import APIRouter, Depends, HTTPException, Query, status-from sqlalchemy import select+from sqlalchemy import or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.api.deps import get_current_userfrom app.db.database import get_db-from app.db.models import Design, InventoryDevice, Node+from app.db.models import Design, Edge, InventoryDevice, Nodefrom app.schemas.nodes import NodeCreate, NodeResponse, NodeUpdate+from app.schemas.utils import (+ SIDES,+ handle_count_field,+ handle_id,+ removed_handle_ids,+ side_default,+)from app.services.doc_links import unlink_documentsfrom app.services.inventory_sync import (facts_from_payload,@@ -21,6 +28,47 @@ from app.services.node_dedupe import find_duplicate_noderouter = APIRouter()+# ---------------------------------------------------------------------------+# Connection-point helpers+# ---------------------------------------------------------------------------+++async def _remap_shrunk_handles(db: AsyncSession, node: Node, sent: dict[str, Any]) -> None:+ """Move this node's edges off the connection points a shrink just deleted.++ The canvas store does the same remap client-side (canvasStore.updateNode), so+ the UI never hits this; an API client — the MCP write tools — lowers a handle+ count without it, and React Flow silently drops an edge whose handle no longer+ exists. Removed handles fall back to the side's slot-0 ID, or to 'bottom' when+ the side went to zero and has no slot 0 left.++ Call before the new counts are written to the node.+ """+ fallbacks: dict[str, str] = {}+ for side in SIDES:+ field = handle_count_field(side)+ new_count = sent.get(field)+ if new_count is None:+ continue+ raw_old = getattr(node, field, None)+ old_count = raw_old if isinstance(raw_old, int) else side_default(side)+ if new_count >= old_count:+ continue+ fallback = 'bottom' if new_count == 0 else handle_id(side, 0)+ for hid in removed_handle_ids(side, old_count, new_count):+ fallbacks[hid] = fallback++ if not fallbacks:+ return++ result = await db.execute(select(Edge).where(or_(Edge.source == node.id, Edge.target == node.id)))+ for edge in result.scalars().all():+ if edge.source == node.id and edge.source_handle in fallbacks:+ edge.source_handle = fallbacks[edge.source_handle]+ if edge.target == node.id and edge.target_handle in fallbacks:+ edge.target_handle = fallbacks[edge.target_handle]++# ---------------------------------------------------------------------------# Auto-positioning helpers# ---------------------------------------------------------------------------@@ -156,6 +204,8 @@ async def update_node(# Dropped rather than rejected so the rest of the edit still lands.if sent.get("parent_id") == node_id:sent.pop("parent_id")+ # Before the new counts land: the old ones are what says which handles go away.+ await _remap_shrunk_handles(db, node, sent)for field, value in node_columns(sent).items():setattr(node, field, value)# The user edited the device, not just its drawing: push the facts down.diff --git a/backend/app/schemas/canvas.py b/backend/app/schemas/canvas.pyindex fff826a..e1c90cf 100644--- a/backend/app/schemas/canvas.py+++ b/backend/app/schemas/canvas.py@@ -1,10 +1,10 @@from typing import Any-from pydantic import BaseModel, field_validator, model_validator+from pydantic import BaseModel, ValidationInfo, field_validator, model_validatorfrom app.schemas.edges import EdgeResponsefrom app.schemas.nodes import NodeResponse-from app.schemas.utils import normalize_animated, normalize_marker+from app.schemas.utils import clamp_handles, normalize_animated, normalize_markerclass NodeSave(BaseModel):@@ -54,6 +54,16 @@ class NodeSave(BaseModel):pos_x: float = 0pos_y: float = 0+ # Same 0..64 clamp the create/update schemas apply, so a full-canvas save+ # cannot store a count the renderer would silently narrow.+ @field_validator('bottom_handles', 'top_handles', 'left_handles', 'right_handles', mode='before')+ @classmethod+ def clamp_handle_count(cls, v: object, info: ValidationInfo) -> object:+ if v is None:+ return None+ side = (info.field_name or '').removesuffix('_handles')+ return clamp_handles(side, v)+@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 38834ed..a58afb8 100644--- a/backend/app/schemas/nodes.py+++ b/backend/app/schemas/nodes.py@@ -1,7 +1,9 @@from datetime import datetimefrom typing import Any-from pydantic import BaseModel+from pydantic import BaseModel, ValidationInfo, field_validator++from app.schemas.utils import clamp_handlesclass NodeBase(BaseModel):@@ -39,6 +41,18 @@ class NodeBase(BaseModel):left_handles: int = 0right_handles: int = 0+ # Connection-point counts are clamped to 0..64 here rather than in the route:+ # the frontend clamps them again at render (handleUtils.clampHandles), so an+ # unclamped row would draw a different node than it stores. See #435 — the MCP+ # write tools reach these fields without the canvas UI's own bounds.+ @field_validator('bottom_handles', 'top_handles', 'left_handles', 'right_handles', mode='before')+ @classmethod+ def clamp_handle_count(cls, v: object, info: ValidationInfo) -> object:+ if v is None:+ return None+ side = (info.field_name or '').removesuffix('_handles')+ return clamp_handles(side, v)+class NodeCreate(NodeBase):# Override pos_x/pos_y so callers can omit them; None signals "auto-place".@@ -85,6 +99,18 @@ class NodeUpdate(BaseModel):left_handles: int | None = Noneright_handles: int | None = None+ # Connection-point counts are clamped to 0..64 here rather than in the route:+ # the frontend clamps them again at render (handleUtils.clampHandles), so an+ # unclamped row would draw a different node than it stores. See #435 — the MCP+ # write tools reach these fields without the canvas UI's own bounds.+ @field_validator('bottom_handles', 'top_handles', 'left_handles', 'right_handles', mode='before')+ @classmethod+ def clamp_handle_count(cls, v: object, info: ValidationInfo) -> object:+ if v is None:+ return None+ side = (info.field_name or '').removesuffix('_handles')+ return clamp_handles(side, v)+class NodeResponse(NodeBase):id: strdiff --git a/backend/app/schemas/utils.py b/backend/app/schemas/utils.pyindex 6f9a924..9e7ebbc 100644--- a/backend/app/schemas/utils.py+++ b/backend/app/schemas/utils.py@@ -1,3 +1,6 @@+import math++def normalize_animated(v: object) -> str:"""Normalize legacy bool/int animated values to string mode ('none'/'snake'/'flow')."""if v is True or v == 1 or v == '1':@@ -25,3 +28,58 @@ def normalize_marker(v: object) -> str:if isinstance(v, str) and v in MARKER_SHAPES:return vreturn 'none'+++# ---------------------------------------------------------------------------+# Connection points (React Flow handles)+# ---------------------------------------------------------------------------+# Mirrors frontend/src/utils/handleUtils.ts — keep the two in step.+#+# Handle IDs: slot 0 = the bare side name ('top' | 'bottom' | 'left' | 'right')+# slot N >= 1 = '{side}-{N + 1}' (e.g. 'bottom-2', 'left-3')+#+# Slot 0 keeps the bare name so edges saved before the multi-handle expansion+# stay valid. Invisible target handles carry a '-t' suffix on the frontend only;+# what is stored on an edge is always the source form.++SIDES = ('top', 'bottom', 'left', 'right')++MIN_HANDLES = 0+MAX_HANDLES = 64+++def side_default(side: str) -> int:+ """Count a side falls back to when the node carries no explicit value.++ Top/bottom default to their historical single handle; left/right to none, so+ an existing diagram gains no side handles unless the user opts in.+ """+ return 1 if side in ('top', 'bottom') else 0+++def handle_count_field(side: str) -> str:+ """The `nodes` column storing a side's handle count."""+ return f"{side}_handles"+++def clamp_handles(side: str, n: object) -> int:+ """Clamp a raw count into 0..64.++ A non-numeric or non-finite value falls back to the side default, so a+ corrupt field still yields the historical count; an explicit 0 is honoured.+ """+ if isinstance(n, bool) or not isinstance(n, int | float):+ return side_default(side)+ if isinstance(n, float) and not math.isfinite(n):+ return side_default(side)+ return max(MIN_HANDLES, min(MAX_HANDLES, math.floor(n)))+++def handle_id(side: str, idx: int) -> str:+ """The source handle ID at a given slot index for a side."""+ return side if idx == 0 else f"{side}-{idx + 1}"+++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)}diff --git a/backend/tests/test_canvas.py b/backend/tests/test_canvas.pyindex ce3c378..73cef35 100644--- a/backend/tests/test_canvas.py+++ b/backend/tests/test_canvas.py@@ -119,6 +119,18 @@ async def test_save_canvas_round_trips_per_side_handles(client: AsyncClient, heaassert node["right_handles"] == 4+async def test_save_canvas_clamps_per_side_handles(client: AsyncClient, headers: dict):+ # Same 0..64 bound the create/update routes apply (#435): the renderer clamps+ # at draw time, so a saved count above it would draw a node the row doesn't+ # describe.+ n1 = node_payload(label="Sw", type="switch", bottom_handles=5000, left_handles=-2)+ await client.post("/api/v1/canvas/save", json={"nodes": [n1], "edges": [], "viewport": {"x": 0, "y": 0, "zoom": 1}}, headers=headers)++ node = (await client.get("/api/v1/canvas", headers=headers)).json()["nodes"][0]+ assert node["bottom_handles"] == 64+ assert node["left_handles"] == 0++async def test_save_canvas_defaults_per_side_handles(client: AsyncClient, headers: dict):# Nodes saved without the new fields fall back to top/bottom=1, left/right=0.n1 = node_payload(label="Srv", type="server")diff --git a/backend/tests/test_nodes.py b/backend/tests/test_nodes.pyindex d1fe57a..d17e977 100644--- a/backend/tests/test_nodes.py+++ b/backend/tests/test_nodes.py@@ -487,3 +487,184 @@ async def test_a_device_node_never_keeps_a_description(client: AsyncClient, head)assert res.json()["description"] is Noneassert res.json()["notes"] == "Backs up nightly."+++# ---------------------------------------------------------------------------+# Connection points (#435)+# ---------------------------------------------------------------------------+# Handle counts became writable over the MCP, which reaches these fields without+# the canvas UI's own bounds and edge bookkeeping. Both now live server-side.+++async def test_handle_count_is_clamped_on_create(client: AsyncClient, headers: dict):+ # The renderer clamps to 0..64 anyway (handleUtils.clampHandles), so an+ # unclamped row would draw a different node than it stores.+ res = await client.post(+ "/api/v1/nodes",+ json={"type": "switch", "label": "sw1", "bottom_handles": 5000, "left_handles": -3},+ headers=headers,+ )+ assert res.status_code == 201+ assert res.json()["bottom_handles"] == 64+ assert res.json()["left_handles"] == 0+++async def test_handle_count_is_clamped_on_update(client: AsyncClient, headers: dict):+ node_id = (+ await client.post("/api/v1/nodes", json={"type": "switch", "label": "sw1"}, headers=headers)+ ).json()["id"]++ res = await client.patch(f"/api/v1/nodes/{node_id}", json={"right_handles": 999}, headers=headers)++ assert res.status_code == 200+ assert res.json()["right_handles"] == 64+++async def test_a_handle_count_of_zero_is_honoured(client: AsyncClient, headers: dict):+ # 0 is a real value, not a missing one: a side can have no connection point.+ node_id = (+ await client.post("/api/v1/nodes", json={"type": "switch", "label": "sw1"}, headers=headers)+ ).json()["id"]++ res = await client.patch(f"/api/v1/nodes/{node_id}", json={"top_handles": 0}, headers=headers)++ assert res.json()["top_handles"] == 0+++async def _edge_by_id(client: AsyncClient, headers: dict, edge_id: str) -> dict:+ edges = (await client.get("/api/v1/edges", headers=headers)).json()+ return next(e for e in edges if e["id"] == edge_id)+++async def test_shrinking_a_side_moves_its_edges_to_slot_zero(client: AsyncClient, headers: dict):+ # Regression: React Flow silently drops an edge whose handle no longer+ # exists, so the link vanishes from the canvas with no error.+ 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": "nas1"}, headers=headers)).json()["id"]+ edge_id = (+ await client.post(+ "/api/v1/edges",+ json={"source": src, "target": tgt, "source_handle": "bottom-4", "target_handle": "top"},+ headers=headers,+ )+ ).json()["id"]++ await client.patch(f"/api/v1/nodes/{src}", json={"bottom_handles": 2}, headers=headers)++ edge = await _edge_by_id(client, headers, edge_id)+ assert edge["source_handle"] == "bottom"+ assert edge["target_handle"] == "top"+++async def test_shrinking_a_side_leaves_the_surviving_handles_alone(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": "nas1"}, headers=headers)).json()["id"]+ edge_id = (+ await client.post(+ "/api/v1/edges",+ json={"source": src, "target": tgt, "source_handle": "bottom-2", "target_handle": "top"},+ headers=headers,+ )+ ).json()["id"]++ await client.patch(f"/api/v1/nodes/{src}", json={"bottom_handles": 2}, headers=headers)++ assert (await _edge_by_id(client, headers, edge_id))["source_handle"] == "bottom-2"+++async def test_a_side_dropped_to_zero_falls_back_to_bottom(client: AsyncClient, headers: dict):+ # Slot 0 goes away with the side, so there is nothing on it to fall back to.+ src = (+ await client.post(+ "/api/v1/nodes", json={"type": "switch", "label": "sw1", "right_handles": 2}, headers=headers+ )+ ).json()["id"]+ tgt = (await client.post("/api/v1/nodes", json={"type": "nas", "label": "nas1"}, headers=headers)).json()["id"]+ edge_id = (+ await client.post(+ "/api/v1/edges",+ json={"source": src, "target": tgt, "source_handle": "right-2", "target_handle": "top"},+ headers=headers,+ )+ ).json()["id"]++ await client.patch(f"/api/v1/nodes/{src}", json={"right_handles": 0}, headers=headers)++ assert (await _edge_by_id(client, headers, edge_id))["source_handle"] == "bottom"+++async def test_the_target_end_is_remapped_too(client: AsyncClient, headers: dict):+ 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": "switch", "label": "sw1", "top_handles": 3}, headers=headers+ )+ ).json()["id"]+ edge_id = (+ await client.post(+ "/api/v1/edges",+ json={"source": src, "target": tgt, "source_handle": "bottom", "target_handle": "top-3"},+ headers=headers,+ )+ ).json()["id"]++ await client.patch(f"/api/v1/nodes/{tgt}", json={"top_handles": 1}, headers=headers)++ edge = await _edge_by_id(client, headers, edge_id)+ assert edge["target_handle"] == "top"+ assert edge["source_handle"] == "bottom"+++async def test_growing_a_side_touches_no_edge(client: AsyncClient, headers: dict):+ src = (+ await client.post(+ "/api/v1/nodes", json={"type": "switch", "label": "sw1", "bottom_handles": 2}, headers=headers+ )+ ).json()["id"]+ tgt = (await client.post("/api/v1/nodes", json={"type": "nas", "label": "nas1"}, headers=headers)).json()["id"]+ edge_id = (+ await client.post(+ "/api/v1/edges",+ json={"source": src, "target": tgt, "source_handle": "bottom-2", "target_handle": "top"},+ headers=headers,+ )+ ).json()["id"]++ await client.patch(f"/api/v1/nodes/{src}", json={"bottom_handles": 8}, headers=headers)++ assert (await _edge_by_id(client, headers, edge_id))["source_handle"] == "bottom-2"+++async def test_another_nodes_edges_are_not_remapped(client: AsyncClient, headers: dict):+ # The shrink is scoped to the node being edited; an unrelated link that+ # happens to sit on the same handle ID must survive untouched.+ shrunk = (+ await client.post(+ "/api/v1/nodes", json={"type": "switch", "label": "sw1", "bottom_handles": 4}, headers=headers+ )+ ).json()["id"]+ other = (+ await client.post(+ "/api/v1/nodes", json={"type": "switch", "label": "sw2", "bottom_handles": 4}, headers=headers+ )+ ).json()["id"]+ tgt = (await client.post("/api/v1/nodes", json={"type": "nas", "label": "nas1"}, headers=headers)).json()["id"]+ edge_id = (+ await client.post(+ "/api/v1/edges",+ json={"source": other, "target": tgt, "source_handle": "bottom-4", "target_handle": "top"},+ headers=headers,+ )+ ).json()["id"]++ await client.patch(f"/api/v1/nodes/{shrunk}", json={"bottom_handles": 1}, headers=headers)++ assert (await _edge_by_id(client, headers, edge_id))["source_handle"] == "bottom-4"diff --git a/mcp/app/tools.py b/mcp/app/tools.pyindex 3faefe4..cf75796 100644--- a/mcp/app/tools.py+++ b/mcp/app/tools.py@@ -62,6 +62,15 @@ _NODE_FIELDS = {# (`merge_properties` / `apply_view` in backend/app/services/inventory_sync.py).# A property with no `key` collapses with every other keyless one — send two# and the node draws one.+ # Connection points. The count is per side; the IDs an edge references are+ # derived from it — slot 0 is the bare side name, slot N >= 1 is+ # '{side}-{N + 1}' (frontend/src/utils/handleUtils.ts). Lowering a count+ # moves the edges that used the dropped handles back to the side's slot 0.+ "top_handles": {"type": "integer", "minimum": 0, "maximum": 64, "description": "Connection points on the top side (default 1). Their IDs are 'top', 'top-2', 'top-3', ..."},+ "bottom_handles": {"type": "integer", "minimum": 0, "maximum": 64, "description": "Connection points on the bottom side (default 1). Their IDs are 'bottom', 'bottom-2', 'bottom-3', ..."},+ "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."},"properties": {"type": "array","description": "Key/value metadata shown on the node. `key` is the identity: two properties sharing one are the same property.",@@ -90,6 +99,15 @@ _ZONE_COLOR_FIELDS = {"text_color": {"type": "string", "description": "Label colour, e.g. '#e6edf3'."},}+# Which connection point each end of an edge attaches to. The IDs are the node's+# 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).+_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."},+}+# Optional design/canvas selector. The backend attaches nodes/edges to the first# design when design_id is omitted (see backend nodes.py / edges.py), so these# tools stay backward compatible; pass design_id to target a specific canvas.@@ -129,7 +147,7 @@ def _build_tools() -> list[Tool]:"required": ["id"],"properties": {"id": {"type": "string"}},}),- Tool(name="create_edge", description="Create a network link between two nodes", inputSchema={+ Tool(name="create_edge", description="Create a network link between two nodes. Pass source_handle/target_handle to choose which connection points it attaches to; omit them and the server picks from the nodes' relative positions.", inputSchema={"type": "object","required": ["source", "target"],"properties": {@@ -137,9 +155,24 @@ def _build_tools() -> list[Tool]:"target": {"type": "string"},"type": {"type": "string", "enum": EDGE_TYPES, "default": "ethernet"},"label": {"type": "string"},+ **_EDGE_HANDLE_FIELDS,**_DESIGN_ID_FIELD,},}),+ Tool(name="update_edge", description="Update an existing link: its type, label, or which connection points it attaches to. Call get_canvas to discover edge ids.", inputSchema={+ "type": "object",+ "required": ["id"],+ "properties": {+ "id": {"type": "string", "description": "Edge id."},+ "type": {"type": "string", "enum": EDGE_TYPES},+ "label": {"type": "string"},+ **_EDGE_HANDLE_FIELDS,+ },+ }),+ Tool(name="list_edges", description="List every link with its full detail — type, label, waypoints, and the source_handle/target_handle each end attaches to. get_canvas slims edges down to id/source/target/type/label; use this when the connection points or styling matter.", inputSchema={+ "type": "object",+ "properties": {},+ }),Tool(name="delete_edge", description="Delete a network link", inputSchema={"type": "object","required": ["id"],@@ -371,6 +404,13 @@ async def _dispatch(name: str, args: dict) -> dict:if name == "create_edge":return await backend.post("/api/v1/edges", args)+ if name == "update_edge":+ edge_id = args.pop("id")+ return await backend.patch(f"/api/v1/edges/{edge_id}", args)++ if name == "list_edges":+ return await backend.get("/api/v1/edges")+if name == "delete_edge":return await backend.delete(f"/api/v1/edges/{args['id']}")diff --git a/mcp/tests/test_tools.py b/mcp/tests/test_tools.pyindex c071fb4..eb60be6 100644--- a/mcp/tests/test_tools.py+++ b/mcp/tests/test_tools.py@@ -688,3 +688,78 @@ def test_update_node_documents_that_status_is_observed_not_set():tool = next(t for t in TOOLS if t.name == "update_node")description = tool.inputSchema["properties"]["status"]["description"]assert "status checker" in description and "unknown" in description+++# ---------------------------------------------------------------------------+# Connection points (#435)+# ---------------------------------------------------------------------------++[email protected]("tool_name", ["create_node", "update_node"])+def test_node_schemas_expose_the_handle_counts(tool_name):+ # They were readable through get_node but not settable — the whole of #435.+ props = _tool_schema(tool_name)+ for side in ("top", "bottom", "left", "right"):+ field = f"{side}_handles"+ assert field in props, f"{tool_name} schema missing {field}"+ assert props[field]["minimum"] == 0+ assert props[field]["maximum"] == 64+ assert "show_port_numbers" in props+++def test_edge_schemas_expose_the_connection_points():+ for tool_name in ("create_edge", "update_edge"):+ props = _tool_schema(tool_name)+ assert "source_handle" in props, f"{tool_name} schema missing source_handle"+ assert "target_handle" in props, f"{tool_name} schema missing target_handle"+++def test_update_edge_schema_cannot_repoint_or_move_an_edge():+ # EdgeUpdate carries neither source/target nor design_id: an edge is deleted+ # and recreated to change what it connects, never patched.+ props = _tool_schema("update_edge")+ assert props.keys() >= {"id"}+ for absent in ("source", "target", "design_id"):+ assert absent not in props+++async def test_update_node_forwards_handle_counts(mock_backend):+ await _dispatch("update_node", {"id": "42", "left_handles": 3, "right_handles": 0})+ mock_backend.patch.assert_called_once_with(+ "/api/v1/nodes/42", {"left_handles": 3, "right_handles": 0}+ )+++async def test_create_node_forwards_handle_counts(mock_backend):+ args = {"type": "switch", "label": "sw1", "bottom_handles": 8, "show_port_numbers": True}+ await _dispatch("create_node", dict(args))+ mock_backend.post.assert_called_once_with("/api/v1/nodes", args)+++async def test_create_edge_forwards_explicit_handles(mock_backend):+ args = {"source": "1", "target": "2", "source_handle": "bottom-3", "target_handle": "left"}+ await _dispatch("create_edge", dict(args))+ mock_backend.post.assert_called_once_with("/api/v1/edges", args)+++async def test_update_edge_patches_by_id(mock_backend):+ await _dispatch("update_edge", {"id": "e7", "source_handle": "right-2", "label": "uplink"})+ mock_backend.patch.assert_called_once_with(+ "/api/v1/edges/e7", {"source_handle": "right-2", "label": "uplink"}+ )+++async def test_list_edges_returns_the_unslimmed_edges(mock_backend):+ # get_canvas slims source_handle/target_handle away; this is how they're read.+ edge = {"id": "e1", "source": "1", "target": "2", "source_handle": "bottom-2", "target_handle": "top"}+ mock_backend.get = AsyncMock(return_value=[edge])++ result = await _dispatch("list_edges", {})++ mock_backend.get.assert_called_once_with("/api/v1/edges")+ assert result == [edge]