From 9eac98549e20f25bb4f81742d7aba88202aa63d1 Mon Sep 17 00:00:00 2001 From: ArmenSL <80694797+ArmenSl@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:15:43 +0100 Subject: [PATCH 1/3] feat(import): keep an existing diagram's layout on B-UML import /get-json-model takes an optional existing_model (the diagram the file updates). The imported Class, Agent or State Machine diagram is then laid out like it: matched elements keep their id, position and size, new ones are placed next to a neighbour, and warnings report what was kept, added and missing. The agent converter now reports the parts of a file it could not read (buml-import-partial) instead of only logging them. Refs #774 --- .../backend/routers/conversion_router.py | 34 +- .../buml_to_json/agent_diagram_converter.py | 29 +- .../services/converters/layout_adoption.py | 513 ++++++++++++++++++ 3 files changed, 561 insertions(+), 15 deletions(-) create mode 100644 besser/utilities/web_modeling_editor/backend/services/converters/layout_adoption.py diff --git a/besser/utilities/web_modeling_editor/backend/routers/conversion_router.py b/besser/utilities/web_modeling_editor/backend/routers/conversion_router.py index 93933720b..bcbb794ac 100644 --- a/besser/utilities/web_modeling_editor/backend/routers/conversion_router.py +++ b/besser/utilities/web_modeling_editor/backend/routers/conversion_router.py @@ -80,6 +80,7 @@ deployment_buml_to_json, ) from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import adopt_element_ids +from besser.utilities.web_modeling_editor.backend.services.converters.layout_adoption import adopt_existing_layout # Backend services - Other services from besser.utilities.web_modeling_editor.backend.services.utils.agent_generation_utils import ( @@ -382,9 +383,12 @@ async def export_buml(input_data: DiagramInput, settings: SettingsDep): ) -def _import_repair_warnings(repairs: list[str]) -> list[dict] | None: - """What the import changed to load a BUML file, in the response's warning shape.""" - return [{"code": "buml-import-repaired", "message": message} for message in repairs] or None +def _import_repair_warnings(repairs: list[str], unread: list[str] | None = None) -> list[dict] | None: + """What the import changed or could not read in a BUML file, in the response's warning shape.""" + return ( + [{"code": "buml-import-repaired", "message": message} for message in repairs] + + [{"code": "buml-import-partial", "message": message} for message in unread or []] + ) or None @router.post("/get-project-json-model", response_model=ProjectExportResponse) @@ -407,10 +411,16 @@ async def get_project_json_model(buml_file: UploadFile = File(...)): @router.post("/get-json-model", response_model=DiagramExportResponse) @handle_endpoint_errors("get_single_json_model") -async def get_single_json_model(buml_file: UploadFile = File(...)): +async def get_single_json_model(buml_file: UploadFile = File(...), existing_model: str = Form(None)): """ Convert a BUML Python file to JSON format for single diagram import. This endpoint handles both full project files and single diagram files. + + When `existing_model` is provided (as a stringified v4 diagram JSON of the + diagram the file updates), the imported diagram is laid out like it: + matched elements keep their id, position and size, new ones are placed + next to a neighbour. `warnings` then reports what was kept, added and not + in the file. Class, Agent and State Machine diagrams only. """ content = await buml_file.read() validate_upload(buml_file, max_size=MAX_BUML_SIZE, allowed_extensions=ALLOWED_BUML_EXTENSIONS, content=content) @@ -422,6 +432,7 @@ async def get_single_json_model(buml_file: UploadFile = File(...)): diagram_type = None parse_error = None repairs: list[str] = [] + unread: list[str] = [] safe_filename = os.path.basename(buml_file.filename) if buml_file.filename else "" diagram_title = safe_filename.rsplit('.', 1)[0] if safe_filename else "Imported Diagram" @@ -539,7 +550,7 @@ def _pick_entry(dtype): elif is_agent: try: logger.info("Detected Agent diagram, parsing...") - agent_json = agent_buml_to_json(buml_content) + agent_json = agent_buml_to_json(buml_content, unread) diagram_data = { "title": diagram_title, "model": agent_json @@ -661,17 +672,20 @@ def _pick_entry(dtype): "KnowledgeGraphDiagram, ComponentDiagram, DeploymentDiagram, or Project." ) + model = {**diagram_data.get("model", {}), "type": diagram_type} + warnings = _import_repair_warnings(repairs, unread) or [] + if existing_model is not None: + model, layout_warnings = adopt_existing_layout(existing_model, model, diagram_type) + warnings.extend(layout_warnings) + # Return the diagram in the format expected by the frontend return { "title": diagram_title, - "model": { - **diagram_data.get("model", {}), - "type": diagram_type - }, + "model": model, "diagramType": diagram_type, "exportedAt": datetime.now(timezone.utc).isoformat(), "version": API_VERSION, - "warnings": _import_repair_warnings(repairs), + "warnings": warnings or None, } @router.post("/get-svg") diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/agent_diagram_converter.py b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/agent_diagram_converter.py index 531dd7811..433acd406 100644 --- a/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/agent_diagram_converter.py +++ b/besser/utilities/web_modeling_editor/backend/services/converters/buml_to_json/agent_diagram_converter.py @@ -14,7 +14,7 @@ import logging import textwrap import uuid -from typing import Any, Dict, List +from typing import Any, Dict, List, Optional from besser.utilities.buml_code_builder.agent_model_builder import GUI_BUILDER_FUNCTION_PREFIX from ..json_to_buml.a2a_tags import format_a2a_line @@ -146,12 +146,19 @@ def analyze_function_node(node: ast.FunctionDef, source_code: str) -> Dict[str, } -def _agent_buml_to_flat_json(content: str) -> Dict[str, Any]: +def _note_unread(warnings: Optional[List[str]], what: str, error: Exception) -> None: + """Record that ``what`` was left out of the diagram because reading it failed.""" + if warnings is not None: + warnings.append(f"Left out {what} of the agent file that could not be read ({type(error).__name__}: {error}).") + + +def _agent_buml_to_flat_json(content: str, warnings: Optional[List[str]] = None) -> Dict[str, Any]: """ Convert an agent Python file content to JSON format matching the frontend structure. Args: content: Agent model Python code as string + warnings: Receives a message for every part of the file that could not be read Returns: Dictionary representing the agent diagram in JSON format @@ -1839,6 +1846,7 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]: except Exception as e: logger.error("Error processing agent body: %s", e, exc_info=True) + _note_unread(warnings, "a state body", e) continue # Add handling for fallback bodies @@ -1981,9 +1989,11 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]: elements[state["id"]]["fallbackBodies"].append(body_id) except Exception as e: logger.warning("Error processing agent fallback body: %s", e, exc_info=True) + _note_unread(warnings, "a fallback body", e) continue except Exception as e: logger.error("Error processing agent state machine: %s", e, exc_info=True) + _note_unread(warnings, "a statement", e) continue # Find initial state and create initial transition initial_state = None @@ -2184,8 +2194,13 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]: result["config"] = {"default_llm_name": default_llm_name_value} return result - except Exception: + except Exception as e: logger.exception("Error converting agent BUML to JSON; returning partial diagram") + if warnings is not None: + warnings.append( + f"The agent file could be read only up to an unsupported statement ({type(e).__name__}: {e}); " + "the diagram holds what was read before it, the rest of the file is not imported." + ) # On error return partial results, also split into canvas / components _COMPONENT_TYPES_FALLBACK = { 'AgentIntent', 'AgentIntentBody', 'AgentRagElement', @@ -2379,7 +2394,7 @@ def _flat_to_v4(flat: Dict[str, Any]) -> Dict[str, Any]: return result -def agent_buml_to_json(content: str) -> Dict[str, Any]: +def agent_buml_to_json(content: str, warnings: Optional[List[str]] = None) -> Dict[str, Any]: """Convert agent B-UML Python code to the v4 AgentDiagram wire shape. Canvas: ``AgentState`` nodes (inline ``data.bodies`` / ``data.fallbackBodies`` @@ -2388,8 +2403,12 @@ def agent_buml_to_json(content: str) -> Dict[str, Any]: ``CommentLink`` edges. Off-canvas: intents (+ ``AgentIntentBody`` entries), LLMs, RAG databases, tools, skills, workspaces and GUIs in the top-level ``components`` map. + + ``warnings`` receives a message for every part of the file that could not + be read and is missing from the diagram (the parser recognises the forms + the B-UML exporter writes, not every way to build an agent). """ - model = _flat_to_v4(_agent_buml_to_flat_json(content)) + model = _flat_to_v4(_agent_buml_to_flat_json(content, warnings)) _restore_a2a_tags(model, _read_a2a(content)) return model diff --git a/besser/utilities/web_modeling_editor/backend/services/converters/layout_adoption.py b/besser/utilities/web_modeling_editor/backend/services/converters/layout_adoption.py new file mode 100644 index 000000000..649da8df8 --- /dev/null +++ b/besser/utilities/web_modeling_editor/backend/services/converters/layout_adoption.py @@ -0,0 +1,513 @@ +"""Lay a diagram imported from B-UML out like the diagram it replaces (issue #774). + +A B-UML ``.py`` file carries no layout for Class, Agent and State Machine +diagrams, so importing one rebuilds the diagram on a grid with fresh ids. +``adopt_layout`` takes the diagram the editor already has and the freshly +imported one (both v4 wire shape, ``{nodes, edges}``) and returns the imported +content laid out like the existing diagram: + +- a node is matched to an existing node by id when the import kept it, else by + type and name (case-insensitive) inside the matched parent, duplicates in + order. A matched node takes the existing id and position, and the existing + size unless its new content needs more room; +- a node renamed in the file is matched to its old self only when, among the + unmatched nodes of its type and parent, it is the one on each side connected + to the same matched neighbours by the same edges (type, direction, content); + any other rename reads as a removal plus an addition; +- member rows (class attributes and methods, agent state bodies) and agent + components keep their existing ids, matched by name inside their match; +- an edge is matched by id, else by type and (matched) ends, preferring one + with the same content. A matched edge takes the existing id and handles, and + its bend points while neither end changed size; +- a new top-level node is placed on the first free slot next to a matched + neighbour it is connected to, else right of the diagram. + +Content always comes from the import. Nothing here reads B-UML. +""" + +import copy +import json +from collections import defaultdict +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple + +# Diagram types whose B-UML import rebuilds the layout and that adopt_layout handles. +# BPMN, Component and Deployment diagrams keep their layout through B-UML already. +LAYOUT_ADOPTION_DIAGRAM_TYPES = frozenset({"ClassDiagram", "AgentDiagram", "StateMachineDiagram"}) + +# Space left between a placed node and its neighbours, in canvas pixels (the grid gap of the converters). +PLACEMENT_GAP = 60 +# How many rings of slots around a neighbour are tried before a new node goes right of the diagram. +MAX_PLACEMENT_RINGS = 8 +# Slot directions around a neighbour, nearest first: right, below, left, above, then the corners. +_SLOT_DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1)) + +# Node data lists whose rows carry their own ids, and the row fields that identify a row. +_ROW_FIELDS = { + "attributes": ("name",), + "methods": ("name",), + "bodies": ("replyType", "name"), + "fallbackBodies": ("replyType", "name"), +} +# Edge data fields that are layout, not content. +_EDGE_LAYOUT_FIELDS = ("points", "isManuallyLayouted") + + +def adopt_layout(existing: Dict[str, Any], imported: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: + """Return ``imported`` laid out like ``existing``, and a report of what was matched. + + Both arguments are v4 diagram models (``nodes`` and ``edges`` lists); neither + is modified. The report holds ``matched`` (nodes that kept their id and + place), ``renamed``, ``added`` (new top-level nodes and the neighbour they + were placed next to), ``notInImport`` (existing nodes the import no longer + has), and the edge counts ``edgesKept``, ``edgesRerouted`` (kept, bend + points dropped because an end changed size) and ``edgesAdded``. + """ + result = copy.deepcopy(imported) + old_nodes = {n["id"]: n for n in _nodes(existing)} + new_nodes = _nodes(result) + taken_ids = _all_ids(result) + + node_map = _match_nodes(list(old_nodes.values()), new_nodes, taken_ids) + renamed = _match_renames(existing, result, old_nodes, new_nodes, node_map, taken_ids) + + id_map = dict(node_map) + resized = set() + for node in new_nodes: + old = old_nodes.get(node_map.get(node["id"])) + if old is None: + continue + _keep_place(node, old, node_map, resized) + for field, key_fields in _ROW_FIELDS.items(): + id_map.update(_match_items( + _rows(old, field), _rows(node, field), taken_ids, + key=lambda row, fields=key_fields: tuple(_norm(row.get(f)) for f in fields), + )) + id_map.update(_match_components(existing.get("components"), result.get("components"), taken_ids)) + result = _replace_ids(result, id_map) + + edge_map, edge_report = _match_edges(existing, result, resized, taken_ids) + result = _replace_ids(result, edge_map) + + added = _place_new_nodes(result, set(node_map.values())) + + matched_old = set(node_map.values()) + report = { + "matched": len(node_map), + "renamed": [ + {"id": old_id, "type": old_nodes[old_id]["type"], + "from": _name(old_nodes[old_id]), "to": name} + for old_id, name in renamed + ], + "added": added, + "notInImport": [ + _describe(n) for n in old_nodes.values() + if n["id"] not in matched_old and (n.get("parentId") is None or n.get("parentId") in matched_old) + ], + **edge_report, + } + return result, report + + +# --------------------------------------------------------------------------- +# Matching +# --------------------------------------------------------------------------- + +def _match_nodes(old_nodes: List[dict], new_nodes: List[dict], taken_ids: set) -> Dict[str, str]: + """New node id -> existing node id: by id first, then by type and name inside matched parents.""" + old_by_id = {n["id"]: n for n in old_nodes} + mapping = {n["id"]: n["id"] for n in new_nodes + if n["id"] in old_by_id and old_by_id[n["id"]]["type"] == n["type"]} + + old_children = _children_index(old_nodes, lambda n: n.get("parentId")) + new_children = _children_index(new_nodes, lambda n: n.get("parentId")) + + def pair(old_parent: Optional[str], new_parent: Optional[str]) -> None: + mapping.update(_match_items( + old_children.get(old_parent, []), new_children.get(new_parent, []), taken_ids, + key=_node_key, already=mapping, + )) + for node in new_children.get(new_parent, []): + if node["id"] in mapping and mapping[node["id"]] in old_children: + pair(mapping[node["id"]], node["id"]) + + pair(None, None) + return mapping + + +def _match_renames(existing: dict, result: dict, old_nodes: Dict[str, dict], new_nodes: List[dict], + node_map: Dict[str, str], taken_ids: set) -> List[Tuple[str, str]]: + """Pair a renamed node with its old self when nothing else could be meant (see module doc).""" + matched_old = set(node_map.values()) + old_left = defaultdict(list) + for n in old_nodes.values(): + if n["id"] not in matched_old and n["id"] not in taken_ids: + old_left[(n.get("parentId"), n["type"])].append(n) + new_left = defaultdict(list) + for n in new_nodes: + if n["id"] not in node_map: + parent = n.get("parentId") + new_left[(node_map.get(parent, parent), n["type"])].append(n) + + old_signatures = _neighbour_signatures(_edges(existing), lambda node_id: node_id if node_id in matched_old else None) + new_signatures = _neighbour_signatures(_edges(result), node_map.get) + renamed = [] + for slot, olds in old_left.items(): + old_by_signature = defaultdict(list) + for old in olds: + if old_signatures.get(old["id"]): + old_by_signature[old_signatures[old["id"]]].append(old) + new_by_signature = defaultdict(list) + for new in new_left.get(slot, []): + if new_signatures.get(new["id"]): + new_by_signature[new_signatures[new["id"]]].append(new) + for signature, news in new_by_signature.items(): + olds_alike = old_by_signature.get(signature, []) + if len(news) == 1 and len(olds_alike) == 1: + node_map[news[0]["id"]] = olds_alike[0]["id"] + renamed.append((olds_alike[0]["id"], _name(news[0]))) + return renamed + + +def _neighbour_signatures(edges: Iterable[dict], resolve: Callable[[str], Optional[str]]) -> Dict[str, frozenset]: + """Node id -> the (edge type, direction, neighbour, content) of its edges to resolvable neighbours.""" + signatures = defaultdict(set) + for edge in edges: + source, target = edge.get("source"), edge.get("target") + if resolve(target) is not None: + signatures[source].add((edge.get("type"), "out", resolve(target), _edge_content(edge))) + if resolve(source) is not None: + signatures[target].add((edge.get("type"), "in", resolve(source), _edge_content(edge))) + return {node_id: frozenset(sig) for node_id, sig in signatures.items()} + + +def _match_components(old: Any, new: Any, taken_ids: set) -> Dict[str, str]: + """Agent components (intents, LLMs, ...) keep their ids, matched by type and name; intent bodies by owner.""" + if not isinstance(old, dict) or not isinstance(new, dict): + return {} + old_items = [c for c in old.values() if isinstance(c, dict) and c.get("id")] + new_items = [c for c in new.values() if isinstance(c, dict) and c.get("id")] + old_by_id = {c["id"]: c for c in old_items} + mapping = {c["id"]: c["id"] for c in new_items + if c["id"] in old_by_id and old_by_id[c["id"]].get("type") == c.get("type")} + mapping.update(_match_items( + [c for c in old_items if not c.get("owner")], [c for c in new_items if not c.get("owner")], + taken_ids, key=_node_key, already=mapping, + )) + old_owned = _children_index([c for c in old_items if c.get("owner")], lambda c: c["owner"]) + new_owned = _children_index([c for c in new_items if c.get("owner")], lambda c: c["owner"]) + for new_owner, items in new_owned.items(): + if new_owner in mapping: + mapping.update(_match_items(old_owned.get(mapping[new_owner], []), items, taken_ids, + key=_node_key, already=mapping)) + return mapping + + +def _match_items(old_items: List[dict], new_items: List[dict], taken_ids: set, key: Callable[[dict], Any], + already: Optional[Dict[str, str]] = None) -> Dict[str, str]: + """New id -> old id for items with equal keys, in order. + + An old id is given once, and never when the import already uses it for something else. + """ + already = already or {} + used = set(already.values()) + buckets = defaultdict(list) + for item in old_items: + if item.get("id") and item["id"] not in used and item["id"] not in taken_ids: + buckets[key(item)].append(item) + mapping = {} + for item in new_items: + if not item.get("id") or item["id"] in already: + continue + candidates = [c for c in buckets.get(key(item), []) if c["id"] not in used] + if candidates: + mapping[item["id"]] = candidates[0]["id"] + used.add(candidates[0]["id"]) + return mapping + + +def _match_edges(existing: dict, result: dict, resized: set, taken_ids: set) -> Tuple[Dict[str, str], Dict[str, int]]: + """Give matched edges their existing id and layout; returns (new id -> old id, edge counts).""" + old_edges = list(_edges(existing)) + new_edges = list(_edges(result)) + old_by_id = {e["id"]: e for e in old_edges if e.get("id")} + mapping = {e["id"]: e["id"] for e in new_edges + if e.get("id") in old_by_id and _edge_ends(old_by_id[e["id"]]) == _edge_ends(e)} + # Same ends and content first (two transitions between the same states differ by intent), then same ends. + for key in (lambda e: (_edge_ends(e), _edge_content(e)), _edge_ends): + mapping.update(_match_items(old_edges, new_edges, taken_ids, key=key, already=mapping)) + + kept = rerouted = 0 + for edge in new_edges: + old = old_by_id.get(mapping.get(edge.get("id"))) + if old is None: + continue + kept += 1 + for handle in ("sourceHandle", "targetHandle"): + if old.get(handle): + edge[handle] = old[handle] + data = edge.setdefault("data", {}) + if {edge.get("source"), edge.get("target")} & resized: + rerouted += 1 + data["points"] = [] + data.pop("isManuallyLayouted", None) + continue + old_data = old.get("data") or {} + for field in _EDGE_LAYOUT_FIELDS: + if field in old_data: + data[field] = copy.deepcopy(old_data[field]) + else: + data.pop(field, None) + data.setdefault("points", []) + return mapping, {"edgesKept": kept, "edgesRerouted": rerouted, "edgesAdded": len(new_edges) - kept} + + +# --------------------------------------------------------------------------- +# Layout +# --------------------------------------------------------------------------- + +def _keep_place(node: dict, old: dict, node_map: Dict[str, str], resized: set) -> None: + """Give a matched node the existing position, and the existing size unless its content needs more.""" + parent = node.get("parentId") + if node_map.get(parent, parent) == old.get("parentId"): + node["position"] = dict(old.get("position") or node.get("position") or {"x": 0, "y": 0}) + old_w, old_h = _size(old) + new_w, new_h = _size(node) + width, height = max(old_w, new_w), max(old_h, new_h) + if (width, height) != (old_w, old_h): + resized.add(old["id"]) + node["width"], node["height"] = width, height + node["measured"] = {"width": width, "height": height} + + +def _place_new_nodes(result: dict, kept_ids: set) -> List[Dict[str, Any]]: + """Move every new top-level node next to a neighbour; returns what was placed where.""" + nodes = {n["id"]: n for n in _nodes(result)} + top_level = [n for n in nodes.values() if n.get("parentId") is None] + new_top = [n for n in top_level if n["id"] not in kept_ids] + taken = [_bounds(n) for n in top_level if n["id"] in kept_ids] + if not taken: + # Nothing matched: the existing diagram tells nothing about where things go. + return [{**_describe(n), "placedNextTo": None} for n in new_top] + + def top_ancestor(node_id: Optional[str]) -> Optional[str]: + seen = set() + while node_id in nodes and nodes[node_id].get("parentId") and node_id not in seen: + seen.add(node_id) + node_id = nodes[node_id]["parentId"] + return node_id if node_id in nodes else None + + neighbours = defaultdict(list) + for edge in _edges(result): + a, b = top_ancestor(edge.get("source")), top_ancestor(edge.get("target")) + if a and b and a != b: + neighbours[a].append(b) + neighbours[b].append(a) + + placed: List[Dict[str, Any]] = [] + placed_ids = set() + for node in new_top: + candidates = neighbours.get(node["id"], []) + anchor_id = next((n for n in candidates if n in kept_ids), None) \ + or next((n for n in candidates if n in placed_ids), None) + width, height = _size(node) + slot = _free_slot(width, height, _bounds(nodes[anchor_id]), taken) if anchor_id else None + if slot is None: + anchor_id = None + slot = _slot_right_of(width, height, taken) + node["position"] = {"x": slot["x"], "y": slot["y"]} + taken.append(slot) + placed_ids.add(node["id"]) + placed.append({**_describe(node), "placedNextTo": _name(nodes[anchor_id]) if anchor_id else None}) + return placed + + +def _free_slot(width: float, height: float, anchor: dict, taken: List[dict]) -> Optional[dict]: + """The first slot around ``anchor``, nearest ring first, that overlaps nothing in ``taken``.""" + step_x = max(anchor["width"], width) + PLACEMENT_GAP + step_y = max(anchor["height"], height) + PLACEMENT_GAP + for ring in range(1, MAX_PLACEMENT_RINGS + 1): + for dx, dy in _SLOT_DIRECTIONS: + slot = {"x": anchor["x"] + dx * ring * step_x, "y": anchor["y"] + dy * ring * step_y, + "width": width, "height": height} + if not any(_overlaps(slot, other) for other in taken): + return slot + return None + + +def _slot_right_of(width: float, height: float, taken: List[dict]) -> dict: + """A slot right of everything in ``taken``, moved down until it overlaps nothing.""" + slot = {"x": max(t["x"] + t["width"] for t in taken) + PLACEMENT_GAP, + "y": min(t["y"] for t in taken), "width": width, "height": height} + while any(_overlaps(slot, other) for other in taken): + slot["y"] += height + PLACEMENT_GAP + return slot + + +def _overlaps(a: dict, b: dict) -> bool: + """True when the boxes are closer than half the placement gap.""" + gap = PLACEMENT_GAP / 2 + return not (a["x"] + a["width"] + gap <= b["x"] or b["x"] + b["width"] + gap <= a["x"] + or a["y"] + a["height"] + gap <= b["y"] or b["y"] + b["height"] + gap <= a["y"]) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _nodes(model: dict) -> List[dict]: + return [n for n in model.get("nodes") or [] if isinstance(n, dict) and n.get("id")] + + +def _edges(model: dict) -> List[dict]: + return [e for e in model.get("edges") or [] if isinstance(e, dict) and e.get("id")] + + +def _rows(node: dict, field: str) -> List[dict]: + rows = (node.get("data") or {}).get(field) + return [r for r in rows if isinstance(r, dict)] if isinstance(rows, list) else [] + + +def _children_index(items: Iterable[dict], parent_of: Callable[[dict], Optional[str]]) -> Dict[Optional[str], list]: + index = defaultdict(list) + for item in items: + index[parent_of(item)].append(item) + return index + + +def _name(item: dict) -> str: + data = item.get("data") + name = data.get("name") if isinstance(data, dict) else item.get("name") + return name if isinstance(name, str) else "" + + +def _norm(value: Any) -> Any: + return value.strip().casefold() if isinstance(value, str) else value + + +def _node_key(item: dict) -> tuple: + return item.get("type"), _norm(_name(item)) + + +def _edge_ends(edge: dict) -> tuple: + return edge.get("type"), edge.get("source"), edge.get("target") + + +def _edge_content(edge: dict) -> str: + data = {k: v for k, v in (edge.get("data") or {}).items() if k not in _EDGE_LAYOUT_FIELDS} + return json.dumps(data, sort_keys=True, default=str) + + +def _size(node: dict) -> Tuple[float, float]: + measured = node.get("measured") or {} + width = node.get("width") or measured.get("width") or 0 + height = node.get("height") or measured.get("height") or 0 + return width, height + + +def _bounds(node: dict) -> dict: + position = node.get("position") or {} + width, height = _size(node) + return {"x": position.get("x", 0), "y": position.get("y", 0), "width": width, "height": height} + + +def _describe(node: dict) -> Dict[str, Any]: + return {"id": node["id"], "type": node.get("type"), "name": _name(node)} + + +def _all_ids(value: Any) -> set: + """Every ``id`` value and ``components`` key in a model.""" + ids = set() + stack = [value] + while stack: + item = stack.pop() + if isinstance(item, dict): + if isinstance(item.get("id"), str): + ids.add(item["id"]) + stack.extend(item.values()) + elif isinstance(item, list): + stack.extend(item) + return ids + + +def _replace_ids(value: Any, mapping: Dict[str, str]) -> Any: + """``value`` with every string (and dict key) found in ``mapping`` replaced: ids and references to them.""" + if not mapping: + return value + if isinstance(value, str): + return mapping.get(value, value) + if isinstance(value, list): + return [_replace_ids(v, mapping) for v in value] + if isinstance(value, dict): + return {mapping.get(k, k): _replace_ids(v, mapping) for k, v in value.items()} + return value + + +# --------------------------------------------------------------------------- +# Import endpoint glue +# --------------------------------------------------------------------------- + +def adopt_existing_layout(existing_model: str, imported: Dict[str, Any], + diagram_type: str) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: + """Lay ``imported`` out like the editor's ``existing_model`` (JSON text); returns (model, warnings). + + ``existing_model`` is the diagram being updated: a v4 model, or a project + diagram entry holding one under ``model``. When it cannot be used (not JSON, + not a v4 model, another diagram type, a type without layout adoption) the + import is returned unchanged with a ``layout-not-adopted`` warning saying why. + Otherwise the warnings report the outcome: ``layout-adopted`` (a summary), + ``element-renamed``, ``element-added`` and ``element-not-in-import``. + """ + existing, reason = _read_existing_model(existing_model, diagram_type) + if existing is None: + return imported, [{"code": "layout-not-adopted", + "message": f"The diagram is imported with a new layout: {reason}"}] + + model, report = adopt_layout(existing, imported) + warnings: List[Dict[str, Any]] = [{ + "code": "layout-adopted", + "message": (f"Kept the place and id of {report['matched']} element(s) of the existing diagram; " + f"{len(report['added'])} new, {len(report['notInImport'])} not in the imported file."), + "matched": report["matched"], + "edgesKept": report["edgesKept"], + "edgesRerouted": report["edgesRerouted"], + "edgesAdded": report["edgesAdded"], + }] + for item in report["renamed"]: + warnings.append({ + "code": "element-renamed", + "message": f"{item['type']} '{item['from']}' is read as renamed to '{item['to']}' and keeps its place.", + "elementId": item["id"], "type": item["type"], "from": item["from"], "name": item["to"], + }) + for item in report["added"]: + where = f"next to '{item['placedNextTo']}'" if item["placedNextTo"] else "right of the diagram" + warnings.append({ + "code": "element-added", + "message": f"New {item['type']} '{item['name']}' placed {where}.", + "elementId": item["id"], "type": item["type"], "name": item["name"], + "placedNextTo": item["placedNextTo"], + }) + for item in report["notInImport"]: + warnings.append({ + "code": "element-not-in-import", + "message": f"{item['type']} '{item['name']}' of the existing diagram is not in the imported file.", + "elementId": item["id"], "type": item["type"], "name": item["name"], + }) + return model, warnings + + +def _read_existing_model(text: str, diagram_type: str) -> Tuple[Optional[Dict[str, Any]], str]: + """The v4 model in ``text``, or None and the reason it cannot be used.""" + if diagram_type not in LAYOUT_ADOPTION_DIAGRAM_TYPES: + return None, f"keeping the layout of an existing {diagram_type} is not supported." + try: + value = json.loads(text) + except (TypeError, ValueError): + return None, "the existing diagram sent with the file is not valid JSON." + if isinstance(value, dict) and isinstance(value.get("model"), dict): + value = value["model"] + if not isinstance(value, dict) or not isinstance(value.get("nodes"), list): + return None, "the existing diagram sent with the file is not a diagram model with nodes." + existing_type = value.get("type") + if existing_type and existing_type != diagram_type: + return None, f"the existing diagram is a {existing_type}, the file holds a {diagram_type}." + return value, "" From 1839b22f2ef3c79882e255cd88b09725e13dab6c Mon Sep 17 00:00:00 2001 From: ArmenSL <80694797+ArmenSl@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:17:28 +0100 Subject: [PATCH 2/3] test(import): cover layout adoption and the partial agent import warning Refs #774 --- .../converters/test_layout_adoption.py | 271 ++++++++++++++++++ .../backend/test_layout_preserving_import.py | 77 +++++ 2 files changed, 348 insertions(+) create mode 100644 tests/utilities/web_modeling_editor/backend/services/converters/test_layout_adoption.py create mode 100644 tests/utilities/web_modeling_editor/backend/test_layout_preserving_import.py diff --git a/tests/utilities/web_modeling_editor/backend/services/converters/test_layout_adoption.py b/tests/utilities/web_modeling_editor/backend/services/converters/test_layout_adoption.py new file mode 100644 index 000000000..753eb3ee9 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/services/converters/test_layout_adoption.py @@ -0,0 +1,271 @@ +"""adopt_layout: an imported diagram laid out like the diagram it replaces (issue #774). + +The models come from the real converters (B-UML -> v4 JSON), the way +``/get-json-model`` builds them, so the tests see the ids and grid positions an +import actually produces. +""" + +import copy + +from besser.BUML.metamodel.state_machine.agent import Agent, AgentReply +from besser.BUML.metamodel.state_machine.state_machine import Body +from besser.BUML.metamodel.structural import ( + BinaryAssociation, + Class, + DomainModel, + Multiplicity, + PrimitiveDataType, + Property, +) +from besser.utilities.buml_code_builder.agent_model_builder import agent_model_to_code +from besser.utilities.buml_code_builder.state_machine_builder import state_machine_to_code +from besser.utilities.web_modeling_editor.backend.services.converters import ( + agent_buml_to_json, + class_buml_to_json, + process_state_machine, + state_machine_to_json, +) +from besser.utilities.web_modeling_editor.backend.services.converters.layout_adoption import ( + adopt_existing_layout, + adopt_layout, +) + + +def agent_source(tmp_path, refined=False): + """The greeting agent; ``refined`` renames ``good`` and adds a ``farewell`` state.""" + agent = Agent("Greeter") + hello = agent.new_intent("hello_intent", ["hi", "hello"]) + bye = agent.new_intent("bye_intent", ["bye"]) + initial = agent.new_state("initial", initial=True) + greeting = agent.new_state("greeting") + good = agent.new_state("feeling_good" if refined else "good") + greeting.set_body(Body("greeting_body", actions=[AgentReply("Hello!")])) + initial.when_intent_matched(hello).go_to(greeting) + greeting.when_intent_matched(hello).go_to(good) + good.go_to(initial) + if refined: + farewell = agent.new_state("farewell") + greeting.when_intent_matched(bye).go_to(farewell) + path = tmp_path / ("refined.py" if refined else "agent.py") + agent_model_to_code(agent, str(path)) + return path.read_text() + + +def laid_out(model): + """``model`` as a user left it: every node moved off the converter's grid, every edge bent.""" + model = copy.deepcopy(model) + for index, node in enumerate(model["nodes"]): + node["position"] = {"x": 37 + 230 * index, "y": 11 - 170 * index} + for edge in model["edges"]: + edge["data"]["points"] = [{"x": 1, "y": 2}, {"x": 3, "y": 4}] + edge["data"]["isManuallyLayouted"] = True + edge["sourceHandle"], edge["targetHandle"] = "bottom", "top" + return model + + +def by_name(model): + return {node["data"]["name"]: node for node in model["nodes"]} + + +def library_model(extra_class=None, rename_author=None): + string = PrimitiveDataType("str") + book = Class("Book", attributes={Property("title", string), Property("isbn", string)}) + author = Class(rename_author or "Author", attributes={Property("name", string)}) + writes = BinaryAssociation("writes", ends={ + Property("books", book, multiplicity=Multiplicity(0, "*")), + Property("authors", author, multiplicity=Multiplicity(1, "*")), + }) + types = {book, author} + if extra_class: + types.add(Class(extra_class, attributes={Property("code", string)})) + return class_buml_to_json(DomainModel("Library", types=types, associations={writes})) + + +def _ids(model): + return {node["id"] for node in model["nodes"]}, {edge["id"] for edge in model["edges"]} + + +def test_unchanged_agent_keeps_every_position_and_id(tmp_path): + existing = laid_out(agent_buml_to_json(agent_source(tmp_path))) + imported = agent_buml_to_json(agent_source(tmp_path)) + assert _ids(imported)[0].isdisjoint(_ids(existing)[0]) # the import alone gives fresh ids + + model, report = adopt_layout(existing, imported) + + assert model["nodes"] == existing["nodes"] + assert model["edges"] == existing["edges"] + assert set(model["components"]) == set(existing["components"]) + assert report["matched"] == 3 and report["added"] == [] and report["notInImport"] == [] + assert report["edgesKept"] == 3 and report["edgesAdded"] == 0 + + +def test_unchanged_class_diagram_keeps_positions_ids_and_attribute_ids(): + existing = laid_out(library_model()) + imported = library_model() + assert _ids(imported)[0].isdisjoint(_ids(existing)[0]) + row_ids = {row["id"] for node in imported["nodes"] for row in node["data"]["attributes"]} + assert row_ids.isdisjoint({row["id"] for node in existing["nodes"] for row in node["data"]["attributes"]}) + + model, report = adopt_layout(existing, imported) + + assert model["nodes"] == existing["nodes"] # positions, sizes, ids and attribute row ids + assert model["edges"] == existing["edges"] # id, handles and bend points of the association + assert report["matched"] == 2 + + +def test_new_state_is_placed_next_to_its_neighbour_without_overlap(tmp_path): + existing = laid_out(agent_buml_to_json(agent_source(tmp_path))) + model, report = adopt_layout(existing, agent_buml_to_json(agent_source(tmp_path, refined=True))) + + old, new = by_name(existing), by_name(model) + for name in ("initial", "greeting"): + assert new[name]["id"] == old[name]["id"] + assert new[name]["position"] == old[name]["position"] + farewell = new["farewell"] + assert report["added"] == [{"id": farewell["id"], "type": "AgentState", "name": "farewell", + "placedNextTo": "greeting"}] + greeting = new["greeting"]["position"] + assert abs(farewell["position"]["x"] - greeting["x"]) + abs(farewell["position"]["y"] - greeting["y"]) < 600 + + def box(node): + return (node["position"]["x"], node["position"]["y"], + node["position"]["x"] + node["width"], node["position"]["y"] + node["height"]) + + for other in model["nodes"]: + if other is not farewell: + a, b = box(farewell), box(other) + assert a[2] <= b[0] or b[2] <= a[0] or a[3] <= b[1] or b[3] <= a[1], other["data"]["name"] + + +def test_renamed_state_keeps_its_place_when_its_connections_say_so(tmp_path): + existing = laid_out(agent_buml_to_json(agent_source(tmp_path))) + model, report = adopt_layout(existing, agent_buml_to_json(agent_source(tmp_path, refined=True))) + + old_good = by_name(existing)["good"] + renamed = by_name(model)["feeling_good"] + assert (renamed["id"], renamed["position"]) == (old_good["id"], old_good["position"]) + assert report["renamed"] == [{"id": old_good["id"], "type": "AgentState", "from": "good", "to": "feeling_good"}] + assert report["notInImport"] == [] + # The three transitions the file still has keep their id and bend points; the new one is routed afresh. + old_edges = {edge["id"]: edge for edge in existing["edges"]} + kept = [edge for edge in model["edges"] if edge["id"] in old_edges] + assert len(kept) == 3 and all(edge["data"] == old_edges[edge["id"]]["data"] for edge in kept) + assert report["edgesKept"] == 3 and report["edgesAdded"] == 1 + + +def test_unconnected_renamed_class_reads_as_removed_and_added(): + existing = laid_out(library_model(extra_class="Shelf")) + model, report = adopt_layout(existing, library_model(extra_class="Rack")) + + old_shelf = by_name(existing)["Shelf"] + assert by_name(model)["Rack"]["id"] != old_shelf["id"] + assert report["renamed"] == [] + assert [item["name"] for item in report["added"]] == ["Rack"] + assert report["notInImport"] == [{"id": old_shelf["id"], "type": "class", "name": "Shelf"}] + + +def test_removed_state_is_reported_and_its_edges_dropped(tmp_path): + existing = laid_out(agent_buml_to_json(agent_source(tmp_path, refined=True))) + model, report = adopt_layout(existing, agent_buml_to_json(agent_source(tmp_path))) + + old_farewell = by_name(existing)["farewell"] + assert report["notInImport"] == [{"id": old_farewell["id"], "type": "AgentState", "name": "farewell"}] + assert old_farewell["id"] not in {e["source"] for e in model["edges"]} | {e["target"] for e in model["edges"]} + + +def test_same_named_nodes_pair_in_order_and_no_id_is_used_twice(): + existing = laid_out(library_model()) + duplicate = copy.deepcopy(existing["nodes"][0]) + duplicate["id"] = "dup-old" + duplicate["position"] = {"x": 900, "y": 900} + existing["nodes"].append(duplicate) + imported = library_model() + extra = copy.deepcopy(imported["nodes"][0]) + extra["id"] = "dup-new" + imported["nodes"].append(extra) + second = copy.deepcopy(imported["nodes"][0]) + second["id"] = "dup-third" + imported["nodes"].append(second) + + model, _ = adopt_layout(existing, imported) + + ids = [node["id"] for node in model["nodes"]] + assert len(ids) == len(set(ids)) + name = existing["nodes"][0]["data"]["name"] + same_name = [node for node in model["nodes"] if node["data"]["name"] == name] + assert [node["id"] for node in same_name[:2]] == [existing["nodes"][0]["id"], "dup-old"] + assert same_name[1]["position"] == {"x": 900, "y": 900} + + +def test_edge_drops_its_bend_points_when_an_end_grew(): + existing = laid_out(library_model()) + imported = library_model() + book = by_name(imported)["Book"] + book["height"] += 200 + book["measured"]["height"] += 200 + + model, report = adopt_layout(existing, imported) + + old_edge = existing["edges"][0] + edge = model["edges"][0] + assert edge["id"] == old_edge["id"] + assert (edge["sourceHandle"], edge["targetHandle"]) == ("bottom", "top") + assert edge["data"]["points"] == [] and "isManuallyLayouted" not in edge["data"] + assert report["edgesRerouted"] == 1 + assert by_name(model)["Book"]["position"] == by_name(existing)["Book"]["position"] + + +def test_state_machine_round_trip_keeps_positions_and_ids(): + def state(node_id, name, x, y): + return {"id": node_id, "type": "State", "position": {"x": x, "y": y}, "width": 160, "height": 40, + "data": {"name": name, "bodies": [], "fallbackBodies": []}} + + existing = { + "version": "4.0.0", "type": "StateMachineDiagram", "title": "Door", + "nodes": [ + {"id": "i", "type": "StateInitialNode", "position": {"x": -300, "y": 5}, "width": 45, "height": 45, + "data": {"name": ""}}, + state("a", "Closed", -120, 0), state("b", "Open", 260, 140), + ], + "edges": [ + {"id": "t0", "source": "i", "target": "a", "type": "StateTransition", + "sourceHandle": "right", "targetHandle": "left", "data": {"name": "", "points": []}}, + {"id": "t1", "source": "a", "target": "b", "type": "StateTransition", + "sourceHandle": "bottom", "targetHandle": "left", "data": {"name": "push", "points": []}}, + ], + } + imported = state_machine_to_json(state_machine_to_code(process_state_machine({"title": "Door", + "model": existing}))) + + model, report = adopt_layout(existing, imported) + + states = {n["data"]["name"]: n for n in model["nodes"] if n["type"] == "State"} + assert {name: (n["id"], n["position"]) for name, n in states.items()} == { + "Closed": ("a", {"x": -120, "y": 0}), "Open": ("b", {"x": 260, "y": 140}), + } + push = next(e for e in model["edges"] if e["data"].get("name") == "push") + assert (push["id"], push["sourceHandle"]) == ("t1", "bottom") + assert report["notInImport"] == [] + + +def test_unusable_existing_model_leaves_the_import_as_is(tmp_path): + imported = agent_buml_to_json(agent_source(tmp_path)) + for text, reason in [ + ("not json {", "not valid JSON"), + ('{"elements": {}, "relationships": {}}', "not a diagram model with nodes"), + ('{"type": "ClassDiagram", "nodes": []}', "the existing diagram is a ClassDiagram"), + ]: + model, warnings = adopt_existing_layout(text, imported, "AgentDiagram") + assert model is imported + assert [w["code"] for w in warnings] == ["layout-not-adopted"] and reason in warnings[0]["message"] + + _, warnings = adopt_existing_layout('{"nodes": []}', imported, "BPMNDiagram") + assert [w["code"] for w in warnings] == ["layout-not-adopted"] + + +def test_empty_existing_diagram_keeps_the_imported_layout(tmp_path): + imported = agent_buml_to_json(agent_source(tmp_path)) + model, warnings = adopt_existing_layout('{"type": "AgentDiagram", "nodes": [], "edges": []}', + imported, "AgentDiagram") + assert [n["position"] for n in model["nodes"]] == [n["position"] for n in imported["nodes"]] + assert [w["code"] for w in warnings] == ["layout-adopted"] + ["element-added"] * 3 diff --git a/tests/utilities/web_modeling_editor/backend/test_layout_preserving_import.py b/tests/utilities/web_modeling_editor/backend/test_layout_preserving_import.py new file mode 100644 index 000000000..cd38fd3f7 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/test_layout_preserving_import.py @@ -0,0 +1,77 @@ +"""/get-json-model with ``existing_model``: a re-imported B-UML file keeps the diagram's layout (issue #774).""" + +import json + +from besser.BUML.metamodel.state_machine.agent import Agent +from besser.utilities.buml_code_builder.agent_model_builder import agent_model_to_code + +URL = "/besser_api/get-json-model" + +# An agent written with keyword arguments, as people (and LLMs) write B-UML by hand. +# The agent parser reads the exporter's positional form only. +KEYWORD_STYLE_AGENT = '''from besser.BUML.metamodel.state_machine.agent import Agent +agent = Agent(name="kw") +hello = agent.new_intent(name="hello", training_sentences=["hi"]) +s0 = agent.new_state(name="initial", initial=True) +s1 = agent.new_state(name="next") +s0.when_intent_matched(hello).go_to(s1) +''' + + +def agent_source(tmp_path, with_farewell): + agent = Agent("Greeter") + hello = agent.new_intent("hello_intent", ["hi"]) + initial = agent.new_state("initial", initial=True) + greeting = agent.new_state("greeting") + initial.when_intent_matched(hello).go_to(greeting) + if with_farewell: + greeting.go_to(agent.new_state("farewell")) + path = tmp_path / "agent.py" + agent_model_to_code(agent, str(path)) + return path.read_text() + + +def post(client, source, existing_model=None): + data = {"existing_model": existing_model} if existing_model is not None else None + response = client.post(URL, files={"buml_file": ("agent.py", source.encode(), "text/plain")}, data=data) + assert response.status_code == 200, response.text + return response.json() + + +def test_reimport_keeps_the_layout_of_the_existing_diagram(client, tmp_path): + first = post(client, agent_source(tmp_path, with_farewell=False)) + existing = first["model"] + for index, node in enumerate(existing["nodes"]): + node["position"] = {"x": 500 + 300 * index, "y": 400} + + body = post(client, agent_source(tmp_path, with_farewell=True), json.dumps(existing)) + + nodes = {node["data"]["name"]: node for node in body["model"]["nodes"]} + for old in existing["nodes"]: + assert (nodes[old["data"]["name"]]["id"], nodes[old["data"]["name"]]["position"]) == \ + (old["id"], old["position"]) + codes = [warning["code"] for warning in body["warnings"]] + assert codes == ["layout-adopted", "element-added"] + added = body["warnings"][1] + assert (added["name"], added["placedNextTo"], added["elementId"]) == \ + ("farewell", "greeting", nodes["farewell"]["id"]) + assert body["diagramType"] == body["model"]["type"] == "AgentDiagram" + + +def test_without_existing_model_the_response_is_unchanged(client, tmp_path): + body = post(client, agent_source(tmp_path, with_farewell=False)) + assert body["warnings"] is None + assert [node["position"] for node in body["model"]["nodes"]] == [{"x": -280, "y": -80}, {"x": 210, "y": -80}] + + +def test_unusable_existing_model_imports_with_a_warning(client, tmp_path): + body = post(client, agent_source(tmp_path, with_farewell=False), "{not json") + assert [warning["code"] for warning in body["warnings"]] == ["layout-not-adopted"] + assert len(body["model"]["nodes"]) == 2 + + +def test_partly_read_agent_says_so(client): + body = post(client, KEYWORD_STYLE_AGENT) + assert body["model"]["nodes"] == [] + assert [warning["code"] for warning in body["warnings"]] == ["buml-import-partial"] + assert "could be read only up to an unsupported statement" in body["warnings"][0]["message"] From 085b15305ed7e7c0e7fa3239383f04580bfc8ecf Mon Sep 17 00:00:00 2001 From: ArmenSL <80694797+ArmenSl@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:35:35 +0100 Subject: [PATCH 3/3] docs(backend): document existing_model and the import warnings of /get-json-model Refs #774 --- docs/source/web_editor_backend.rst | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/docs/source/web_editor_backend.rst b/docs/source/web_editor_backend.rst index daebb90e4..672ca2e71 100644 --- a/docs/source/web_editor_backend.rst +++ b/docs/source/web_editor_backend.rst @@ -650,7 +650,22 @@ Conversion - ``POST /get-json-model`` -- BUML Python file to JSON (auto-detects diagram type) - ``POST /get-project-json-model`` -- BUML project file to JSON. Both import endpoints answer 400 with the reason when a model cannot be read, and list in ``warnings`` (``{code, message}``) what they repaired to - load it, e.g. a composition whose owner end was not navigable + load it, e.g. a composition whose owner end was not navigable. ``/get-json-model`` also lists the parts of an + agent file it could not read (``buml-import-partial``) rather than returning a shorter diagram silently. + + Updating an existing diagram from a file: ``/get-json-model`` takes an optional ``existing_model`` form field, + the editor's v4 model of the diagram the file updates (as JSON text; a project diagram entry with the model + under ``model`` works too). For a Class, Agent or State Machine diagram the import is then laid out like it + (``services/converters/layout_adoption.py``): an element matched by id, or else by type and name inside its + matched parent, keeps its id, position and size (the size grows when its new content needs more room), as do + its attribute, method and body rows and the agent's components; a renamed element is recognised only when its + connections to matched neighbours are unchanged; a new element is placed next to a matched neighbour it is + connected to; a matched edge keeps its id, handles and bend points (the points are dropped when an end grew). + ``warnings`` reports the outcome: ``layout-adopted`` (summary and edge counts), ``element-renamed``, + ``element-added`` (with ``placedNextTo``) and ``element-not-in-import``, each with the ``elementId``, ``type`` + and ``name``. An ``existing_model`` that is not JSON, not a v4 model, of another diagram type, or of a type + without layout adoption leaves the import as is, with a ``layout-not-adopted`` warning saying why. Without the + field the response is unchanged - ``POST /get-json-model-from-image`` -- Image to ClassDiagram JSON (requires OpenAI API key) - ``POST /get-json-model-from-kg`` -- **Deprecated.** Knowledge graph (TTL/RDF/JSON) to ClassDiagram JSON through OpenAI (requires an OpenAI API key). Use ``/kg/import-owl`` and ``/kg/to-class-diagram`` instead - ``POST /csv-to-domain-model`` -- CSV **or XLSX** files to domain model JSON (both extensions are accepted; XLSX needs ``openpyxl``)