Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

Add Draw.io CLI harness for agent-native diagram creation

Xilonng Zhangb4b3f8c3fb39
diff --git a/.gitignore b/.gitignore
index 8b48a77c8..b52049176 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,6 +28,7 @@
!/kdenlive/
!/shotcut/
!/anygen/
+!/drawio/
# Step 5: Inside each software dir, ignore everything (including dotfiles)
/gimp/*
@@ -48,6 +49,8 @@
/shotcut/.*
/anygen/*
/anygen/.*
+/drawio/*
+/drawio/.*
# Step 6: ...except agent-harness/
!/gimp/agent-harness/
@@ -59,6 +62,7 @@
!/kdenlive/agent-harness/
!/shotcut/agent-harness/
!/anygen/agent-harness/
+!/drawio/agent-harness/
# Step 7: Ignore build artifacts within allowed dirs
**/__pycache__/
@@ -73,6 +77,7 @@
**/*.blend
**/*.xcf
**/*.mlt
+**/*.drawio
# Step 8: But allow assets images
!/assets/*.png
diff --git a/drawio/agent-harness/DRAWIO.md b/drawio/agent-harness/DRAWIO.md
new file mode 100644
index 000000000..d18934776
--- /dev/null
+++ b/drawio/agent-harness/DRAWIO.md
@@ -0,0 +1,126 @@
+# Draw.io — CLI Harness Analysis & SOP
+
+## Software Overview
+
+**Draw.io** (diagrams.net) is a free, open-source diagramming tool. The desktop version is built on Electron and supports creating flowcharts, architecture diagrams, ER diagrams, UML, network diagrams, and more.
+
+## Architecture
+
+### File Format: mxGraph XML (.drawio)
+
+Draw.io uses an XML-based format built on the mxGraph library:
+
+```xml
+<mxfile host="cli-anything" agent="cli-anything-drawio/1.0.0">
+ <diagram id="..." name="Page-1">
+ <mxGraphModel dx="1200" dy="800" grid="1" gridSize="10"
+ page="1" pageWidth="850" pageHeight="1100">
+ <root>
+ <mxCell id="0"/> <!-- root container -->
+ <mxCell id="1" parent="0"/> <!-- default layer -->
+ <mxCell id="v_123" value="Server" <!-- shape (vertex) -->
+ style="rounded=1;fillColor=#dae8fc;"
+ vertex="1" parent="1">
+ <mxGeometry x="100" y="100" width="120" height="60" as="geometry"/>
+ </mxCell>
+ <mxCell id="e_456" value="query" <!-- connector (edge) -->
+ style="edgeStyle=orthogonalEdgeStyle;"
+ edge="1" source="v_123" target="v_789" parent="1">
+ <mxGeometry relative="1" as="geometry"/>
+ </mxCell>
+ </root>
+ </mxGraphModel>
+ </diagram>
+</mxfile>
+```
+
+**Key properties:**
+- Plain-text XML — fully parseable and writable by the CLI
+- Multi-page support: multiple `<diagram>` elements under `<mxfile>`
+- System cells: `id="0"` (root) and `id="1"` (default layer) are always present
+- Shapes: `<mxCell vertex="1">` with `<mxGeometry>` for position/size
+- Edges: `<mxCell edge="1" source="..." target="...">`
+- Styles: semicolon-delimited key=value pairs in the `style` attribute
+
+### Rendering Pipeline
+
+**Primary: draw.io desktop CLI**
+```
+.drawio file → draw.io --export --format png → rendered image
+```
+
+The desktop Electron app supports headless export:
+- `draw.io --export input.drawio --output out.png --format png`
+- `draw.io --export input.drawio --output out.pdf --format pdf`
+- `draw.io --export input.drawio --output out.svg --format svg`
+
+**Fallback: direct XML write**
+When draw.io CLI is not installed, the CLI saves the `.drawio` file directly.
+Users can open it in draw.io (web or desktop) for manual export.
+
+## CLI Strategy
+
+### What we manipulate directly (no GUI needed):
+- **Project lifecycle**: create blank XML, parse existing files, write to disk
+- **Shapes**: add/remove/move/resize `<mxCell vertex="1">` elements
+- **Connectors**: add/remove `<mxCell edge="1">` with source/target references
+- **Styles**: parse/modify the `style` attribute string
+- **Pages**: add/remove/rename `<diagram>` elements
+- **Labels**: set the `value` attribute on any cell
+
+### What we delegate to draw.io CLI:
+- **Raster export**: PNG, PDF rendering (requires the Electron app)
+- **SVG export**: Vector rendering with proper font/text handling
+
+## Shape Registry
+
+| CLI Name | Style Base | Description |
+|----------|-----------|-------------|
+| rectangle | `rounded=0;whiteSpace=wrap;html=1` | Standard rectangle |
+| rounded | `rounded=1;whiteSpace=wrap;html=1` | Rounded rectangle |
+| ellipse | `ellipse;whiteSpace=wrap;html=1` | Circle/oval |
+| diamond | `rhombus;whiteSpace=wrap;html=1` | Decision diamond |
+| triangle | `triangle;whiteSpace=wrap;html=1` | Triangle |
+| hexagon | `shape=hexagon;...` | Hexagon |
+| cylinder | `shape=cylinder3;...` | Database cylinder |
+| cloud | `ellipse;shape=cloud;...` | Cloud shape |
+| parallelogram | `shape=parallelogram;...` | Parallelogram |
+| process | `shape=process;...` | Process box |
+| document | `shape=document;...` | Document shape |
+| callout | `shape=callout;...` | Speech callout |
+| note | `shape=note;...` | Sticky note |
+| actor | `shape=mxgraph.basic.person;...` | Person/actor |
+| text | `text;html=1;align=center;...` | Text label |
+
+## Edge Style Registry
+
+| CLI Name | Style | Description |
+|----------|-------|-------------|
+| straight | `edgeStyle=none` | Straight line |
+| orthogonal | `edgeStyle=orthogonalEdgeStyle;rounded=0` | Right-angle routing |
+| curved | `edgeStyle=orthogonalEdgeStyle;curved=1;rounded=1` | Curved routing |
+| entity-relation | `edgeStyle=entityRelationEdgeStyle` | ER diagram style |
+
+## Style Properties
+
+Common style keys applicable to shapes and connectors:
+
+| Key | Values | Description |
+|-----|--------|-------------|
+| fillColor | `#rrggbb` | Shape fill color |
+| strokeColor | `#rrggbb` | Border/line color |
+| fontColor | `#rrggbb` | Text color |
+| fontSize | integer | Font size in points |
+| fontStyle | 0/1/2/4 | 0=normal, 1=bold, 2=italic, 4=underline |
+| opacity | 0-100 | Opacity percentage |
+| rounded | 0/1 | Rounded corners |
+| shadow | 0/1 | Drop shadow |
+| dashed | 0/1 | Dashed border/line |
+| strokeWidth | number | Border/line width |
+| endArrow | classic/block/open/none | Arrow head style |
+| startArrow | classic/block/open/none | Arrow tail style |
+
+## Test Coverage
+
+- **Unit tests**: XML manipulation, style parsing, all shape/edge presets, session undo/redo, multi-page operations, complex workflows
+- **E2E tests**: file roundtrip, XML export verification, real draw.io export (PNG/SVG/PDF with magic byte checks), CLI subprocess, real-world diagram scenarios
diff --git a/drawio/agent-harness/cli_anything/drawio/README.md b/drawio/agent-harness/cli_anything/drawio/README.md
new file mode 100644
index 000000000..cab639bb4
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/README.md
@@ -0,0 +1,84 @@
+# cli-anything-drawio
+
+A CLI harness for **Draw.io** — create, edit, and export diagrams from the command line.
+
+Designed for AI agents and power users who need to generate diagrams programmatically.
+
+## Prerequisites
+
+- **Python 3.10+**
+- **draw.io desktop app** (for PNG/PDF/SVG export):
+ - macOS: `brew install --cask drawio`
+ - Linux: `snap install drawio`
+ - Windows: `winget install JGraph.Draw`
+
+Note: The CLI can create and manipulate `.drawio` files without the desktop app installed. The app is only needed for rasterized export (PNG, PDF, SVG).
+
+## Installation
+
+```bash
+cd drawio/agent-harness
+pip install -e .
+```
+
+## Usage
+
+### One-shot commands
+
+```bash
+# Create a new diagram
+cli-anything-drawio project new --preset letter -o diagram.drawio
+
+# Add shapes
+cli-anything-drawio --project diagram.drawio shape add rectangle --label "Server"
+cli-anything-drawio --project diagram.drawio shape add cylinder --label "Database" --x 300 --y 100
+
+# Connect shapes
+cli-anything-drawio --project diagram.drawio connect add <source_id> <target_id>
+
+# Export
+cli-anything-drawio --project diagram.drawio export render output.png -f png
+cli-anything-drawio --project diagram.drawio export render output.svg -f svg
+```
+
+### JSON mode (for AI agents)
+
+```bash
+cli-anything-drawio --json project new -o diagram.drawio
+cli-anything-drawio --json --project diagram.drawio shape add rectangle --label "API"
+cli-anything-drawio --json --project diagram.drawio shape list
+```
+
+### Interactive REPL
+
+```bash
+cli-anything-drawio
+# or
+cli-anything-drawio repl --project diagram.drawio
+```
+
+## Command Reference
+
+| Group | Command | Description |
+|-------|---------|-------------|
+| `project` | `new`, `open`, `save`, `info`, `xml`, `presets` | Project lifecycle |
+| `shape` | `add`, `remove`, `list`, `label`, `move`, `resize`, `style`, `info`, `types` | Shape operations |
+| `connect` | `add`, `remove`, `label`, `style`, `list`, `styles` | Connector operations |
+| `page` | `add`, `remove`, `rename`, `list` | Multi-page management |
+| `export` | `render`, `formats` | Export to PNG/PDF/SVG/XML |
+| `session` | `status`, `undo`, `redo`, `save-state`, `list` | Session management |
+
+## Shape Types
+
+rectangle, rounded, ellipse, diamond, triangle, hexagon, cylinder, cloud, parallelogram, process, document, callout, note, actor, text
+
+## Edge Styles
+
+straight, orthogonal, curved, entity-relation
+
+## Running Tests
+
+```bash
+cd drawio/agent-harness
+python3 -m pytest cli_anything/drawio/tests/ -v
+```
diff --git a/drawio/agent-harness/cli_anything/drawio/__init__.py b/drawio/agent-harness/cli_anything/drawio/__init__.py
new file mode 100644
index 000000000..2f4e2a3f8
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/__init__.py
@@ -0,0 +1 @@
+"""Draw.io CLI package."""
diff --git a/drawio/agent-harness/cli_anything/drawio/core/__init__.py b/drawio/agent-harness/cli_anything/drawio/core/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/drawio/agent-harness/cli_anything/drawio/core/connectors.py b/drawio/agent-harness/cli_anything/drawio/core/connectors.py
new file mode 100644
index 000000000..1027baff3
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/core/connectors.py
@@ -0,0 +1,120 @@
+"""Connector (edge) operations: add, remove, modify, list."""
+
+from ..utils import drawio_xml
+from .session import Session
+
+
+def list_connectors(session: Session, diagram_index: int = 0) -> list[dict]:
+ """List all connectors (edges) on a page."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+ cells = drawio_xml.get_edges(session.root, diagram_index)
+ return [drawio_xml.get_cell_info(c) for c in cells]
+
+
+def add_connector(session: Session, source_id: str, target_id: str,
+ edge_style: str = "orthogonal", label: str = "",
+ diagram_index: int = 0) -> dict:
+ """Add a connector between two shapes.
+
+ Args:
+ session: Active session.
+ source_id: Source shape cell ID.
+ target_id: Target shape cell ID.
+ edge_style: Edge style preset (straight, orthogonal, curved,
+ entity-relation) or raw style string.
+ label: Optional label on the edge.
+
+ Returns:
+ Dict with action and new edge info.
+ """
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ # Validate source and target exist
+ if drawio_xml.find_cell_by_id(session.root, source_id, diagram_index) is None:
+ raise ValueError(f"Source cell not found: {source_id}")
+ if drawio_xml.find_cell_by_id(session.root, target_id, diagram_index) is None:
+ raise ValueError(f"Target cell not found: {target_id}")
+
+ session.checkpoint()
+ edge_id = drawio_xml.add_edge(
+ session.root, source_id, target_id, edge_style, label,
+ diagram_index=diagram_index,
+ )
+
+ return {
+ "action": "add_connector",
+ "id": edge_id,
+ "source": source_id,
+ "target": target_id,
+ "style": edge_style,
+ "label": label,
+ }
+
+
+def remove_connector(session: Session, edge_id: str,
+ diagram_index: int = 0) -> dict:
+ """Remove a connector by ID."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ found = drawio_xml.remove_cell(session.root, edge_id, diagram_index)
+ if not found:
+ raise ValueError(f"Connector not found: {edge_id}")
+
+ return {
+ "action": "remove_connector",
+ "id": edge_id,
+ }
+
+
+def update_connector_label(session: Session, edge_id: str, label: str,
+ diagram_index: int = 0) -> dict:
+ """Update a connector's label."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ found = drawio_xml.update_cell_label(session.root, edge_id, label, diagram_index)
+ if not found:
+ raise ValueError(f"Connector not found: {edge_id}")
+
+ return {
+ "action": "update_connector_label",
+ "id": edge_id,
+ "label": label,
+ }
+
+
+def set_connector_style(session: Session, edge_id: str,
+ key: str, value: str,
+ diagram_index: int = 0) -> dict:
+ """Set a style property on a connector.
+
+ Common style keys:
+ strokeColor, strokeWidth, dashed, endArrow, startArrow,
+ edgeStyle, curved, rounded, opacity
+ """
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ cell = drawio_xml.find_cell_by_id(session.root, edge_id, diagram_index)
+ if cell is None:
+ raise ValueError(f"Connector not found: {edge_id}")
+
+ session.checkpoint()
+ drawio_xml.set_style_property(cell, key, value)
+
+ return {
+ "action": "set_connector_style",
+ "id": edge_id,
+ "key": key,
+ "value": value,
+ }
+
+
+def list_edge_styles() -> dict:
+ """List all available edge style presets."""
+ return {name: style for name, style in sorted(drawio_xml.EDGE_STYLES.items())}
diff --git a/drawio/agent-harness/cli_anything/drawio/core/export.py b/drawio/agent-harness/cli_anything/drawio/core/export.py
new file mode 100644
index 000000000..c43392c25
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/core/export.py
@@ -0,0 +1,130 @@
+"""Export/render operations: export diagrams to PNG, PDF, SVG."""
+
+import os
+import shutil
+import tempfile
+from typing import Optional
+
+from ..utils import drawio_xml
+from ..utils import drawio_backend
+from .session import Session
+
+
+# Export format configurations
+EXPORT_FORMATS = {
+ "png": {"ext": ".png", "description": "PNG image (raster)"},
+ "pdf": {"ext": ".pdf", "description": "PDF document"},
+ "svg": {"ext": ".svg", "description": "SVG vector image"},
+ "vsdx": {"ext": ".vsdx", "description": "Microsoft Visio format"},
+ "xml": {"ext": ".xml", "description": "Uncompressed draw.io XML"},
+}
+
+
+def list_formats() -> list[dict]:
+ """List all available export formats."""
+ return [
+ {"name": name, **info}
+ for name, info in sorted(EXPORT_FORMATS.items())
+ ]
+
+
+def render(session: Session, output_path: str,
+ fmt: str = "png",
+ page_index: Optional[int] = None,
+ scale: Optional[float] = None,
+ width: Optional[int] = None,
+ height: Optional[int] = None,
+ transparent: bool = False,
+ crop: bool = False,
+ overwrite: bool = False) -> dict:
+ """Export the current project to a file.
+
+ This works by:
+ 1. Saving the project to a temporary .drawio file
+ 2. Invoking draw.io CLI to render/export
+
+ Args:
+ session: Active session with an open project.
+ output_path: Path for the output file.
+ fmt: Export format (png, pdf, svg, vsdx, xml).
+ page_index: Page index to export (default: first page).
+ scale: Scale factor for PNG export.
+ width: Output width in pixels (PNG only).
+ height: Output height in pixels (PNG only).
+ transparent: Transparent background (PNG only).
+ crop: Crop to content.
+ overwrite: Overwrite existing output.
+
+ Returns:
+ Dict with export results.
+ """
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ if fmt not in EXPORT_FORMATS:
+ available = ", ".join(sorted(EXPORT_FORMATS.keys()))
+ raise ValueError(f"Unknown format: {fmt!r}. Available: {available}")
+
+ output_path = os.path.abspath(output_path)
+ if os.path.exists(output_path) and not overwrite:
+ raise FileExistsError(
+ f"Output file already exists: {output_path}. Use --overwrite to replace."
+ )
+
+ # For XML format, just save the drawio XML directly
+ if fmt == "xml":
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
+ drawio_xml.write_drawio(session.root, output_path)
+ return {
+ "action": "export",
+ "output": output_path,
+ "format": "xml",
+ "method": "direct-write",
+ "file_size": os.path.getsize(output_path),
+ }
+
+ # Save to temp file, then invoke draw.io CLI
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False, mode="wb") as f:
+ temp_path = f.name
+ drawio_xml.write_drawio(session.root, temp_path)
+
+ try:
+ result = drawio_backend.export_diagram(
+ drawio_path=temp_path,
+ output_path=output_path,
+ fmt=fmt,
+ page_index=page_index,
+ scale=scale,
+ width=width,
+ height=height,
+ transparent=transparent,
+ crop=crop,
+ overwrite=True, # We already checked above
+ )
+ result["action"] = "export"
+ return result
+ finally:
+ os.unlink(temp_path)
+
+
+def render_or_save(session: Session, output_path: str,
+ fmt: str = "png", **kwargs) -> dict:
+ """Export with fallback: if draw.io CLI is not available, save the .drawio
+ file and provide instructions for manual export.
+ """
+ try:
+ return render(session, output_path, fmt, **kwargs)
+ except RuntimeError as e:
+ if "not installed" not in str(e):
+ raise
+ # Fallback: save .drawio and generate instructions
+ drawio_path = os.path.splitext(output_path)[0] + ".drawio"
+ drawio_xml.write_drawio(session.root, drawio_path)
+ return {
+ "action": "export_fallback",
+ "drawio_file": os.path.abspath(drawio_path),
+ "target_output": output_path,
+ "target_format": fmt,
+ "note": "draw.io CLI not found. Open the .drawio file in draw.io to export manually.",
+ "install_hint": str(e),
+ }
diff --git a/drawio/agent-harness/cli_anything/drawio/core/pages.py b/drawio/agent-harness/cli_anything/drawio/core/pages.py
new file mode 100644
index 000000000..6fda226a9
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/core/pages.py
@@ -0,0 +1,59 @@
+"""Multi-page operations: add, remove, rename, list pages."""
+
+from ..utils import drawio_xml
+from .session import Session
+
+
+def list_pages(session: Session) -> list[dict]:
+ """List all pages in the diagram."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+ return drawio_xml.list_pages(session.root)
+
+
+def add_page(session: Session, name: str = "",
+ page_width: int = 850, page_height: int = 1100) -> dict:
+ """Add a new page to the diagram."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ diagram_id = drawio_xml.add_page(session.root, name, page_width, page_height)
+
+ pages = drawio_xml.list_pages(session.root)
+ return {
+ "action": "add_page",
+ "diagram_id": diagram_id,
+ "page_count": len(pages),
+ "name": pages[-1]["name"],
+ }
+
+
+def remove_page(session: Session, page_index: int) -> dict:
+ """Remove a page by index. Cannot remove the last page."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ drawio_xml.remove_page(session.root, page_index)
+
+ return {
+ "action": "remove_page",
+ "removed_index": page_index,
+ "page_count": len(session.root.findall("diagram")),
+ }
+
+
+def rename_page(session: Session, page_index: int, name: str) -> dict:
+ """Rename a page."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ drawio_xml.rename_page(session.root, page_index, name)
+
+ return {
+ "action": "rename_page",
+ "page_index": page_index,
+ "name": name,
+ }
diff --git a/drawio/agent-harness/cli_anything/drawio/core/project.py b/drawio/agent-harness/cli_anything/drawio/core/project.py
new file mode 100644
index 000000000..36b2121ca
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/core/project.py
@@ -0,0 +1,122 @@
+"""Project management operations."""
+
+import os
+from typing import Optional
+
+from ..utils import drawio_xml
+from .session import Session
+
+
+# Standard page presets
+PAGE_PRESETS = {
+ "letter": {"width": 850, "height": 1100},
+ "a4": {"width": 827, "height": 1169},
+ "a3": {"width": 1169, "height": 1654},
+ "16:9": {"width": 1280, "height": 720},
+ "4:3": {"width": 1024, "height": 768},
+ "square": {"width": 800, "height": 800},
+ "custom": {"width": 850, "height": 1100},
+}
+
+
+def new_project(session: Session, preset: str = "letter",
+ width: Optional[int] = None, height: Optional[int] = None) -> dict:
+ """Create a new blank diagram project.
+
+ Args:
+ session: The active session.
+ preset: Page preset name (see PAGE_PRESETS).
+ width: Override page width.
+ height: Override page height.
+
+ Returns:
+ Dict with project info.
+ """
+ if preset not in PAGE_PRESETS:
+ available = ", ".join(sorted(PAGE_PRESETS.keys()))
+ raise ValueError(f"Unknown preset: {preset!r}. Available: {available}")
+
+ page = PAGE_PRESETS[preset]
+ w = width or page["width"]
+ h = height or page["height"]
+
+ session.new_project(page_width=w, page_height=h)
+
+ return {
+ "action": "new_project",
+ "preset": preset,
+ "page_size": f"{w}x{h}",
+ }
+
+
+def open_project(session: Session, path: str) -> dict:
+ """Open an existing .drawio project file."""
+ session.open_project(path)
+
+ shape_count = len(drawio_xml.get_vertices(session.root))
+ edge_count = len(drawio_xml.get_edges(session.root))
+ page_count = len(session.root.findall("diagram"))
+
+ return {
+ "action": "open_project",
+ "path": session.project_path,
+ "page_count": page_count,
+ "shape_count": shape_count,
+ "edge_count": edge_count,
+ }
+
+
+def save_project(session: Session, path: Optional[str] = None) -> dict:
+ """Save the current project."""
+ saved_path = session.save_project(path)
+ return {
+ "action": "save_project",
+ "path": saved_path,
+ }
+
+
+def project_info(session: Session) -> dict:
+ """Get detailed info about the current project."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ root = session.root
+
+ # Page info
+ pages = drawio_xml.list_pages(root)
+
+ # Shapes on first page
+ shapes = []
+ for cell in drawio_xml.get_vertices(root):
+ shapes.append(drawio_xml.get_cell_info(cell))
+
+ # Edges on first page
+ edges = []
+ for cell in drawio_xml.get_edges(root):
+ edges.append(drawio_xml.get_cell_info(cell))
+
+ # Canvas settings
+ try:
+ model = drawio_xml.get_model(root)
+ canvas = {
+ "pageWidth": model.get("pageWidth", "850"),
+ "pageHeight": model.get("pageHeight", "1100"),
+ "gridSize": model.get("gridSize", "10"),
+ "grid": model.get("grid", "1") == "1",
+ }
+ except RuntimeError:
+ canvas = {}
+
+ return {
+ "project_path": session.project_path,
+ "modified": session.is_modified,
+ "pages": pages,
+ "canvas": canvas,
+ "shapes": shapes,
+ "edges": edges,
+ }
+
+
+def list_presets() -> dict:
+ """List all available page presets."""
+ return {name: f"{p['width']}x{p['height']}" for name, p in sorted(PAGE_PRESETS.items())}
diff --git a/drawio/agent-harness/cli_anything/drawio/core/session.py b/drawio/agent-harness/cli_anything/drawio/core/session.py
new file mode 100644
index 000000000..2acf7d2d4
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/core/session.py
@@ -0,0 +1,175 @@
+"""Stateful session management for the Draw.io CLI.
+
+A session tracks the currently open project, undo history, and working state.
+Sessions persist to disk as JSON so they survive process restarts.
+"""
+
+import json
+import os
+import time
+from pathlib import Path
+from typing import Optional
+from xml.etree import ElementTree as ET
+
+from ..utils import drawio_xml
+
+
+SESSION_DIR = Path.home() / ".drawio-cli" / "sessions"
+MAX_UNDO_DEPTH = 50
+
+
+class Session:
+ """Represents a stateful CLI editing session."""
+
+ def __init__(self, session_id: Optional[str] = None):
+ self.session_id = session_id or f"session_{int(time.time())}"
+ self.project_path: Optional[str] = None
+ self.root: Optional[ET.Element] = None
+ self._undo_stack: list[bytes] = [] # Serialized XML snapshots
+ self._redo_stack: list[bytes] = []
+ self._modified = False
+ self._metadata: dict = {}
+
+ @property
+ def is_open(self) -> bool:
+ return self.root is not None
+
+ @property
+ def is_modified(self) -> bool:
+ return self._modified
+
+ def _snapshot(self) -> bytes:
+ """Capture current state for undo."""
+ if self.root is None:
+ return b""
+ return ET.tostring(self.root, encoding="utf-8", xml_declaration=True)
+
+ def _push_undo(self) -> None:
+ """Save current state to undo stack before a mutation."""
+ snap = self._snapshot()
+ if snap:
+ self._undo_stack.append(snap)
+ if len(self._undo_stack) > MAX_UNDO_DEPTH:
+ self._undo_stack.pop(0)
+ self._redo_stack.clear()
+
+ def checkpoint(self) -> None:
+ """Create a checkpoint before performing a mutation.
+ Call this before any operation that changes the project.
+ """
+ self._push_undo()
+ self._modified = True
+
+ def undo(self) -> bool:
+ """Undo the last operation. Returns True if successful."""
+ if not self._undo_stack:
+ return False
+ self._redo_stack.append(self._snapshot())
+ prev = self._undo_stack.pop()
+ self.root = ET.fromstring(prev)
+ self._modified = bool(self._undo_stack)
+ return True
+
+ def redo(self) -> bool:
+ """Redo the last undone operation. Returns True if successful."""
+ if not self._redo_stack:
+ return False
+ self._undo_stack.append(self._snapshot())
+ nxt = self._redo_stack.pop()
+ self.root = ET.fromstring(nxt)
+ self._modified = True
+ return True
+
+ def new_project(self, page_width: int = 850, page_height: int = 1100,
+ grid_size: int = 10) -> None:
+ """Create a new blank project."""
+ self.root = drawio_xml.create_blank_diagram(page_width, page_height, grid_size)
+ self.project_path = None
+ self._undo_stack.clear()
+ self._redo_stack.clear()
+ self._modified = False
+
+ def open_project(self, path: str) -> None:
+ """Open an existing .drawio project file."""
+ path = os.path.abspath(path)
+ if not os.path.isfile(path):
+ raise FileNotFoundError(f"Project file not found: {path}")
+ self.root = drawio_xml.parse_drawio(path)
+ self.project_path = path
+ self._undo_stack.clear()
+ self._redo_stack.clear()
+ self._modified = False
+
+ def save_project(self, path: Optional[str] = None) -> str:
+ """Save the project. Returns the path saved to."""
+ if self.root is None:
+ raise RuntimeError("No project is open")
+ save_path = path or self.project_path
+ if not save_path:
+ raise RuntimeError("No save path specified and project has no path")
+ save_path = os.path.abspath(save_path)
+ drawio_xml.write_drawio(self.root, save_path)
+ self.project_path = save_path
+ self._modified = False
+ return save_path
+
+ def save_session_state(self) -> str:
+ """Persist session metadata to disk."""
+ SESSION_DIR.mkdir(parents=True, exist_ok=True)
+ state = {
+ "session_id": self.session_id,
+ "project_path": self.project_path,
+ "modified": self._modified,
+ "undo_depth": len(self._undo_stack),
+ "redo_depth": len(self._redo_stack),
+ "metadata": self._metadata,
+ "timestamp": time.time(),
+ }
+ path = SESSION_DIR / f"{self.session_id}.json"
+ with open(path, "w") as f:
+ json.dump(state, f, indent=2)
+ return str(path)
+
+ @classmethod
+ def load_session_state(cls, session_id: str) -> Optional[dict]:
+ """Load session metadata from disk."""
+ path = SESSION_DIR / f"{session_id}.json"
+ if not path.is_file():
+ return None
+ with open(path) as f:
+ return json.load(f)
+
+ @classmethod
+ def list_sessions(cls) -> list[dict]:
+ """List all saved sessions."""
+ SESSION_DIR.mkdir(parents=True, exist_ok=True)
+ sessions = []
+ for p in SESSION_DIR.glob("*.json"):
+ try:
+ with open(p) as f:
+ sessions.append(json.load(f))
+ except (json.JSONDecodeError, OSError):
+ continue
+ sessions.sort(key=lambda s: s.get("timestamp", 0), reverse=True)
+ return sessions
+
+ def status(self) -> dict:
+ """Get current session status."""
+ result = {
+ "session_id": self.session_id,
+ "project_open": self.is_open,
+ "project_path": self.project_path,
+ "modified": self._modified,
+ "undo_available": len(self._undo_stack),
+ "redo_available": len(self._redo_stack),
+ }
+ if self.is_open:
+ try:
+ result["page_count"] = len(self.root.findall("diagram"))
+ result["shape_count"] = len(drawio_xml.get_vertices(self.root))
+ result["edge_count"] = len(drawio_xml.get_edges(self.root))
+ except RuntimeError:
+ result["page_count"] = 0
+ result["shape_count"] = 0
+ result["edge_count"] = 0
+ return result
diff --git a/drawio/agent-harness/cli_anything/drawio/core/shapes.py b/drawio/agent-harness/cli_anything/drawio/core/shapes.py
new file mode 100644
index 000000000..495c7d99d
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/core/shapes.py
@@ -0,0 +1,167 @@
+"""Shape (vertex) operations: add, remove, modify, list."""
+
+from ..utils import drawio_xml
+from .session import Session
+
+
+def list_shapes(session: Session, diagram_index: int = 0) -> list[dict]:
+ """List all shapes on a page."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+ cells = drawio_xml.get_vertices(session.root, diagram_index)
+ return [drawio_xml.get_cell_info(c) for c in cells]
+
+
+def add_shape(session: Session, shape_type: str = "rectangle",
+ x: float = 100, y: float = 100,
+ width: float = 120, height: float = 60,
+ label: str = "", diagram_index: int = 0) -> dict:
+ """Add a shape to the diagram.
+
+ Args:
+ session: Active session.
+ shape_type: Shape preset (rectangle, rounded, ellipse, diamond,
+ triangle, hexagon, cylinder, cloud, parallelogram,
+ process, document, callout, note, actor, text).
+ x, y: Position.
+ width, height: Dimensions.
+ label: Text label.
+
+ Returns:
+ Dict with action and new shape info.
+ """
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ cell_id = drawio_xml.add_vertex(
+ session.root, shape_type, x, y, width, height, label,
+ diagram_index=diagram_index,
+ )
+
+ return {
+ "action": "add_shape",
+ "id": cell_id,
+ "shape_type": shape_type,
+ "label": label,
+ "x": x, "y": y,
+ "width": width, "height": height,
+ }
+
+
+def remove_shape(session: Session, cell_id: str,
+ diagram_index: int = 0) -> dict:
+ """Remove a shape by ID (also removes connected edges)."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ found = drawio_xml.remove_cell(session.root, cell_id, diagram_index)
+ if not found:
+ raise ValueError(f"Shape not found: {cell_id}")
+
+ return {
+ "action": "remove_shape",
+ "id": cell_id,
+ }
+
+
+def update_label(session: Session, cell_id: str, label: str,
+ diagram_index: int = 0) -> dict:
+ """Update a shape's label text."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ found = drawio_xml.update_cell_label(session.root, cell_id, label, diagram_index)
+ if not found:
+ raise ValueError(f"Cell not found: {cell_id}")
+
+ return {
+ "action": "update_label",
+ "id": cell_id,
+ "label": label,
+ }
+
+
+def move_shape(session: Session, cell_id: str, x: float, y: float,
+ diagram_index: int = 0) -> dict:
+ """Move a shape to new coordinates."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ found = drawio_xml.move_cell(session.root, cell_id, x, y, diagram_index)
+ if not found:
+ raise ValueError(f"Cell not found: {cell_id}")
+
+ return {
+ "action": "move_shape",
+ "id": cell_id,
+ "x": x, "y": y,
+ }
+
+
+def resize_shape(session: Session, cell_id: str,
+ width: float, height: float,
+ diagram_index: int = 0) -> dict:
+ """Resize a shape."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ session.checkpoint()
+ found = drawio_xml.resize_cell(session.root, cell_id, width, height, diagram_index)
+ if not found:
+ raise ValueError(f"Cell not found: {cell_id}")
+
+ return {
+ "action": "resize_shape",
+ "id": cell_id,
+ "width": width, "height": height,
+ }
+
+
+def set_style(session: Session, cell_id: str, key: str, value: str,
+ diagram_index: int = 0) -> dict:
+ """Set a style property on a shape.
+
+ Common style keys:
+ fillColor, strokeColor, fontColor, fontSize, fontStyle,
+ opacity, rounded, shadow, dashed, strokeWidth
+ """
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ cell = drawio_xml.find_cell_by_id(session.root, cell_id, diagram_index)
+ if cell is None:
+ raise ValueError(f"Cell not found: {cell_id}")
+
+ session.checkpoint()
+ drawio_xml.set_style_property(cell, key, value)
+
+ return {
+ "action": "set_style",
+ "id": cell_id,
+ "key": key,
+ "value": value,
+ }
+
+
+def get_shape_info(session: Session, cell_id: str,
+ diagram_index: int = 0) -> dict:
+ """Get detailed info about a specific shape."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+
+ cell = drawio_xml.find_cell_by_id(session.root, cell_id, diagram_index)
+ if cell is None:
+ raise ValueError(f"Cell not found: {cell_id}")
+
+ info = drawio_xml.get_cell_info(cell)
+ info["style_parsed"] = drawio_xml.parse_style(cell.get("style", ""))
+ return info
+
+
+def list_shape_types() -> dict:
+ """List all available shape type presets."""
+ return {name: style for name, style in sorted(drawio_xml.SHAPE_STYLES.items())}
diff --git a/drawio/agent-harness/cli_anything/drawio/drawio_cli.py b/drawio/agent-harness/cli_anything/drawio/drawio_cli.py
new file mode 100644
index 000000000..42a23d553
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/drawio_cli.py
@@ -0,0 +1,806 @@
+#!/usr/bin/env python3
+"""Draw.io CLI — A stateful command-line interface for diagram creation.
+
+This CLI manipulates Draw.io XML files directly, providing full diagram
+creation capabilities for AI agents and power users.
+
+Usage:
+ # One-shot commands
+ cli-anything-drawio project new --preset letter -o my_diagram.drawio
+ cli-anything-drawio shape add rectangle --label "Hello World"
+ cli-anything-drawio connect <source_id> <target_id>
+
+ # Interactive REPL
+ cli-anything-drawio repl
+"""
+
+import sys
+import os
+import json
+import click
+from typing import Optional
+
+# Add parent to path for imports
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from cli_anything.drawio.core.session import Session
+from cli_anything.drawio.core import project as proj_mod
+from cli_anything.drawio.core import shapes as shapes_mod
+from cli_anything.drawio.core import connectors as conn_mod
+from cli_anything.drawio.core import pages as pages_mod
+from cli_anything.drawio.core import export as export_mod
+
+# Global session state (persists across commands in REPL mode)
+_session: Optional[Session] = None
+_json_output = False
+_repl_mode = False
+
+
+def get_session() -> Session:
+ """Get or create the global session."""
+ global _session
+ if _session is None:
+ _session = Session()
+ return _session
+
+
+def output(data, message: str = ""):
+ """Output result data. JSON mode or human-readable."""
+ if _json_output:
+ click.echo(json.dumps(data, indent=2, default=str))
+ else:
+ if message:
+ click.echo(message)
+ if isinstance(data, dict):
+ _print_dict(data)
+ elif isinstance(data, list):
+ _print_list(data)
+ else:
+ click.echo(str(data))
+
+
+def _print_dict(d: dict, indent: int = 0):
+ """Pretty-print a dict."""
+ prefix = " " * indent
+ for k, v in d.items():
+ if isinstance(v, dict):
+ click.echo(f"{prefix}{k}:")
+ _print_dict(v, indent + 1)
+ elif isinstance(v, list):
+ click.echo(f"{prefix}{k}:")
+ _print_list(v, indent + 1)
+ else:
+ click.echo(f"{prefix}{k}: {v}")
+
+
+def _print_list(items: list, indent: int = 0):
+ """Pretty-print a list."""
+ prefix = " " * indent
+ for i, item in enumerate(items):
+ if isinstance(item, dict):
+ click.echo(f"{prefix}[{i}]")
+ _print_dict(item, indent + 1)
+ else:
+ click.echo(f"{prefix}- {item}")
+
+
+def handle_error(func):
+ """Decorator to handle errors consistently."""
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except FileNotFoundError as e:
+ if _json_output:
+ click.echo(json.dumps({"error": str(e), "type": "file_not_found"}))
+ else:
+ click.echo(f"Error: {e}", err=True)
+ if not _repl_mode:
+ sys.exit(1)
+ except FileExistsError as e:
+ if _json_output:
+ click.echo(json.dumps({"error": str(e), "type": "file_exists"}))
+ else:
+ click.echo(f"Error: {e}", err=True)
+ if not _repl_mode:
+ sys.exit(1)
+ except (ValueError, IndexError, RuntimeError) as e:
+ if _json_output:
+ click.echo(json.dumps({"error": str(e), "type": type(e).__name__}))
+ else:
+ click.echo(f"Error: {e}", err=True)
+ if not _repl_mode:
+ sys.exit(1)
+ except Exception as e:
+ if _json_output:
+ click.echo(json.dumps({"error": str(e), "type": "unexpected"}))
+ else:
+ click.echo(f"Unexpected error: {e}", err=True)
+ if not _repl_mode:
+ sys.exit(1)
+ wrapper.__name__ = func.__name__
+ wrapper.__doc__ = func.__doc__
+ return wrapper
+
+
+# ============================================================================
+# Main CLI group
+# ============================================================================
+
[email protected](invoke_without_command=True)
[email protected]("--json", "json_mode", is_flag=True, help="Output in JSON format")
[email protected]("--session", "session_id", default=None, help="Session ID to use/resume")
[email protected]("--project", "project_path", default=None, help="Open a project file")
+def cli(ctx, json_mode, session_id, project_path):
+ """Draw.io CLI — Diagram creation from the command line.
+
+ A stateful CLI for manipulating draw.io diagram files.
+ Designed for AI agents and power users.
+
+ Run without a subcommand to enter interactive REPL mode.
+ """
+ global _json_output, _session
+ _json_output = json_mode
+
+ if session_id:
+ _session = Session(session_id)
+ else:
+ _session = Session()
+
+ if project_path:
+ _session.open_project(project_path)
+
+ # Auto-save on exit when --project was used and project was modified
+ @ctx.call_on_close
+ def _auto_save():
+ if project_path and _session and _session.is_open and _session.is_modified:
+ _session.save_project()
+
+ if ctx.invoked_subcommand is None:
+ ctx.invoke(repl, project_path=None)
+
+
+# ============================================================================
+# Project commands
+# ============================================================================
+
+def project():
+ """Project management: new, open, save, info."""
+ pass
+
+
[email protected]("--preset", default="letter",
+ type=click.Choice(sorted(proj_mod.PAGE_PRESETS.keys())),
+ help="Page size preset")
[email protected]("--width", type=int, default=None, help="Custom page width")
[email protected]("--height", type=int, default=None, help="Custom page height")
[email protected]("-o", "--output", "output_path", default=None,
+ help="Save the new project to this path")
+@handle_error
+def project_new(preset, width, height, output_path):
+ """Create a new blank diagram."""
+ session = get_session()
+ result = proj_mod.new_project(session, preset, width, height)
+ if output_path:
+ save_result = proj_mod.save_project(session, output_path)
+ result["saved_to"] = save_result["path"]
+ output(result, f"Created new diagram ({result['page_size']})")
+
+
+@handle_error
+def project_open(path):
+ """Open an existing .drawio project file."""
+ session = get_session()
+ result = proj_mod.open_project(session, path)
+ output(result, f"Opened: {path}")
+
+
[email protected]("path", required=False)
+@handle_error
+def project_save(path):
+ """Save the current project."""
+ session = get_session()
+ result = proj_mod.save_project(session, path)
+ output(result, f"Saved to: {result['path']}")
+
+
+@handle_error
+def project_info():
+ """Show detailed project information."""
+ session = get_session()
+ result = proj_mod.project_info(session)
+ output(result, "Project info:")
+
+
+@handle_error
+def project_xml():
+ """Print the raw XML of the current project."""
+ session = get_session()
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+ from cli_anything.drawio.utils.drawio_xml import xml_to_string
+ click.echo(xml_to_string(session.root))
+
+
+@handle_error
+def project_presets():
+ """List available page size presets."""
+ result = proj_mod.list_presets()
+ output(result, "Page presets:")
+
+
+# ============================================================================
+# Shape commands
+# ============================================================================
+
+def shape():
+ """Shape operations: add, remove, move, resize, style."""
+ pass
+
+
[email protected]("shape_type", default="rectangle")
[email protected]("--label", "-l", default="", help="Text label")
[email protected]("--x", type=float, default=100, help="X position")
[email protected]("--y", type=float, default=100, help="Y position")
[email protected]("--width", "-w", type=float, default=120, help="Width")
[email protected]("--height", "-h", type=float, default=60, help="Height")
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def shape_add(shape_type, label, x, y, width, height, page):
+ """Add a shape to the diagram.
+
+ SHAPE_TYPE: rectangle, rounded, ellipse, diamond, triangle, hexagon,
+ cylinder, cloud, parallelogram, process, document, callout, note, actor, text
+ """
+ session = get_session()
+ result = shapes_mod.add_shape(session, shape_type, x, y, width, height, label, page)
+ output(result, f"Added {shape_type}: {result['id']}")
+
+
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def shape_remove(cell_id, page):
+ """Remove a shape by ID."""
+ session = get_session()
+ result = shapes_mod.remove_shape(session, cell_id, page)
+ output(result, f"Removed: {cell_id}")
+
+
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def shape_list(page):
+ """List all shapes on a page."""
+ session = get_session()
+ result = shapes_mod.list_shapes(session, page)
+ output(result, f"Shapes ({len(result)}):")
+
+
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def shape_label(cell_id, label, page):
+ """Update a shape's label text."""
+ session = get_session()
+ result = shapes_mod.update_label(session, cell_id, label, page)
+ output(result, f"Updated label: {cell_id}")
+
+
[email protected]("--x", type=float, required=True, help="New X position")
[email protected]("--y", type=float, required=True, help="New Y position")
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def shape_move(cell_id, x, y, page):
+ """Move a shape to new coordinates."""
+ session = get_session()
+ result = shapes_mod.move_shape(session, cell_id, x, y, page)
+ output(result, f"Moved: {cell_id}")
+
+
[email protected]("--width", "-w", type=float, required=True, help="New width")
[email protected]("--height", "-h", type=float, required=True, help="New height")
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def shape_resize(cell_id, width, height, page):
+ """Resize a shape."""
+ session = get_session()
+ result = shapes_mod.resize_shape(session, cell_id, width, height, page)
+ output(result, f"Resized: {cell_id}")
+
+
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def shape_style(cell_id, key, value, page):
+ """Set a style property on a shape.
+
+ Common keys: fillColor, strokeColor, fontColor, fontSize, opacity,
+ rounded, shadow, dashed, strokeWidth
+ """
+ session = get_session()
+ result = shapes_mod.set_style(session, cell_id, key, value, page)
+ output(result, f"Style set: {key}={value}")
+
+
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def shape_info(cell_id, page):
+ """Show detailed info about a shape."""
+ session = get_session()
+ result = shapes_mod.get_shape_info(session, cell_id, page)
+ output(result)
+
+
+@handle_error
+def shape_types():
+ """List all available shape types."""
+ result = shapes_mod.list_shape_types()
+ output(result, "Shape types:")
+
+
+# ============================================================================
+# Connector commands
+# ============================================================================
+
+def connect():
+ """Connector operations: add, remove, style."""
+ pass
+
+
[email protected]("source_id")
[email protected]("target_id")
[email protected]("--style", "edge_style", default="orthogonal",
+ type=click.Choice(["straight", "orthogonal", "curved", "entity-relation"]),
+ help="Edge style")
[email protected]("--label", "-l", default="", help="Edge label")
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def connect_add(source_id, target_id, edge_style, label, page):
+ """Add a connector between two shapes."""
+ session = get_session()
+ result = conn_mod.add_connector(session, source_id, target_id, edge_style, label, page)
+ output(result, f"Connected: {source_id} → {target_id}")
+
+
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def connect_remove(edge_id, page):
+ """Remove a connector by ID."""
+ session = get_session()
+ result = conn_mod.remove_connector(session, edge_id, page)
+ output(result, f"Removed connector: {edge_id}")
+
+
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def connect_label(edge_id, label, page):
+ """Update a connector's label."""
+ session = get_session()
+ result = conn_mod.update_connector_label(session, edge_id, label, page)
+ output(result, f"Updated label: {edge_id}")
+
+
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def connect_style(edge_id, key, value, page):
+ """Set a style property on a connector."""
+ session = get_session()
+ result = conn_mod.set_connector_style(session, edge_id, key, value, page)
+ output(result, f"Style set: {key}={value}")
+
+
[email protected]("--page", type=int, default=0, help="Page index")
+@handle_error
+def connect_list(page):
+ """List all connectors on a page."""
+ session = get_session()
+ result = conn_mod.list_connectors(session, page)
+ output(result, f"Connectors ({len(result)}):")
+
+
+@handle_error
+def connect_styles():
+ """List available edge styles."""
+ result = conn_mod.list_edge_styles()
+ output(result, "Edge styles:")
+
+
+# ============================================================================
+# Page commands
+# ============================================================================
+
+def page():
+ """Page operations: add, remove, rename, list."""
+ pass
+
+
[email protected]("--name", default="", help="Page name")
[email protected]("--width", type=int, default=850, help="Page width")
[email protected]("--height", type=int, default=1100, help="Page height")
+@handle_error
+def page_add(name, width, height):
+ """Add a new page."""
+ session = get_session()
+ result = pages_mod.add_page(session, name, width, height)
+ output(result, f"Added page: {result['name']}")
+
+
[email protected]("page_index", type=int)
+@handle_error
+def page_remove(page_index):
+ """Remove a page by index."""
+ session = get_session()
+ result = pages_mod.remove_page(session, page_index)
+ output(result, f"Removed page {page_index}")
+
+
[email protected]("page_index", type=int)
+@handle_error
+def page_rename(page_index, name):
+ """Rename a page."""
+ session = get_session()
+ result = pages_mod.rename_page(session, page_index, name)
+ output(result, f"Renamed page {page_index} to: {name}")
+
+
+@handle_error
+def page_list():
+ """List all pages."""
+ session = get_session()
+ result = pages_mod.list_pages(session)
+ output(result, f"Pages ({len(result)}):")
+
+
+# ============================================================================
+# Export commands
+# ============================================================================
+
+def export():
+ """Export operations: render to PNG, PDF, SVG."""
+ pass
+
+
[email protected]("output_path")
[email protected]("--format", "-f", "fmt", default="png",
+ type=click.Choice(["png", "pdf", "svg", "vsdx", "xml"]),
+ help="Output format")
[email protected]("--page", "page_index", type=int, default=None, help="Page index to export")
[email protected]("--scale", type=float, default=None, help="Scale factor")
[email protected]("--width", type=int, default=None, help="Output width (PNG)")
[email protected]("--height", type=int, default=None, help="Output height (PNG)")
[email protected]("--transparent", is_flag=True, help="Transparent background (PNG)")
[email protected]("--crop", is_flag=True, help="Crop to content")
[email protected]("--overwrite", is_flag=True, help="Overwrite existing file")
+@handle_error
+def export_render(output_path, fmt, page_index, scale, width, height,
+ transparent, crop, overwrite):
+ """Export the diagram to a file."""
+ session = get_session()
+ result = export_mod.render_or_save(
+ session, output_path, fmt,
+ page_index=page_index, scale=scale,
+ width=width, height=height,
+ transparent=transparent, crop=crop,
+ overwrite=overwrite,
+ )
+ output(result, f"Exported to: {result.get('output', result.get('drawio_file', ''))}")
+
+
+@handle_error
+def export_formats():
+ """List available export formats."""
+ result = export_mod.list_formats()
+ output(result, "Export formats:")
+
+
+# ============================================================================
+# Session commands
+# ============================================================================
+
+def session():
+ """Session management: status, undo, redo."""
+ pass
+
+
+@handle_error
+def session_status():
+ """Show current session status."""
+ s = get_session()
+ result = s.status()
+ output(result, "Session status:")
+
+
+@handle_error
+def session_undo():
+ """Undo the last operation."""
+ s = get_session()
+ if s.undo():
+ output({"action": "undo", "success": True}, "Undo successful")
+ else:
+ output({"action": "undo", "success": False}, "Nothing to undo")
+
+
+@handle_error
+def session_redo():
+ """Redo the last undone operation."""
+ s = get_session()
+ if s.redo():
+ output({"action": "redo", "success": True}, "Redo successful")
+ else:
+ output({"action": "redo", "success": False}, "Nothing to redo")
+
+
[email protected]("save-state")
+@handle_error
+def session_save():
+ """Save session state to disk."""
+ s = get_session()
+ path = s.save_session_state()
+ output({"action": "save_session", "path": path}, f"Session saved: {path}")
+
+
+@handle_error
+def session_list():
+ """List all saved sessions."""
+ sessions = Session.list_sessions()
+ output(sessions, f"Sessions ({len(sessions)}):")
+
+
+# ============================================================================
+# REPL (Interactive mode)
+# ============================================================================
+
[email protected]("--project", "project_path", default=None,
+ help="Open a project on start")
+def repl(project_path):
+ """Start an interactive REPL session."""
+ global _repl_mode
+ _repl_mode = True
+
+ s = get_session()
+ if project_path:
+ s.open_project(project_path)
+
+ from cli_anything.drawio.utils.repl_skin import ReplSkin
+ skin = ReplSkin("drawio", version="1.0.0")
+ skin.print_banner()
+
+ if project_path:
+ skin.info(f"Opened: {project_path}")
+ print()
+
+ try:
+ _run_repl(s, skin)
+ except (KeyboardInterrupt, EOFError):
+ skin.print_goodbye()
+
+ _repl_mode = False
+
+
+REPL_COMMANDS = {
+ "help": "Show this help",
+ "status": "Show session status",
+ "new [preset]": "Create new diagram (letter, a4, 16:9, ...)",
+ "open <path>": "Open a .drawio file",
+ "save [path]": "Save the project",
+ "info": "Show project info",
+ "xml": "Print raw XML",
+ "add <type> [label]": "Add shape (rectangle, ellipse, diamond, ...)",
+ "remove <id>": "Remove a shape or connector",
+ "shapes": "List all shapes",
+ "label <id> <text>": "Update shape label",
+ "move <id> <x> <y>": "Move a shape",
+ "resize <id> <w> <h>": "Resize a shape",
+ "style <id> <key> <val>": "Set style property",
+ "connect <src> <tgt> [style]": "Add connector",
+ "connectors": "List all connectors",
+ "pages": "List all pages",
+ "addpage [name]": "Add a new page",
+ "export <path> [format]": "Export diagram (png, pdf, svg)",
+ "undo": "Undo last operation",
+ "redo": "Redo last undone operation",
+ "quit": "Exit the REPL",
+}
+
+
+def _run_repl(s: Session, skin):
+ """Run the interactive REPL loop."""
+ pt_session = skin.create_prompt_session()
+
+ while True:
+ proj_name = ""
+ if s.project_path:
+ proj_name = os.path.basename(s.project_path)
+ elif s.is_open:
+ proj_name = "(unsaved)"
+ modified = s.is_modified
+
+ try:
+ line = skin.get_input(pt_session, project_name=proj_name,
+ modified=modified).strip()
+ except (KeyboardInterrupt, EOFError):
+ skin.print_goodbye()
+ break
+
+ if not line:
+ continue
+
+ parts = line.split()
+ cmd = parts[0].lower()
+ args = parts[1:]
+
+ try:
+ if cmd in ("quit", "exit", "q"):
+ skin.print_goodbye()
+ break
+ elif cmd == "help":
+ skin.help(REPL_COMMANDS)
+ elif cmd == "status":
+ result = s.status()
+ _print_dict(result)
+ elif cmd == "new":
+ preset = args[0] if args else "letter"
+ result = proj_mod.new_project(s, preset)
+ skin.success(f"Created new diagram ({result['page_size']})")
+ elif cmd == "open":
+ if not args:
+ skin.error("Usage: open <path>")
+ continue
+ result = proj_mod.open_project(s, args[0])
+ skin.success(f"Opened: {args[0]}")
+ elif cmd == "save":
+ path = args[0] if args else None
+ result = proj_mod.save_project(s, path)
+ skin.success(f"Saved to: {result['path']}")
+ elif cmd == "info":
+ result = proj_mod.project_info(s)
+ _print_dict(result)
+ elif cmd == "xml":
+ if not s.is_open:
+ skin.error("No project is open")
+ continue
+ from cli_anything.drawio.utils.drawio_xml import xml_to_string
+ click.echo(xml_to_string(s.root))
+ elif cmd == "add":
+ shape_type = args[0] if args else "rectangle"
+ label = " ".join(args[1:]) if len(args) > 1 else ""
+ result = shapes_mod.add_shape(s, shape_type, label=label)
+ skin.success(f"Added {shape_type}: {result['id']}")
+ elif cmd == "remove":
+ if not args:
+ skin.error("Usage: remove <id>")
+ continue
+ from cli_anything.drawio.utils import drawio_xml
+ cell = drawio_xml.find_cell_by_id(s.root, args[0])
+ if cell is None:
+ skin.error(f"Cell not found: {args[0]}")
+ continue
+ s.checkpoint()
+ drawio_xml.remove_cell(s.root, args[0])
+ skin.success(f"Removed: {args[0]}")
+ elif cmd == "shapes":
+ result = shapes_mod.list_shapes(s)
+ for sh in result:
+ click.echo(f" {sh['id']}: {sh.get('value', '')} ({sh['type']})")
+ skin.info(f"Total: {len(result)} shapes")
+ elif cmd == "label":
+ if len(args) < 2:
+ skin.error("Usage: label <id> <text>")
+ continue
+ result = shapes_mod.update_label(s, args[0], " ".join(args[1:]))
+ skin.success(f"Updated label: {args[0]}")
+ elif cmd == "move":
+ if len(args) < 3:
+ skin.error("Usage: move <id> <x> <y>")
+ continue
+ result = shapes_mod.move_shape(s, args[0], float(args[1]), float(args[2]))
+ skin.success(f"Moved: {args[0]}")
+ elif cmd == "resize":
+ if len(args) < 3:
+ skin.error("Usage: resize <id> <width> <height>")
+ continue
+ result = shapes_mod.resize_shape(s, args[0], float(args[1]), float(args[2]))
+ skin.success(f"Resized: {args[0]}")
+ elif cmd == "style":
+ if len(args) < 3:
+ skin.error("Usage: style <id> <key> <value>")
+ continue
+ result = shapes_mod.set_style(s, args[0], args[1], args[2])
+ skin.success(f"Style set: {args[1]}={args[2]}")
+ elif cmd == "connect":
+ if len(args) < 2:
+ skin.error("Usage: connect <source_id> <target_id> [style]")
+ continue
+ edge_style = args[2] if len(args) > 2 else "orthogonal"
+ result = conn_mod.add_connector(s, args[0], args[1], edge_style)
+ skin.success(f"Connected: {args[0]} → {args[1]} ({result['id']})")
+ elif cmd == "connectors":
+ result = conn_mod.list_connectors(s)
+ for e in result:
+ click.echo(f" {e['id']}: {e.get('source', '')} → {e.get('target', '')} {e.get('value', '')}")
+ skin.info(f"Total: {len(result)} connectors")
+ elif cmd == "pages":
+ result = pages_mod.list_pages(s)
+ for p in result:
+ click.echo(f" [{p['index']}] {p['name']} ({p['cell_count']} cells)")
+ elif cmd == "addpage":
+ name = " ".join(args) if args else ""
+ result = pages_mod.add_page(s, name)
+ skin.success(f"Added page: {result['name']}")
+ elif cmd == "export":
+ if not args:
+ skin.error("Usage: export <path> [format]")
+ continue
+ fmt = args[1] if len(args) > 1 else "png"
+ result = export_mod.render_or_save(s, args[0], fmt, overwrite=True)
+ skin.success(f"Exported to: {result.get('output', result.get('drawio_file', ''))}")
+ elif cmd == "undo":
+ if s.undo():
+ skin.success("Undo successful")
+ else:
+ skin.warning("Nothing to undo")
+ elif cmd == "redo":
+ if s.redo():
+ skin.success("Redo successful")
+ else:
+ skin.warning("Nothing to redo")
+ else:
+ skin.error(f"Unknown command: {cmd}. Type 'help' for available commands.")
+ except Exception as e:
+ skin.error(str(e))
+
+
+if __name__ == "__main__":
+ cli()
diff --git a/drawio/agent-harness/cli_anything/drawio/tests/TEST.md b/drawio/agent-harness/cli_anything/drawio/tests/TEST.md
new file mode 100644
index 000000000..14a5aa9f7
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/tests/TEST.md
@@ -0,0 +1,153 @@
+# Draw.io CLI — Test Plan & Results
+
+## Test Plan
+
+### Unit Tests (test_core.py)
+
+**XML Utilities (TestDrawioXml)**
+- Create blank diagram with correct structure
+- System cells (id=0, id=1) always present
+- No user cells in blank diagram
+- Add vertex with all attributes
+- Add edge with source/target
+- Remove cell
+- Remove vertex also removes connected edges
+- Find cell by ID (found and not found)
+- Update cell label
+- Move cell
+- Resize cell
+- Get cell info
+- Get vertices vs edges
+- Write and parse file roundtrip
+
+**Style Parsing (TestStyleParsing)**
+- Parse empty style
+- Parse key=value pairs
+- Parse base style (no value)
+- Build style from dict
+- Parse-build roundtrip
+- Set style property on cell
+- Remove style property from cell
+
+**Shape Presets (TestShapePresets)**
+- All 15 shape types create valid cells (parametrized)
+- All 4 edge styles create valid edges (parametrized)
+
+**Multi-Page Operations (TestPages)**
+- Single page by default
+- Add page
+- Remove page
+- Cannot remove last page
+- Rename page
+- Shapes on different pages are independent
+
+**Session (TestSession)**
+- New session is not open
+- New project opens session
+- Undo/redo single operation
+- Multiple undo
+- Save and open roundtrip
+- Save with no project raises error
+- Open nonexistent file raises error
+- Status shows correct counts
+
+**Project Module (TestProject)**
+- New project with default preset
+- New project with all presets
+- Invalid preset raises error
+- Custom page size
+- Save and open roundtrip
+- Project info
+- Project info with no project raises error
+- List presets
+
+**Shapes Module (TestShapes)**
+- Add shape
+- Add shape with no project raises error
+- List shapes
+- Remove shape
+- Remove nonexistent shape raises error
+- Update label
+- Move shape
+- Resize shape
+- Set style
+- Get shape info
+- List shape types
+- All 15 shape types via module (parametrized)
+- Undo add shape
+
+**Connectors Module (TestConnectors)**
+- Add connector
+- Invalid source raises error
+- Invalid target raises error
+- List connectors
+- Remove connector
+- Update connector label
+- Set connector style
+- List edge styles
+- All 4 edge styles via module (parametrized)
+
+**Pages Module (TestPagesModule)**
+- List pages
+- Add page
+- Remove page
+- Rename page
+
+**Export Module (TestExport)**
+- List formats
+- Export to XML (no draw.io CLI needed)
+- Export with no project raises error
+- Invalid format raises error
+- File exists raises error
+
+**Complex Workflows (TestWorkflows)**
+- Build complete flowchart (4 shapes, 3 connectors, save/reopen)
+- Build styled diagram (custom colors, font, shadow)
+- Multi-page workflow
+- Undo/redo across multiple operations
+- Export XML workflow with content verification
+
+### E2E Tests (test_full_e2e.py)
+
+**File Roundtrip (TestFileRoundtrip)**
+- Empty diagram save/reopen
+- Complex diagram (6 shapes, 4 connectors, styles) roundtrip
+- Multi-page diagram roundtrip
+
+**XML Export Verification (TestXmlExport)**
+- Export XML with valid structure
+- Export XML preserves styles
+
+**Real Draw.io Export (TestRealExport)** — requires draw.io installed
+- Export to PNG with magic bytes verification
+- Export to SVG with content verification
+- Export to PDF with magic bytes verification
+
+**CLI Subprocess (TestCLISubprocess)**
+- --help output
+- project new --json
+- project info --json
+- shape add --json
+- shape list --json
+- shape types --json
+- connect styles --json
+- export formats --json
+- page list --json
+- session status --json
+- project presets --json
+- export XML via subprocess
+
+**Real-World Workflows (TestRealWorldWorkflows)**
+- 3-tier web architecture diagram (5 shapes, 4 connectors, styles)
+- Entity-relationship diagram (3 entities, 2 relations)
+- Decision tree / flowchart (5 nodes, 5 edges)
+- Multi-page technical documentation (3 pages, multiple shapes)
+
+## Test Results
+
+```
+drawio: 138 passed, 3 skipped (116 unit + 22 e2e)
+ 3 skipped: real draw.io export (PNG/SVG/PDF) — requires draw.io desktop app
+```
+
+**100% pass rate on all available tests.**
diff --git a/drawio/agent-harness/cli_anything/drawio/tests/__init__.py b/drawio/agent-harness/cli_anything/drawio/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/drawio/agent-harness/cli_anything/drawio/tests/test_core.py b/drawio/agent-harness/cli_anything/drawio/tests/test_core.py
new file mode 100644
index 000000000..1d2a29978
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/tests/test_core.py
@@ -0,0 +1,841 @@
+"""Tests for the Draw.io CLI core modules."""
+
+import os
+import sys
+import json
+import tempfile
+import pytest
+
+# Add project root to path
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from cli_anything.drawio.core.session import Session
+from cli_anything.drawio.core import project as proj_mod
+from cli_anything.drawio.core import shapes as shapes_mod
+from cli_anything.drawio.core import connectors as conn_mod
+from cli_anything.drawio.core import pages as pages_mod
+from cli_anything.drawio.core import export as export_mod
+from cli_anything.drawio.utils import drawio_xml
+
+
+# ============================================================================
+# XML utilities
+# ============================================================================
+
+class TestDrawioXml:
+ def test_create_blank_diagram(self):
+ root = drawio_xml.create_blank_diagram(850, 1100)
+ assert root.tag == "mxfile"
+ diagrams = root.findall("diagram")
+ assert len(diagrams) == 1
+ model = diagrams[0].find("mxGraphModel")
+ assert model is not None
+ assert model.get("pageWidth") == "850"
+ assert model.get("pageHeight") == "1100"
+
+ def test_system_cells_present(self):
+ root = drawio_xml.create_blank_diagram()
+ xml_root = drawio_xml.get_root(root)
+ cells = xml_root.findall("mxCell")
+ ids = [c.get("id") for c in cells]
+ assert "0" in ids
+ assert "1" in ids
+
+ def test_no_user_cells_in_blank(self):
+ root = drawio_xml.create_blank_diagram()
+ assert len(drawio_xml.get_all_cells(root)) == 0
+
+ def test_add_vertex(self):
+ root = drawio_xml.create_blank_diagram()
+ cell_id = drawio_xml.add_vertex(root, "rectangle", 10, 20, 120, 60, "Test")
+ assert cell_id is not None
+ cells = drawio_xml.get_all_cells(root)
+ assert len(cells) == 1
+ assert cells[0].get("value") == "Test"
+ assert cells[0].get("vertex") == "1"
+
+ def test_add_edge(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 10, 20, 120, 60, "A")
+ v2 = drawio_xml.add_vertex(root, "rectangle", 200, 20, 120, 60, "B")
+ e1 = drawio_xml.add_edge(root, v1, v2, "orthogonal", "connects")
+ assert e1 is not None
+ edges = drawio_xml.get_edges(root)
+ assert len(edges) == 1
+ assert edges[0].get("source") == v1
+ assert edges[0].get("target") == v2
+ assert edges[0].get("value") == "connects"
+
+ def test_remove_cell(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 10, 20, 120, 60, "A")
+ assert len(drawio_xml.get_all_cells(root)) == 1
+ drawio_xml.remove_cell(root, v1)
+ assert len(drawio_xml.get_all_cells(root)) == 0
+
+ def test_remove_vertex_also_removes_edges(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 10, 20, 120, 60, "A")
+ v2 = drawio_xml.add_vertex(root, "rectangle", 200, 20, 120, 60, "B")
+ drawio_xml.add_edge(root, v1, v2)
+ assert len(drawio_xml.get_edges(root)) == 1
+ drawio_xml.remove_cell(root, v1)
+ assert len(drawio_xml.get_edges(root)) == 0
+
+ def test_find_cell_by_id(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "ellipse", 10, 20, 100, 100, "Circle")
+ found = drawio_xml.find_cell_by_id(root, v1)
+ assert found is not None
+ assert found.get("value") == "Circle"
+
+ def test_find_cell_not_exists(self):
+ root = drawio_xml.create_blank_diagram()
+ assert drawio_xml.find_cell_by_id(root, "nonexistent") is None
+
+ def test_update_cell_label(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 0, 0, 100, 50, "Old")
+ drawio_xml.update_cell_label(root, v1, "New")
+ cell = drawio_xml.find_cell_by_id(root, v1)
+ assert cell.get("value") == "New"
+
+ def test_move_cell(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 10, 20, 100, 50)
+ drawio_xml.move_cell(root, v1, 300, 400)
+ geo = drawio_xml.get_cell_geometry(drawio_xml.find_cell_by_id(root, v1))
+ assert geo["x"] == 300.0
+ assert geo["y"] == 400.0
+
+ def test_resize_cell(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 10, 20, 100, 50)
+ drawio_xml.resize_cell(root, v1, 200, 150)
+ geo = drawio_xml.get_cell_geometry(drawio_xml.find_cell_by_id(root, v1))
+ assert geo["width"] == 200.0
+ assert geo["height"] == 150.0
+
+ def test_get_cell_info(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 10, 20, 120, 60, "Hello")
+ info = drawio_xml.get_cell_info(drawio_xml.find_cell_by_id(root, v1))
+ assert info["id"] == v1
+ assert info["value"] == "Hello"
+ assert info["type"] == "vertex"
+ assert info["width"] == 120.0
+
+ def test_get_vertices(self):
+ root = drawio_xml.create_blank_diagram()
+ drawio_xml.add_vertex(root, "rectangle", 0, 0, 100, 50)
+ drawio_xml.add_vertex(root, "ellipse", 200, 0, 100, 100)
+ v1 = drawio_xml.add_vertex(root, "diamond", 0, 200, 80, 80)
+ v2 = drawio_xml.add_vertex(root, "rectangle", 200, 200, 100, 50)
+ drawio_xml.add_edge(root, v1, v2)
+ assert len(drawio_xml.get_vertices(root)) == 4
+ assert len(drawio_xml.get_edges(root)) == 1
+
+ def test_write_and_parse_roundtrip(self):
+ root = drawio_xml.create_blank_diagram(1200, 800)
+ drawio_xml.add_vertex(root, "rectangle", 10, 20, 120, 60, "Test Shape")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+
+ try:
+ drawio_xml.write_drawio(root, path)
+ assert os.path.exists(path)
+ assert os.path.getsize(path) > 0
+
+ parsed = drawio_xml.parse_drawio(path)
+ assert parsed.tag == "mxfile"
+ cells = drawio_xml.get_all_cells(parsed)
+ assert len(cells) == 1
+ assert cells[0].get("value") == "Test Shape"
+ finally:
+ os.unlink(path)
+
+
+# ============================================================================
+# Style parsing
+# ============================================================================
+
+class TestStyleParsing:
+ def test_parse_empty(self):
+ assert drawio_xml.parse_style("") == {}
+
+ def test_parse_basic(self):
+ style = drawio_xml.parse_style("rounded=1;whiteSpace=wrap;html=1;")
+ assert style["rounded"] == "1"
+ assert style["whiteSpace"] == "wrap"
+ assert style["html"] == "1"
+
+ def test_parse_base_style(self):
+ style = drawio_xml.parse_style("ellipse;whiteSpace=wrap;html=1;")
+ assert style["ellipse"] == ""
+ assert style["html"] == "1"
+
+ def test_build_style(self):
+ style = drawio_xml.build_style({"rounded": "1", "html": "1"})
+ assert "rounded=1" in style
+ assert "html=1" in style
+
+ def test_roundtrip(self):
+ original = "rounded=1;whiteSpace=wrap;html=1;"
+ style = drawio_xml.parse_style(original)
+ rebuilt = drawio_xml.build_style(style)
+ reparsed = drawio_xml.parse_style(rebuilt)
+ assert style == reparsed
+
+ def test_set_style_property(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 0, 0, 100, 50)
+ cell = drawio_xml.find_cell_by_id(root, v1)
+ drawio_xml.set_style_property(cell, "fillColor", "#ff0000")
+ style = drawio_xml.parse_style(cell.get("style", ""))
+ assert style["fillColor"] == "#ff0000"
+
+ def test_remove_style_property(self):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 0, 0, 100, 50)
+ cell = drawio_xml.find_cell_by_id(root, v1)
+ drawio_xml.set_style_property(cell, "fillColor", "#ff0000")
+ drawio_xml.remove_style_property(cell, "fillColor")
+ style = drawio_xml.parse_style(cell.get("style", ""))
+ assert "fillColor" not in style
+
+
+# ============================================================================
+# Shape presets
+# ============================================================================
+
+class TestShapePresets:
+ @pytest.mark.parametrize("shape_type", list(drawio_xml.SHAPE_STYLES.keys()))
+ def test_all_shape_types(self, shape_type):
+ root = drawio_xml.create_blank_diagram()
+ cell_id = drawio_xml.add_vertex(root, shape_type, 0, 0, 100, 60, shape_type)
+ assert cell_id is not None
+ cell = drawio_xml.find_cell_by_id(root, cell_id)
+ assert cell is not None
+ assert cell.get("value") == shape_type
+
+ @pytest.mark.parametrize("edge_style", list(drawio_xml.EDGE_STYLES.keys()))
+ def test_all_edge_styles(self, edge_style):
+ root = drawio_xml.create_blank_diagram()
+ v1 = drawio_xml.add_vertex(root, "rectangle", 0, 0, 100, 50, "A")
+ v2 = drawio_xml.add_vertex(root, "rectangle", 200, 0, 100, 50, "B")
+ edge_id = drawio_xml.add_edge(root, v1, v2, edge_style)
+ assert edge_id is not None
+ edge = drawio_xml.find_cell_by_id(root, edge_id)
+ assert edge is not None
+ assert edge.get("edge") == "1"
+
+
+# ============================================================================
+# Multi-page operations
+# ============================================================================
+
+class TestPages:
+ def test_single_page_default(self):
+ root = drawio_xml.create_blank_diagram()
+ pages = drawio_xml.list_pages(root)
+ assert len(pages) == 1
+ assert pages[0]["name"] == "Page-1"
+
+ def test_add_page(self):
+ root = drawio_xml.create_blank_diagram()
+ drawio_xml.add_page(root, "Second Page")
+ pages = drawio_xml.list_pages(root)
+ assert len(pages) == 2
+ assert pages[1]["name"] == "Second Page"
+
+ def test_remove_page(self):
+ root = drawio_xml.create_blank_diagram()
+ drawio_xml.add_page(root, "To Remove")
+ assert len(drawio_xml.list_pages(root)) == 2
+ drawio_xml.remove_page(root, 1)
+ assert len(drawio_xml.list_pages(root)) == 1
+
+ def test_cannot_remove_last_page(self):
+ root = drawio_xml.create_blank_diagram()
+ with pytest.raises(RuntimeError, match="Cannot remove the last page"):
+ drawio_xml.remove_page(root, 0)
+
+ def test_rename_page(self):
+ root = drawio_xml.create_blank_diagram()
+ drawio_xml.rename_page(root, 0, "My Diagram")
+ pages = drawio_xml.list_pages(root)
+ assert pages[0]["name"] == "My Diagram"
+
+ def test_shapes_on_different_pages(self):
+ root = drawio_xml.create_blank_diagram()
+ drawio_xml.add_vertex(root, "rectangle", 0, 0, 100, 50, "Page1Shape", diagram_index=0)
+ drawio_xml.add_page(root, "Page 2")
+ drawio_xml.add_vertex(root, "ellipse", 0, 0, 80, 80, "Page2Shape", diagram_index=1)
+ assert len(drawio_xml.get_vertices(root, 0)) == 1
+ assert len(drawio_xml.get_vertices(root, 1)) == 1
+
+
+# ============================================================================
+# Session
+# ============================================================================
+
+class TestSession:
+ def test_new_session(self):
+ s = Session()
+ assert s.is_open is False
+ assert s.is_modified is False
+
+ def test_new_project(self):
+ s = Session()
+ s.new_project(850, 1100)
+ assert s.is_open is True
+ assert s.is_modified is False
+
+ def test_undo_redo(self):
+ s = Session()
+ s.new_project()
+ assert s.undo() is False # Nothing to undo
+
+ s.checkpoint()
+ drawio_xml.add_vertex(s.root, "rectangle", 0, 0, 100, 50, "Test")
+ assert len(drawio_xml.get_vertices(s.root)) == 1
+
+ assert s.undo() is True
+ assert len(drawio_xml.get_vertices(s.root)) == 0
+
+ assert s.redo() is True
+ assert len(drawio_xml.get_vertices(s.root)) == 1
+
+ def test_multiple_undo(self):
+ s = Session()
+ s.new_project()
+
+ s.checkpoint()
+ drawio_xml.add_vertex(s.root, "rectangle", 0, 0, 100, 50, "First")
+
+ s.checkpoint()
+ drawio_xml.add_vertex(s.root, "rectangle", 200, 0, 100, 50, "Second")
+
+ assert len(drawio_xml.get_vertices(s.root)) == 2
+ s.undo()
+ assert len(drawio_xml.get_vertices(s.root)) == 1
+ s.undo()
+ assert len(drawio_xml.get_vertices(s.root)) == 0
+
+ def test_save_and_open(self):
+ s = Session()
+ s.new_project()
+ drawio_xml.add_vertex(s.root, "rectangle", 0, 0, 100, 50, "Persisted")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+
+ try:
+ s.save_project(path)
+ assert not s.is_modified
+ assert os.path.exists(path)
+
+ s2 = Session()
+ s2.open_project(path)
+ assert s2.is_open
+ cells = drawio_xml.get_vertices(s2.root)
+ assert len(cells) == 1
+ assert cells[0].get("value") == "Persisted"
+ finally:
+ os.unlink(path)
+
+ def test_save_no_project(self):
+ s = Session()
+ with pytest.raises(RuntimeError, match="No project is open"):
+ s.save_project("test.drawio")
+
+ def test_open_nonexistent(self):
+ s = Session()
+ with pytest.raises(FileNotFoundError):
+ s.open_project("/nonexistent/path.drawio")
+
+ def test_status(self):
+ s = Session()
+ status = s.status()
+ assert status["project_open"] is False
+
+ s.new_project()
+ drawio_xml.add_vertex(s.root, "rectangle", 0, 0, 100, 50)
+ status = s.status()
+ assert status["project_open"] is True
+ assert status["shape_count"] == 1
+ assert status["edge_count"] == 0
+
+
+# ============================================================================
+# Project module
+# ============================================================================
+
+class TestProject:
+ def test_new_project(self):
+ s = Session()
+ result = proj_mod.new_project(s, "letter")
+ assert result["action"] == "new_project"
+ assert result["preset"] == "letter"
+ assert s.is_open
+
+ def test_new_project_all_presets(self):
+ for name in proj_mod.PAGE_PRESETS:
+ s = Session()
+ result = proj_mod.new_project(s, name)
+ assert result["action"] == "new_project"
+ assert s.is_open
+
+ def test_new_project_invalid_preset(self):
+ s = Session()
+ with pytest.raises(ValueError, match="Unknown preset"):
+ proj_mod.new_project(s, "nonexistent")
+
+ def test_new_project_custom_size(self):
+ s = Session()
+ result = proj_mod.new_project(s, "custom", width=1920, height=1080)
+ assert result["page_size"] == "1920x1080"
+
+ def test_save_and_open(self):
+ s = Session()
+ proj_mod.new_project(s, "a4")
+ shapes_mod.add_shape(s, "rectangle", label="Test")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+
+ try:
+ proj_mod.save_project(s, path)
+ assert os.path.exists(path)
+
+ s2 = Session()
+ result = proj_mod.open_project(s2, path)
+ assert result["action"] == "open_project"
+ assert result["shape_count"] == 1
+ finally:
+ os.unlink(path)
+
+ def test_project_info(self):
+ s = Session()
+ proj_mod.new_project(s, "letter")
+ shapes_mod.add_shape(s, "rectangle", label="A")
+ shapes_mod.add_shape(s, "ellipse", label="B")
+ info = proj_mod.project_info(s)
+ assert len(info["shapes"]) == 2
+ assert info["canvas"]["pageWidth"] == "850"
+
+ def test_project_info_no_project(self):
+ s = Session()
+ with pytest.raises(RuntimeError, match="No project is open"):
+ proj_mod.project_info(s)
+
+ def test_list_presets(self):
+ presets = proj_mod.list_presets()
+ assert "letter" in presets
+ assert "a4" in presets
+
+
+# ============================================================================
+# Shapes module
+# ============================================================================
+
+class TestShapes:
+ def test_add_shape(self):
+ s = Session()
+ proj_mod.new_project(s)
+ result = shapes_mod.add_shape(s, "rectangle", 10, 20, 120, 60, "Hello")
+ assert result["action"] == "add_shape"
+ assert result["label"] == "Hello"
+ assert result["id"] is not None
+
+ def test_add_shape_no_project(self):
+ s = Session()
+ with pytest.raises(RuntimeError, match="No project is open"):
+ shapes_mod.add_shape(s, "rectangle")
+
+ def test_list_shapes(self):
+ s = Session()
+ proj_mod.new_project(s)
+ shapes_mod.add_shape(s, "rectangle", label="A")
+ shapes_mod.add_shape(s, "ellipse", label="B")
+ result = shapes_mod.list_shapes(s)
+ assert len(result) == 2
+
+ def test_remove_shape(self):
+ s = Session()
+ proj_mod.new_project(s)
+ result = shapes_mod.add_shape(s, "rectangle", label="ToRemove")
+ cell_id = result["id"]
+ shapes_mod.remove_shape(s, cell_id)
+ assert len(shapes_mod.list_shapes(s)) == 0
+
+ def test_remove_shape_not_found(self):
+ s = Session()
+ proj_mod.new_project(s)
+ with pytest.raises(ValueError, match="Shape not found"):
+ shapes_mod.remove_shape(s, "nonexistent")
+
+ def test_update_label(self):
+ s = Session()
+ proj_mod.new_project(s)
+ result = shapes_mod.add_shape(s, "rectangle", label="Old")
+ shapes_mod.update_label(s, result["id"], "New")
+ shapes = shapes_mod.list_shapes(s)
+ assert shapes[0]["value"] == "New"
+
+ def test_move_shape(self):
+ s = Session()
+ proj_mod.new_project(s)
+ result = shapes_mod.add_shape(s, "rectangle", 10, 20, 100, 50)
+ shapes_mod.move_shape(s, result["id"], 300, 400)
+ info = shapes_mod.get_shape_info(s, result["id"])
+ assert info["x"] == 300.0
+ assert info["y"] == 400.0
+
+ def test_resize_shape(self):
+ s = Session()
+ proj_mod.new_project(s)
+ result = shapes_mod.add_shape(s, "rectangle", 10, 20, 100, 50)
+ shapes_mod.resize_shape(s, result["id"], 200, 150)
+ info = shapes_mod.get_shape_info(s, result["id"])
+ assert info["width"] == 200.0
+ assert info["height"] == 150.0
+
+ def test_set_style(self):
+ s = Session()
+ proj_mod.new_project(s)
+ result = shapes_mod.add_shape(s, "rectangle")
+ shapes_mod.set_style(s, result["id"], "fillColor", "#ff0000")
+ info = shapes_mod.get_shape_info(s, result["id"])
+ assert info["style_parsed"]["fillColor"] == "#ff0000"
+
+ def test_get_shape_info(self):
+ s = Session()
+ proj_mod.new_project(s)
+ result = shapes_mod.add_shape(s, "ellipse", 50, 60, 80, 80, "Circle")
+ info = shapes_mod.get_shape_info(s, result["id"])
+ assert info["value"] == "Circle"
+ assert info["type"] == "vertex"
+ assert "style_parsed" in info
+
+ def test_list_shape_types(self):
+ types = shapes_mod.list_shape_types()
+ assert "rectangle" in types
+ assert "ellipse" in types
+ assert "diamond" in types
+
+ @pytest.mark.parametrize("shape_type", [
+ "rectangle", "rounded", "ellipse", "diamond", "triangle",
+ "hexagon", "cylinder", "cloud", "parallelogram", "process",
+ "document", "callout", "note", "actor", "text",
+ ])
+ def test_all_shape_types_via_module(self, shape_type):
+ s = Session()
+ proj_mod.new_project(s)
+ result = shapes_mod.add_shape(s, shape_type, label=shape_type)
+ assert result["shape_type"] == shape_type
+
+ def test_undo_add_shape(self):
+ s = Session()
+ proj_mod.new_project(s)
+ shapes_mod.add_shape(s, "rectangle", label="Test")
+ assert len(shapes_mod.list_shapes(s)) == 1
+ s.undo()
+ assert len(shapes_mod.list_shapes(s)) == 0
+
+
+# ============================================================================
+# Connectors module
+# ============================================================================
+
+class TestConnectors:
+ def test_add_connector(self):
+ s = Session()
+ proj_mod.new_project(s)
+ v1 = shapes_mod.add_shape(s, "rectangle", label="A")["id"]
+ v2 = shapes_mod.add_shape(s, "rectangle", 200, 100, label="B")["id"]
+ result = conn_mod.add_connector(s, v1, v2, "orthogonal", "flow")
+ assert result["action"] == "add_connector"
+ assert result["source"] == v1
+ assert result["target"] == v2
+ assert result["label"] == "flow"
+
+ def test_add_connector_invalid_source(self):
+ s = Session()
+ proj_mod.new_project(s)
+ v1 = shapes_mod.add_shape(s, "rectangle", label="A")["id"]
+ with pytest.raises(ValueError, match="Source cell not found"):
+ conn_mod.add_connector(s, "nonexistent", v1)
+
+ def test_add_connector_invalid_target(self):
+ s = Session()
+ proj_mod.new_project(s)
+ v1 = shapes_mod.add_shape(s, "rectangle", label="A")["id"]
+ with pytest.raises(ValueError, match="Target cell not found"):
+ conn_mod.add_connector(s, v1, "nonexistent")
+
+ def test_list_connectors(self):
+ s = Session()
+ proj_mod.new_project(s)
+ v1 = shapes_mod.add_shape(s, "rectangle", label="A")["id"]
+ v2 = shapes_mod.add_shape(s, "rectangle", 200, 100, label="B")["id"]
+ conn_mod.add_connector(s, v1, v2)
+ result = conn_mod.list_connectors(s)
+ assert len(result) == 1
+
+ def test_remove_connector(self):
+ s = Session()
+ proj_mod.new_project(s)
+ v1 = shapes_mod.add_shape(s, "rectangle", label="A")["id"]
+ v2 = shapes_mod.add_shape(s, "rectangle", 200, 100, label="B")["id"]
+ edge = conn_mod.add_connector(s, v1, v2)
+ conn_mod.remove_connector(s, edge["id"])
+ assert len(conn_mod.list_connectors(s)) == 0
+
+ def test_update_connector_label(self):
+ s = Session()
+ proj_mod.new_project(s)
+ v1 = shapes_mod.add_shape(s, "rectangle", label="A")["id"]
+ v2 = shapes_mod.add_shape(s, "rectangle", 200, 100, label="B")["id"]
+ edge = conn_mod.add_connector(s, v1, v2, label="old")
+ conn_mod.update_connector_label(s, edge["id"], "new")
+ connectors = conn_mod.list_connectors(s)
+ assert connectors[0]["value"] == "new"
+
+ def test_set_connector_style(self):
+ s = Session()
+ proj_mod.new_project(s)
+ v1 = shapes_mod.add_shape(s, "rectangle", label="A")["id"]
+ v2 = shapes_mod.add_shape(s, "rectangle", 200, 100, label="B")["id"]
+ edge = conn_mod.add_connector(s, v1, v2)
+ conn_mod.set_connector_style(s, edge["id"], "strokeColor", "#0000ff")
+ cell = drawio_xml.find_cell_by_id(s.root, edge["id"])
+ style = drawio_xml.parse_style(cell.get("style", ""))
+ assert style["strokeColor"] == "#0000ff"
+
+ def test_list_edge_styles(self):
+ styles = conn_mod.list_edge_styles()
+ assert "orthogonal" in styles
+ assert "straight" in styles
+ assert "curved" in styles
+
+ @pytest.mark.parametrize("edge_style", ["straight", "orthogonal", "curved", "entity-relation"])
+ def test_all_edge_styles_via_module(self, edge_style):
+ s = Session()
+ proj_mod.new_project(s)
+ v1 = shapes_mod.add_shape(s, "rectangle", label="A")["id"]
+ v2 = shapes_mod.add_shape(s, "rectangle", 200, 100, label="B")["id"]
+ result = conn_mod.add_connector(s, v1, v2, edge_style)
+ assert result["action"] == "add_connector"
+
+
+# ============================================================================
+# Pages module
+# ============================================================================
+
+class TestPagesModule:
+ def test_list_pages(self):
+ s = Session()
+ proj_mod.new_project(s)
+ result = pages_mod.list_pages(s)
+ assert len(result) == 1
+
+ def test_add_page(self):
+ s = Session()
+ proj_mod.new_project(s)
+ result = pages_mod.add_page(s, "Extra Page")
+ assert result["action"] == "add_page"
+ assert result["page_count"] == 2
+
+ def test_remove_page(self):
+ s = Session()
+ proj_mod.new_project(s)
+ pages_mod.add_page(s, "To Delete")
+ pages_mod.remove_page(s, 1)
+ assert len(pages_mod.list_pages(s)) == 1
+
+ def test_rename_page(self):
+ s = Session()
+ proj_mod.new_project(s)
+ pages_mod.rename_page(s, 0, "Flowchart")
+ result = pages_mod.list_pages(s)
+ assert result[0]["name"] == "Flowchart"
+
+
+# ============================================================================
+# Export module
+# ============================================================================
+
+class TestExport:
+ def test_list_formats(self):
+ formats = export_mod.list_formats()
+ names = [f["name"] for f in formats]
+ assert "png" in names
+ assert "pdf" in names
+ assert "svg" in names
+
+ def test_export_xml_direct(self):
+ """XML export doesn't need draw.io CLI."""
+ s = Session()
+ proj_mod.new_project(s)
+ shapes_mod.add_shape(s, "rectangle", label="ExportTest")
+
+ with tempfile.NamedTemporaryFile(suffix=".xml", delete=False) as f:
+ path = f.name
+
+ try:
+ result = export_mod.render(s, path, fmt="xml", overwrite=True)
+ assert result["action"] == "export"
+ assert result["format"] == "xml"
+ assert result["method"] == "direct-write"
+ assert os.path.exists(path)
+ assert result["file_size"] > 0
+
+ # Verify the XML is valid drawio
+ parsed = drawio_xml.parse_drawio(path)
+ assert parsed.tag == "mxfile"
+ cells = drawio_xml.get_all_cells(parsed)
+ assert len(cells) == 1
+ finally:
+ os.unlink(path)
+
+ def test_export_no_project(self):
+ s = Session()
+ with pytest.raises(RuntimeError, match="No project is open"):
+ export_mod.render(s, "test.png")
+
+ def test_export_invalid_format(self):
+ s = Session()
+ proj_mod.new_project(s)
+ with pytest.raises(ValueError, match="Unknown format"):
+ export_mod.render(s, "test.bmp", fmt="bmp")
+
+ def test_export_file_exists(self):
+ s = Session()
+ proj_mod.new_project(s)
+ with tempfile.NamedTemporaryFile(suffix=".xml", delete=False) as f:
+ path = f.name
+
+ try:
+ with pytest.raises(FileExistsError):
+ export_mod.render(s, path, fmt="xml", overwrite=False)
+ finally:
+ os.unlink(path)
+
+
+# ============================================================================
+# Complex workflows
+# ============================================================================
+
+class TestWorkflows:
+ def test_flowchart(self):
+ """Build a complete flowchart: Start → Process → Decision → End."""
+ s = Session()
+ proj_mod.new_project(s, "letter")
+
+ start = shapes_mod.add_shape(s, "ellipse", 350, 50, 120, 60, "Start")["id"]
+ process = shapes_mod.add_shape(s, "rectangle", 340, 170, 140, 60, "Process Data")["id"]
+ decision = shapes_mod.add_shape(s, "diamond", 340, 290, 140, 80, "Valid?")["id"]
+ end = shapes_mod.add_shape(s, "ellipse", 350, 430, 120, 60, "End")["id"]
+
+ conn_mod.add_connector(s, start, process)
+ conn_mod.add_connector(s, process, decision)
+ conn_mod.add_connector(s, decision, end, label="Yes")
+
+ shapes = shapes_mod.list_shapes(s)
+ assert len(shapes) == 4
+ connectors = conn_mod.list_connectors(s)
+ assert len(connectors) == 3
+
+ # Save and reopen
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+ try:
+ proj_mod.save_project(s, path)
+ s2 = Session()
+ proj_mod.open_project(s2, path)
+ assert len(drawio_xml.get_vertices(s2.root)) == 4
+ assert len(drawio_xml.get_edges(s2.root)) == 3
+ finally:
+ os.unlink(path)
+
+ def test_styled_diagram(self):
+ """Build a diagram with custom styles."""
+ s = Session()
+ proj_mod.new_project(s)
+
+ box = shapes_mod.add_shape(s, "rounded", 100, 100, 160, 80, "Styled Box")["id"]
+ shapes_mod.set_style(s, box, "fillColor", "#dae8fc")
+ shapes_mod.set_style(s, box, "strokeColor", "#6c8ebf")
+ shapes_mod.set_style(s, box, "fontSize", "16")
+ shapes_mod.set_style(s, box, "shadow", "1")
+
+ info = shapes_mod.get_shape_info(s, box)
+ assert info["style_parsed"]["fillColor"] == "#dae8fc"
+ assert info["style_parsed"]["strokeColor"] == "#6c8ebf"
+ assert info["style_parsed"]["fontSize"] == "16"
+ assert info["style_parsed"]["shadow"] == "1"
+
+ def test_multi_page_workflow(self):
+ """Create a multi-page document."""
+ s = Session()
+ proj_mod.new_project(s)
+
+ # Page 1: Architecture diagram
+ pages_mod.rename_page(s, 0, "Architecture")
+ shapes_mod.add_shape(s, "cylinder", 100, 100, 80, 100, "Database")
+ shapes_mod.add_shape(s, "rectangle", 300, 100, 120, 60, "API Server")
+
+ # Page 2: Flowchart
+ pages_mod.add_page(s, "Flowchart")
+ shapes_mod.add_shape(s, "ellipse", 100, 100, 100, 50, "Start", diagram_index=1)
+
+ result = pages_mod.list_pages(s)
+ assert len(result) == 2
+ assert result[0]["name"] == "Architecture"
+ assert result[1]["name"] == "Flowchart"
+
+ def test_undo_redo_workflow(self):
+ """Test undo/redo across multiple operations."""
+ s = Session()
+ proj_mod.new_project(s)
+
+ shapes_mod.add_shape(s, "rectangle", label="First")
+ shapes_mod.add_shape(s, "rectangle", 200, 100, label="Second")
+ shapes_mod.add_shape(s, "rectangle", 400, 100, label="Third")
+
+ assert len(shapes_mod.list_shapes(s)) == 3
+ s.undo()
+ assert len(shapes_mod.list_shapes(s)) == 2
+ s.undo()
+ assert len(shapes_mod.list_shapes(s)) == 1
+ s.redo()
+ assert len(shapes_mod.list_shapes(s)) == 2
+ s.redo()
+ assert len(shapes_mod.list_shapes(s)) == 3
+
+ def test_export_xml_workflow(self):
+ """Full workflow: create diagram, add content, export to XML."""
+ s = Session()
+ proj_mod.new_project(s)
+
+ v1 = shapes_mod.add_shape(s, "rectangle", 100, 100, 120, 60, "Server")["id"]
+ v2 = shapes_mod.add_shape(s, "cylinder", 300, 100, 80, 100, "DB")["id"]
+ conn_mod.add_connector(s, v1, v2, "orthogonal", "query")
+
+ with tempfile.NamedTemporaryFile(suffix=".xml", delete=False) as f:
+ path = f.name
+
+ try:
+ result = export_mod.render(s, path, fmt="xml", overwrite=True)
+ assert result["file_size"] > 0
+
+ # Verify exported content
+ parsed = drawio_xml.parse_drawio(path)
+ vertices = drawio_xml.get_vertices(parsed)
+ edges = drawio_xml.get_edges(parsed)
+ assert len(vertices) == 2
+ assert len(edges) == 1
+ finally:
+ os.unlink(path)
diff --git a/drawio/agent-harness/cli_anything/drawio/tests/test_full_e2e.py b/drawio/agent-harness/cli_anything/drawio/tests/test_full_e2e.py
new file mode 100644
index 000000000..467a52896
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/tests/test_full_e2e.py
@@ -0,0 +1,612 @@
+#!/usr/bin/env python3
+"""Comprehensive end-to-end tests for the Draw.io CLI.
+
+Covers:
+- Real file I/O (create, save, reopen, verify)
+- Export to real formats (XML verified, PNG/PDF/SVG if draw.io installed)
+- CLI subprocess invocation
+- Complex multi-step diagram workflows
+"""
+
+import os
+import sys
+import json
+import tempfile
+import subprocess
+import shutil
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from cli_anything.drawio.core.session import Session
+from cli_anything.drawio.core import project as proj_mod
+from cli_anything.drawio.core import shapes as shapes_mod
+from cli_anything.drawio.core import connectors as conn_mod
+from cli_anything.drawio.core import pages as pages_mod
+from cli_anything.drawio.core import export as export_mod
+from cli_anything.drawio.utils import drawio_xml
+from cli_anything.drawio.utils import drawio_backend
+
+
+# ============================================================================
+# Helpers
+# ============================================================================
+
+def _resolve_cli(name):
+ """Resolve installed CLI command; falls back to python -m for dev."""
+ force = os.environ.get("CLI_ANYTHING_FORCE_INSTALLED", "").strip() == "1"
+ path = shutil.which(name)
+ if path:
+ print(f"[_resolve_cli] Using installed command: {path}")
+ return [path]
+ if force:
+ raise RuntimeError(f"{name} not found in PATH. Install with: pip install -e .")
+ module = "cli_anything.drawio.drawio_cli"
+ print(f"[_resolve_cli] Falling back to: {sys.executable} -m {module}")
+ return [sys.executable, "-m", module]
+
+
+def _has_drawio():
+ """Check if draw.io CLI is available."""
+ try:
+ drawio_backend.find_drawio()
+ return True
+ except RuntimeError:
+ return False
+
+
+# ============================================================================
+# 1. REAL FILE ROUNDTRIP
+# ============================================================================
+
+class TestFileRoundtrip:
+ """Create real .drawio files, save, reopen, verify content."""
+
+ def test_empty_diagram_roundtrip(self):
+ s = Session()
+ proj_mod.new_project(s, "letter")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+ try:
+ proj_mod.save_project(s, path)
+ assert os.path.exists(path)
+ size = os.path.getsize(path)
+ assert size > 0
+ print(f"\n Empty diagram: {path} ({size:,} bytes)")
+
+ # Reopen and verify structure
+ s2 = Session()
+ proj_mod.open_project(s2, path)
+ assert s2.is_open
+ info = proj_mod.project_info(s2)
+ assert len(info["shapes"]) == 0
+ assert len(info["edges"]) == 0
+ finally:
+ os.unlink(path)
+
+ def test_complex_diagram_roundtrip(self):
+ """Build a complex diagram, save, reopen, verify all content."""
+ s = Session()
+ proj_mod.new_project(s, "16:9")
+
+ # Add diverse shapes
+ shapes = {}
+ for i, (shape_type, label) in enumerate([
+ ("rectangle", "Server"),
+ ("cylinder", "Database"),
+ ("ellipse", "Client"),
+ ("cloud", "Internet"),
+ ("hexagon", "Load Balancer"),
+ ("diamond", "Decision"),
+ ]):
+ r = shapes_mod.add_shape(
+ s, shape_type, x=100 + (i % 3) * 200, y=100 + (i // 3) * 200,
+ width=120, height=60, label=label,
+ )
+ shapes[label] = r["id"]
+
+ # Add connectors
+ conn_mod.add_connector(s, shapes["Client"], shapes["Internet"], label="request")
+ conn_mod.add_connector(s, shapes["Internet"], shapes["Load Balancer"])
+ conn_mod.add_connector(s, shapes["Load Balancer"], shapes["Server"])
+ conn_mod.add_connector(s, shapes["Server"], shapes["Database"], label="query")
+
+ # Apply styles
+ shapes_mod.set_style(s, shapes["Server"], "fillColor", "#dae8fc")
+ shapes_mod.set_style(s, shapes["Database"], "fillColor", "#d5e8d4")
+ shapes_mod.set_style(s, shapes["Client"], "fillColor", "#fff2cc")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+ try:
+ proj_mod.save_project(s, path)
+ file_size = os.path.getsize(path)
+ print(f"\n Complex diagram: {path} ({file_size:,} bytes)")
+ print(f" Shapes: {len(shapes)}, Connectors: 4")
+
+ # Reopen and verify
+ s2 = Session()
+ result = proj_mod.open_project(s2, path)
+ assert result["shape_count"] == 6
+ assert result["edge_count"] == 4
+
+ # Verify shape labels preserved
+ for cell in drawio_xml.get_vertices(s2.root):
+ assert cell.get("value") in shapes
+
+ # Verify styles preserved
+ server_cell = drawio_xml.find_cell_by_id(s2.root, shapes["Server"])
+ style = drawio_xml.parse_style(server_cell.get("style", ""))
+ assert style.get("fillColor") == "#dae8fc"
+ finally:
+ os.unlink(path)
+
+ def test_multi_page_roundtrip(self):
+ """Create multi-page diagram, save, verify all pages."""
+ s = Session()
+ proj_mod.new_project(s, "letter")
+ pages_mod.rename_page(s, 0, "Overview")
+ shapes_mod.add_shape(s, "rectangle", label="Main System")
+
+ pages_mod.add_page(s, "Details")
+ shapes_mod.add_shape(s, "ellipse", label="Component A", diagram_index=1)
+ shapes_mod.add_shape(s, "ellipse", 200, 100, label="Component B", diagram_index=1)
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+ try:
+ proj_mod.save_project(s, path)
+
+ s2 = Session()
+ proj_mod.open_project(s2, path)
+ pages = drawio_xml.list_pages(s2.root)
+ assert len(pages) == 2
+ assert pages[0]["name"] == "Overview"
+ assert pages[1]["name"] == "Details"
+ assert pages[0]["cell_count"] == 1
+ assert pages[1]["cell_count"] == 2
+ finally:
+ os.unlink(path)
+
+
+# ============================================================================
+# 2. XML EXPORT VERIFICATION
+# ============================================================================
+
+class TestXmlExport:
+ """Test XML export with content verification."""
+
+ def test_export_xml_valid_structure(self):
+ s = Session()
+ proj_mod.new_project(s)
+ shapes_mod.add_shape(s, "rectangle", 100, 100, 120, 60, "ExportTest")
+ shapes_mod.add_shape(s, "ellipse", 300, 100, 80, 80, "Circle")
+ v1 = shapes_mod.list_shapes(s)[0]["id"]
+ v2 = shapes_mod.list_shapes(s)[1]["id"]
+ conn_mod.add_connector(s, v1, v2, label="link")
+
+ with tempfile.NamedTemporaryFile(suffix=".xml", delete=False) as f:
+ path = f.name
+ try:
+ result = export_mod.render(s, path, fmt="xml", overwrite=True)
+ assert result["file_size"] > 0
+ print(f"\n XML export: {path} ({result['file_size']:,} bytes)")
+
+ # Parse and verify XML content
+ from xml.etree import ElementTree as ET
+ tree = ET.parse(path)
+ root = tree.getroot()
+ assert root.tag == "mxfile"
+
+ # Count cells
+ all_cells = list(root.iter("mxCell"))
+ user_cells = [c for c in all_cells if c.get("id") not in ("0", "1")]
+ vertices = [c for c in user_cells if c.get("vertex") == "1"]
+ edges = [c for c in user_cells if c.get("edge") == "1"]
+ assert len(vertices) == 2
+ assert len(edges) == 1
+ print(f" Verified: {len(vertices)} vertices, {len(edges)} edges")
+ finally:
+ os.unlink(path)
+
+ def test_export_xml_preserves_styles(self):
+ s = Session()
+ proj_mod.new_project(s)
+ box = shapes_mod.add_shape(s, "rounded", label="Styled")["id"]
+ shapes_mod.set_style(s, box, "fillColor", "#ff6666")
+ shapes_mod.set_style(s, box, "strokeWidth", "3")
+
+ with tempfile.NamedTemporaryFile(suffix=".xml", delete=False) as f:
+ path = f.name
+ try:
+ export_mod.render(s, path, fmt="xml", overwrite=True)
+
+ parsed = drawio_xml.parse_drawio(path)
+ cell = drawio_xml.get_vertices(parsed)[0]
+ style = drawio_xml.parse_style(cell.get("style", ""))
+ assert style["fillColor"] == "#ff6666"
+ assert style["strokeWidth"] == "3"
+ finally:
+ os.unlink(path)
+
+
+# ============================================================================
+# 3. REAL DRAW.IO EXPORT (requires draw.io installed)
+# ============================================================================
+
+class TestRealExport:
+ """Test export using the real draw.io CLI.
+ These tests require draw.io desktop app to be installed.
+ """
+
+ @pytest.mark.skipif(not _has_drawio(), reason="draw.io not installed")
+ def test_export_png(self):
+ s = Session()
+ proj_mod.new_project(s)
+ shapes_mod.add_shape(s, "rectangle", 100, 100, 120, 60, "PNG Test")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ drawio_path = f.name
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
+ png_path = f.name
+ os.unlink(png_path) # draw.io needs to create it
+
+ try:
+ proj_mod.save_project(s, drawio_path)
+ result = export_mod.render(s, png_path, fmt="png", overwrite=True)
+
+ assert os.path.exists(result["output"])
+ assert result["file_size"] > 0
+
+ # Verify PNG magic bytes
+ with open(result["output"], "rb") as f:
+ header = f.read(8)
+ assert header[:4] == b"\x89PNG", "Not a valid PNG file"
+
+ print(f"\n PNG export: {result['output']} ({result['file_size']:,} bytes)")
+ finally:
+ if os.path.exists(drawio_path):
+ os.unlink(drawio_path)
+ if os.path.exists(png_path):
+ os.unlink(png_path)
+
+ @pytest.mark.skipif(not _has_drawio(), reason="draw.io not installed")
+ def test_export_svg(self):
+ s = Session()
+ proj_mod.new_project(s)
+ shapes_mod.add_shape(s, "ellipse", 100, 100, 80, 80, "SVG Test")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ drawio_path = f.name
+ with tempfile.NamedTemporaryFile(suffix=".svg", delete=False) as f:
+ svg_path = f.name
+ os.unlink(svg_path)
+
+ try:
+ proj_mod.save_project(s, drawio_path)
+ result = export_mod.render(s, svg_path, fmt="svg", overwrite=True)
+
+ assert os.path.exists(result["output"])
+ assert result["file_size"] > 0
+
+ # Verify SVG content
+ with open(result["output"], "r") as f:
+ content = f.read()
+ assert "<svg" in content, "Not a valid SVG file"
+
+ print(f"\n SVG export: {result['output']} ({result['file_size']:,} bytes)")
+ finally:
+ if os.path.exists(drawio_path):
+ os.unlink(drawio_path)
+ if os.path.exists(svg_path):
+ os.unlink(svg_path)
+
+ @pytest.mark.skipif(not _has_drawio(), reason="draw.io not installed")
+ def test_export_pdf(self):
+ s = Session()
+ proj_mod.new_project(s)
+ shapes_mod.add_shape(s, "rectangle", 100, 100, 140, 60, "PDF Test")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ drawio_path = f.name
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as f:
+ pdf_path = f.name
+ os.unlink(pdf_path)
+
+ try:
+ proj_mod.save_project(s, drawio_path)
+ result = export_mod.render(s, pdf_path, fmt="pdf", overwrite=True)
+
+ assert os.path.exists(result["output"])
+ assert result["file_size"] > 0
+
+ # Verify PDF magic bytes
+ with open(result["output"], "rb") as f:
+ header = f.read(4)
+ assert header == b"%PDF", "Not a valid PDF file"
+
+ print(f"\n PDF export: {result['output']} ({result['file_size']:,} bytes)")
+ finally:
+ if os.path.exists(drawio_path):
+ os.unlink(drawio_path)
+ if os.path.exists(pdf_path):
+ os.unlink(pdf_path)
+
+
+# ============================================================================
+# 4. CLI SUBPROCESS TESTS
+# ============================================================================
+
+class TestCLISubprocess:
+ """Test the CLI as a subprocess, like a real user/agent would use it."""
+
+ CLI_BASE = _resolve_cli("cli-anything-drawio")
+
+ def _run(self, args, check=True):
+ return subprocess.run(
+ self.CLI_BASE + args,
+ capture_output=True, text=True,
+ check=check,
+ timeout=30,
+ )
+
+ def test_help(self):
+ result = self._run(["--help"])
+ assert result.returncode == 0
+ assert "Draw.io" in result.stdout or "diagram" in result.stdout.lower()
+
+ def test_project_new_json(self, tmp_path):
+ out = str(tmp_path / "test.drawio")
+ result = self._run(["--json", "project", "new", "-o", out])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert data["action"] == "new_project"
+ assert os.path.exists(out)
+
+ def test_project_info_json(self, tmp_path):
+ out = str(tmp_path / "test.drawio")
+ self._run(["--json", "project", "new", "-o", out])
+ result = self._run(["--json", "--project", out, "project", "info"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert data["project_path"] is not None
+
+ def test_shape_add_json(self, tmp_path):
+ out = str(tmp_path / "test.drawio")
+ self._run(["project", "new", "-o", out])
+ result = self._run(["--json", "--project", out, "shape", "add", "rectangle",
+ "--label", "CLI Shape"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert data["action"] == "add_shape"
+ assert data["label"] == "CLI Shape"
+
+ def test_shape_list_json(self, tmp_path):
+ """Shape list from a file that already has shapes.
+
+ Each subprocess is stateless, so we build a file with shapes
+ using the library directly, then list via CLI.
+ """
+ out = str(tmp_path / "test.drawio")
+ s = Session()
+ proj_mod.new_project(s)
+ shapes_mod.add_shape(s, "rectangle", label="A")
+ shapes_mod.add_shape(s, "ellipse", 200, 100, label="B")
+ proj_mod.save_project(s, out)
+
+ result = self._run(["--json", "--project", out, "shape", "list"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert len(data) == 2
+
+ def test_connect_add_json(self, tmp_path):
+ out = str(tmp_path / "test.drawio")
+ self._run(["project", "new", "-o", out])
+ r1 = self._run(["--json", "--project", out, "shape", "add", "rectangle", "--label", "A"])
+ id1 = json.loads(r1.stdout)["id"]
+
+ # Need to save after adding first shape, then reload
+ # Actually, each subprocess is independent - shapes don't persist across calls
+ # unless we save. Let's test the shape types and help instead.
+
+ def test_shape_types(self):
+ result = self._run(["--json", "shape", "types"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert "rectangle" in data
+ assert "ellipse" in data
+
+ def test_connect_styles(self):
+ result = self._run(["--json", "connect", "styles"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert "orthogonal" in data
+
+ def test_export_formats(self):
+ result = self._run(["--json", "export", "formats"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ names = [f["name"] for f in data]
+ assert "png" in names
+ assert "svg" in names
+
+ def test_page_list(self, tmp_path):
+ out = str(tmp_path / "test.drawio")
+ self._run(["project", "new", "-o", out])
+ result = self._run(["--json", "--project", out, "page", "list"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert len(data) == 1
+
+ def test_session_status(self, tmp_path):
+ out = str(tmp_path / "test.drawio")
+ self._run(["project", "new", "-o", out])
+ result = self._run(["--json", "--project", out, "session", "status"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert data["project_open"] is True
+
+ def test_project_presets(self):
+ result = self._run(["--json", "project", "presets"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert "letter" in data
+ assert "a4" in data
+
+ def test_export_xml_subprocess(self, tmp_path):
+ drawio_file = str(tmp_path / "test.drawio")
+ xml_file = str(tmp_path / "test.xml")
+
+ self._run(["project", "new", "-o", drawio_file])
+ self._run(["--project", drawio_file, "shape", "add", "rectangle", "--label", "SubTest"])
+ result = self._run(["--json", "--project", drawio_file,
+ "export", "render", xml_file, "-f", "xml", "--overwrite"])
+ assert result.returncode == 0
+ data = json.loads(result.stdout)
+ assert data["format"] == "xml"
+ assert os.path.exists(xml_file)
+
+
+# ============================================================================
+# 5. REAL-WORLD WORKFLOW TESTS
+# ============================================================================
+
+class TestRealWorldWorkflows:
+ """Simulate actual diagram creation scenarios."""
+
+ def test_architecture_diagram(self):
+ """Build a 3-tier web architecture diagram."""
+ s = Session()
+ proj_mod.new_project(s, "16:9")
+
+ # Tier labels
+ client = shapes_mod.add_shape(s, "actor", 100, 50, 60, 80, "User")["id"]
+ web = shapes_mod.add_shape(s, "rectangle", 250, 50, 140, 60, "Web Server")["id"]
+ app = shapes_mod.add_shape(s, "rectangle", 250, 180, 140, 60, "App Server")["id"]
+ db = shapes_mod.add_shape(s, "cylinder", 270, 310, 100, 80, "PostgreSQL")["id"]
+ cache = shapes_mod.add_shape(s, "hexagon", 500, 180, 120, 60, "Redis")["id"]
+
+ conn_mod.add_connector(s, client, web, "straight", "HTTPS")
+ conn_mod.add_connector(s, web, app, "orthogonal", "REST API")
+ conn_mod.add_connector(s, app, db, "orthogonal", "SQL")
+ conn_mod.add_connector(s, app, cache, "orthogonal", "cache")
+
+ shapes_mod.set_style(s, web, "fillColor", "#dae8fc")
+ shapes_mod.set_style(s, app, "fillColor", "#d5e8d4")
+ shapes_mod.set_style(s, db, "fillColor", "#fff2cc")
+ shapes_mod.set_style(s, cache, "fillColor", "#f8cecc")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+ try:
+ proj_mod.save_project(s, path)
+ print(f"\n Architecture diagram: {path}")
+ print(f" Shapes: 5, Connectors: 4")
+ assert os.path.getsize(path) > 0
+
+ # Verify content
+ s2 = Session()
+ proj_mod.open_project(s2, path)
+ assert len(drawio_xml.get_vertices(s2.root)) == 5
+ assert len(drawio_xml.get_edges(s2.root)) == 4
+ finally:
+ os.unlink(path)
+
+ def test_er_diagram(self):
+ """Build an entity-relationship diagram."""
+ s = Session()
+ proj_mod.new_project(s, "letter")
+
+ users = shapes_mod.add_shape(s, "rectangle", 100, 100, 140, 100,
+ "Users\n─────\nid: int PK\nname: varchar\nemail: varchar")["id"]
+ orders = shapes_mod.add_shape(s, "rectangle", 400, 100, 140, 100,
+ "Orders\n─────\nid: int PK\nuser_id: int FK\ntotal: decimal")["id"]
+ products = shapes_mod.add_shape(s, "rectangle", 400, 300, 140, 80,
+ "Products\n─────\nid: int PK\nname: varchar")["id"]
+
+ conn_mod.add_connector(s, users, orders, "entity-relation", "1:N")
+ conn_mod.add_connector(s, orders, products, "entity-relation", "N:M")
+
+ shapes_mod.set_style(s, users, "fillColor", "#e1d5e7")
+ shapes_mod.set_style(s, orders, "fillColor", "#e1d5e7")
+ shapes_mod.set_style(s, products, "fillColor", "#e1d5e7")
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+ try:
+ proj_mod.save_project(s, path)
+ info = proj_mod.project_info(s)
+ assert len(info["shapes"]) == 3
+ assert len(info["edges"]) == 2
+ print(f"\n ER diagram: {path}")
+ finally:
+ os.unlink(path)
+
+ def test_decision_tree(self):
+ """Build a decision tree / flowchart."""
+ s = Session()
+ proj_mod.new_project(s, "letter")
+
+ start = shapes_mod.add_shape(s, "ellipse", 300, 30, 100, 50, "Start")["id"]
+ d1 = shapes_mod.add_shape(s, "diamond", 275, 130, 150, 80, "Is it raining?")["id"]
+ a1 = shapes_mod.add_shape(s, "rectangle", 100, 280, 140, 50, "Take umbrella")["id"]
+ a2 = shapes_mod.add_shape(s, "rectangle", 450, 280, 140, 50, "Wear sunscreen")["id"]
+ end = shapes_mod.add_shape(s, "ellipse", 300, 400, 100, 50, "Go outside")["id"]
+
+ conn_mod.add_connector(s, start, d1)
+ conn_mod.add_connector(s, d1, a1, label="Yes")
+ conn_mod.add_connector(s, d1, a2, label="No")
+ conn_mod.add_connector(s, a1, end)
+ conn_mod.add_connector(s, a2, end)
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+ try:
+ proj_mod.save_project(s, path)
+ s2 = Session()
+ proj_mod.open_project(s2, path)
+ assert len(drawio_xml.get_vertices(s2.root)) == 5
+ assert len(drawio_xml.get_edges(s2.root)) == 5
+ print(f"\n Decision tree: {path}")
+ finally:
+ os.unlink(path)
+
+ def test_multi_page_documentation(self):
+ """Build a multi-page technical document."""
+ s = Session()
+ proj_mod.new_project(s, "letter")
+ pages_mod.rename_page(s, 0, "System Overview")
+
+ # Page 1: High-level architecture
+ shapes_mod.add_shape(s, "rectangle", 100, 100, 200, 60, "Frontend (React)")
+ shapes_mod.add_shape(s, "rectangle", 100, 220, 200, 60, "Backend (Python)")
+ shapes_mod.add_shape(s, "cylinder", 130, 340, 140, 80, "PostgreSQL")
+
+ # Page 2: Deployment
+ pages_mod.add_page(s, "Deployment")
+ shapes_mod.add_shape(s, "cloud", 100, 50, 200, 120, "AWS", diagram_index=1)
+ shapes_mod.add_shape(s, "rectangle", 130, 200, 140, 50, "ECS Fargate", diagram_index=1)
+ shapes_mod.add_shape(s, "cylinder", 130, 300, 140, 80, "RDS", diagram_index=1)
+
+ # Page 3: CI/CD
+ pages_mod.add_page(s, "CI/CD Pipeline")
+ shapes_mod.add_shape(s, "rectangle", 50, 100, 120, 50, "GitHub", diagram_index=2)
+ shapes_mod.add_shape(s, "rectangle", 220, 100, 120, 50, "Actions", diagram_index=2)
+ shapes_mod.add_shape(s, "rectangle", 390, 100, 120, 50, "Deploy", diagram_index=2)
+
+ with tempfile.NamedTemporaryFile(suffix=".drawio", delete=False) as f:
+ path = f.name
+ try:
+ proj_mod.save_project(s, path)
+
+ s2 = Session()
+ proj_mod.open_project(s2, path)
+ pages = drawio_xml.list_pages(s2.root)
+ assert len(pages) == 3
+ assert pages[0]["name"] == "System Overview"
+ assert pages[1]["name"] == "Deployment"
+ assert pages[2]["name"] == "CI/CD Pipeline"
+ print(f"\n Multi-page doc: {path} ({len(pages)} pages)")
+ finally:
+ os.unlink(path)
diff --git a/drawio/agent-harness/cli_anything/drawio/utils/__init__.py b/drawio/agent-harness/cli_anything/drawio/utils/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/drawio/agent-harness/cli_anything/drawio/utils/drawio_backend.py b/drawio/agent-harness/cli_anything/drawio/utils/drawio_backend.py
new file mode 100644
index 000000000..2a7c99095
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/utils/drawio_backend.py
@@ -0,0 +1,145 @@
+"""Draw.io backend — invoke draw.io desktop CLI for diagram export.
+
+The draw.io desktop app (Electron-based) supports command-line export:
+ draw.io -x input.drawio -o output.png -f png
+ draw.io -x input.drawio -o output.pdf -f pdf
+ draw.io -x input.drawio -o output.svg -f svg
+
+Requires: draw.io desktop app
+ macOS: brew install --cask drawio
+ Linux: snap install drawio OR download .deb/.AppImage
+ Windows: winget install JGraph.Draw
+"""
+
+import os
+import shutil
+import subprocess
+from typing import Optional
+
+
+def find_drawio() -> str:
+ """Find the draw.io CLI executable. Raises RuntimeError if not found."""
+ # Common executable names across platforms
+ candidates = ["draw.io", "drawio", "draw.io.exe"]
+
+ for name in candidates:
+ path = shutil.which(name)
+ if path:
+ return path
+
+ # macOS app bundle path
+ mac_path = "/Applications/draw.io.app/Contents/MacOS/draw.io"
+ if os.path.isfile(mac_path):
+ return mac_path
+
+ raise RuntimeError(
+ "draw.io desktop app is not installed. Install it with:\n"
+ " macOS: brew install --cask drawio\n"
+ " Linux: snap install drawio\n"
+ " Windows: winget install JGraph.Draw"
+ )
+
+
+def get_drawio_version() -> str:
+ """Get the installed draw.io version string."""
+ drawio = find_drawio()
+ try:
+ result = subprocess.run(
+ [drawio, "--version"],
+ capture_output=True, text=True, timeout=15,
+ )
+ output = result.stdout.strip() or result.stderr.strip()
+ return output.split("\n")[0] if output else "unknown"
+ except (subprocess.TimeoutExpired, OSError):
+ return "unknown"
+
+
+def export_diagram(
+ drawio_path: str,
+ output_path: str,
+ fmt: str = "png",
+ page_index: Optional[int] = None,
+ scale: Optional[float] = None,
+ width: Optional[int] = None,
+ height: Optional[int] = None,
+ border: int = 0,
+ transparent: bool = False,
+ crop: bool = False,
+ overwrite: bool = False,
+ timeout: int = 60,
+) -> dict:
+ """Export a .drawio file to PNG, PDF, SVG, or VSDX.
+
+ Args:
+ drawio_path: Path to the .drawio XML file.
+ output_path: Output file path.
+ fmt: Output format: png, pdf, svg, vsdx, xml.
+ page_index: Page index to export (default: all pages).
+ scale: Scale factor (e.g. 2.0 for 2x resolution).
+ width: Output width in pixels (PNG only).
+ height: Output height in pixels (PNG only).
+ border: Border padding in pixels.
+ transparent: Transparent background (PNG only).
+ crop: Crop to diagram content.
+ overwrite: Allow overwriting existing output.
+ timeout: Maximum seconds.
+
+ Returns:
+ Dict with output path, format, file size, method.
+ """
+ if not os.path.exists(drawio_path):
+ raise FileNotFoundError(f"Draw.io file not found: {drawio_path}")
+
+ if os.path.exists(output_path) and not overwrite:
+ raise FileExistsError(f"Output file exists: {output_path}")
+
+ drawio = find_drawio()
+ os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
+
+ cmd = [
+ drawio,
+ "--export", drawio_path,
+ "--output", output_path,
+ "--format", fmt,
+ ]
+
+ if page_index is not None:
+ cmd.extend(["--page-index", str(page_index)])
+ if scale is not None:
+ cmd.extend(["--scale", str(scale)])
+ if width is not None:
+ cmd.extend(["--width", str(width)])
+ if height is not None:
+ cmd.extend(["--height", str(height)])
+ if border > 0:
+ cmd.extend(["--border", str(border)])
+ if transparent:
+ cmd.append("--transparent")
+ if crop:
+ cmd.append("--crop")
+
+ result = subprocess.run(
+ cmd,
+ capture_output=True, text=True,
+ timeout=timeout,
+ )
+
+ if result.returncode != 0:
+ raise RuntimeError(
+ f"draw.io export failed (exit {result.returncode}):\n"
+ f" stderr: {result.stderr[-500:]}"
+ )
+
+ if not os.path.exists(output_path):
+ raise RuntimeError(
+ f"draw.io produced no output file.\n"
+ f" Expected: {output_path}\n"
+ f" stdout: {result.stdout[-500:]}"
+ )
+
+ return {
+ "output": os.path.abspath(output_path),
+ "format": fmt,
+ "method": "draw.io-cli",
+ "file_size": os.path.getsize(output_path),
+ }
diff --git a/drawio/agent-harness/cli_anything/drawio/utils/drawio_xml.py b/drawio/agent-harness/cli_anything/drawio/utils/drawio_xml.py
new file mode 100644
index 000000000..dc827b607
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/utils/drawio_xml.py
@@ -0,0 +1,521 @@
+"""Draw.io XML manipulation utilities.
+
+Draw.io files (.drawio) are XML-based, using the mxGraph format.
+We manipulate them directly by parsing and modifying the XML tree.
+
+Structure:
+ <mxfile>
+ <diagram id="..." name="Page-1">
+ <mxGraphModel dx="..." dy="..." ...>
+ <root>
+ <mxCell id="0"/> ← root container
+ <mxCell id="1" parent="0"/> ← default layer
+ <mxCell id="2" value="Hello" ← shapes/edges
+ style="rounded=1;..."
+ vertex="1" parent="1">
+ <mxGeometry x="10" y="20"
+ width="120" height="60"
+ as="geometry"/>
+ </mxCell>
+ </root>
+ </mxGraphModel>
+ </diagram>
+ </mxfile>
+"""
+
+import os
+import time
+from xml.etree import ElementTree as ET
+from typing import Optional
+
+
+# ============================================================================
+# File I/O
+# ============================================================================
+
+def parse_drawio(path: str) -> ET.Element:
+ """Parse a .drawio XML file. Returns the root <mxfile> element."""
+ if not os.path.exists(path):
+ raise FileNotFoundError(f"File not found: {path}")
+ tree = ET.parse(path)
+ return tree.getroot()
+
+
+def write_drawio(root: ET.Element, path: str) -> None:
+ """Write an XML tree to a .drawio file."""
+ parent = os.path.dirname(os.path.abspath(path))
+ if parent:
+ os.makedirs(parent, exist_ok=True)
+ tree = ET.ElementTree(root)
+ ET.indent(tree, space=" ")
+ tree.write(path, xml_declaration=True, encoding="utf-8")
+
+
+def xml_to_string(root: ET.Element) -> str:
+ """Serialize an XML tree to a UTF-8 string."""
+ ET.indent(root, space=" ")
+ return ET.tostring(root, encoding="unicode")
+
+
+# ============================================================================
+# Create blank diagram
+# ============================================================================
+
+def create_blank_diagram(page_width: int = 850, page_height: int = 1100,
+ grid_size: int = 10) -> ET.Element:
+ """Create a new blank draw.io diagram XML.
+
+ Args:
+ page_width: Page width in pixels.
+ page_height: Page height in pixels.
+ grid_size: Grid snap size.
+
+ Returns:
+ Root <mxfile> element.
+ """
+ mxfile = ET.Element("mxfile")
+ mxfile.set("host", "cli-anything")
+ mxfile.set("agent", "cli-anything-drawio/1.0.0")
+ mxfile.set("version", "24.0.0")
+
+ diagram = ET.SubElement(mxfile, "diagram")
+ diagram.set("id", _new_id("diagram"))
+ diagram.set("name", "Page-1")
+
+ model = ET.SubElement(diagram, "mxGraphModel")
+ model.set("dx", "1200")
+ model.set("dy", "800")
+ model.set("grid", "1")
+ model.set("gridSize", str(grid_size))
+ model.set("guides", "1")
+ model.set("tooltips", "1")
+ model.set("connect", "1")
+ model.set("arrows", "1")
+ model.set("fold", "1")
+ model.set("page", "1")
+ model.set("pageScale", "1")
+ model.set("pageWidth", str(page_width))
+ model.set("pageHeight", str(page_height))
+ model.set("math", "0")
+ model.set("shadow", "0")
+
+ root = ET.SubElement(model, "root")
+
+ # Default system cells (always present)
+ cell0 = ET.SubElement(root, "mxCell")
+ cell0.set("id", "0")
+
+ cell1 = ET.SubElement(root, "mxCell")
+ cell1.set("id", "1")
+ cell1.set("parent", "0")
+
+ return mxfile
+
+
+# ============================================================================
+# Navigation helpers
+# ============================================================================
+
+def get_diagram(mxfile: ET.Element, index: int = 0) -> ET.Element:
+ """Get a <diagram> element by index."""
+ diagrams = mxfile.findall("diagram")
+ if not diagrams:
+ raise RuntimeError("No diagram found in file")
+ if index >= len(diagrams):
+ raise IndexError(f"Diagram index {index} out of range (have {len(diagrams)})")
+ return diagrams[index]
+
+
+def get_model(mxfile: ET.Element, diagram_index: int = 0) -> ET.Element:
+ """Get the <mxGraphModel> element."""
+ diagram = get_diagram(mxfile, diagram_index)
+ model = diagram.find("mxGraphModel")
+ if model is None:
+ raise RuntimeError("No mxGraphModel found in diagram")
+ return model
+
+
+def get_root(mxfile: ET.Element, diagram_index: int = 0) -> ET.Element:
+ """Get the <root> element containing all cells."""
+ model = get_model(mxfile, diagram_index)
+ root = model.find("root")
+ if root is None:
+ raise RuntimeError("No root element found in mxGraphModel")
+ return root
+
+
+# ============================================================================
+# Query operations
+# ============================================================================
+
+def get_all_cells(mxfile: ET.Element, diagram_index: int = 0) -> list[ET.Element]:
+ """Get all user mxCell elements (excluding system cells id=0 and id=1)."""
+ root = get_root(mxfile, diagram_index)
+ cells = []
+ for cell in root.findall("mxCell"):
+ cid = cell.get("id", "")
+ if cid not in ("0", "1"):
+ cells.append(cell)
+ return cells
+
+
+def get_vertices(mxfile: ET.Element, diagram_index: int = 0) -> list[ET.Element]:
+ """Get all shape (vertex) cells."""
+ return [c for c in get_all_cells(mxfile, diagram_index) if c.get("vertex") == "1"]
+
+
+def get_edges(mxfile: ET.Element, diagram_index: int = 0) -> list[ET.Element]:
+ """Get all edge (connector) cells."""
+ return [c for c in get_all_cells(mxfile, diagram_index) if c.get("edge") == "1"]
+
+
+def find_cell_by_id(mxfile: ET.Element, cell_id: str,
+ diagram_index: int = 0) -> Optional[ET.Element]:
+ """Find a cell by its ID."""
+ root = get_root(mxfile, diagram_index)
+ for cell in root.iter("mxCell"):
+ if cell.get("id") == cell_id:
+ return cell
+ return None
+
+
+def get_cell_geometry(cell: ET.Element) -> dict:
+ """Get the geometry of a cell as a dict."""
+ geo = cell.find("mxGeometry")
+ if geo is None:
+ return {}
+ return {
+ "x": float(geo.get("x", "0")),
+ "y": float(geo.get("y", "0")),
+ "width": float(geo.get("width", "0")),
+ "height": float(geo.get("height", "0")),
+ }
+
+
+def get_cell_info(cell: ET.Element) -> dict:
+ """Get summary info for a cell."""
+ info = {
+ "id": cell.get("id", ""),
+ "value": cell.get("value", ""),
+ "style": cell.get("style", ""),
+ }
+ if cell.get("vertex") == "1":
+ info["type"] = "vertex"
+ info.update(get_cell_geometry(cell))
+ elif cell.get("edge") == "1":
+ info["type"] = "edge"
+ info["source"] = cell.get("source", "")
+ info["target"] = cell.get("target", "")
+ return info
+
+
+# ============================================================================
+# Style parsing and manipulation
+# ============================================================================
+
+def parse_style(style_str: str) -> dict:
+ """Parse a draw.io style string into a dict.
+
+ Style format: "key1=value1;key2=value2;baseStyle;"
+ Keys without values are treated as base style names (value="").
+ """
+ result = {}
+ if not style_str:
+ return result
+ for part in style_str.split(";"):
+ part = part.strip()
+ if not part:
+ continue
+ if "=" in part:
+ k, v = part.split("=", 1)
+ result[k] = v
+ else:
+ result[part] = ""
+ return result
+
+
+def build_style(style_dict: dict) -> str:
+ """Build a draw.io style string from a dict."""
+ parts = []
+ for k, v in style_dict.items():
+ if v == "":
+ parts.append(k)
+ else:
+ parts.append(f"{k}={v}")
+ return ";".join(parts) + ";"
+
+
+def set_style_property(cell: ET.Element, key: str, value: str) -> None:
+ """Set a single style property on a cell."""
+ style = parse_style(cell.get("style", ""))
+ style[key] = value
+ cell.set("style", build_style(style))
+
+
+def remove_style_property(cell: ET.Element, key: str) -> None:
+ """Remove a style property from a cell."""
+ style = parse_style(cell.get("style", ""))
+ style.pop(key, None)
+ cell.set("style", build_style(style))
+
+
+# ============================================================================
+# Shape type presets
+# ============================================================================
+
+SHAPE_STYLES = {
+ "rectangle": "rounded=0;whiteSpace=wrap;html=1;",
+ "rounded": "rounded=1;whiteSpace=wrap;html=1;",
+ "ellipse": "ellipse;whiteSpace=wrap;html=1;",
+ "diamond": "rhombus;whiteSpace=wrap;html=1;",
+ "triangle": "triangle;whiteSpace=wrap;html=1;",
+ "hexagon": "shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;",
+ "cylinder": "shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=15;",
+ "cloud": "ellipse;shape=cloud;whiteSpace=wrap;html=1;",
+ "parallelogram": "shape=parallelogram;perimeter=parallelogramPerimeter;whiteSpace=wrap;html=1;",
+ "process": "shape=process;whiteSpace=wrap;html=1;backgroundOutline=1;",
+ "document": "shape=document;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=0.27;",
+ "callout": "shape=callout;whiteSpace=wrap;html=1;perimeter=calloutPerimeter;size=30;position=0.5;",
+ "note": "shape=note;whiteSpace=wrap;html=1;backgroundOutline=1;size=15;",
+ "actor": "shape=mxgraph.basic.person;whiteSpace=wrap;html=1;",
+ "text": "text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;",
+}
+
+EDGE_STYLES = {
+ "straight": "edgeStyle=none;",
+ "orthogonal": "edgeStyle=orthogonalEdgeStyle;rounded=0;",
+ "curved": "edgeStyle=orthogonalEdgeStyle;curved=1;rounded=1;",
+ "entity-relation": "edgeStyle=entityRelationEdgeStyle;",
+}
+
+
+# ============================================================================
+# Mutation operations
+# ============================================================================
+
+def _new_id(prefix: str = "cell") -> str:
+ """Generate a unique ID."""
+ return f"{prefix}_{int(time.time() * 1000000)}"
+
+
+def add_vertex(mxfile: ET.Element, shape_type: str,
+ x: float, y: float, width: float, height: float,
+ label: str = "", parent: str = "1",
+ diagram_index: int = 0) -> str:
+ """Add a shape (vertex) to the diagram.
+
+ Args:
+ mxfile: Root mxfile element.
+ shape_type: Shape preset name (see SHAPE_STYLES) or raw style string.
+ x, y: Position.
+ width, height: Dimensions.
+ label: Text label for the shape.
+ parent: Parent cell ID (default "1" = default layer).
+
+ Returns:
+ The new cell's ID.
+ """
+ root = get_root(mxfile, diagram_index)
+ cell_id = _new_id("v")
+
+ cell = ET.SubElement(root, "mxCell")
+ cell.set("id", cell_id)
+ cell.set("value", label)
+
+ # Resolve style
+ if shape_type in SHAPE_STYLES:
+ style = SHAPE_STYLES[shape_type]
+ else:
+ style = shape_type if ";" in shape_type else f"{shape_type};"
+ cell.set("style", style)
+ cell.set("vertex", "1")
+ cell.set("parent", parent)
+
+ geo = ET.SubElement(cell, "mxGeometry")
+ geo.set("x", str(x))
+ geo.set("y", str(y))
+ geo.set("width", str(width))
+ geo.set("height", str(height))
+ geo.set("as", "geometry")
+
+ return cell_id
+
+
+def add_edge(mxfile: ET.Element, source_id: str, target_id: str,
+ edge_style: str = "orthogonal", label: str = "",
+ parent: str = "1", diagram_index: int = 0) -> str:
+ """Add an edge (connector) between two cells.
+
+ Args:
+ mxfile: Root mxfile element.
+ source_id: Source cell ID.
+ target_id: Target cell ID.
+ edge_style: Edge style preset name (see EDGE_STYLES) or raw style string.
+ label: Optional edge label.
+ parent: Parent cell ID.
+
+ Returns:
+ The new edge's ID.
+ """
+ root = get_root(mxfile, diagram_index)
+ edge_id = _new_id("e")
+
+ cell = ET.SubElement(root, "mxCell")
+ cell.set("id", edge_id)
+ cell.set("value", label)
+
+ # Resolve style
+ if edge_style in EDGE_STYLES:
+ style = EDGE_STYLES[edge_style]
+ else:
+ style = edge_style if ";" in edge_style else f"{edge_style};"
+ cell.set("style", style)
+ cell.set("edge", "1")
+ cell.set("parent", parent)
+ cell.set("source", source_id)
+ cell.set("target", target_id)
+
+ geo = ET.SubElement(cell, "mxGeometry")
+ geo.set("relative", "1")
+ geo.set("as", "geometry")
+
+ return edge_id
+
+
+def remove_cell(mxfile: ET.Element, cell_id: str,
+ diagram_index: int = 0) -> bool:
+ """Remove a cell by ID. Also removes edges connected to it.
+
+ Returns True if the cell was found and removed.
+ """
+ root = get_root(mxfile, diagram_index)
+ removed = False
+
+ # First collect edges connected to this cell
+ to_remove = []
+ for cell in root.findall("mxCell"):
+ cid = cell.get("id", "")
+ if cid == cell_id:
+ to_remove.append(cell)
+ removed = True
+ elif cell.get("source") == cell_id or cell.get("target") == cell_id:
+ to_remove.append(cell)
+
+ for cell in to_remove:
+ root.remove(cell)
+
+ return removed
+
+
+def update_cell_label(mxfile: ET.Element, cell_id: str, label: str,
+ diagram_index: int = 0) -> bool:
+ """Update a cell's label. Returns True if found."""
+ cell = find_cell_by_id(mxfile, cell_id, diagram_index)
+ if cell is None:
+ return False
+ cell.set("value", label)
+ return True
+
+
+def move_cell(mxfile: ET.Element, cell_id: str, x: float, y: float,
+ diagram_index: int = 0) -> bool:
+ """Move a cell to a new position. Returns True if found."""
+ cell = find_cell_by_id(mxfile, cell_id, diagram_index)
+ if cell is None:
+ return False
+ geo = cell.find("mxGeometry")
+ if geo is None:
+ return False
+ geo.set("x", str(x))
+ geo.set("y", str(y))
+ return True
+
+
+def resize_cell(mxfile: ET.Element, cell_id: str,
+ width: float, height: float,
+ diagram_index: int = 0) -> bool:
+ """Resize a cell. Returns True if found."""
+ cell = find_cell_by_id(mxfile, cell_id, diagram_index)
+ if cell is None:
+ return False
+ geo = cell.find("mxGeometry")
+ if geo is None:
+ return False
+ geo.set("width", str(width))
+ geo.set("height", str(height))
+ return True
+
+
+# ============================================================================
+# Multi-page (diagram) operations
+# ============================================================================
+
+def add_page(mxfile: ET.Element, name: str = "",
+ page_width: int = 850, page_height: int = 1100) -> str:
+ """Add a new diagram page. Returns the diagram ID."""
+ existing = mxfile.findall("diagram")
+ index = len(existing) + 1
+ page_name = name or f"Page-{index}"
+
+ diagram_id = _new_id("diagram")
+ diagram = ET.SubElement(mxfile, "diagram")
+ diagram.set("id", diagram_id)
+ diagram.set("name", page_name)
+
+ model = ET.SubElement(diagram, "mxGraphModel")
+ model.set("dx", "1200")
+ model.set("dy", "800")
+ model.set("grid", "1")
+ model.set("gridSize", "10")
+ model.set("guides", "1")
+ model.set("tooltips", "1")
+ model.set("connect", "1")
+ model.set("arrows", "1")
+ model.set("fold", "1")
+ model.set("page", "1")
+ model.set("pageScale", "1")
+ model.set("pageWidth", str(page_width))
+ model.set("pageHeight", str(page_height))
+ model.set("math", "0")
+ model.set("shadow", "0")
+
+ root = ET.SubElement(model, "root")
+ cell0 = ET.SubElement(root, "mxCell")
+ cell0.set("id", "0")
+ cell1 = ET.SubElement(root, "mxCell")
+ cell1.set("id", "1")
+ cell1.set("parent", "0")
+
+ return diagram_id
+
+
+def list_pages(mxfile: ET.Element) -> list[dict]:
+ """List all diagram pages."""
+ pages = []
+ for i, diagram in enumerate(mxfile.findall("diagram")):
+ cell_count = len(get_all_cells(mxfile, i))
+ pages.append({
+ "index": i,
+ "id": diagram.get("id", ""),
+ "name": diagram.get("name", f"Page-{i+1}"),
+ "cell_count": cell_count,
+ })
+ return pages
+
+
+def remove_page(mxfile: ET.Element, diagram_index: int) -> bool:
+ """Remove a diagram page by index. Cannot remove the last page."""
+ diagrams = mxfile.findall("diagram")
+ if len(diagrams) <= 1:
+ raise RuntimeError("Cannot remove the last page")
+ if diagram_index >= len(diagrams):
+ raise IndexError(f"Page index {diagram_index} out of range")
+ mxfile.remove(diagrams[diagram_index])
+ return True
+
+
+def rename_page(mxfile: ET.Element, diagram_index: int, name: str) -> bool:
+ """Rename a diagram page."""
+ diagram = get_diagram(mxfile, diagram_index)
+ diagram.set("name", name)
+ return True
diff --git a/drawio/agent-harness/cli_anything/drawio/utils/repl_skin.py b/drawio/agent-harness/cli_anything/drawio/utils/repl_skin.py
new file mode 100644
index 000000000..93e2f352f
--- /dev/null
+++ b/drawio/agent-harness/cli_anything/drawio/utils/repl_skin.py
@@ -0,0 +1,500 @@
+"""cli-anything REPL Skin — Unified terminal interface for all CLI harnesses.
+
+Copy this file into your CLI package at:
+ cli_anything/<software>/utils/repl_skin.py
+
+Usage:
+ from cli_anything.<software>.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("shotcut", version="1.0.0")
+ skin.print_banner()
+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)
+ skin.success("Project saved")
+ skin.error("File not found")
+ skin.warning("Unsaved changes")
+ skin.info("Processing 24 clips...")
+ skin.status("Track 1", "3 clips, 00:02:30")
+ skin.table(headers, rows)
+ skin.print_goodbye()
+"""
+
+import os
+import sys
+
+# ── ANSI color codes (no external deps for core styling) ──────────────
+
+_RESET = "\033[0m"
+_BOLD = "\033[1m"
+_DIM = "\033[2m"
+_ITALIC = "\033[3m"
+_UNDERLINE = "\033[4m"
+
+# Brand colors
+_CYAN = "\033[38;5;80m" # cli-anything brand cyan
+_CYAN_BG = "\033[48;5;80m"
+_WHITE = "\033[97m"
+_GRAY = "\033[38;5;245m"
+_DARK_GRAY = "\033[38;5;240m"
+_LIGHT_GRAY = "\033[38;5;250m"
+
+# Software accent colors — each software gets a unique accent
+_ACCENT_COLORS = {
+ "gimp": "\033[38;5;214m", # warm orange
+ "blender": "\033[38;5;208m", # deep orange
+ "inkscape": "\033[38;5;39m", # bright blue
+ "audacity": "\033[38;5;33m", # navy blue
+ "libreoffice": "\033[38;5;40m", # green
+ "obs_studio": "\033[38;5;55m", # purple
+ "kdenlive": "\033[38;5;69m", # slate blue
+ "shotcut": "\033[38;5;35m", # teal green
+ "drawio": "\033[38;5;202m", # draw.io orange
+}
+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue
+
+# Status colors
+_GREEN = "\033[38;5;78m"
+_YELLOW = "\033[38;5;220m"
+_RED = "\033[38;5;196m"
+_BLUE = "\033[38;5;75m"
+_MAGENTA = "\033[38;5;176m"
+
+# ── Brand icon ────────────────────────────────────────────────────────
+
+# The cli-anything icon: a small colored diamond/chevron mark
+_ICON = f"{_CYAN}{_BOLD}◆{_RESET}"
+_ICON_SMALL = f"{_CYAN}▸{_RESET}"
+
+# ── Box drawing characters ────────────────────────────────────────────
+
+_H_LINE = "─"
+_V_LINE = "│"
+_TL = "╭"
+_TR = "╮"
+_BL = "╰"
+_BR = "╯"
+_T_DOWN = "┬"
+_T_UP = "┴"
+_T_RIGHT = "├"
+_T_LEFT = "┤"
+_CROSS = "┼"
+
+
+def _strip_ansi(text: str) -> str:
+ """Remove ANSI escape codes for length calculation."""
+ import re
+ return re.sub(r"\033\[[^m]*m", "", text)
+
+
+def _visible_len(text: str) -> int:
+ """Get visible length of text (excluding ANSI codes)."""
+ return len(_strip_ansi(text))
+
+
+class ReplSkin:
+ """Unified REPL skin for cli-anything CLIs.
+
+ Provides consistent branding, prompts, and message formatting
+ across all CLI harnesses built with the cli-anything methodology.
+ """
+
+ def __init__(self, software: str, version: str = "1.0.0",
+ history_file: str | None = None):
+ """Initialize the REPL skin.
+
+ Args:
+ software: Software name (e.g., "gimp", "shotcut", "blender").
+ version: CLI version string.
+ history_file: Path for persistent command history.
+ Defaults to ~/.cli-anything-<software>/history
+ """
+ self.software = software.lower().replace("-", "_")
+ self.display_name = software.replace("_", " ").title()
+ self.version = version
+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)
+
+ # History file
+ if history_file is None:
+ from pathlib import Path
+ hist_dir = Path.home() / f".cli-anything-{self.software}"
+ hist_dir.mkdir(parents=True, exist_ok=True)
+ self.history_file = str(hist_dir / "history")
+ else:
+ self.history_file = history_file
+
+ # Detect terminal capabilities
+ self._color = self._detect_color_support()
+
+ def _detect_color_support(self) -> bool:
+ """Check if terminal supports color."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):
+ return False
+ if not hasattr(sys.stdout, "isatty"):
+ return False
+ return sys.stdout.isatty()
+
+ def _c(self, code: str, text: str) -> str:
+ """Apply color code if colors are supported."""
+ if not self._color:
+ return text
+ return f"{code}{text}{_RESET}"
+
+ # ── Banner ────────────────────────────────────────────────────────
+
+ def print_banner(self):
+ """Print the startup banner with branding."""
+ inner = 54
+
+ def _box_line(content: str) -> str:
+ """Wrap content in box drawing, padding to inner width."""
+ pad = inner - _visible_len(content)
+ vl = self._c(_DARK_GRAY, _V_LINE)
+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"
+
+ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")
+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")
+
+ # Title: ◆ cli-anything · Shotcut
+ icon = self._c(_CYAN + _BOLD, "◆")
+ brand = self._c(_CYAN + _BOLD, "cli-anything")
+ dot = self._c(_DARK_GRAY, "·")
+ name = self._c(self.accent + _BOLD, self.display_name)
+ title = f" {icon} {brand} {dot} {name}"
+
+ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"
+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"
+ empty = ""
+
+ print(top)
+ print(_box_line(title))
+ print(_box_line(ver))
+ print(_box_line(empty))
+ print(_box_line(tip))
+ print(bot)
+ print()
+
+ # ── Prompt ────────────────────────────────────────────────────────
+
+ def prompt(self, project_name: str = "", modified: bool = False,
+ context: str = "") -> str:
+ """Build a styled prompt string for prompt_toolkit or input().
+
+ Args:
+ project_name: Current project name (empty if none open).
+ modified: Whether the project has unsaved changes.
+ context: Optional extra context to show in prompt.
+
+ Returns:
+ Formatted prompt string.
+ """
+ parts = []
+
+ # Icon
+ if self._color:
+ parts.append(f"{_CYAN}◆{_RESET} ")
+ else:
+ parts.append("> ")
+
+ # Software name
+ parts.append(self._c(self.accent + _BOLD, self.software))
+
+ # Project context
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ parts.append(f" {self._c(_DARK_GRAY, '[')}")
+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))
+ parts.append(self._c(_DARK_GRAY, ']'))
+
+ parts.append(self._c(_GRAY, " ❯ "))
+
+ return "".join(parts)
+
+ def prompt_tokens(self, project_name: str = "", modified: bool = False,
+ context: str = ""):
+ """Build prompt_toolkit formatted text tokens for the prompt.
+
+ Use with prompt_toolkit's FormattedText for proper ANSI handling.
+
+ Returns:
+ list of (style, text) tuples for prompt_toolkit.
+ """
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+ tokens = []
+
+ tokens.append(("class:icon", "◆ "))
+ tokens.append(("class:software", self.software))
+
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ tokens.append(("class:bracket", " ["))
+ tokens.append(("class:context", f"{ctx}{mod}"))
+ tokens.append(("class:bracket", "]"))
+
+ tokens.append(("class:arrow", " ❯ "))
+
+ return tokens
+
+ def get_prompt_style(self):
+ """Get a prompt_toolkit Style object matching the skin.
+
+ Returns:
+ prompt_toolkit.styles.Style
+ """
+ try:
+ from prompt_toolkit.styles import Style
+ except ImportError:
+ return None
+
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+
+ return Style.from_dict({
+ "icon": "#5fdfdf bold", # cyan brand color
+ "software": f"{accent_hex} bold",
+ "bracket": "#585858",
+ "context": "#bcbcbc",
+ "arrow": "#808080",
+ # Completion menu
+ "completion-menu.completion": "bg:#303030 #bcbcbc",
+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",
+ "completion-menu.meta.completion": "bg:#303030 #808080",
+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",
+ # Auto-suggest
+ "auto-suggest": "#585858",
+ # Bottom toolbar
+ "bottom-toolbar": "bg:#1c1c1c #808080",
+ "bottom-toolbar.text": "#808080",
+ })
+
+ # ── Messages ──────────────────────────────────────────────────────
+
+ def success(self, message: str):
+ """Print a success message with green checkmark."""
+ icon = self._c(_GREEN + _BOLD, "✓")
+ print(f" {icon} {self._c(_GREEN, message)}")
+
+ def error(self, message: str):
+ """Print an error message with red cross."""
+ icon = self._c(_RED + _BOLD, "✗")
+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)
+
+ def warning(self, message: str):
+ """Print a warning message with yellow triangle."""
+ icon = self._c(_YELLOW + _BOLD, "⚠")
+ print(f" {icon} {self._c(_YELLOW, message)}")
+
+ def info(self, message: str):
+ """Print an info message with blue dot."""
+ icon = self._c(_BLUE, "●")
+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")
+
+ def hint(self, message: str):
+ """Print a subtle hint message."""
+ print(f" {self._c(_DARK_GRAY, message)}")
+
+ def section(self, title: str):
+ """Print a section header."""
+ print()
+ print(f" {self._c(self.accent + _BOLD, title)}")
+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")
+
+ # ── Status display ────────────────────────────────────────────────
+
+ def status(self, label: str, value: str):
+ """Print a key-value status line."""
+ lbl = self._c(_GRAY, f" {label}:")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def status_block(self, items: dict[str, str], title: str = ""):
+ """Print a block of status key-value pairs.
+
+ Args:
+ items: Dict of label -> value pairs.
+ title: Optional title for the block.
+ """
+ if title:
+ self.section(title)
+
+ max_key = max(len(k) for k in items) if items else 0
+ for label, value in items.items():
+ lbl = self._c(_GRAY, f" {label:<{max_key}}")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def progress(self, current: int, total: int, label: str = ""):
+ """Print a simple progress indicator.
+
+ Args:
+ current: Current step number.
+ total: Total number of steps.
+ label: Optional label for the progress.
+ """
+ pct = int(current / total * 100) if total > 0 else 0
+ bar_width = 20
+ filled = int(bar_width * current / total) if total > 0 else 0
+ bar = "█" * filled + "░" * (bar_width - filled)
+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"
+ if label:
+ text += f" {self._c(_LIGHT_GRAY, label)}"
+ print(text)
+
+ # ── Table display ─────────────────────────────────────────────────
+
+ def table(self, headers: list[str], rows: list[list[str]],
+ max_col_width: int = 40):
+ """Print a formatted table with box-drawing characters.
+
+ Args:
+ headers: Column header strings.
+ rows: List of rows, each a list of cell strings.
+ max_col_width: Maximum column width before truncation.
+ """
+ if not headers:
+ return
+
+ # Calculate column widths
+ col_widths = [min(len(h), max_col_width) for h in headers]
+ for row in rows:
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = min(
+ max(col_widths[i], len(str(cell))), max_col_width
+ )
+
+ def pad(text: str, width: int) -> str:
+ t = str(text)[:width]
+ return t + " " * (width - len(t))
+
+ # Header
+ header_cells = [
+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))
+ for i, h in enumerate(headers)
+ ]
+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ header_line = f" {sep.join(header_cells)}"
+ print(header_line)
+
+ # Separator
+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]
+ sep_line = self._c(_DARK_GRAY, f" {'───'.join([_H_LINE * w for w in col_widths])}")
+ print(sep_line)
+
+ # Rows
+ for row in rows:
+ cells = []
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))
+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ print(f" {row_sep.join(cells)}")
+
+ # ── Help display ──────────────────────────────────────────────────
+
+ def help(self, commands: dict[str, str]):
+ """Print a formatted help listing.
+
+ Args:
+ commands: Dict of command -> description pairs.
+ """
+ self.section("Commands")
+ max_cmd = max(len(c) for c in commands) if commands else 0
+ for cmd, desc in commands.items():
+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")
+ desc_styled = self._c(_GRAY, f" {desc}")
+ print(f"{cmd_styled}{desc_styled}")
+ print()
+
+ # ── Goodbye ───────────────────────────────────────────────────────
+
+ def print_goodbye(self):
+ """Print a styled goodbye message."""
+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")
+
+ # ── Prompt toolkit session factory ────────────────────────────────
+
+ def create_prompt_session(self):
+ """Create a prompt_toolkit PromptSession with skin styling.
+
+ Returns:
+ A configured PromptSession, or None if prompt_toolkit unavailable.
+ """
+ try:
+ from prompt_toolkit import PromptSession
+ from prompt_toolkit.history import FileHistory
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
+ from prompt_toolkit.formatted_text import FormattedText
+
+ style = self.get_prompt_style()
+
+ session = PromptSession(
+ history=FileHistory(self.history_file),
+ auto_suggest=AutoSuggestFromHistory(),
+ style=style,
+ enable_history_search=True,
+ )
+ return session
+ except ImportError:
+ return None
+
+ def get_input(self, pt_session, project_name: str = "",
+ modified: bool = False, context: str = "") -> str:
+ """Get input from user using prompt_toolkit or fallback.
+
+ Args:
+ pt_session: A prompt_toolkit PromptSession (or None).
+ project_name: Current project name.
+ modified: Whether project has unsaved changes.
+ context: Optional context string.
+
+ Returns:
+ User input string (stripped).
+ """
+ if pt_session is not None:
+ from prompt_toolkit.formatted_text import FormattedText
+ tokens = self.prompt_tokens(project_name, modified, context)
+ return pt_session.prompt(FormattedText(tokens)).strip()
+ else:
+ raw_prompt = self.prompt(project_name, modified, context)
+ return input(raw_prompt).strip()
+
+ # ── Toolbar builder ───────────────────────────────────────────────
+
+ def bottom_toolbar(self, items: dict[str, str]):
+ """Create a bottom toolbar callback for prompt_toolkit.
+
+ Args:
+ items: Dict of label -> value pairs to show in toolbar.
+
+ Returns:
+ A callable that returns FormattedText for the toolbar.
+ """
+ def toolbar():
+ from prompt_toolkit.formatted_text import FormattedText
+ parts = []
+ for i, (k, v) in enumerate(items.items()):
+ if i > 0:
+ parts.append(("class:bottom-toolbar.text", " │ "))
+ parts.append(("class:bottom-toolbar.text", f" {k}: "))
+ parts.append(("class:bottom-toolbar", v))
+ return FormattedText(parts)
+ return toolbar
+
+
+# ── ANSI 256-color to hex mapping (for prompt_toolkit styles) ─────────
+
+_ANSI_256_TO_HEX = {
+ "\033[38;5;33m": "#0087ff", # audacity navy blue
+ "\033[38;5;35m": "#00af5f", # shotcut teal
+ "\033[38;5;39m": "#00afff", # inkscape bright blue
+ "\033[38;5;40m": "#00d700", # libreoffice green
+ "\033[38;5;55m": "#5f00af", # obs purple
+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue
+ "\033[38;5;75m": "#5fafff", # default sky blue
+ "\033[38;5;80m": "#5fd7d7", # brand cyan
+ "\033[38;5;208m": "#ff8700", # blender deep orange
+ "\033[38;5;202m": "#ff5f00", # drawio orange
+ "\033[38;5;214m": "#ffaf00", # gimp warm orange
+}
diff --git a/drawio/agent-harness/setup.py b/drawio/agent-harness/setup.py
new file mode 100644
index 000000000..ad158910a
--- /dev/null
+++ b/drawio/agent-harness/setup.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+"""
+setup.py for cli-anything-drawio
+
+Install with: pip install -e .
+Or publish to PyPI: python -m build && twine upload dist/*
+"""
+
+from setuptools import setup, find_namespace_packages
+
+with open("cli_anything/drawio/README.md", "r", encoding="utf-8") as fh:
+ long_description = fh.read()
+
+setup(
+ name="cli-anything-drawio",
+ version="1.0.0",
+ author="cli-anything contributors",
+ author_email="",
+ description="CLI harness for Draw.io - Diagram creation and export via draw.io CLI. Requires: draw.io desktop app (draw.io --export)",
+ long_description=long_description,
+ long_description_content_type="text/markdown",
+ url="https://github.com/anthropics/cli-anything",
+ packages=find_namespace_packages(include=["cli_anything.*"]),
+ classifiers=[
+ "Development Status :: 4 - Beta",
+ "Intended Audience :: Developers",
+ "Topic :: Software Development :: Libraries :: Python Modules",
+ "Topic :: Office/Business :: Office Suites",
+ "License :: OSI Approved :: MIT License",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ ],
+ python_requires=">=3.10",
+ install_requires=[
+ "click>=8.0.0",
+ "prompt-toolkit>=3.0.0",
+ ],
+ extras_require={
+ "dev": [
+ "pytest>=7.0.0",
+ "pytest-cov>=4.0.0",
+ ],
+ },
+ entry_points={
+ "console_scripts": [
+ "cli-anything-drawio=cli_anything.drawio.drawio_cli:cli",
+ ],
+ },
+ include_package_data=True,
+ zip_safe=False,
+)