Skip to content

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

Python

feat(preview): add live preview protocol and motion demos

yuhao9b85f07fc928
diff --git a/.gitignore b/.gitignore
index 47ca0e880..d954fd069 100644
--- a/.gitignore
+++ b/.gitignore
@@ -269,6 +269,11 @@ assets/gen_typing_gif.py
!/matrix_registry.json
!/docs/
/docs/*
+!/docs/PREVIEW_PROTOCOL.md
+!/docs/PREVIEW_PROGRESS.md
+!/docs/FREECAD_VIDEO_REFERENCE.md
+!/docs/scripts/
+!/docs/scripts/**
!/docs/hub/
/docs/hub/registry-dates.json
!/notebooklm/
diff --git a/blender/agent-harness/cli_anything/blender/blender_cli.py b/blender/agent-harness/cli_anything/blender/blender_cli.py
index bea340bc0..4816d4f60 100644
--- a/blender/agent-harness/cli_anything/blender/blender_cli.py
+++ b/blender/agent-harness/cli_anything/blender/blender_cli.py
@@ -32,6 +32,7 @@ from cli_anything.blender.core import modifiers as mod_mod
from cli_anything.blender.core import lighting as light_mod
from cli_anything.blender.core import animation as anim_mod
from cli_anything.blender.core import render as render_mod
+from cli_anything.blender.core import preview as preview_mod
# Global session state
_session: Optional[Session] = None
@@ -813,6 +814,50 @@ def render_script(output_path, frame, animation):
click.echo(script)
+def preview_group():
+ """Preview bundle capture and inspection."""
+ pass
+
+
+@preview_group.command("recipes")
+@handle_error
+def preview_recipes():
+ """List available preview recipes."""
+ output(preview_mod.list_recipes(), "Preview recipes:")
+
+
+@preview_group.command("capture")
[email protected]("--recipe", default="quick", help="Preview recipe name")
[email protected]("--force", is_flag=True, help="Bypass preview cache")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory")
+@handle_error
+def preview_capture(recipe, force, root_dir):
+ """Capture a preview bundle for the active scene."""
+ sess = get_session()
+ result = preview_mod.capture(
+ sess,
+ recipe=recipe,
+ force=force,
+ root_dir=root_dir,
+ command=f"cli-anything-blender --project {sess.project_path or ''} preview capture --recipe {recipe}".strip(),
+ )
+ bundle_dir = result.get("_bundle_dir", result.get("bundle_dir", ""))
+ status = "Reused preview bundle" if result.get("cached") else "Created preview bundle"
+ output(result, f"{status}: {bundle_dir}")
+
+
+@preview_group.command("latest")
[email protected]("--recipe", default=None, help="Filter by recipe name")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory")
+@handle_error
+def preview_latest(recipe, root_dir):
+ """Show the latest preview bundle manifest."""
+ sess = get_session()
+ result = preview_mod.latest(project_path=sess.project_path, recipe=recipe, root_dir=root_dir)
+ output(result, f"Latest preview bundle: {result.get('_bundle_dir', '')}")
+
+
# ── Session Commands ────────────────────────────────────────────
@cli.group()
def session():
@@ -886,6 +931,7 @@ def repl(project_path):
"light": "add|set|list",
"animation": "keyframe|remove-keyframe|frame-range|fps|list-keyframes",
"render": "settings|info|presets|execute|script",
+ "preview": "recipes|capture|latest",
"session": "status|undo|redo|history",
"help": "show this help",
"quit": "exit REPL",
diff --git a/blender/agent-harness/cli_anything/blender/core/preview.py b/blender/agent-harness/cli_anything/blender/core/preview.py
new file mode 100644
index 000000000..0048f1259
--- /dev/null
+++ b/blender/agent-harness/cli_anything/blender/core/preview.py
@@ -0,0 +1,284 @@
+"""Preview bundle generation for the Blender harness."""
+
+from __future__ import annotations
+
+import copy
+import os
+from typing import Any, Dict, List, Optional, Tuple
+
+from ..utils import blender_backend
+from ..utils.preview_bundle import (
+ artifact_record,
+ finalize_bundle,
+ find_latest_manifest,
+ fingerprint_data,
+ prepare_bundle,
+)
+from . import render as render_mod
+from .lighting import add_camera, add_light
+from .session import Session
+
+HARNESS_VERSION = "1.0.0"
+
+RECIPES: Dict[str, Dict[str, Any]] = {
+ "quick": {
+ "description": "Two still renders for fast scene review",
+ "primary_preset": "eevee_preview",
+ "secondary_preset": "workbench",
+ "secondary_resolution_percentage": 50,
+ "timeout": 300,
+ },
+}
+
+
+def list_recipes() -> List[Dict[str, Any]]:
+ """Return available preview recipes."""
+ return [
+ {
+ "name": name,
+ "description": config["description"],
+ "bundle_kind": "capture",
+ "artifacts": ["hero", "gallery"],
+ "presets": [config["primary_preset"], config["secondary_preset"]],
+ }
+ for name, config in RECIPES.items()
+ ]
+
+
+def _project_fingerprint(session: Session) -> str:
+ project = session.get_project()
+ return fingerprint_data(
+ {
+ "project_path": session.project_path,
+ "project": project,
+ }
+ )
+
+
+def _ensure_preview_rig(project: Dict[str, Any]) -> List[str]:
+ warnings: List[str] = []
+ cameras = project.setdefault("cameras", [])
+ if not cameras:
+ add_camera(
+ project,
+ name="PreviewCamera",
+ location=[6.5, -6.5, 4.75],
+ rotation=[63.0, 0.0, 46.0],
+ focal_length=45.0,
+ set_active=True,
+ )
+ warnings.append("No camera found; injected PreviewCamera for bundle capture.")
+ elif not any(camera.get("is_active") for camera in cameras):
+ cameras[0]["is_active"] = True
+ warnings.append(f"No active camera set; using {cameras[0]['name']} as the preview camera.")
+
+ lights = project.setdefault("lights", [])
+ if not lights:
+ add_light(
+ project,
+ light_type="SUN",
+ name="PreviewSun",
+ rotation=[42.0, 0.0, 32.0],
+ power=2.2,
+ )
+ warnings.append("No light found; injected PreviewSun for preview legibility.")
+
+ return warnings
+
+
+def _render_image(
+ project: Dict[str, Any],
+ output_path: str,
+ *,
+ preset: str,
+ frame: int,
+ timeout: int,
+ resolution_percentage: Optional[int] = None,
+) -> Tuple[Dict[str, Any], Dict[str, Any]]:
+ render_project = copy.deepcopy(project)
+ kwargs: Dict[str, Any] = {
+ "preset": preset,
+ "output_format": "PNG",
+ "film_transparent": False,
+ }
+ if resolution_percentage is not None:
+ kwargs["resolution_percentage"] = resolution_percentage
+ render_mod.set_render_settings(render_project, **kwargs)
+ script = render_mod.generate_bpy_script(render_project, output_path, frame=frame, animation=False)
+ backend_result = blender_backend.render_scene_headless(script, output_path, timeout=timeout)
+ settings = render_mod.get_render_settings(render_project)
+ return backend_result, settings
+
+
+def capture(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ command: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Render a preview bundle for the active Blender project."""
+ if not session.has_project():
+ raise RuntimeError("No scene loaded. Use 'scene new' or 'scene open' first.")
+ if recipe not in RECIPES:
+ raise ValueError(
+ f"Unknown preview recipe: {recipe!r}. Available: {', '.join(sorted(RECIPES))}"
+ )
+
+ config = RECIPES[recipe]
+ source_fingerprint = _project_fingerprint(session)
+ prepared = prepare_bundle(
+ software="blender",
+ recipe=recipe,
+ bundle_kind="capture",
+ source_fingerprint=source_fingerprint,
+ options=config,
+ harness_version=HARNESS_VERSION,
+ project_path=session.project_path,
+ root_dir=root_dir,
+ force=force,
+ )
+ if prepared["cached"]:
+ manifest = dict(prepared["manifest"])
+ manifest["cached"] = True
+ return manifest
+
+ project = copy.deepcopy(session.get_project())
+ warnings = _ensure_preview_rig(project)
+ bundle_dir = prepared["bundle_dir"]
+ artifacts_dir = prepared["artifacts_dir"]
+ frame = int(project.get("scene", {}).get("frame_current", 1) or 1)
+
+ hero_path = os.path.join(artifacts_dir, "hero.png")
+ hero_result, hero_settings = _render_image(
+ project,
+ hero_path,
+ preset=config["primary_preset"],
+ frame=frame,
+ timeout=config["timeout"],
+ )
+
+ alt_path = os.path.join(artifacts_dir, "workbench.png")
+ alt_result, alt_settings = _render_image(
+ project,
+ alt_path,
+ preset=config["secondary_preset"],
+ frame=frame,
+ timeout=config["timeout"],
+ resolution_percentage=config["secondary_resolution_percentage"],
+ )
+
+ def _size(settings: Dict[str, Any]) -> Tuple[int, int]:
+ effective = settings.get("effective_resolution", "0x0").split("x", 1)
+ try:
+ return int(effective[0]), int(effective[1])
+ except (ValueError, IndexError):
+ return 0, 0
+
+ hero_w, hero_h = _size(hero_settings)
+ alt_w, alt_h = _size(alt_settings)
+
+ artifacts = [
+ artifact_record(
+ bundle_dir,
+ hero_result["output"],
+ artifact_id="hero",
+ role="hero",
+ kind="image",
+ label="Eevee preview",
+ width=hero_w or None,
+ height=hero_h or None,
+ preset=config["primary_preset"],
+ blender_method=hero_result.get("method"),
+ ),
+ artifact_record(
+ bundle_dir,
+ alt_result["output"],
+ artifact_id="workbench",
+ role="gallery",
+ kind="image",
+ label="Workbench structure view",
+ width=alt_w or None,
+ height=alt_h or None,
+ preset=config["secondary_preset"],
+ blender_method=alt_result.get("method"),
+ ),
+ ]
+
+ scene = project.get("scene", {})
+ metrics = {
+ "object_count": len(project.get("objects", [])),
+ "material_count": len(project.get("materials", [])),
+ "camera_count": len(project.get("cameras", [])),
+ "light_count": len(project.get("lights", [])),
+ "frame_current": frame,
+ }
+ summary = {
+ "headline": f"Blender {recipe} preview rendered for frame {frame}",
+ "facts": {
+ "recipe": recipe,
+ "scene_name": project.get("name", "untitled"),
+ "frame": frame,
+ "hero_resolution": hero_settings.get("effective_resolution"),
+ "workbench_resolution": alt_settings.get("effective_resolution"),
+ **metrics,
+ },
+ "warnings": warnings,
+ "next_actions": [
+ "Inspect hero.png for shading, materials, and framing.",
+ "Inspect workbench.png for silhouette and structural problems.",
+ ],
+ }
+
+ manifest = finalize_bundle(
+ bundle_dir=bundle_dir,
+ bundle_id=prepared["bundle_id"],
+ bundle_kind="capture",
+ software="blender",
+ recipe=recipe,
+ source={
+ "project_path": session.project_path,
+ "project_name": os.path.basename(session.project_path) if session.project_path else project.get("name"),
+ "project_fingerprint": source_fingerprint,
+ },
+ artifacts=artifacts,
+ summary=summary,
+ cache_key=prepared["cache_key"],
+ generator={
+ "entry_point": "cli-anything-blender",
+ "harness_version": HARNESS_VERSION,
+ "command": command or f"cli-anything-blender preview capture --recipe {recipe}",
+ },
+ status="partial" if warnings else "ok",
+ warnings=warnings or None,
+ context={
+ "frame_range": f"{scene.get('frame_start', 1)}-{scene.get('frame_end', 250)}",
+ "fps": scene.get("fps", 24),
+ "primary_preset": config["primary_preset"],
+ "secondary_preset": config["secondary_preset"],
+ },
+ metrics=metrics,
+ labels=["3d", "scene", "preview"],
+ )
+ manifest["cached"] = False
+ return manifest
+
+
+def latest(
+ *,
+ project_path: Optional[str] = None,
+ recipe: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Return the latest preview bundle manifest for Blender."""
+ manifest = find_latest_manifest(
+ software="blender",
+ recipe=recipe,
+ bundle_kind="capture",
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if manifest is None:
+ raise FileNotFoundError("No Blender preview bundle found")
+ return manifest
diff --git a/blender/agent-harness/cli_anything/blender/tests/test_core.py b/blender/agent-harness/cli_anything/blender/tests/test_core.py
index 102b2cd98..e689c12f5 100644
--- a/blender/agent-harness/cli_anything/blender/tests/test_core.py
+++ b/blender/agent-harness/cli_anything/blender/tests/test_core.py
@@ -7,6 +7,7 @@ import json
import os
import sys
import tempfile
+from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -37,6 +38,8 @@ from cli_anything.blender.core.render import (
set_render_settings, get_render_settings, list_render_presets,
render_scene, RENDER_PRESETS, VALID_ENGINES,
)
+from cli_anything.blender.core import preview as preview_mod
+from cli_anything.blender.utils import blender_backend
from cli_anything.blender.core.session import Session
@@ -1033,3 +1036,51 @@ class TestSession:
sess.undo()
assert len(sess.get_project()["objects"][0]["modifiers"]) == 0
+
+
+class TestPreview:
+ def test_list_recipes(self):
+ recipes = preview_mod.list_recipes()
+ assert recipes
+ assert recipes[0]["name"] == "quick"
+
+ def test_capture_bundle(self, tmp_path, monkeypatch):
+ sess = Session()
+ proj = create_scene(name="PreviewScene")
+ sess.set_project(proj, str(tmp_path / "scene.json"))
+
+ call_count = {"value": 0}
+
+ def fake_render(script_content, output_path, timeout=300):
+ call_count["value"] += 1
+ Path(output_path).write_bytes(b"\x89PNG\r\n\x1a\npreview")
+ return {
+ "output": output_path,
+ "method": "blender-headless",
+ "file_size": os.path.getsize(output_path),
+ }
+
+ monkeypatch.setattr(blender_backend, "render_scene_headless", fake_render)
+
+ manifest = preview_mod.capture(sess, root_dir=str(tmp_path))
+ assert manifest["software"] == "blender"
+ assert manifest["recipe"] == "quick"
+ assert manifest["status"] == "partial"
+ assert call_count["value"] == 2
+ assert any(item["role"] == "hero" for item in manifest["artifacts"])
+ assert any(item["artifact_id"] == "workbench" for item in manifest["artifacts"])
+
+ def test_latest_bundle(self, tmp_path, monkeypatch):
+ sess = Session()
+ proj = create_scene(name="PreviewScene")
+ sess.set_project(proj)
+
+ def fake_render(script_content, output_path, timeout=300):
+ Path(output_path).write_bytes(b"\x89PNG\r\n\x1a\npreview")
+ return {"output": output_path, "method": "blender-headless"}
+
+ monkeypatch.setattr(blender_backend, "render_scene_headless", fake_render)
+
+ created = preview_mod.capture(sess, root_dir=str(tmp_path))
+ latest = preview_mod.latest(root_dir=str(tmp_path))
+ assert latest["bundle_id"] == created["bundle_id"]
diff --git a/blender/agent-harness/cli_anything/blender/tests/test_full_e2e.py b/blender/agent-harness/cli_anything/blender/tests/test_full_e2e.py
index 38f781053..dec61089c 100644
--- a/blender/agent-harness/cli_anything/blender/tests/test_full_e2e.py
+++ b/blender/agent-harness/cli_anything/blender/tests/test_full_e2e.py
@@ -21,6 +21,7 @@ from cli_anything.blender.core.modifiers import add_modifier, list_modifiers
from cli_anything.blender.core.lighting import add_camera, add_light, set_camera, set_light, list_cameras, list_lights
from cli_anything.blender.core.animation import add_keyframe, set_frame_range, set_fps, list_keyframes
from cli_anything.blender.core.render import set_render_settings, render_scene, generate_bpy_script, get_render_settings
+from cli_anything.blender.core import preview as preview_mod
from cli_anything.blender.core.session import Session
from cli_anything.blender.utils.bpy_gen import generate_full_script
@@ -31,6 +32,23 @@ def tmp_dir():
yield d
+PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
+
+
+def _artifact_path(manifest, artifact_id):
+ for artifact in manifest["artifacts"]:
+ if artifact["artifact_id"] == artifact_id:
+ return os.path.join(manifest["_bundle_dir"], artifact["path"])
+ raise KeyError(f"Artifact not found: {artifact_id}")
+
+
+def _assert_png(path):
+ assert os.path.isfile(path), f"Missing PNG artifact: {path}"
+ with open(path, "rb") as fh:
+ assert fh.read(8) == PNG_MAGIC, f"Invalid PNG header: {path}"
+ assert os.path.getsize(path) > 0, f"Empty PNG artifact: {path}"
+
+
# ── Scene Lifecycle ─────────────────────────────────────────────
class TestSceneLifecycle:
@@ -571,10 +589,11 @@ def _resolve_cli(name):
class TestCLISubprocess:
CLI_BASE = _resolve_cli("cli-anything-blender")
- def _run(self, args, check=True):
+ def _run(self, args, check=True, timeout=30):
return subprocess.run(
self.CLI_BASE + args,
capture_output=True, text=True,
+ timeout=timeout,
check=check,
)
@@ -641,6 +660,94 @@ class TestCLISubprocess:
result = self._run(["scene", "open", "/nonexistent/file.json"], check=False)
assert result.returncode != 0
+ def test_cli_preview_capture(self, tmp_dir):
+ proj_path = os.path.join(tmp_dir, "preview_scene.json")
+
+ proj = create_scene(name="cli-preview", profile="preview")
+ add_object(proj, mesh_type="plane", name="Ground", scale=[4, 4, 1])
+ add_object(proj, mesh_type="cube", name="Product", location=[0, 0, 1])
+ create_material(proj, name="Clay", color=[0.82, 0.5, 0.28, 1.0], roughness=0.35)
+ assign_material(proj, 0, 1)
+ add_camera(
+ proj,
+ name="PreviewCam",
+ location=[6.5, -6.0, 4.5],
+ rotation=[63, 0, 46],
+ set_active=True,
+ )
+ add_light(proj, light_type="SUN", name="Sun", rotation=[-42, 0, 30], power=2.4)
+ save_scene(proj, proj_path)
+
+ result = self._run(
+ ["--json", "--project", proj_path, "preview", "capture", "--root-dir", tmp_dir],
+ check=False,
+ timeout=240,
+ )
+ assert result.returncode == 0, result.stderr
+ manifest = json.loads(result.stdout)
+ assert manifest["software"] == "blender"
+ hero_path = _artifact_path(manifest, "hero")
+ workbench_path = _artifact_path(manifest, "workbench")
+ _assert_png(hero_path)
+ _assert_png(workbench_path)
+
+ latest = self._run(
+ ["--json", "preview", "latest", "--recipe", "quick", "--root-dir", tmp_dir],
+ check=False,
+ timeout=60,
+ )
+ assert latest.returncode == 0, latest.stderr
+ latest_manifest = json.loads(latest.stdout)
+ assert latest_manifest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n Blender preview bundle: {manifest['_bundle_dir']}")
+ print(f" Blender preview hero: {hero_path}")
+ print(f" Blender preview workbench: {workbench_path}")
+
+
+class TestPreviewE2E:
+ def test_capture_preview_bundle(self, tmp_dir):
+ proj = create_scene(name="preview-test", profile="preview")
+ add_object(proj, mesh_type="plane", name="Ground", scale=[5, 5, 1])
+ add_object(proj, mesh_type="cube", name="Body", location=[0, 0, 1], scale=[1.2, 1.2, 1.2])
+ add_object(proj, mesh_type="sphere", name="Accent", location=[2.2, 0.3, 1.0], scale=[0.7, 0.7, 0.7])
+ create_material(proj, name="OrangeClay", color=[0.84, 0.45, 0.19, 1.0], roughness=0.32)
+ create_material(proj, name="BlueAccent", color=[0.18, 0.42, 0.82, 1.0], metallic=0.1, roughness=0.25)
+ assign_material(proj, 0, 1)
+ assign_material(proj, 1, 2)
+ add_camera(
+ proj,
+ name="MainCam",
+ location=[7, -6, 5],
+ rotation=[63, 0, 46],
+ focal_length=50,
+ set_active=True,
+ )
+ add_light(proj, light_type="SUN", name="KeySun", rotation=[-45, 0, 30], power=2.3)
+
+ proj_path = os.path.join(tmp_dir, "preview_scene.json")
+ save_scene(proj, proj_path)
+
+ sess = Session()
+ sess.set_project(proj, path=proj_path)
+
+ manifest = preview_mod.capture(sess, root_dir=tmp_dir, force=True)
+ assert manifest["software"] == "blender"
+ assert manifest["bundle_kind"] == "capture"
+ assert manifest["status"] in ("ok", "partial")
+
+ hero_path = _artifact_path(manifest, "hero")
+ workbench_path = _artifact_path(manifest, "workbench")
+ _assert_png(hero_path)
+ _assert_png(workbench_path)
+
+ latest = preview_mod.latest(project_path=proj_path, recipe="quick", root_dir=tmp_dir)
+ assert latest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n Blender preview bundle: {manifest['_bundle_dir']}")
+ print(f" Blender preview hero: {hero_path}")
+ print(f" Blender preview workbench: {workbench_path}")
+
# ── Script Validity Tests ───────────────────────────────────────
diff --git a/blender/agent-harness/cli_anything/blender/utils/preview_bundle.py b/blender/agent-harness/cli_anything/blender/utils/preview_bundle.py
new file mode 100644
index 000000000..3cba5dbf0
--- /dev/null
+++ b/blender/agent-harness/cli_anything/blender/utils/preview_bundle.py
@@ -0,0 +1,304 @@
+"""Shared helpers for CLI-Anything preview bundles."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import mimetypes
+import os
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, Iterable, Optional
+
+PROTOCOL_VERSION = "preview-bundle/v1"
+
+
+def _slug(value: str) -> str:
+ text = (value or "preview").strip().lower()
+ text = re.sub(r"[^a-z0-9]+", "-", text)
+ text = re.sub(r"-{2,}", "-", text).strip("-")
+ return text or "preview"
+
+
+def _json_dumps(data: Any) -> str:
+ return json.dumps(
+ data,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ )
+
+
+def hash_data(data: Any) -> str:
+ return hashlib.sha256(_json_dumps(data).encode("utf-8")).hexdigest()
+
+
+def fingerprint_data(data: Any) -> str:
+ return f"sha256:{hash_data(data)}"
+
+
+def fingerprint_file(path: str) -> str:
+ resolved = os.path.abspath(path)
+ stat = os.stat(resolved)
+ return fingerprint_data(
+ {
+ "path": resolved,
+ "size": stat.st_size,
+ "mtime_ns": stat.st_mtime_ns,
+ }
+ )
+
+
+def bundle_root(
+ software: str,
+ recipe: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Path:
+ if root_dir:
+ base = Path(root_dir).expanduser().resolve()
+ elif project_path:
+ base = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews"
+ else:
+ base = Path.home() / ".cli-anything" / "previews"
+ return base / _slug(software) / _slug(recipe)
+
+
+def build_cache_key(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ protocol_version: str = PROTOCOL_VERSION,
+) -> str:
+ return fingerprint_data(
+ {
+ "protocol_version": protocol_version,
+ "software": software,
+ "recipe": recipe,
+ "bundle_kind": bundle_kind,
+ "source_fingerprint": source_fingerprint,
+ "options": options or {},
+ "harness_version": harness_version or "",
+ }
+ )
+
+
+def _iter_manifests(search_root: Path) -> Iterable[Path]:
+ if not search_root.exists():
+ return []
+ return sorted(search_root.rglob("manifest.json"), reverse=True)
+
+
+def _load_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def find_cached_manifest(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ cache_key: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ root = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir)
+ for manifest_path in _iter_manifests(root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if (
+ manifest.get("protocol_version") == PROTOCOL_VERSION
+ and manifest.get("software") == software
+ and manifest.get("recipe") == recipe
+ and manifest.get("bundle_kind") == bundle_kind
+ and manifest.get("status") in {"ok", "partial"}
+ and manifest.get("cache_key") == cache_key
+ ):
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def find_latest_manifest(
+ software: str,
+ recipe: Optional[str] = None,
+ bundle_kind: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ if root_dir:
+ search_root = Path(root_dir).expanduser().resolve() / _slug(software)
+ elif project_path:
+ search_root = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews" / _slug(software)
+ else:
+ search_root = Path.home() / ".cli-anything" / "previews" / _slug(software)
+ if recipe:
+ search_root = search_root / _slug(recipe)
+ for manifest_path in _iter_manifests(search_root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if manifest.get("software") != software:
+ continue
+ if recipe and manifest.get("recipe") != recipe:
+ continue
+ if bundle_kind and manifest.get("bundle_kind") != bundle_kind:
+ continue
+ if manifest.get("status") not in {"ok", "partial"}:
+ continue
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def prepare_bundle(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+) -> Dict[str, Any]:
+ cache_key = build_cache_key(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ source_fingerprint=source_fingerprint,
+ options=options or {},
+ harness_version=harness_version,
+ )
+ if not force:
+ cached = find_cached_manifest(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ cache_key=cache_key,
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if cached:
+ return {
+ "cached": True,
+ "cache_key": cache_key,
+ "bundle_id": cached.get("bundle_id"),
+ "bundle_dir": cached["_bundle_dir"],
+ "manifest_path": cached["_manifest_path"],
+ "summary_path": os.path.join(cached["_bundle_dir"], cached.get("summary_path", "summary.json")),
+ "manifest": cached,
+ }
+
+ now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ bundle_id = f"{now}_{cache_key.split(':', 1)[-1][:8]}_{_slug(recipe)}"
+ out_dir = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir) / bundle_id
+ artifacts_dir = out_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=False)
+ return {
+ "cached": False,
+ "cache_key": cache_key,
+ "bundle_id": bundle_id,
+ "bundle_dir": str(out_dir.resolve()),
+ "artifacts_dir": str(artifacts_dir.resolve()),
+ "manifest_path": str((out_dir / "manifest.json").resolve()),
+ "summary_path": str((out_dir / "summary.json").resolve()),
+ }
+
+
+def artifact_record(
+ bundle_dir: str,
+ path: str,
+ artifact_id: str,
+ role: str,
+ kind: str,
+ label: str,
+ media_type: Optional[str] = None,
+ **extra: Any,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ file_path = Path(path).resolve()
+ rel_path = file_path.relative_to(bundle_path).as_posix()
+ record: Dict[str, Any] = {
+ "artifact_id": artifact_id,
+ "role": role,
+ "kind": kind,
+ "label": label,
+ "media_type": media_type or mimetypes.guess_type(str(file_path))[0] or "application/octet-stream",
+ "path": rel_path,
+ }
+ if file_path.exists():
+ record["bytes"] = file_path.stat().st_size
+ record.update({k: v for k, v in extra.items() if v is not None})
+ return record
+
+
+def write_json(path: str, data: Any) -> str:
+ output_path = Path(path).resolve()
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(output_path, "w", encoding="utf-8") as fh:
+ json.dump(data, fh, indent=2, ensure_ascii=False, default=str)
+ fh.write("\n")
+ return str(output_path)
+
+
+def finalize_bundle(
+ bundle_dir: str,
+ bundle_id: str,
+ bundle_kind: str,
+ software: str,
+ recipe: str,
+ source: Dict[str, Any],
+ artifacts: list[Dict[str, Any]],
+ summary: Dict[str, Any],
+ cache_key: str,
+ generator: Dict[str, Any],
+ status: str = "ok",
+ warnings: Optional[list[str]] = None,
+ context: Optional[Dict[str, Any]] = None,
+ metrics: Optional[Dict[str, Any]] = None,
+ labels: Optional[list[str]] = None,
+ source_bundles: Optional[list[Dict[str, Any]]] = None,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ summary_rel = "summary.json"
+ summary_path = write_json(str(bundle_path / summary_rel), summary)
+ manifest = {
+ "protocol_version": PROTOCOL_VERSION,
+ "bundle_id": bundle_id,
+ "bundle_kind": bundle_kind,
+ "software": software,
+ "recipe": recipe,
+ "status": status,
+ "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
+ "cache_key": cache_key,
+ "generator": generator,
+ "source": source,
+ "summary_path": summary_rel,
+ "artifacts": artifacts,
+ }
+ if warnings:
+ manifest["warnings"] = warnings
+ if context:
+ manifest["context"] = context
+ if metrics:
+ manifest["metrics"] = metrics
+ if labels:
+ manifest["labels"] = labels
+ if source_bundles:
+ manifest["source_bundles"] = source_bundles
+ manifest_path = write_json(str(bundle_path / "manifest.json"), manifest)
+ manifest["_manifest_path"] = manifest_path
+ manifest["_bundle_dir"] = str(bundle_path)
+ manifest["_summary_path"] = summary_path
+ return manifest
diff --git a/cli-anything-plugin/HARNESS.md b/cli-anything-plugin/HARNESS.md
index b96751cd8..0a4f64da4 100644
--- a/cli-anything-plugin/HARNESS.md
+++ b/cli-anything-plugin/HARNESS.md
@@ -495,6 +495,16 @@ These are non-negotiable. Every harness MUST follow all of them.
- **Be idempotent where possible** — Running the same command twice should be safe.
- **Provide introspection** — `info`, `list`, `status` commands are critical for agents
to understand current state before acting.
+- **Preview meaningful intermediate state** — Harnesses that can expose useful
+ visual checkpoints SHOULD implement a `preview` command group with at least
+ `preview recipes`, `preview capture`, and `preview latest`. Diff-oriented
+ tools SHOULD also expose `preview diff`.
+- **Use the shared preview bundle protocol** — Preview-capable harnesses SHOULD
+ emit `preview-bundle/v1` bundles as described in `docs/PREVIEW_PROTOCOL.md`.
+ The bundle is the contract; the renderer remains the real software.
+- **Do not screen-scrape GUI windows for previews** — Preview artifacts must be
+ produced by the real backend or by native inspection/export paths operating
+ on real project/capture state.
- **JSON output mode** — Every command MUST support `--json` for machine parsing.
- **Use the unified REPL skin** — Copy `cli-anything-plugin/repl_skin.py` to
`utils/repl_skin.py` and use `ReplSkin` for banner, prompt, help, and messages.
diff --git a/cli-anything-plugin/preview_bundle.py b/cli-anything-plugin/preview_bundle.py
new file mode 100644
index 000000000..3cba5dbf0
--- /dev/null
+++ b/cli-anything-plugin/preview_bundle.py
@@ -0,0 +1,304 @@
+"""Shared helpers for CLI-Anything preview bundles."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import mimetypes
+import os
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, Iterable, Optional
+
+PROTOCOL_VERSION = "preview-bundle/v1"
+
+
+def _slug(value: str) -> str:
+ text = (value or "preview").strip().lower()
+ text = re.sub(r"[^a-z0-9]+", "-", text)
+ text = re.sub(r"-{2,}", "-", text).strip("-")
+ return text or "preview"
+
+
+def _json_dumps(data: Any) -> str:
+ return json.dumps(
+ data,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ )
+
+
+def hash_data(data: Any) -> str:
+ return hashlib.sha256(_json_dumps(data).encode("utf-8")).hexdigest()
+
+
+def fingerprint_data(data: Any) -> str:
+ return f"sha256:{hash_data(data)}"
+
+
+def fingerprint_file(path: str) -> str:
+ resolved = os.path.abspath(path)
+ stat = os.stat(resolved)
+ return fingerprint_data(
+ {
+ "path": resolved,
+ "size": stat.st_size,
+ "mtime_ns": stat.st_mtime_ns,
+ }
+ )
+
+
+def bundle_root(
+ software: str,
+ recipe: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Path:
+ if root_dir:
+ base = Path(root_dir).expanduser().resolve()
+ elif project_path:
+ base = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews"
+ else:
+ base = Path.home() / ".cli-anything" / "previews"
+ return base / _slug(software) / _slug(recipe)
+
+
+def build_cache_key(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ protocol_version: str = PROTOCOL_VERSION,
+) -> str:
+ return fingerprint_data(
+ {
+ "protocol_version": protocol_version,
+ "software": software,
+ "recipe": recipe,
+ "bundle_kind": bundle_kind,
+ "source_fingerprint": source_fingerprint,
+ "options": options or {},
+ "harness_version": harness_version or "",
+ }
+ )
+
+
+def _iter_manifests(search_root: Path) -> Iterable[Path]:
+ if not search_root.exists():
+ return []
+ return sorted(search_root.rglob("manifest.json"), reverse=True)
+
+
+def _load_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def find_cached_manifest(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ cache_key: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ root = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir)
+ for manifest_path in _iter_manifests(root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if (
+ manifest.get("protocol_version") == PROTOCOL_VERSION
+ and manifest.get("software") == software
+ and manifest.get("recipe") == recipe
+ and manifest.get("bundle_kind") == bundle_kind
+ and manifest.get("status") in {"ok", "partial"}
+ and manifest.get("cache_key") == cache_key
+ ):
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def find_latest_manifest(
+ software: str,
+ recipe: Optional[str] = None,
+ bundle_kind: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ if root_dir:
+ search_root = Path(root_dir).expanduser().resolve() / _slug(software)
+ elif project_path:
+ search_root = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews" / _slug(software)
+ else:
+ search_root = Path.home() / ".cli-anything" / "previews" / _slug(software)
+ if recipe:
+ search_root = search_root / _slug(recipe)
+ for manifest_path in _iter_manifests(search_root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if manifest.get("software") != software:
+ continue
+ if recipe and manifest.get("recipe") != recipe:
+ continue
+ if bundle_kind and manifest.get("bundle_kind") != bundle_kind:
+ continue
+ if manifest.get("status") not in {"ok", "partial"}:
+ continue
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def prepare_bundle(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+) -> Dict[str, Any]:
+ cache_key = build_cache_key(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ source_fingerprint=source_fingerprint,
+ options=options or {},
+ harness_version=harness_version,
+ )
+ if not force:
+ cached = find_cached_manifest(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ cache_key=cache_key,
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if cached:
+ return {
+ "cached": True,
+ "cache_key": cache_key,
+ "bundle_id": cached.get("bundle_id"),
+ "bundle_dir": cached["_bundle_dir"],
+ "manifest_path": cached["_manifest_path"],
+ "summary_path": os.path.join(cached["_bundle_dir"], cached.get("summary_path", "summary.json")),
+ "manifest": cached,
+ }
+
+ now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ bundle_id = f"{now}_{cache_key.split(':', 1)[-1][:8]}_{_slug(recipe)}"
+ out_dir = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir) / bundle_id
+ artifacts_dir = out_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=False)
+ return {
+ "cached": False,
+ "cache_key": cache_key,
+ "bundle_id": bundle_id,
+ "bundle_dir": str(out_dir.resolve()),
+ "artifacts_dir": str(artifacts_dir.resolve()),
+ "manifest_path": str((out_dir / "manifest.json").resolve()),
+ "summary_path": str((out_dir / "summary.json").resolve()),
+ }
+
+
+def artifact_record(
+ bundle_dir: str,
+ path: str,
+ artifact_id: str,
+ role: str,
+ kind: str,
+ label: str,
+ media_type: Optional[str] = None,
+ **extra: Any,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ file_path = Path(path).resolve()
+ rel_path = file_path.relative_to(bundle_path).as_posix()
+ record: Dict[str, Any] = {
+ "artifact_id": artifact_id,
+ "role": role,
+ "kind": kind,
+ "label": label,
+ "media_type": media_type or mimetypes.guess_type(str(file_path))[0] or "application/octet-stream",
+ "path": rel_path,
+ }
+ if file_path.exists():
+ record["bytes"] = file_path.stat().st_size
+ record.update({k: v for k, v in extra.items() if v is not None})
+ return record
+
+
+def write_json(path: str, data: Any) -> str:
+ output_path = Path(path).resolve()
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(output_path, "w", encoding="utf-8") as fh:
+ json.dump(data, fh, indent=2, ensure_ascii=False, default=str)
+ fh.write("\n")
+ return str(output_path)
+
+
+def finalize_bundle(
+ bundle_dir: str,
+ bundle_id: str,
+ bundle_kind: str,
+ software: str,
+ recipe: str,
+ source: Dict[str, Any],
+ artifacts: list[Dict[str, Any]],
+ summary: Dict[str, Any],
+ cache_key: str,
+ generator: Dict[str, Any],
+ status: str = "ok",
+ warnings: Optional[list[str]] = None,
+ context: Optional[Dict[str, Any]] = None,
+ metrics: Optional[Dict[str, Any]] = None,
+ labels: Optional[list[str]] = None,
+ source_bundles: Optional[list[Dict[str, Any]]] = None,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ summary_rel = "summary.json"
+ summary_path = write_json(str(bundle_path / summary_rel), summary)
+ manifest = {
+ "protocol_version": PROTOCOL_VERSION,
+ "bundle_id": bundle_id,
+ "bundle_kind": bundle_kind,
+ "software": software,
+ "recipe": recipe,
+ "status": status,
+ "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
+ "cache_key": cache_key,
+ "generator": generator,
+ "source": source,
+ "summary_path": summary_rel,
+ "artifacts": artifacts,
+ }
+ if warnings:
+ manifest["warnings"] = warnings
+ if context:
+ manifest["context"] = context
+ if metrics:
+ manifest["metrics"] = metrics
+ if labels:
+ manifest["labels"] = labels
+ if source_bundles:
+ manifest["source_bundles"] = source_bundles
+ manifest_path = write_json(str(bundle_path / "manifest.json"), manifest)
+ manifest["_manifest_path"] = manifest_path
+ manifest["_bundle_dir"] = str(bundle_path)
+ manifest["_summary_path"] = summary_path
+ return manifest
diff --git a/cli-hub/cli_hub/cli.py b/cli-hub/cli_hub/cli.py
index de922f073..78e4b9ef2 100644
--- a/cli-hub/cli_hub/cli.py
+++ b/cli-hub/cli_hub/cli.py
@@ -3,6 +3,8 @@
import os
import shutil
import sys
+import json as json_mod
+from pathlib import Path
import click
@@ -17,6 +19,18 @@ from cli_hub.analytics import (
track_uninstall,
track_visit,
)
+from cli_hub.preview import (
+ inspect_bundle,
+ inspect_session,
+ is_live_session_ref,
+ load_session,
+ open_in_browser,
+ render_html,
+ render_inspect_text,
+ render_live_html,
+ render_session_text,
+ start_static_server,
+)
def _invocation_command(ctx, version):
@@ -250,5 +264,107 @@ def launch(name, args):
os.execvp(entry, [entry] + list(args))
[email protected](name="preview", invoke_without_command=True)
+def preview(ctx):
+ """Inspect preview bundles emitted by CLI-Anything harnesses."""
+ if ctx.invoked_subcommand is None:
+ click.echo(ctx.get_help())
+
+
[email protected]("preview_ref")
[email protected]("--json", "as_json", is_flag=True, help="Output preview metadata as JSON.")
+def preview_inspect(preview_ref, as_json):
+ """Inspect a preview bundle or live session."""
+ if is_live_session_ref(preview_ref):
+ payload = inspect_session(preview_ref)
+ if as_json:
+ click.echo(json_mod.dumps(payload, indent=2))
+ return
+ click.echo(render_session_text(preview_ref), nl=False)
+ return
+ if as_json:
+ click.echo(json_mod.dumps(inspect_bundle(preview_ref), indent=2))
+ return
+ click.echo(render_inspect_text(preview_ref), nl=False)
+
+
[email protected]("preview_ref")
[email protected]("--output", "-o", "output_path", default=None, help="Output HTML path.")
[email protected]("--poll-ms", default=1500, show_default=True, help="Polling interval for live session pages.")
+def preview_html(preview_ref, output_path, poll_ms):
+ """Render HTML for a preview bundle or live session."""
+ if is_live_session_ref(preview_ref):
+ session_dir, _session = load_session(preview_ref)
+ if output_path is None:
+ output_path = os.path.join(session_dir, "live.html")
+ rendered = render_live_html(preview_ref, output_path, poll_ms=poll_ms)
+ click.echo(rendered)
+ return
+ if output_path is None:
+ payload = inspect_bundle(preview_ref)
+ output_path = os.path.join(payload["bundle_dir"], "preview.html")
+ rendered = render_html(preview_ref, output_path)
+ click.echo(rendered)
+
+
+def _serve_live_session(session_ref, poll_ms, auto_open, port):
+ session_dir, session = load_session(session_ref)
+ output_path = Path(session_dir) / "live.html"
+ render_live_html(session_ref, str(output_path), poll_ms=poll_ms)
+ server, base_url = start_static_server(str(session_dir), port=port)
+ live_url = f"{base_url}/live.html"
+ click.echo(f"Live preview URL: {live_url}")
+ if auto_open:
+ launched = open_in_browser(live_url)
+ if launched.get("launched"):
+ click.echo(f"Opened in {launched['browser']}: pid {launched['pid']}")
+ else:
+ click.echo(
+ "Browser launch unavailable. Open this manually:\n"
+ f" {live_url}\n"
+ f" Suggested command: {session.get('watch_command') or f'cli-hub preview watch {session_dir} --open'}"
+ )
+ click.echo("Press Ctrl-C to stop the live preview server.")
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ click.echo("\nStopped live preview server.")
+ finally:
+ server.server_close()
+
+
[email protected]("session_ref")
[email protected]("--poll-ms", default=1500, show_default=True, help="Polling interval for the live page.")
[email protected]("--port", default=0, show_default=True, help="Preferred localhost port. Use 0 for auto.")
[email protected]("--open/--no-open", "auto_open", default=False, help="Open a separate browser window.")
+def preview_watch(session_ref, poll_ms, port, auto_open):
+ """Serve and watch a live preview session."""
+ _serve_live_session(session_ref, poll_ms=poll_ms, auto_open=auto_open, port=port)
+
+
[email protected]("preview_ref")
[email protected]("--output", "-o", "output_path", default=None, help="Override the generated HTML path.")
[email protected]("--poll-ms", default=1500, show_default=True, help="Polling interval when opening a live session.")
[email protected]("--port", default=0, show_default=True, help="Preferred localhost port for live sessions.")
+def preview_open(preview_ref, output_path, poll_ms, port):
+ """Open a preview bundle or live session in a browser window."""
+ if is_live_session_ref(preview_ref):
+ _serve_live_session(preview_ref, poll_ms=poll_ms, auto_open=True, port=port)
+ return
+ if output_path is None:
+ payload = inspect_bundle(preview_ref)
+ output_path = os.path.join(payload["bundle_dir"], "preview.html")
+ rendered = render_html(preview_ref, output_path)
+ launched = open_in_browser(Path(rendered).resolve().as_uri())
+ click.echo(rendered)
+ if launched.get("launched"):
+ click.echo(f"Opened in {launched['browser']}: pid {launched['pid']}")
+ else:
+ click.echo(f"Open this file manually: {rendered}")
if __name__ == "__main__":
main()
diff --git a/cli-hub/cli_hub/preview.py b/cli-hub/cli_hub/preview.py
new file mode 100644
index 000000000..100fad3a6
--- /dev/null
+++ b/cli-hub/cli_hub/preview.py
@@ -0,0 +1,1045 @@
+"""Preview bundle inspection, live session rendering, and popup helpers."""
+
+from __future__ import annotations
+
+import functools
+import html
+import json
+import os
+import shutil
+import subprocess
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any, Dict, Tuple
+
+
+def _read_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def resolve_bundle_ref(bundle_ref: str) -> Tuple[Path, Path]:
+ ref = Path(bundle_ref).expanduser().resolve()
+ if ref.is_dir():
+ manifest = ref / "manifest.json"
+ if not manifest.is_file():
+ raise FileNotFoundError(f"manifest.json not found in bundle directory: {ref}")
+ return ref, manifest
+ if ref.is_file():
+ if ref.name != "manifest.json":
+ raise ValueError("Bundle ref must be a bundle directory or a manifest.json path")
+ return ref.parent, ref
+ raise FileNotFoundError(f"Bundle ref not found: {bundle_ref}")
+
+
+def resolve_session_ref(session_ref: str) -> Tuple[Path, Path]:
+ ref = Path(session_ref).expanduser().resolve()
+ if ref.is_dir():
+ session_path = ref / "session.json"
+ if not session_path.is_file():
+ raise FileNotFoundError(f"session.json not found in live session directory: {ref}")
+ return ref, session_path
+ if ref.is_file():
+ if ref.name != "session.json":
+ raise ValueError("Session ref must be a live session directory or a session.json path")
+ return ref.parent, ref
+ raise FileNotFoundError(f"Session ref not found: {session_ref}")
+
+
+def is_live_session_ref(preview_ref: str) -> bool:
+ ref = Path(preview_ref).expanduser().resolve()
+ if ref.is_dir():
+ return (ref / "session.json").is_file()
+ return ref.is_file() and ref.name == "session.json"
+
+
+def load_bundle(bundle_ref: str) -> Tuple[Path, Dict[str, Any], Dict[str, Any]]:
+ bundle_dir, manifest_path = resolve_bundle_ref(bundle_ref)
+ manifest = _read_json(manifest_path)
+ summary_rel = manifest.get("summary_path", "summary.json")
+ summary_path = (bundle_dir / summary_rel).resolve()
+ summary = _read_json(summary_path) if summary_path.is_file() else {}
+ return bundle_dir, manifest, summary
+
+
+def load_session(session_ref: str) -> Tuple[Path, Dict[str, Any]]:
+ session_dir, session_path = resolve_session_ref(session_ref)
+ return session_dir, _read_json(session_path)
+
+
+def format_bytes(size: int) -> str:
+ if size < 1024:
+ return f"{size} B"
+ if size < 1024 * 1024:
+ return f"{size / 1024:.1f} KB"
+ if size < 1024 * 1024 * 1024:
+ return f"{size / (1024 * 1024):.1f} MB"
+ return f"{size / (1024 * 1024 * 1024):.1f} GB"
+
+
+def inspect_bundle(bundle_ref: str) -> Dict[str, Any]:
+ bundle_dir, manifest, summary = load_bundle(bundle_ref)
+ return {
+ "bundle_dir": str(bundle_dir),
+ "manifest": manifest,
+ "summary": summary,
+ "artifact_count": len(manifest.get("artifacts", [])),
+ }
+
+
+def inspect_session(session_ref: str) -> Dict[str, Any]:
+ session_dir, session = load_session(session_ref)
+ current_bundle = None
+ try:
+ current_bundle = inspect_bundle(str(session_dir / session.get("current_link", "current")))
+ except (FileNotFoundError, ValueError):
+ current_bundle = None
+ return {
+ "session_dir": str(session_dir),
+ "session": session,
+ "current_bundle": current_bundle,
+ }
+
+
+def render_inspect_text(bundle_ref: str) -> str:
+ bundle_dir, manifest, summary = load_bundle(bundle_ref)
+ lines = [
+ f"Bundle: {bundle_dir}",
+ f"Protocol: {manifest.get('protocol_version', 'unknown')}",
+ f"Software: {manifest.get('software', 'unknown')}",
+ f"Recipe: {manifest.get('recipe', 'unknown')}",
+ f"Kind: {manifest.get('bundle_kind', 'unknown')}",
+ f"Status: {manifest.get('status', 'unknown')}",
+ f"Created: {manifest.get('created_at', 'unknown')}",
+ ]
+ source = manifest.get("source", {})
+ if source:
+ lines.append(
+ "Source: "
+ + (
+ source.get("project_path")
+ or source.get("capture_path")
+ or source.get("project_name")
+ or "n/a"
+ )
+ )
+ if source.get("project_fingerprint"):
+ lines.append(f"Fingerprint: {source['project_fingerprint']}")
+ elif source.get("capture_fingerprint"):
+ lines.append(f"Fingerprint: {source['capture_fingerprint']}")
+ if summary:
+ lines.append("")
+ lines.append("Summary")
+ lines.append(f" Headline: {summary.get('headline', '(none)')}")
+ facts = summary.get("facts", {})
+ for key, value in facts.items():
+ lines.append(f" {key}: {value}")
+ for warning in summary.get("warnings", []):
+ lines.append(f" Warning: {warning}")
+ lines.append("")
+ lines.append("Artifacts")
+ for artifact in manifest.get("artifacts", []):
+ desc = (
+ f" - {artifact.get('artifact_id', '?')} "
+ f"[{artifact.get('role', '?')}] {artifact.get('label', '')}"
+ )
+ desc += f" -> {artifact.get('path', '')}"
+ if artifact.get("bytes") is not None:
+ desc += f" ({format_bytes(int(artifact['bytes']))})"
+ lines.append(desc)
+ return "\n".join(lines) + "\n"
+
+
+def render_session_text(session_ref: str) -> str:
+ session_dir, session = load_session(session_ref)
+ lines = [
+ f"Live Session: {session_dir}",
+ f"Protocol: {session.get('protocol_version', 'unknown')}",
+ f"Software: {session.get('software', 'unknown')}",
+ f"Recipe: {session.get('recipe', 'unknown')}",
+ f"Status: {session.get('status', 'unknown')}",
+ f"Updated: {session.get('updated_at', 'unknown')}",
+ f"Current: {session.get('current_bundle_id', 'n/a')}",
+ f"Project: {session.get('project_path') or session.get('project_name') or 'n/a'}",
+ ]
+ if session.get("watch_command"):
+ lines.append(f"Watch: {session['watch_command']}")
+ history = session.get("history", [])
+ if history:
+ lines.append("")
+ lines.append("History")
+ for item in history:
+ lines.append(
+ f" - {item.get('bundle_id', '?')} "
+ f"[{item.get('status', 'unknown')}] {item.get('created_at', 'unknown')}"
+ )
+ return "\n".join(lines) + "\n"
+
+
+def _artifact_href(output_dir: Path, bundle_dir: Path, artifact_path: str) -> str:
+ target = (bundle_dir / artifact_path).resolve()
+ return os.path.relpath(target, output_dir)
+
+
+def _render_artifact_card(output_dir: Path, bundle_dir: Path, artifact: Dict[str, Any]) -> str:
+ role = html.escape(artifact.get("role", "artifact"))
+ label = html.escape(artifact.get("label", artifact.get("artifact_id", "artifact")))
+ path_ref = _artifact_href(output_dir, bundle_dir, artifact.get("path", ""))
+ media_type = artifact.get("media_type", "")
+ size = artifact.get("bytes")
+ meta = []
+ if artifact.get("width") and artifact.get("height"):
+ meta.append(f"{artifact['width']}×{artifact['height']}")
+ if artifact.get("duration_s") is not None:
+ meta.append(f"{artifact['duration_s']}s")
+ if size is not None:
+ meta.append(format_bytes(int(size)))
+ meta_line = " · ".join(meta)
+
+ if media_type.startswith("image/"):
+ body = f'<img src="{html.escape(path_ref)}" alt="{label}" loading="lazy">'
+ elif media_type.startswith("video/"):
+ body = (
+ f'<video controls preload="metadata" src="{html.escape(path_ref)}">'
+ "Your browser does not support embedded video."
+ "</video>"
+ )
+ else:
+ body = (
+ '<div class="artifact-file">'
+ f'<a href="{html.escape(path_ref)}">{html.escape(artifact.get("path", ""))}</a>'
+ "</div>"
+ )
+
+ badge = f'<span class="artifact-role">{role}</span>'
+ details = f'<div class="artifact-meta">{html.escape(meta_line)}</div>' if meta_line else ""
+ return (
+ '<article class="artifact-card">'
+ f"{badge}"
+ f'<h3>{label}</h3>'
+ f"{details}"
+ f"{body}"
+ "</article>"
+ )
+
+
+def render_html(bundle_ref: str, output_path: str) -> str:
+ bundle_dir, manifest, summary = load_bundle(bundle_ref)
+ output_file = Path(output_path).expanduser().resolve()
+ output_file.parent.mkdir(parents=True, exist_ok=True)
+
+ headline = html.escape(
+ summary.get("headline", f"{manifest.get('software', 'Preview')} preview bundle")
+ )
+ warnings = summary.get("warnings", [])
+ facts = summary.get("facts", {})
+ fact_cards = "".join(
+ f'<div class="fact-card"><span>{html.escape(str(key))}</span><strong>{html.escape(str(value))}</strong></div>'
+ for key, value in facts.items()
+ )
+ warning_html = "".join(f"<li>{html.escape(str(item))}</li>" for item in warnings)
+ artifact_cards = "".join(
+ _render_artifact_card(output_file.parent, bundle_dir, artifact)
+ for artifact in manifest.get("artifacts", [])
+ )
+
+ html_text = f"""<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width,initial-scale=1">
+ <title>{html.escape(manifest.get("software", "Preview"))} Preview Bundle</title>
+ <style>
+ :root {{
+ --paper: #f6f1e8;
+ --ink: #171717;
+ --muted: #5b554c;
+ --panel: rgba(255,255,255,0.68);
+ --edge: rgba(23,23,23,0.14);
+ --accent: #b23a2b;
+ --accent-soft: rgba(178,58,43,0.1);
+ --shadow: 0 20px 60px rgba(25,20,14,0.12);
+ }}
+ * {{ box-sizing: border-box; }}
+ body {{
+ margin: 0;
+ font-family: "Georgia", "Times New Roman", serif;
+ color: var(--ink);
+ background:
+ radial-gradient(circle at top left, rgba(178,58,43,0.12), transparent 28rem),
+ radial-gradient(circle at bottom right, rgba(23,23,23,0.08), transparent 30rem),
+ linear-gradient(180deg, #fbf7ef 0%, var(--paper) 100%);
+ min-height: 100vh;
+ }}
+ .shell {{
+ max-width: 1280px;
+ margin: 0 auto;
+ padding: 32px 18px 60px;
+ }}
+ .hero {{
+ border: 1px solid var(--edge);
+ background: var(--panel);
+ backdrop-filter: blur(10px);
+ box-shadow: var(--shadow);
+ border-radius: 28px;
+ overflow: hidden;
+ }}
+ .hero-top {{
+ padding: 28px 28px 18px;
+ border-bottom: 1px solid var(--edge);
+ display: grid;
+ gap: 16px;
+ background:
+ linear-gradient(135deg, rgba(178,58,43,0.12), transparent 45%),
+ linear-gradient(180deg, rgba(255,255,255,0.9), rgba(255,255,255,0.58));
+ }}
+ .kicker {{
+ text-transform: uppercase;
+ letter-spacing: 0.16em;
+ font-size: 12px;
+ color: var(--muted);
+ }}
+ h1 {{
+ margin: 0;
+ font-size: clamp(2rem, 4vw, 4rem);
+ line-height: 0.92;
+ font-weight: 600;
+ }}
+ .subtitle {{
+ color: var(--muted);
+ font-size: 1rem;
+ max-width: 60rem;
+ }}
+ .facts {{
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
+ gap: 12px;
+ }}
+ .fact-card {{
+ border: 1px solid var(--edge);
+ border-radius: 18px;
+ background: rgba(255,255,255,0.72);
+ padding: 14px 16px;
+ }}
+ .fact-card span {{
+ display: block;
+ color: var(--muted);
+ font-size: 12px;
+ text-transform: uppercase;
+ letter-spacing: 0.12em;
+ margin-bottom: 8px;
+ }}
+ .fact-card strong {{
+ font-size: 1.02rem;
+ }}
+ .warning-box {{
+ margin-top: 16px;
+ border: 1px solid rgba(178,58,43,0.28);
+ background: var(--accent-soft);
+ border-radius: 18px;
+ padding: 14px 18px;
+ }}
+ .warning-box ul {{
+ margin: 10px 0 0;
+ padding-left: 18px;
+ }}
+ .meta-grid {{
+ padding: 24px 28px 28px;
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+ gap: 12px;
+ }}
+ .meta-item {{
+ border-left: 2px solid var(--accent);
+ padding-left: 12px;
+ color: var(--muted);
+ }}
+ .meta-item strong {{
+ color: var(--ink);
+ display: block;
+ margin-top: 4px;
+ }}
+ .section {{
+ margin-top: 28px;
+ }}
+ .section h2 {{
+ margin: 0 0 14px;
+ font-size: 1.1rem;
+ text-transform: uppercase;
+ letter-spacing: 0.12em;
+ color: var(--muted);
+ }}
+ .artifact-grid {{
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
+ gap: 18px;
+ }}
+ .artifact-card {{
+ position: relative;
+ border: 1px solid var(--edge);
+ border-radius: 24px;
+ background: rgba(255,255,255,0.78);
+ padding: 16px;
+ box-shadow: 0 16px 40px rgba(33,28,22,0.08);
+ overflow: hidden;
+ }}
+ .artifact-role {{
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ border-radius: 999px;
+ background: var(--accent-soft);
+ color: var(--accent);
+ padding: 6px 10px;
+ font-size: 11px;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ margin-bottom: 10px;
+ }}
+ .artifact-card h3 {{
+ margin: 0 0 8px;
+ font-size: 1.08rem;
+ }}
+ .artifact-meta {{
+ color: var(--muted);
+ font-size: 0.9rem;
+ margin-bottom: 14px;
+ }}
+ .artifact-card img,
+ .artifact-card video {{
+ display: block;
+ width: 100%;
+ border-radius: 16px;
+ border: 1px solid var(--edge);
+ background: #ffffff;
+ }}
+ .artifact-file {{
+ border: 1px dashed var(--edge);
+ border-radius: 16px;
+ padding: 14px;
+ background: rgba(255,255,255,0.58);
+ word-break: break-word;
+ }}
+ .artifact-file a {{
+ color: var(--accent);
+ text-decoration: none;
+ }}
+ @media (max-width: 720px) {{
+ .shell {{ padding: 18px 12px 36px; }}
+ .hero-top, .meta-grid {{ padding: 20px 18px; }}
+ }}
+ </style>
+</head>
+<body>
+ <main class="shell">
+ <section class="hero">
+ <div class="hero-top">
+ <div class="kicker">CLI-Anything Preview Bundle</div>
+ <h1>{headline}</h1>
+ <div class="subtitle">Software: {html.escape(str(manifest.get("software", "unknown")))} · Recipe: {html.escape(str(manifest.get("recipe", "unknown")))} · Kind: {html.escape(str(manifest.get("bundle_kind", "capture")))}</div>
+ <div class="facts">{fact_cards or '<div class="fact-card"><span>Artifacts</span><strong>' + str(len(manifest.get("artifacts", []))) + '</strong></div>'}</div>
+ {"<div class='warning-box'><strong>Warnings</strong><ul>" + warning_html + "</ul></div>" if warning_html else ""}
+ </div>
+ <div class="meta-grid">
+ <div class="meta-item">Bundle ID<strong>{html.escape(str(manifest.get("bundle_id", "unknown")))}</strong></div>
+ <div class="meta-item">Status<strong>{html.escape(str(manifest.get("status", "unknown")))}</strong></div>
+ <div class="meta-item">Created<strong>{html.escape(str(manifest.get("created_at", "unknown")))}</strong></div>
+ <div class="meta-item">Source<strong>{html.escape(str(manifest.get("source", {}).get("project_path") or manifest.get("source", {}).get("capture_path") or "n/a"))}</strong></div>
+ </div>
+ </section>
+ <section class="section">
+ <h2>Artifacts</h2>
+ <div class="artifact-grid">{artifact_cards}</div>
+ </section>
+ </main>
+</body>
+</html>
+"""
+ with open(output_file, "w", encoding="utf-8") as fh:
+ fh.write(html_text)
+ return str(output_file)
+
+
+def render_live_html(session_ref: str, output_path: str, poll_ms: int = 1500) -> str:
+ session_dir, session = load_session(session_ref)
+ output_file = Path(output_path).expanduser().resolve()
+ output_file.parent.mkdir(parents=True, exist_ok=True)
+ headline = html.escape(
+ session.get("project_name")
+ or session.get("project_path")
+ or f"{session.get('software', 'Preview')} live preview"
+ )
+ poll_ms = max(250, int(poll_ms))
+ html_text = f"""<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width,initial-scale=1">
+ <title>{html.escape(str(session.get("software", "Preview")))} Live Preview</title>
+ <style>
+ :root {{
+ --paper: #efe8dc;
+ --ink: #111215;
+ --muted: #64615b;
+ --panel: rgba(255,255,255,0.8);
+ --panel-strong: rgba(255,255,255,0.92);
+ --edge: rgba(17,18,21,0.12);
+ --accent: #c24b2f;
+ --accent-soft: rgba(194,75,47,0.12);
+ --success: #147a4b;
+ --shadow: 0 24px 60px rgba(27,22,18,0.14);
+ --mono: "SFMono-Regular", "Menlo", "Consolas", monospace;
+ --sans: "Avenir Next", "Segoe UI", sans-serif;
+ }}
+ * {{ box-sizing: border-box; }}
+ body {{
+ margin: 0;
+ color: var(--ink);
+ font-family: var(--sans);
+ background:
+ radial-gradient(circle at top left, rgba(194,75,47,0.18), transparent 24rem),
+ radial-gradient(circle at bottom right, rgba(0,0,0,0.08), transparent 28rem),
+ linear-gradient(180deg, #f8f2e8 0%, var(--paper) 100%);
+ min-height: 100vh;
+ }}
+ .shell {{
+ max-width: 1480px;
+ margin: 0 auto;
+ padding: 22px 18px 32px;
+ }}
+ .masthead {{
+ display: grid;
+ gap: 14px;
+ padding: 20px 22px;
+ border: 1px solid var(--edge);
+ border-radius: 28px;
+ background:
+ linear-gradient(135deg, rgba(194,75,47,0.14), transparent 48%),
+ linear-gradient(180deg, rgba(255,255,255,0.94), rgba(255,255,255,0.7));
+ box-shadow: var(--shadow);
+ backdrop-filter: blur(12px);
+ }}
+ .eyebrow {{
+ text-transform: uppercase;
+ letter-spacing: 0.16em;
+ font-size: 12px;
+ color: var(--muted);
+ }}
+ .title-row {{
+ display: flex;
+ flex-wrap: wrap;
+ gap: 14px;
+ align-items: baseline;
+ justify-content: space-between;
+ }}
+ h1 {{
+ margin: 0;
+ font-family: "Iowan Old Style", "Georgia", serif;
+ font-size: clamp(2rem, 4vw, 3.75rem);
+ line-height: 0.94;
+ font-weight: 600;
+ }}
+ .status-chip {{
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ border-radius: 999px;
+ padding: 9px 14px;
+ background: rgba(20,122,75,0.12);
+ color: var(--success);
+ font-size: 12px;
+ font-weight: 700;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ }}
+ .status-chip[data-state="error"] {{
+ background: var(--accent-soft);
+ color: var(--accent);
+ }}
+ .subtitle {{
+ color: var(--muted);
+ font-size: 1rem;
+ max-width: 64rem;
+ }}
+ .fact-row {{
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
+ gap: 12px;
+ }}
+ .fact-card {{
+ border: 1px solid var(--edge);
+ border-radius: 18px;
+ background: rgba(255,255,255,0.74);
+ padding: 14px 16px;
+ }}
+ .fact-card span {{
+ display: block;
+ margin-bottom: 7px;
+ color: var(--muted);
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.14em;
+ }}
+ .fact-card strong {{
+ display: block;
+ font-size: 1rem;
+ word-break: break-word;
+ }}
+ .command-strip {{
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+ }}
+ .command-chip {{
+ border: 1px solid var(--edge);
+ border-radius: 999px;
+ padding: 10px 14px;
+ background: rgba(255,255,255,0.72);
+ font-family: var(--mono);
+ font-size: 12px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 100%;
+ }}
+ .grid {{
+ margin-top: 20px;
+ display: grid;
+ grid-template-columns: minmax(0, 1.9fr) minmax(320px, 0.9fr);
+ gap: 18px;
+ }}
+ .panel {{
+ border: 1px solid var(--edge);
+ border-radius: 28px;
+ background: var(--panel);
+ box-shadow: var(--shadow);
+ overflow: hidden;
+ min-height: 220px;
+ }}
+ .panel-header {{
+ padding: 16px 18px;
+ border-bottom: 1px solid var(--edge);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ background: var(--panel-strong);
+ }}
+ .panel-header h2 {{
+ margin: 0;
+ font-size: 0.95rem;
+ text-transform: uppercase;
+ letter-spacing: 0.14em;
+ color: var(--muted);
+ }}
+ .panel-body {{
+ padding: 18px;
+ }}
+ .hero-frame {{
+ display: block;
+ width: 100%;
+ border-radius: 20px;
+ border: 1px solid var(--edge);
+ background: #fff;
+ min-height: 280px;
+ object-fit: contain;
+ }}
+ video.hero-frame {{
+ background: #0e1013;
+ }}
+ .stack {{
+ display: grid;
+ gap: 18px;
+ }}
+ .gallery {{
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 14px;
+ }}
+ .thumb {{
+ border: 1px solid var(--edge);
+ border-radius: 20px;
+ padding: 10px;
+ background: rgba(255,255,255,0.7);
+ }}
+ .thumb img {{
+ display: block;
+ width: 100%;
+ border-radius: 14px;
+ border: 1px solid var(--edge);
+ background: #fff;
+ }}
+ .thumb .label {{
+ margin-top: 10px;
+ font-size: 0.9rem;
+ font-weight: 600;
+ }}
+ .thumb .meta {{
+ margin-top: 4px;
+ color: var(--muted);
+ font-size: 0.82rem;
+ }}
+ .notes {{
+ display: grid;
+ gap: 10px;
+ color: var(--muted);
+ font-size: 0.95rem;
+ }}
+ .notes ul {{
+ margin: 0;
+ padding-left: 18px;
+ }}
+ .history {{
+ display: grid;
+ gap: 10px;
+ }}
+ .history-item {{
+ border: 1px solid var(--edge);
+ border-radius: 16px;
+ background: rgba(255,255,255,0.72);
+ padding: 12px 14px;
+ }}
+ .history-item strong {{
+ display: block;
+ font-size: 0.92rem;
+ }}
+ .history-item span {{
+ display: block;
+ margin-top: 4px;
+ font-size: 0.82rem;
+ color: var(--muted);
+ word-break: break-word;
+ }}
+ .empty {{
+ padding: 28px;
+ border: 1px dashed var(--edge);
+ border-radius: 18px;
+ background: rgba(255,255,255,0.46);
+ color: var(--muted);
+ text-align: center;
+ }}
+ @media (max-width: 1100px) {{
+ .grid {{ grid-template-columns: 1fr; }}
+ }}
+ @media (max-width: 700px) {{
+ .shell {{ padding: 14px 10px 20px; }}
+ .masthead, .panel-body, .panel-header {{ padding-left: 14px; padding-right: 14px; }}
+ .command-chip {{ white-space: normal; }}
+ }}
+ </style>
+</head>
+<body>
+ <main class="shell">
+ <section class="masthead">
+ <div class="eyebrow">CLI-Anything Live Preview Session</div>
+ <div class="title-row">
+ <h1>{headline}</h1>
+ <div id="status-chip" class="status-chip">Watching</div>
+ </div>
+ <div id="subtitle" class="subtitle">Polling the latest preview bundle every {poll_ms} ms.</div>
+ <div id="fact-row" class="fact-row"></div>
+ <div id="command-strip" class="command-strip"></div>
+ </section>
+ <section class="grid">
+ <div class="stack">
+ <article class="panel">
+ <div class="panel-header">
+ <h2>Hero Frame</h2>
+ <span id="hero-meta" class="subtitle">Waiting for the first bundle</span>
+ </div>
+ <div class="panel-body" id="hero-slot">
+ <div class="empty">Run <code>{html.escape(session.get("publish_command", "shotcut preview live push"))}</code> to publish or refresh the session.</div>
+ </div>
+ </article>
+ <article class="panel">
+ <div class="panel-header">
+ <h2>Gallery</h2>
+ <span id="gallery-meta" class="subtitle">Sampled stills for fast visual checks</span>
+ </div>
+ <div class="panel-body">
+ <div id="gallery" class="gallery"></div>
+ </div>
+ </article>
+ </div>
+ <div class="stack">
+ <article class="panel">
+ <div class="panel-header">
+ <h2>Review Clip</h2>
+ <span id="clip-meta" class="subtitle">Low-res preview render</span>
+ </div>
+ <div class="panel-body" id="clip-slot">
+ <div class="empty">No preview clip has been published yet.</div>
+ </div>
+ </article>
+ <article class="panel">
+ <div class="panel-header">
+ <h2>Session Notes</h2>
+ <span class="subtitle">Agent-native summary + refresh state</span>
+ </div>
+ <div class="panel-body">
+ <div id="notes" class="notes"></div>
+ </div>
+ </article>
+ <article class="panel">
+ <div class="panel-header">
+ <h2>Recent Bundles</h2>
+ <span id="history-meta" class="subtitle">Latest publishes first</span>
+ </div>
+ <div class="panel-body">
+ <div id="history" class="history"></div>
+ </div>
+ </article>
+ </div>
+ </section>
+ </main>
+ <script>
+ const POLL_MS = {poll_ms};
+ const CURRENT_LINK = {json.dumps(session.get("current_link", "current"))};
+
+ function escapeHtml(value) {{
+ return String(value ?? "")
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;")
+ .replaceAll('"', "&quot;");
+ }}
+
+ async function fetchJson(path) {{
+ const sep = path.includes("?") ? "&" : "?";
+ const response = await fetch(`${{path}}${{sep}}ts=${{Date.now()}}`, {{ cache: "no-store" }});
+ if (!response.ok) {{
+ throw new Error(`Failed to load ${{path}} (${{response.status}})`);
+ }}
+ return response.json();
+ }}
+
+ function setStatus(text, isError = false) {{
+ const chip = document.getElementById("status-chip");
+ chip.textContent = text;
+ chip.dataset.state = isError ? "error" : "ok";
+ }}
+
+ function renderFacts(session, manifest, summary) {{
+ const facts = Object.assign(
+ {{
+ software: manifest.software || session.software || "unknown",
+ recipe: manifest.recipe || session.recipe || "unknown",
+ bundle: manifest.bundle_id || session.current_bundle_id || "n/a",
+ updated: session.updated_at || "unknown",
+ }},
+ summary.facts || {{}}
+ );
+ const row = document.getElementById("fact-row");
+ row.innerHTML = Object.entries(facts)
+ .slice(0, 8)
+ .map(([key, value]) => `
+ <div class="fact-card">
+ <span>${{escapeHtml(key)}}</span>
+ <strong>${{escapeHtml(value)}}</strong>
+ </div>
+ `)
+ .join("");
+ }}
+
+ function renderCommands(session) {{
+ const commands = [
+ session.publish_command,
+ session.watch_command,
+ session.inspect_command,
+ ].filter(Boolean);
+ const strip = document.getElementById("command-strip");
+ strip.innerHTML = commands.map((command) => `<div class="command-chip">${{escapeHtml(command)}}</div>`).join("");
+ }}
+
+ function artifactUrl(session, artifact) {{
+ const rev = encodeURIComponent(session.updated_at || Date.now());
+ return `${{CURRENT_LINK}}/${{artifact.path}}?rev=${{rev}}`;
+ }}
+
+ function pickArtifact(manifest, role, mediaPrefix) {{
+ return (manifest.artifacts || []).find((artifact) => artifact.role === role)
+ || (manifest.artifacts || []).find((artifact) => (artifact.media_type || "").startsWith(mediaPrefix));
+ }}
+
+ function renderHero(session, manifest) {{
+ const hero = pickArtifact(manifest, "hero", "image/");
+ const slot = document.getElementById("hero-slot");
+ const meta = document.getElementById("hero-meta");
+ if (!hero) {{
+ slot.innerHTML = '<div class="empty">No hero frame was published in the current bundle.</div>';
+ meta.textContent = "No hero frame";
+ return;
+ }}
+ slot.innerHTML = `<img class="hero-frame" src="${{artifactUrl(session, hero)}}" alt="${{escapeHtml(hero.label || hero.artifact_id || "Hero frame")}}">`;
+ const bits = [];
+ if (hero.width && hero.height) bits.push(`${{hero.width}}×${{hero.height}}`);
+ if (hero.time_s != null) bits.push(`t=${{hero.time_s}}s`);
+ meta.textContent = bits.join(" · ") || (hero.label || "Hero frame");
+ }}
+
+ function renderClip(session, manifest) {{
+ const clip = pickArtifact(manifest, "preview-clip", "video/");
+ const slot = document.getElementById("clip-slot");
+ const meta = document.getElementById("clip-meta");
+ if (!clip) {{
+ slot.innerHTML = '<div class="empty">No preview clip was published in the current bundle.</div>';
+ meta.textContent = "No clip";
+ return;
+ }}
+ slot.innerHTML = `
+ <video class="hero-frame" controls preload="metadata" src="${{artifactUrl(session, clip)}}">
+ Your browser does not support embedded video.
+ </video>
+ `;
+ const bits = [];
+ if (clip.width && clip.height) bits.push(`${{clip.width}}×${{clip.height}}`);
+ if (clip.duration_s != null) bits.push(`${{clip.duration_s}}s`);
+ if (clip.render_method) bits.push(clip.render_method);
+ meta.textContent = bits.join(" · ") || (clip.label || "Preview clip");
+ }}
+
+ function renderGallery(session, manifest) {{
+ const items = (manifest.artifacts || [])
+ .filter((artifact) => artifact.role === "gallery" && (artifact.media_type || "").startsWith("image/"));
+ const root = document.getElementById("gallery");
+ if (!items.length) {{
+ root.innerHTML = '<div class="empty">No gallery frames were published in the current bundle.</div>';
+ return;
+ }}
+ root.innerHTML = items.map((artifact) => `
+ <article class="thumb">
+ <img src="${{artifactUrl(session, artifact)}}" alt="${{escapeHtml(artifact.label || artifact.artifact_id || "Gallery frame")}}">
+ <div class="label">${{escapeHtml(artifact.label || artifact.artifact_id || "Frame")}}</div>
+ <div class="meta">${{artifact.time_s != null ? `t=${{artifact.time_s}}s` : ""}}</div>
+ </article>
+ `).join("");
+ }}
+
+ function renderNotes(session, manifest, summary) {{
+ const warnings = summary.warnings || manifest.warnings || [];
+ const actions = summary.next_actions || [];
+ const notes = document.getElementById("notes");
+ const lines = [
+ `<div><strong>Current bundle</strong><br>${{escapeHtml(session.current_bundle_id || manifest.bundle_id || "n/a")}}</div>`,
+ `<div><strong>Session path</strong><br>${{escapeHtml(session.project_path || session.project_name || "n/a")}}</div>`,
+ `<div><strong>Last update</strong><br>${{escapeHtml(session.updated_at || "unknown")}}</div>`,
+ ];
+ if (warnings.length) {{
+ lines.push(`<div><strong>Warnings</strong><ul>${{warnings.map((item) => `<li>${{escapeHtml(item)}}</li>`).join("")}}</ul></div>`);
+ }}
+ if (actions.length) {{
+ lines.push(`<div><strong>Suggested checks</strong><ul>${{actions.map((item) => `<li>${{escapeHtml(item)}}</li>`).join("")}}</ul></div>`);
+ }}
+ notes.innerHTML = lines.join("");
+ }}
+
+ function renderHistory(session) {{
+ const history = session.history || [];
+ const root = document.getElementById("history");
+ if (!history.length) {{
+ root.innerHTML = '<div class="empty">No live preview publishes yet.</div>';
+ return;
+ }}
+ root.innerHTML = history.map((item) => `
+ <article class="history-item">
+ <strong>${{escapeHtml(item.bundle_id || "unknown")}}</strong>
+ <span>${{escapeHtml(item.created_at || "unknown")}}</span>
+ <span>${{escapeHtml(item.bundle_dir || "")}}</span>
+ </article>
+ `).join("");
+ }}
+
+ async function refresh() {{
+ try {{
+ const session = await fetchJson("session.json");
+ const manifest = await fetchJson(`${{CURRENT_LINK}}/manifest.json`);
+ let summary = {{}};
+ const summaryPath = manifest.summary_path ? `${{CURRENT_LINK}}/${{manifest.summary_path}}` : `${{CURRENT_LINK}}/summary.json`;
+ try {{
+ summary = await fetchJson(summaryPath);
+ }} catch (error) {{
+ summary = {{}};
+ }}
+
+ document.getElementById("subtitle").textContent =
+ (summary.headline || "Latest bundle loaded") +
+ ` · polling every ${{POLL_MS}} ms`;
+
+ renderFacts(session, manifest, summary);
+ renderCommands(session);
+ renderHero(session, manifest);
+ renderClip(session, manifest);
+ renderGallery(session, manifest);
+ renderNotes(session, manifest, summary);
+ renderHistory(session);
+ setStatus("Watching", false);
+ }} catch (error) {{
+ setStatus("Waiting", true);
+ document.getElementById("notes").innerHTML = `<div><strong>Viewer state</strong><br>${{escapeHtml(error.message)}}</div>`;
+ }}
+ }}
+
+ refresh();
+ window.setInterval(refresh, POLL_MS);
+ </script>
+</body>
+</html>
+"""
+ with open(output_file, "w", encoding="utf-8") as fh:
+ fh.write(html_text)
+ return str(output_file)
+
+
+class _NoCacheHandler(SimpleHTTPRequestHandler):
+ """Serve preview assets without cache so live sessions refresh correctly."""
+
+ def end_headers(self) -> None:
+ self.send_header("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
+ self.send_header("Pragma", "no-cache")
+ self.send_header("Expires", "0")
+ super().end_headers()
+
+ def log_message(self, format: str, *args: Any) -> None:
+ return
+
+
+def start_static_server(directory: str, host: str = "127.0.0.1", port: int = 0) -> Tuple[ThreadingHTTPServer, str]:
+ root = Path(directory).expanduser().resolve()
+ handler = functools.partial(_NoCacheHandler, directory=str(root))
+ server = ThreadingHTTPServer((host, int(port)), handler)
+ base_url = f"http://{host}:{server.server_port}"
+ return server, base_url
+
+
+def open_in_browser(target: str) -> Dict[str, Any]:
+ candidates = [
+ ("chromium", ["chromium", f"--app={target}"]),
+ ("google-chrome", ["google-chrome", f"--app={target}"]),
+ ("google-chrome-stable", ["google-chrome-stable", f"--app={target}"]),
+ ("microsoft-edge", ["microsoft-edge", f"--app={target}"]),
+ ("firefox", ["firefox", "--new-window", target]),
+ ("xdg-open", ["xdg-open", target]),
+ ]
+ for label, command in candidates:
+ binary = shutil.which(command[0])
+ if not binary:
+ continue
+ full_command = [binary] + command[1:]
+ process = subprocess.Popen(
+ full_command,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ return {
+ "launched": True,
+ "browser": label,
+ "pid": process.pid,
+ "command": full_command,
+ }
+ return {
+ "launched": False,
+ "browser": None,
+ "command": [],
+ "reason": "No supported browser launcher found on PATH",
+ }
diff --git a/cli-hub/tests/test_cli_hub.py b/cli-hub/tests/test_cli_hub.py
index 22f87c1f0..2085a09bd 100644
--- a/cli-hub/tests/test_cli_hub.py
+++ b/cli-hub/tests/test_cli_hub.py
@@ -12,6 +12,15 @@ import requests
from cli_hub import __version__
from cli_hub.registry import fetch_registry, fetch_all_clis, get_cli, search_clis, list_categories
+from cli_hub.preview import (
+ inspect_bundle,
+ inspect_session,
+ open_in_browser,
+ render_html,
+ render_inspect_text,
+ render_live_html,
+ render_session_text,
+)
from cli_hub.installer import (
install_cli,
uninstall_cli,
@@ -77,6 +86,94 @@ SAMPLE_REGISTRY = {
}
+def _make_preview_bundle(tmp_path: Path) -> Path:
+ bundle_dir = tmp_path / "preview-bundle"
+ artifacts_dir = bundle_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True)
+ (artifacts_dir / "hero.png").write_bytes(b"\x89PNG\r\n\x1a\npreview")
+ (artifacts_dir / "preview.mp4").write_bytes(b"\x00\x00\x00\x18ftypmp42")
+ summary = {
+ "headline": "Quick preview rendered",
+ "facts": {
+ "duration_s": 6.0,
+ "resolution": "640x360",
+ },
+ "warnings": [],
+ }
+ manifest = {
+ "protocol_version": "preview-bundle/v1",
+ "bundle_id": "20260419T104530Z_deadbeef_quick",
+ "bundle_kind": "capture",
+ "software": "shotcut",
+ "recipe": "quick",
+ "status": "ok",
+ "created_at": "2026-04-19T10:45:30Z",
+ "generator": {"entry_point": "cli-anything-shotcut", "command": "cli-anything-shotcut preview capture --recipe quick"},
+ "source": {"project_path": "/tmp/demo.mlt", "project_fingerprint": "sha256:test"},
+ "summary_path": "summary.json",
+ "artifacts": [
+ {
+ "artifact_id": "hero",
+ "role": "hero",
+ "kind": "image",
+ "label": "Midpoint frame",
+ "media_type": "image/png",
+ "path": "artifacts/hero.png",
+ "width": 960,
+ "height": 540,
+ "bytes": (artifacts_dir / "hero.png").stat().st_size,
+ },
+ {
+ "artifact_id": "clip",
+ "role": "preview-clip",
+ "kind": "clip",
+ "label": "Preview clip",
+ "media_type": "video/mp4",
+ "path": "artifacts/preview.mp4",
+ "width": 640,
+ "height": 360,
+ "duration_s": 6.0,
+ "bytes": (artifacts_dir / "preview.mp4").stat().st_size,
+ },
+ ],
+ }
+ (bundle_dir / "summary.json").write_text(json.dumps(summary, indent=2))
+ (bundle_dir / "manifest.json").write_text(json.dumps(manifest, indent=2))
+ return bundle_dir
+
+
+def _make_preview_session(tmp_path: Path) -> Path:
+ bundle_dir = _make_preview_bundle(tmp_path)
+ session_dir = tmp_path / "live-session"
+ session_dir.mkdir()
+ (session_dir / "current").symlink_to(bundle_dir, target_is_directory=True)
+ session = {
+ "protocol_version": "preview-live/v1",
+ "software": "shotcut",
+ "recipe": "quick",
+ "status": "active",
+ "session_name": "demo-live",
+ "project_path": "/tmp/demo.mlt",
+ "project_name": "demo.mlt",
+ "updated_at": "2026-04-20T09:00:00Z",
+ "current_link": "current",
+ "current_bundle_id": "20260419T104530Z_deadbeef_quick",
+ "watch_command": "cli-hub preview watch /tmp/live-session --open",
+ "publish_command": "cli-anything-shotcut preview live push --recipe quick",
+ "inspect_command": "cli-hub preview inspect /tmp/live-session",
+ "history": [
+ {
+ "bundle_id": "20260419T104530Z_deadbeef_quick",
+ "bundle_dir": str(bundle_dir),
+ "created_at": "2026-04-19T10:45:30Z",
+ "status": "ok",
+ }
+ ],
+ }
+ (session_dir / "session.json").write_text(json.dumps(session, indent=2))
+ return session_dir
+
+
# ─── Registry tests ───────────────────────────────────────────────────
@@ -152,6 +249,102 @@ class TestRegistry:
cats = list_categories()
assert cats == ["3d", "audio", "image"]
+
+class TestPreviewBundle:
+ """Tests for preview bundle inspection and HTML rendering."""
+
+ def test_inspect_bundle(self, tmp_path):
+ bundle_dir = _make_preview_bundle(tmp_path)
+ payload = inspect_bundle(str(bundle_dir))
+ assert payload["artifact_count"] == 2
+ assert payload["manifest"]["software"] == "shotcut"
+ assert payload["summary"]["headline"] == "Quick preview rendered"
+
+ def test_render_inspect_text(self, tmp_path):
+ bundle_dir = _make_preview_bundle(tmp_path)
+ text = render_inspect_text(str(bundle_dir))
+ assert "Bundle:" in text
+ assert "Artifacts" in text
+ assert "Midpoint frame" in text
+
+ def test_render_html(self, tmp_path):
+ bundle_dir = _make_preview_bundle(tmp_path)
+ output_path = tmp_path / "preview.html"
+ rendered = render_html(str(bundle_dir), str(output_path))
+ assert rendered == str(output_path.resolve())
+ content = output_path.read_text()
+ assert "CLI-Anything Preview Bundle" in content
+ assert "Quick preview rendered" in content
+ assert "artifacts/hero.png" in content
+ assert "artifacts/preview.mp4" in content
+
+ def test_preview_inspect_cli_command(self, tmp_path):
+ bundle_dir = _make_preview_bundle(tmp_path)
+ runner = click.testing.CliRunner()
+ result = runner.invoke(main, ["preview", "inspect", str(bundle_dir)])
+ assert result.exit_code == 0
+ assert "Quick preview rendered" in result.output
+
+ def test_preview_html_cli_command(self, tmp_path):
+ bundle_dir = _make_preview_bundle(tmp_path)
+ output_path = tmp_path / "bundle-preview.html"
+ runner = click.testing.CliRunner()
+ result = runner.invoke(main, ["preview", "html", str(bundle_dir), "-o", str(output_path)])
+ assert result.exit_code == 0
+ assert str(output_path) in result.output
+ assert output_path.is_file()
+
+ def test_inspect_session(self, tmp_path):
+ session_dir = _make_preview_session(tmp_path)
+ payload = inspect_session(str(session_dir))
+ assert payload["session"]["software"] == "shotcut"
+ assert payload["current_bundle"]["manifest"]["bundle_id"] == "20260419T104530Z_deadbeef_quick"
+
+ def test_render_session_text(self, tmp_path):
+ session_dir = _make_preview_session(tmp_path)
+ text = render_session_text(str(session_dir))
+ assert "Live Session:" in text
+ assert "Watch:" in text
+ assert "History" in text
+
+ def test_render_live_html(self, tmp_path):
+ session_dir = _make_preview_session(tmp_path)
+ output_path = tmp_path / "live.html"
+ rendered = render_live_html(str(session_dir), str(output_path), poll_ms=800)
+ assert rendered == str(output_path.resolve())
+ content = output_path.read_text()
+ assert "CLI-Anything Live Preview Session" in content
+ assert 'const CURRENT_LINK = "current";' in content
+ assert "manifest = await fetchJson(`${CURRENT_LINK}/manifest.json`);" in content
+ assert "const POLL_MS = 800;" in content
+
+ @patch("cli_hub.preview.subprocess.Popen")
+ @patch("cli_hub.preview.shutil.which")
+ def test_open_in_browser_prefers_app_mode(self, mock_which, mock_popen):
+ mock_which.side_effect = lambda binary: f"/usr/bin/{binary}" if binary == "chromium" else None
+ mock_popen.return_value = MagicMock(pid=4321)
+ result = open_in_browser("http://127.0.0.1:9933/live.html")
+ assert result["launched"] is True
+ assert result["browser"] == "chromium"
+ assert "--app=http://127.0.0.1:9933/live.html" in result["command"]
+
+ def test_preview_inspect_cli_handles_session(self, tmp_path):
+ session_dir = _make_preview_session(tmp_path)
+ runner = click.testing.CliRunner()
+ result = runner.invoke(main, ["preview", "inspect", str(session_dir)])
+ assert result.exit_code == 0
+ assert "Live Session:" in result.output
+
+ def test_preview_html_cli_renders_session(self, tmp_path):
+ session_dir = _make_preview_session(tmp_path)
+ output_path = tmp_path / "session-live.html"
+ runner = click.testing.CliRunner()
+ result = runner.invoke(main, ["preview", "html", str(session_dir), "-o", str(output_path), "--poll-ms", "700"])
+ assert result.exit_code == 0
+ assert output_path.is_file()
+ assert "const POLL_MS = 700;" in output_path.read_text()
+
+
# ─── Installer tests ──────────────────────────────────────────────────
diff --git a/docs/FREECAD_VIDEO_REFERENCE.md b/docs/FREECAD_VIDEO_REFERENCE.md
new file mode 100644
index 000000000..a053ce866
--- /dev/null
+++ b/docs/FREECAD_VIDEO_REFERENCE.md
@@ -0,0 +1,302 @@
+# FreeCAD Demo Video Reference
+
+Last updated: 2026-04-22 UTC
+
+This file records the programmatic video artifacts built from real
+`cli-anything-freecad` trajectories and real FreeCAD preview bundles.
+
+## Curiosity V6
+
+Source trajectory:
+
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json`
+
+Current render target:
+
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/demo.mp4`
+
+Final rendered artifact:
+
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/demo.mp4`
+- duration: `116.166667s`
+- size: `3,011,924 bytes`
+
+Polished split-screen re-render:
+
+- `/root/preview-artifacts/20260422/freecad-curiosity-v6/demo-polished.mp4`
+- duration: `71.416667s`
+- size: `2,266,665 bytes`
+
+Render command:
+
+```bash
+python3 /root/CLI-Anything-preview/docs/scripts/freecad_live_preview_demo.py \
+ render \
+ --timeline /root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json \
+ --speed 8
+```
+
+Ending showcase method:
+
+- reuse the real final `Curiosity v6` project JSON
+- add a staged ground and marker bed as extra real geometry
+- generate extra real FreeCAD `preview capture` hero bundles for a sequence of
+ posed translations
+- append those real hero captures as a final full-screen showcase segment in the
+ programmatic video
+
+Expected showcase cache location:
+
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase/sequence.json`
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase/projects/`
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase/captures/`
+
+Key stills:
+
+- trajectory end:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/stills/trajectory-end.png`
+- showcase start:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/stills/showcase-start.png`
+- showcase mid:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/stills/showcase-mid.png`
+- showcase final:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/stills/showcase-final.png`
+
+Implementation notes:
+
+- the main split-screen section uses the real `Curiosity v6` live session
+ timeline and real copied preview bundles
+- the ending showcase uses `12` extra real FreeCAD hero captures
+- the showcase segment begins after the main trajectory body and is rendered as
+ a full-screen ending panel
+- the current render was produced with `--speed 8`, which keeps the long real
+ trajectory readable without turning the video into a many-minute raw replay
+
+Polished render command:
+
+```bash
+python3 - <<'PY'
+import importlib.util
+from pathlib import Path
+script = Path('/root/CLI-Anything-preview/docs/scripts/freecad_live_preview_demo.py')
+spec = importlib.util.spec_from_file_location('freecad_live_preview_demo', script)
+mod = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(mod)
+print(
+ mod.render_video(
+ Path('/root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json'),
+ output_path=Path('/root/preview-artifacts/20260422/freecad-curiosity-v6/demo-polished.mp4'),
+ fps=12,
+ speed=14.0,
+ keep_frames=True,
+ )
+)
+PY
+```
+
+Polished split-screen changes:
+
+- left panel is now a designed `Agent Command Stream`, not a literal terminal
+- command cards use the real captured command strings, normalized for
+ readability
+- the ending no longer uses sparse hero-capture blending
+- the ending now uses the real combo motion sequence:
+ - one full turntable rotation
+ - followed by forward travel
+- ending frames are pulled from `cli-anything-freecad motion render-video`
+ output via:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion/`
+
+Key stills for the polished render:
+
+- early command stream:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6/stills/early-command-stream.png`
+- mid preview monitor:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6/stills/mid-preview-monitor.png`
+- showcase rotation:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6/stills/showcase-rotation.png`
+- showcase final drive:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6/stills/showcase-final-drive.png`
+
+Notes:
+
+- the split-screen body of the video is still based on the real CLI trajectory
+ and the real live preview session
+- the ending showcase is not a screen recording; it is a composition of extra
+ real FreeCAD preview captures derived from the final project state
+
+## Curiosity V6 True Motion Showcase
+
+Source trajectory:
+
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json`
+
+True-motion render target:
+
+- `/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/curiosity_true_motion.mp4`
+
+Final rendered artifact:
+
+- `/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/curiosity_true_motion.mp4`
+- duration: `6.0s`
+- frame count: `73`
+- size: `315,872 bytes`
+
+Render command:
+
+```bash
+python3 /root/CLI-Anything-preview/docs/scripts/freecad_live_preview_demo.py \
+ motion-showcase \
+ --timeline /root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json \
+ --output-dir /root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion \
+ --fps 12
+```
+
+Method:
+
+- reuse the real final `Curiosity v6` project JSON
+- add the staged showcase ground/markers as real geometry
+- generate `13` motion key poses across `6.0s`
+- store those keyframes in the project `motions` collection
+- invoke `cli-anything-freecad motion render-video`
+- render every frame through real FreeCAD GUI capture and encode with `ffmpeg`
+
+Artifacts:
+
+- motion project:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/curiosity_true_motion.json`
+- motion manifest:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/motion_manifest.json`
+- frame sequence:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/frames/sequence.json`
+
+Key stills:
+
+- start:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/stills/start.png`
+- mid:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/stills/mid.png`
+- final:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/stills/final.png`
+
+Notes:
+
+- this showcase uses real frame-by-frame FreeCAD renders
+- no blend-based or synthetic in-between motion is used
+- motion is currently driven by part-placement keyframes, not native Assembly joint simulation
+
+## Curiosity Turntable Motion
+
+Source trajectory:
+
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json`
+
+Turntable render target:
+
+- `/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/curiosity_turntable_motion.mp4`
+
+Final rendered artifact:
+
+- `/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/curiosity_turntable_motion.mp4`
+- duration: `7.0s`
+- frame count: `85`
+- size: `719,298 bytes`
+
+Render command:
+
+```bash
+python3 /root/CLI-Anything-preview/docs/scripts/freecad_live_preview_demo.py \
+ motion-showcase \
+ --motion-style spin \
+ --timeline /root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json \
+ --output-dir /root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion \
+ --fps 12
+```
+
+Method:
+
+- reuse the real final `Curiosity v6` project JSON
+- add the staged showcase ground/markers as real geometry
+- generate `19` turntable key poses across `7.0s`
+- rotate the rover around its stage-centered pivot
+- invoke `cli-anything-freecad motion render-video`
+- render every frame through real FreeCAD GUI capture and encode with `ffmpeg`
+
+Artifacts:
+
+- motion project:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/curiosity_turntable_motion.json`
+- motion manifest:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/motion_manifest.json`
+- frame sequence:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/frames/sequence.json`
+
+Key stills:
+
+- start:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/stills/start.png`
+- mid:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/stills/mid.png`
+- final:
+ `/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/stills/final.png`
+
+Notes:
+
+- this turntable is also a real frame-by-frame FreeCAD render
+- no synthetic in-between frames are used
+- orientation is currently driven by per-part placement keyframes, not native Assembly joint simulation
+
+## Curiosity Combo Motion
+
+Source trajectory:
+
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json`
+
+Combo render target:
+
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion/curiosity_combo_motion.mp4`
+
+Final rendered artifact:
+
+- `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion/curiosity_combo_motion.mp4`
+- duration: `9.0s`
+- frame count: `109`
+
+Render command:
+
+```bash
+python3 /root/CLI-Anything-preview/docs/scripts/freecad_live_preview_demo.py \
+ motion-showcase \
+ --motion-style combo \
+ --timeline /root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json \
+ --output-dir /root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion \
+ --fps 12
+```
+
+Method:
+
+- reuse the real final `Curiosity v6` project JSON
+- add the staged showcase ground/markers as real geometry
+- generate `25` motion key poses across `9.0s`
+- first do one full turntable rotation
+- then drive forward across the stage
+- render every frame through real FreeCAD GUI capture
+- encode the result to MP4 with `ffmpeg`
+
+Artifacts:
+
+- motion project:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion/curiosity_combo_motion.json`
+- motion manifest:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion/motion_manifest.json`
+- frame sequence:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion/frames/sequence.json`
+
+Key stills:
+
+- start:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion/stills/start.png`
+- mid:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion/stills/mid.png`
+- final:
+ `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase-motion/stills/final.png`
diff --git a/docs/PREVIEW_PROGRESS.md b/docs/PREVIEW_PROGRESS.md
new file mode 100644
index 000000000..2632c1286
--- /dev/null
+++ b/docs/PREVIEW_PROGRESS.md
@@ -0,0 +1,919 @@
+# Preview Progress
+
+Last updated: 2026-04-22 UTC
+
+This file tracks the current state of the preview work on the dedicated preview
+branch and records the next design direction for live popup preview windows.
+
+## Workspace
+
+- Repo: `/root/CLI-Anything-preview`
+- Branch: `feat/preview-protocol`
+- Primary protocol doc: `docs/PREVIEW_PROTOCOL.md`
+
+## What Is Implemented
+
+The current branch already has a working first-pass preview stack:
+
+- Shared preview bundle helper:
+ `cli-anything-plugin/preview_bundle.py`
+- Shared static viewer/inspector:
+ `cli-hub/cli_hub/preview.py`
+- Preview protocol documented:
+ `docs/PREVIEW_PROTOCOL.md`
+- Harness-level preview support implemented for:
+ - `shotcut`
+ - `openscreen`
+ - `blender`
+ - `freecad`
+ - `renderdoc`
+
+The current shape is:
+
+- harnesses emit `preview-bundle/v1` bundles
+- `cli-hub` can inspect or render static HTML for a bundle
+- preview commands are normalized around:
+ - `preview recipes`
+ - `preview capture`
+ - `preview latest`
+- `renderdoc` also has `preview diff`
+
+## New In This Iteration
+
+The preview branch now has working first-pass live popup preview loops for
+`shotcut` and `freecad`.
+
+The current FreeCAD demo selection notes now live in:
+
+- `docs/FREECAD_DEMO_PROPOSALS.md`
+
+The first selected post-landmark showcase is:
+
+- `mars-rover`
+
+The current FreeCAD mechanical-modeling quality push also added:
+
+- `part bounds`
+- `part align`
+- a new `Curiosity v6` connector pass:
+ - mirrored right-side wheel outboard alignment
+ - 6 wheel-level axle blocks
+ - 4 suspension pivot housings
+ - a full real live-preview rerun after those connector parts were added
+
+These commands provide primitive-level world bounding boxes and bbox-anchor
+alignment so CLI-built models do not have to rely purely on guessed
+`-pos/-rot` placements.
+
+The current FreeCAD video tooling now also has:
+
+- a true `combo` motion ending for Curiosity:
+ - one full rotation
+ - then forward travel
+- a redesigned split-screen left panel:
+ - `Agent Command Stream`
+ - card-based command display instead of a literal terminal dump
+- a render fix in the demo script so custom output paths create parent
+ directories before calling `ffmpeg`
+
+What was added:
+
+- `shotcut` live session lifecycle:
+ - `preview live start`
+ - `preview live push`
+ - `preview live status`
+ - `preview live stop`
+- `shotcut` producer-side auto polling:
+ - `preview live start --mode poll --source-poll-ms ...`
+ - hidden background `preview live monitor --session-dir ...`
+ - project-file fingerprint polling with automatic preview recapture
+- `freecad` live session lifecycle:
+ - `preview live start`
+ - `preview live push`
+ - `preview live status`
+ - `preview live stop`
+- `freecad` producer-side auto polling:
+ - `preview live start --mode poll --source-poll-ms ...`
+ - hidden background `preview live monitor --session-dir ...`
+ - saved project JSON fingerprint polling with automatic preview recapture
+ - demo tooling for `freecad`:
+ - `docs/scripts/freecad_live_preview_demo.py collect`
+ - `docs/scripts/freecad_live_preview_demo.py render`
+ - `docs/scripts/freecad_live_preview_demo.py run-all`
+ - scenarios:
+ - `orbital-relay`
+ - `empire-state-building`
+ - `taipei-101`
+- `cli-hub` live viewer surface:
+ - `preview inspect` now understands live sessions
+ - `preview html` now renders live-session HTML
+ - `preview watch` now serves a live session over localhost with auto-refresh
+ - `preview open` now opens bundles or live sessions in a separate window
+
+The live split now looks like this:
+
+- harness owns preview bundle generation and live-session state publication
+- harness can now also own source-state polling and automatic bundle refresh
+- `cli-hub` owns the popup window, local server, polling page, and browser launch
+
+This is the intended cross-software direction.
+
+## Current Validation Status
+
+### Fully verified on this machine
+
+- `shotcut`
+ - preview implementation works
+ - black-frame issue was fixed by preferring the ffmpeg preview path
+ - preview E2E passes
+ - live preview session + live viewer now works end-to-end
+ - automatic poll mode now works end-to-end without manual `preview live push`
+- `openscreen`
+ - preview implementation works
+ - preview E2E passes
+- `blender`
+ - preview implementation works
+ - preview E2E passes
+- `freecad`
+ - preview implementation works on the current Ubuntu machine after local
+ environment setup
+ - preview E2E passes
+ - live preview session + live poll mode now work end-to-end
+ - a real programmatic demo video now exists, built from real CLI outputs and
+ real live preview bundles
+ - preview macro now reconstructs real body/additive/subtractive primitive
+ features plus linear/polar/mirror pattern features with placement
+ - multiple real Taipei 101 studies now exist; the old shipped scenario has
+ been replaced because the earlier stacked-box version was not acceptable
+ - preview/export macro generation now also reconstructs `part mirror` for
+ primitive-backed mirrored parts, which was required for truthful symmetric
+ mechanical builds like the rover
+ - a first real `mars-rover` live-preview trajectory now exists and completes
+ successfully end-to-end
+ - the live demo collector now treats preview events as a stable sequence even
+ when FreeCAD live sessions change bundle ids without strictly monotonic
+ `bundle_count` behavior
+ - a real `curiosity` live-preview trajectory now exists and completes
+ successfully end-to-end
+ - the harness now has primitive-level `part bounds` and `part align`
+ commands, with unit and CLI subprocess coverage
+ - a fuller `Curiosity v6` run now exists and completes successfully with
+ explicit suspension connector parts; the final right/front views are much
+ more symmetric and structurally coherent than the earlier `v5` build
+ - a polished Curiosity split-screen video now exists with:
+ - real command-card trajectory view
+ - real live preview bundles
+ - a true frame-by-frame combo motion ending
+
+### Partially verified on this machine
+
+- `renderdoc`
+ - replaying existing `.rdc` captures works
+ - `renderdoccmd thumb` works on suitable sample captures
+ - local capture generation on this machine is still blocked by the current
+ graphics backend environment
+
+## Current Machine Notes
+
+### FreeCAD
+
+To make `freecad` preview work on this Ubuntu machine, the environment had to
+be completed locally:
+
+- FreeCAD AppImage extracted under `/opt/freecad/app`
+- local launcher/wrapper installed at `/usr/local/bin/freecad`
+- wrapper forces GUI-capable execution through `xvfb-run` for script-driven
+ preview capture
+
+This is machine-local setup, not repo content.
+
+Result:
+
+- `freecad` preview E2E now passes on this machine
+- generated 4-view preview images are valid and non-empty
+
+### RenderDoc
+
+To make `renderdoc` preview usable on this Ubuntu machine, the environment had
+to be completed locally:
+
+- RenderDoc installed under `/opt/renderdoc`
+- `renderdoccmd` and `qrenderdoc` exposed in `/usr/local/bin`
+- Vulkan and shader tooling installed:
+ - `vulkan-tools`
+ - `glslang-tools`
+
+Important limitation discovered on this machine:
+
+- in the current terminal Ubuntu environment using software rendering
+ (`llvmpipe` / `lavapipe`), RenderDoc can inject into demo apps and expose the
+ in-app API, but local `StartFrameCapture`/`EndFrameCapture` still returns no
+ saved captures
+- this is not a CLI wiring issue; it is a backend/runtime limitation of the
+ current graphics environment
+
+What still works:
+
+- replaying existing `.rdc` captures
+- exporting thumbnails from existing `.rdc` files when the capture includes a
+ usable embedded thumbnail
+
+## Local Artifacts
+
+Useful local verification outputs currently available:
+
+- consolidated final artifacts:
+ - `/root/preview-artifacts/20260420/final/freecad-preview.png`
+ - `/root/preview-artifacts/20260420/final/renderdoc-preview.png`
+- FreeCAD live poll demo artifacts:
+ - `/root/preview-artifacts/20260421/freecad-live-demo/live-root/freecad/live/project-379d4e4a-quick/session.json`
+ - `/root/preview-artifacts/20260421/freecad-live-demo/live-root/freecad/quick/20260421T051634Z_88a6b6d6_quick/artifacts/hero.png`
+ - `/root/preview-artifacts/20260421/freecad-live-demo/live.html`
+- FreeCAD programmatic video demo artifacts:
+ - `/root/preview-artifacts/20260421/freecad-live-video/demo.mp4`
+ - `/root/preview-artifacts/20260421/freecad-live-video/trajectory.json`
+ - `/root/preview-artifacts/20260421/freecad-live-video/live.html`
+ - `/root/preview-artifacts/20260421/freecad-live-video/stills/frame_10s.png`
+ - `/root/preview-artifacts/20260421/freecad-live-video/stills/frame_35s.png`
+ - `/root/preview-artifacts/20260421/freecad-live-video/stills/frame_60s.png`
+- FreeCAD skyscraper demo artifacts:
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-video/demo.mp4`
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-video/trajectory.json`
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-video/live.html`
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-video/stills/frame_15s.png`
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-video/stills/frame_55s.png`
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-video/stills/frame_95s.png`
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-video/snapshots/15_spire-tip/front.png`
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-video/snapshots/15_spire-tip/hero.png`
+- FreeCAD rover prototype artifacts:
+ - `/root/preview-artifacts/20260421/freecad-mars-rover-proto3/trajectory.json`
+ - `/root/preview-artifacts/20260421/freecad-mars-rover-proto3/live.html`
+ - `/root/preview-artifacts/20260421/freecad-mars-rover-proto3/snapshots/21_sample-head/hero.png`
+ - `/root/preview-artifacts/20260421/freecad-mars-rover-proto3/snapshots/21_sample-head/front.png`
+ - `/root/preview-artifacts/20260421/freecad-mars-rover-proto3/snapshots/21_sample-head/top.png`
+ - this rover run produced `22` real CLI commands and `21` real preview
+ updates on the current machine
+- FreeCAD Curiosity artifacts:
+ - `/root/preview-artifacts/20260421/freecad-curiosity-proto4/trajectory.json`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-proto4/live.html`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-proto4/snapshots/35_deck-sensor-pack/hero.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-proto4/snapshots/35_deck-sensor-pack/front.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-proto4/snapshots/35_deck-sensor-pack/top.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-proto4/snapshots/35_deck-sensor-pack/right.png`
+ - this Curiosity run produced `36` real CLI commands and `35` real preview
+ updates on the current machine
+ - average preview refresh latency on this run was `8.503s`
+- FreeCAD Curiosity arm/attachment refinement artifacts:
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v3-armfix-preview/freecad/quick/20260421T162607Z_12c18d75_quick/artifacts/hero.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v3-armfix-preview/freecad/quick/20260421T162607Z_12c18d75_quick/artifacts/front.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v3-armfix-preview/freecad/quick/20260421T162607Z_12c18d75_quick/artifacts/top.png`
+ - these were generated from the real Curiosity project after applying
+ `part align` fixes to the upper/fore arm and turret chain
+- FreeCAD Curiosity full suspension/alignment refinement:
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v5/trajectory.json`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v5/live.html`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v5/snapshots/58_align-sensor-pack/hero.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v5/snapshots/58_align-sensor-pack/front.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v5/snapshots/58_align-sensor-pack/right.png`
+ - this run produced `62` real CLI commands and `58` real preview updates
+ - average preview refresh latency on this run was `14.454s`
+ - suspension updates now include explicit wheel-plane alignment for
+ rocker/bogie/link parts before the upper assembly stack is added
+- FreeCAD Curiosity connector rebuild:
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/trajectory.json`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/live.html`
+ - suspension connector checkpoint:
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/snapshots/50_align-right-bogie-pivot-housing/right.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/snapshots/50_align-right-bogie-pivot-housing/front.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/snapshots/50_align-right-bogie-pivot-housing/hero.png`
+ - final v6 snapshot:
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/snapshots/82_align-sensor-pack/hero.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/snapshots/82_align-sensor-pack/front.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/snapshots/82_align-sensor-pack/right.png`
+ - this run produced `85` real CLI commands and `82` real preview updates
+ - average preview refresh latency on this run was `10.059s`
+ - compared with `v5`, the biggest gains are symmetric right-side track width
+ and visibly attached wheel/suspension connectors in the key front/right
+ views
+ - a programmatic video now also exists for this same `v6` trajectory:
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/demo.mp4`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/showcase/sequence.json`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/stills/showcase-start.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/stills/showcase-mid.png`
+ - `/root/preview-artifacts/20260421/freecad-curiosity-v6/stills/showcase-final.png`
+ - the ending showcase is built from extra real FreeCAD hero captures derived
+ from the final `Curiosity v6` project on a staged ground run
+- Shotcut live preview demo artifacts:
+ - `/root/preview-artifacts/20260420/shotcut-live-demo/live-viewer-shot.png`
+ - `/root/preview-artifacts/20260420/shotcut-live-demo/live-root/shotcut/live/project-9e62c8c7-quick/live.html`
+ - `/root/preview-artifacts/20260420/shotcut-live-demo/live-root/shotcut/live/project-9e62c8c7-quick/session.json`
+- Temporary poll-mode demo artifacts:
+ - `/tmp/shotcut-poll-demo/live-initial.png`
+ - `/tmp/shotcut-poll-demo/live-updated.png`
+ - `/tmp/shotcut-poll-demo/live-red-updated.png`
+ - `/tmp/shotcut-poll-demo/live-root/shotcut/live/project-35fa4f1f-quick/session.json`
+- FreeCAD bundle snapshots:
+ - `/root/preview-artifacts/20260420/freecad/`
+- RenderDoc sample replay artifacts:
+ - `/root/preview-artifacts/20260420/renderdoc/sample/`
+
+Interpretation:
+
+- `freecad-preview.png` is a real 4-view preview contact sheet generated from
+ the FreeCAD preview path on this machine
+- the `20260421/freecad-live-demo/` directory proves the new FreeCAD poll-mode
+ behavior: after a saved-project mutation, the live session advances from
+ bundle 1 to 2 without any manual `preview live push` command
+- the `20260421/freecad-live-video/` directory contains a real end-to-end demo
+ of an agent-like CLI build on the left and the actual FreeCAD live preview
+ outputs on the right; the video is programmatic, but the underlying commands,
+ outputs, timings, and preview images are all real
+- the `20260421/freecad-empire-state-video/` directory does the same for a
+ tiny Empire State Building reproduction built entirely with
+ `cli-anything-freecad` primitives and real poll-mode preview refresh
+ - after self-review, this Empire State Building attempt is not considered
+ shippable because the silhouette still reads as a generic stepped tower
+- the `20260421/freecad-taipei-101-video/` directory is a second real
+ skyscraper experiment built with the same CLI + real live preview pipeline
+ - after later review, it is also not shippable as a Taipei 101 demo; the
+ silhouette is still too generic and the command script only builds a crude
+ stacked-box approximation
+ - do not treat it as a finished landmark reproduction
+- after the FreeCAD body/additive/pattern preview alignment work, a new set of
+ real Taipei studies was generated directly against the improved harness:
+ - `/root/preview-artifacts/20260421/taipei-body-proto1/`
+ - `/root/preview-artifacts/20260421/taipei-body-proto7/`
+ - `/root/preview-artifacts/20260421/taipei-parts-proto2/`
+ - the current best silhouette is the stepped-shoulder parts study in
+ `/root/preview-artifacts/20260421/taipei-parts-proto2/`
+ - `docs/scripts/freecad_live_preview_demo.py` now uses that newer Taipei 101
+ step generator instead of the earlier incorrect stacked-box scenario
+- the updated `taipei-101` scenario was then re-collected end-to-end into:
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-rework/trajectory.json`
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-rework/final-preview.html`
+ - `/root/preview-artifacts/20260421/freecad-taipei-101-rework/snapshots/30_spire-tip/`
+ - this rework run produced `31` real CLI commands and `30` real preview
+ updates on the current machine
+- while starting the rover direction, one more real preview gap was exposed:
+ `part mirror` objects were valid project state but were not reconstructed by
+ the FreeCAD preview macro layer
+ - this caused preview drift or stalled capture once symmetric right-side
+ wheel copies entered the project
+ - the macro generator now resolves mirrored primitive parts into renderable
+ mirrored primitives for preview/export
+- the first rover prototype is not yet the final showcase model, but it now
+ reads clearly as a six-wheel exploration rover in real `hero/front/top`
+ preview and is a stronger subject for continued iteration than the failed
+ landmark demos
+- `renderdoc-preview.png` is a real thumbnail exported on this machine from an
+ existing `.rdc` sample capture
+- `live-viewer-shot.png` is a real screenshot of the new Shotcut live preview
+ window UI, rendered from the live-session viewer over localhost on this
+ machine
+- the `/tmp/shotcut-poll-demo/` artifacts prove the new poll-mode behavior:
+ after project-file mutations, the live session advances from bundle 1 to 2 to
+ 3 without any manual `preview live push` command
+
+## Gaps Still Open
+
+### Cross-process live session stability
+
+This iteration exposed and fixed an important issue:
+
+- the first implementation derived the live session name partly from the
+ in-process `session_id`
+- that broke one-shot CLI usage because each command got a different session dir
+
+The current behavior is now:
+
+- if a project has a saved `project_path`, live session identity is derived from
+ the stable project path + recipe
+- only unsaved in-memory projects fall back to `session_id`
+
+That is the correct agent-facing behavior for one-shot command flows.
+
+### RenderDoc capture generation
+
+The current repo implementation of `renderdoc` preview still assumes that a
+real replayable capture already exists.
+
+That is normal for RenderDoc as a product, but on this machine there is a
+further limitation:
+
+- generating a fresh `.rdc` locally from test apps is not currently reliable in
+ the present software-rendered terminal environment
+
+This means:
+
+- `renderdoc` preview is usable for existing captures
+- `renderdoc` preview is not yet fully self-hosted on this specific machine
+
+### FreeCAD boolean preview gap
+
+While building the video demo, one real limitation showed up:
+
+- after `part boolean fuse`, the current FreeCAD preview path can still produce
+ a bundle, but it may degrade to `partial` with no image artifacts
+
+This is why the current demo trajectory avoids boolean operations and uses only
+part additions that keep the live preview image stream valid.
+
+### Empire State Building attempt
+
+I explicitly reviewed the first Empire State Building video and artifacts after
+they were generated.
+
+Result:
+
+- the model was too generic and did not read as the Empire State Building
+- the right fix was not to keep claiming it was correct
+
+Current disposition:
+
+- keep the Empire State attempt only as an experiment
+- do not treat it as the shipped skyscraper demo
+- do not treat the old Taipei 101 stacked-box run as shipped either
+- the current Taipei 101 work has moved to the newer study artifacts and the
+ updated `freecad_live_preview_demo.py` scenario
+
+### FreeCAD body preview alignment
+
+The main FreeCAD gap behind the bad landmark demos was real:
+
+- the CLI could describe richer body/additive/pattern edits than the preview
+ macro could faithfully reconstruct
+
+This is now improved in the current branch:
+
+- additive and subtractive body primitives now accept feature placement
+- the preview/export macro now reconstructs:
+ - additive/subtractive `box/cylinder/sphere/cone/torus/wedge`
+ - `linear_pattern`
+ - `polar_pattern`
+ - `mirrored`
+ - `multi_transform` as a sequential expansion of supported pattern features
+- full verification now passes on this machine:
+ - `cli_anything/freecad/tests/test_core.py` -> `76 passed`
+ - `cli_anything/freecad/tests/test_full_e2e.py -k 'macro_generation or preview_capture_bundle or preview_capture_subprocess or preview_live_poll_auto_refresh'` -> `6 passed`
+
+### Shared runtime cleanup
+
+The preview bundle helper currently exists in:
+
+- canonical form in `cli-anything-plugin/preview_bundle.py`
+- copied form in each harness under `utils/preview_bundle.py`
+
+That is acceptable for a first pass, but the long-term direction should be:
+
+- one shared runtime helper
+- no more copy-based drift
+
+## Design Question: Can Preview Support A Separate Real-Time Popup Window?
+
+Short answer:
+
+- yes, but it should be implemented as a host/viewer feature, not as five
+ different app-specific mini GUIs
+- the generic solution should target near-real-time live preview sessions, not a
+ universal raw GUI-streaming protocol
+
+## Recommended Position
+
+The root design should be:
+
+- keep bundle generation in the harness
+- add a new live session abstraction above bundles
+- let `cli-hub` own the popup window and live refresh behavior
+
+In other words:
+
+- harnesses publish preview updates
+- `cli-hub` opens and updates the separate window
+
+This is the cleanest split for both agents and humans.
+
+## Why The Window Should Live In `cli-hub`
+
+Reasons:
+
+- popup behavior is cross-harness UI logic, not app-specific rendering logic
+- the viewer already understands the preview bundle contract
+- Linux/Ubuntu popup behavior belongs to the host layer
+- this avoids rebuilding the same preview monitor in every harness
+
+If every harness implements its own popup window:
+
+- command surfaces drift
+- dependencies drift
+- live refresh logic gets duplicated
+- Linux windowing quirks get re-solved five times
+
+## What "Real-Time" Should Mean Here
+
+There are two possible meanings:
+
+1. True continuous streaming at interactive frame rates
+2. Fast, repeated preview refresh in a dedicated live window
+
+The generic cross-software solution should target the second one.
+
+That means:
+
+- auto-refreshing stills
+- low-res review clip replacement
+- event-driven redraw after each mutating command
+- optional periodic refresh for long-running tasks
+
+This is realistic across video, CAD, 3D, and GPU-debug workflows.
+
+A universal 30-60 FPS live remote viewport for all supported software is not a
+good root abstraction for CLI-Anything.
+
+## Proposed New Abstraction: Live Preview Session
+
+The current protocol is bundle-centric.
+
+To support popup live preview, add a second object:
+
+- `Live Preview Session`
+
+Recommended shape:
+
+```text
+<root>/
+ sessions/
+ <session_id>/
+ session.json
+ current/
+ manifest.json
+ summary.json
+ artifacts/
+ history/
+ <bundle_id_1>/
+ <bundle_id_2>/
+```
+
+Where:
+
+- `history/` stores immutable preview bundles
+- `current/` points to the newest visible state for the live viewer
+- `session.json` stores session metadata and refresh sequence numbers
+
+This adds one key capability:
+
+- the live window can watch one stable path while harnesses keep publishing new
+ preview states
+
+## Proposed Command Surface
+
+### `cli-hub`
+
+Add these commands:
+
+- `cli-hub preview open <bundle-or-session>`
+ - open a preview in a separate window if possible
+- `cli-hub preview watch <session-dir>`
+ - run a live preview viewer against a session
+- `cli-hub preview serve <bundle-or-session>`
+ - start a local HTTP server for a preview viewer
+
+Useful flags:
+
+- `--open`
+- `--browser default|chromium|firefox`
+- `--app-mode`
+- `--poll-ms 500`
+- `--host 127.0.0.1`
+- `--port 0`
+
+### Harnesses
+
+Keep harness surfaces minimal and standardized:
+
+- `preview live start --recipe quick [--open]`
+- `preview live push`
+- `preview live stop`
+- `preview live status`
+
+Behavior:
+
+- `start` creates a live session and optionally opens the viewer window
+- `push` publishes a new preview state into the session
+- `stop` closes the session cleanly
+- `status` reports session path, viewer URL, and last update metadata
+
+The first implementation can make `push` explicit.
+
+Later, mutating commands can optionally trigger `push` automatically when a
+session is active.
+
+## Popup Window Strategy On Linux/Ubuntu
+
+This must support a normal Ubuntu terminal inside a desktop session.
+
+Recommended open order:
+
+1. `chromium --app=http://127.0.0.1:PORT/...`
+2. `google-chrome --app=...`
+3. `microsoft-edge --app=...`
+4. `firefox --new-window ...`
+5. `xdg-open ...`
+
+Rules:
+
+- if `DISPLAY` or `WAYLAND_DISPLAY` is set, `--open` may launch a popup window
+- if the machine is headless, do not fail the preview command just because a
+ popup cannot open
+- print the local URL and keep serving
+
+Why browser app mode is the recommended root solution:
+
+- no extra heavy GUI dependency in the repo
+- easy image/video/JSON layout
+- easy auto-refresh
+- simple Linux popup support from terminal
+- agents and humans can share the same viewer
+
+## Recommended Live Transport
+
+The simplest reliable approach is:
+
+- local HTTP server
+- polling-based viewer refresh first
+
+Recommended first pass:
+
+- viewer polls `session.json` every 500-1000 ms
+- if sequence number changes, reload manifest and updated assets
+
+Later upgrade path:
+
+- optional SSE or websocket push
+
+Do not start with websocket complexity unless polling becomes a real bottleneck.
+
+## How Each Software Fits
+
+### Shotcut / Openscreen
+
+Good candidates for live window preview.
+
+Live behavior:
+
+- regenerate low-res review clip
+- regenerate sampled frames/contact sheet
+- viewer auto-reloads clip and hero frames
+
+This is near-real-time, not frame-by-frame editing playback.
+
+### Blender
+
+Good candidate for live preview.
+
+Live behavior:
+
+- re-run fast Workbench or Eevee preview
+- publish hero still, alternate still, or turntable clip
+- viewer auto-refreshes images and metadata
+
+### FreeCAD
+
+Good candidate for live preview.
+
+Live behavior:
+
+- regenerate isometric/front/top/right images
+- viewer updates the 4-view layout
+
+This is especially strong for agent verification after geometric mutations.
+
+### RenderDoc
+
+RenderDoc is different.
+
+Live behavior should mean:
+
+- watch for newly selected capture/event state
+- refresh thumbnail/output-target/pipeline summaries
+
+It is not a continuous render monitor in the same sense as Blender or Shotcut.
+
+## Non-Goals For The First Live Window Version
+
+- no universal remote framebuffer streaming
+- no requirement for 60 FPS interactive playback
+- no per-harness custom desktop app
+- no mandatory Qt dependency for the whole repo
+
+## Phased Implementation Plan
+
+### Phase 1: Popup For Existing Bundles
+
+Goal:
+
+- open an existing preview bundle in a separate window from terminal
+
+Deliverables:
+
+- `cli-hub preview open`
+- browser app-mode launch on Linux/Ubuntu
+- headless fallback to URL output
+
+This is the fastest high-value step.
+
+### Phase 2: Live Session Protocol
+
+Goal:
+
+- let a viewer watch one stable session while bundles keep updating
+
+Deliverables:
+
+- `session.json`
+- `current/` + `history/`
+- `cli-hub preview watch`
+- polling-based live reload
+
+### Phase 3: Harness Integration
+
+Goal:
+
+- let the main preview-capable harnesses publish live updates
+
+Recommended first set:
+
+- `shotcut`
+- `openscreen`
+- `blender`
+- `freecad`
+
+RenderDoc should come after the live session machinery is stable.
+
+### Phase 4: Auto-Publish Hooks
+
+Goal:
+
+- when a live session is active, mutating commands publish a fresh preview
+ automatically
+
+This should be opt-in, because automatic preview generation can be expensive.
+
+## Recommended Immediate Next Step
+
+The next concrete move should be:
+
+- implement `cli-hub preview open`
+- implement `cli-hub preview watch`
+- use browser-window popup as the default Linux/Ubuntu strategy
+
+Reason:
+
+- this produces a real popup preview window quickly
+- it works for both agents and humans
+- it does not force any harness-specific GUI redesign
+- it composes cleanly with the existing bundle protocol
+
+## Bottom Line
+
+Yes, the preview system can support a separate live popup window.
+
+The correct root design is:
+
+- not "every harness owns a live monitor"
+- but "every harness publishes preview state, and `cli-hub` owns the live
+ popup viewer"
+
+That is the most generic, minimal, and extensible solution for CLI-Anything.
+
+## 2026-04-22: FreeCAD Motion CLI
+
+Status:
+
+- implemented a real `motion` command group for `cli-anything-freecad`
+- kept motion separate from preview/live preview
+- motion output is now `keyframes -> real FreeCAD GUI frame renders -> ffmpeg video`
+
+New CLI surface:
+
+- `motion new`
+- `motion list`
+- `motion get`
+- `motion delete`
+- `motion keyframe`
+- `motion sample`
+- `motion render-frames`
+- `motion render-video`
+
+Current scope:
+
+- target kind supported today: `part`
+- interpolation: linear position + Euler rotation interpolation between keyframes
+- camera presets: `hero`, `front`, `top`, `right`
+- fit modes: `initial`, `per-frame`
+- video formats: `mp4`, `webm`, `gif`
+
+Implementation notes:
+
+- new core module: [freecad/core/motion.py](/root/CLI-Anything-preview/freecad/agent-harness/cli_anything/freecad/core/motion.py)
+- FreeCAD sequence rendering is done in one GUI macro process, not one FreeCAD process per frame
+- frame directories now write a `sequence.json` manifest for later editing / reuse
+- this is a truthful frame-by-frame render path; it does not synthesize in-between motion frames
+
+Validation:
+
+- `test_core.py -k 'TestMotion or test_get_info'` -> `6 passed`
+- `test_full_e2e.py -k 'motion_render_frames_subprocess or motion_render_video_subprocess'` -> `2 passed`
+- targeted unit run including motion/bounds/align -> `9 passed`
+
+Real smoke artifact:
+
+- project: [/root/preview-artifacts/20260422/freecad-motion-smoke/project.json](/root/preview-artifacts/20260422/freecad-motion-smoke/project.json)
+- frames: [/root/preview-artifacts/20260422/freecad-motion-smoke/frames](/root/preview-artifacts/20260422/freecad-motion-smoke/frames)
+- video: [rollout.mp4](/root/preview-artifacts/20260422/freecad-motion-smoke/rollout.mp4)
+
+Current limitation:
+
+- motion currently animates part placements only
+- it does not yet drive FreeCAD Assembly joints / Simulation objects directly
+- it is enough for our current CLI-built rover/Curiosity-style showcase flow, but not yet a native joint-solver animation pipeline
+
+## 2026-04-22: Curiosity V6 True Motion Showcase
+
+Status:
+
+- connected the new FreeCAD `motion` CLI to the real `Curiosity v6` final project
+- added a reusable `motion-showcase` mode to [freecad_live_preview_demo.py](/root/CLI-Anything-preview/docs/scripts/freecad_live_preview_demo.py)
+- rendered a fully real frame-by-frame Curiosity showcase video
+
+New script path:
+
+- `python3 docs/scripts/freecad_live_preview_demo.py motion-showcase --timeline ... --output-dir ...`
+
+What it does:
+
+- loads the real final `Curiosity v6` project from the existing trajectory
+- adds the showcase stage geometry as real parts
+- writes `13` key poses into a real project `motions` collection
+- calls `cli-anything-freecad motion render-video`
+- preserves the real frame sequence and stills
+
+Artifact set:
+
+- motion project: [curiosity_true_motion.json](/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/curiosity_true_motion.json)
+- video: [curiosity_true_motion.mp4](/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/curiosity_true_motion.mp4)
+- manifest: [motion_manifest.json](/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/motion_manifest.json)
+- frames: [/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/frames](/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/frames)
+- stills:
+ [start.png](/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/stills/start.png)
+ [mid.png](/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/stills/mid.png)
+ [final.png](/root/preview-artifacts/20260422/freecad-curiosity-v6-true-motion/stills/final.png)
+
+Verification:
+
+- script `py_compile` passed
+- `motion-showcase` run completed successfully
+- output stats:
+ - duration: `6.0s`
+ - fps: `12`
+ - frame count: `73`
+ - file size: `315,872 bytes`
+
+Quality note:
+
+- this is now a truthful motion render path
+- the motion itself is still placement-driven rather than joint-solver-driven
+- visually, the rover translation and staged ground read correctly, but native wheel/rocker-bogie mechanism simulation is still future work
+
+## 2026-04-22: Curiosity Turntable Motion
+
+Status:
+
+- extended `motion-showcase` to support `--motion-style spin`
+- rendered a second real frame-by-frame Curiosity motion clip for rotation / turntable presentation
+
+Artifact set:
+
+- motion project: [curiosity_turntable_motion.json](/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/curiosity_turntable_motion.json)
+- video: [curiosity_turntable_motion.mp4](/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/curiosity_turntable_motion.mp4)
+- manifest: [motion_manifest.json](/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/motion_manifest.json)
+- frames: [/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/frames](/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/frames)
+- stills:
+ [start.png](/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/stills/start.png)
+ [mid.png](/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/stills/mid.png)
+ [final.png](/root/preview-artifacts/20260422/freecad-curiosity-v6-turntable-motion/stills/final.png)
+
+Verification:
+
+- script `py_compile` passed after the spin-mode changes
+- `motion-showcase --motion-style spin` completed successfully
+- output stats:
+ - duration: `7.0s`
+ - fps: `12`
+ - frame count: `85`
+ - file size: `719,298 bytes`
+- manual visual check of `start/mid/final` confirms a genuine turntable-style rotation view change
+
+Quality note:
+
+- this is a true rendered turntable, not a sparse-pose blend
+- it still uses placement-driven motion rather than FreeCAD Assembly/Robot mechanism simulation
diff --git a/docs/PREVIEW_PROTOCOL.md b/docs/PREVIEW_PROTOCOL.md
new file mode 100644
index 000000000..f2940792f
--- /dev/null
+++ b/docs/PREVIEW_PROTOCOL.md
@@ -0,0 +1,791 @@
+# Preview Protocol
+
+This document proposes a minimal, cross-harness protocol for previewing
+intermediate results in CLI-Anything workflows.
+
+The short version:
+
+- Every participating harness emits a standard `Preview Bundle`.
+- A bundle is just a directory with a `manifest.json`, a `summary.json`, and
+ preview artifacts such as images, clips, JSON dumps, or model files.
+- Harnesses still use the real software for rendering. The protocol standardizes
+ the preview artifact contract, not the renderer.
+- `cli-hub` becomes the generic viewer/inspector for bundles, instead of every
+ harness inventing its own monitor UI.
+
+This gives agents and humans one stable way to consume intermediate outputs
+across video, CAD, 3D, GPU debugging, and similar workflows.
+
+## Why This Exists
+
+CLI-Anything already has strong rules for final rendering:
+
+- use the real software
+- manipulate native formats
+- verify real output files
+
+What it does not yet have is a cross-harness protocol for intermediate visual
+feedback.
+
+Today, preview-related capability exists in many local forms:
+
+- video thumbnail extraction
+- screenshot export
+- render presets
+- capture thumbnails
+- output-target dumps
+
+But these are app-local commands. They do not produce a uniform artifact shape
+that an agent runtime, `cli-hub`, or a future host UI can consume in the same
+way across tools.
+
+The missing abstraction is not "a universal monitor widget". The missing
+abstraction is "a universal preview artifact protocol".
+
+## Design Goals
+
+1. Keep the rendering path honest.
+ Previews must still come from the real software, its real backend, or its
+ real project format. No toy reimplementation of the app's renderer.
+2. Be generic across domains.
+ The same protocol should handle video timelines, CAD views, Blender renders,
+ RenderDoc outputs, and similar cases.
+3. Be cheap enough to use often.
+ Previews should be fast, low-resolution, cacheable, and small enough for
+ agent loops.
+4. Be simple enough to adopt incrementally.
+ A harness should be able to add preview support with one command group and a
+ small helper, not a new frontend app.
+5. Work in headless environments.
+ Bundle generation and validation must not require a GUI.
+
+## Non-Goals
+
+- This is not a replacement for final render/export.
+- This is not a live remote framebuffer or GUI streaming protocol.
+- This does not require every harness to support interactive timeline scrubbing.
+- This does not force one preview artifact type. Different apps may emit
+ images, clips, JSON, or multiple artifacts together.
+
+## Core Model
+
+The protocol has three layers:
+
+1. Harness layer
+ The harness generates real preview artifacts and writes a `Preview Bundle`.
+2. Viewer layer
+ `cli-hub` reads any compliant bundle and renders a generic inspection view.
+3. Host/runtime layer
+ An agent host may decide to attach selected bundle artifacts back into model
+ context, but this is outside the harness itself.
+
+The central object is the `Preview Bundle`.
+
+## Preview Bundle
+
+A preview bundle is a directory with a small, stable layout:
+
+```text
+<bundle_dir>/
+ manifest.json
+ summary.json
+ artifacts/
+ hero.png
+ gallery_01.png
+ gallery_02.png
+ preview.mp4
+ pipeline_diff.json
+```
+
+`manifest.json` is the machine contract.
+
+`summary.json` is the human/agent summary.
+
+`artifacts/` contains preview outputs generated by the real software or by
+native tools that inspect those real outputs.
+
+## Default Bundle Location
+
+When a project path is known:
+
+```text
+<project_dir>/.cli-anything/previews/<software>/<recipe>/<bundle_id>/
+```
+
+When there is no stable project path yet:
+
+```text
+~/.cli-anything/previews/<software>/<recipe>/<bundle_id>/
+```
+
+Rationale:
+
+- preview artifacts stay near the project when possible
+- bundles are easy to garbage-collect
+- `cli-hub` can scan a predictable root
+
+## Bundle ID
+
+Recommended bundle id:
+
+```text
+<UTC timestamp>_<short fingerprint>_<recipe>
+```
+
+Example:
+
+```text
+20260419T104530Z_9f0a2c4b_quick
+```
+
+The fingerprint should be derived from:
+
+- project fingerprint or capture fingerprint
+- recipe name
+- normalized preview args
+- harness version
+- protocol version
+
+This makes bundles cacheable and reproducible.
+
+## Manifest Schema
+
+Required top-level fields:
+
+| Field | Type | Notes |
+|---|---|---|
+| `protocol_version` | string | Start with `preview-bundle/v1` |
+| `bundle_id` | string | Stable id for this bundle |
+| `bundle_kind` | string | `capture` or `diff` |
+| `software` | string | Harness name, e.g. `shotcut` |
+| `recipe` | string | Harness recipe name, e.g. `quick`, `quad`, `turntable` |
+| `status` | string | `ok`, `partial`, or `error` |
+| `created_at` | string | ISO-8601 UTC |
+| `generator` | object | CLI command, harness version, backend info |
+| `source` | object | Project/capture identity and fingerprint |
+| `artifacts` | array | Preview artifact descriptors |
+| `summary_path` | string | Relative path to `summary.json` |
+
+Recommended optional fields:
+
+| Field | Type | Notes |
+|---|---|---|
+| `source_bundles` | array | For diff bundles |
+| `context` | object | App-specific context, e.g. event id, frame, camera |
+| `warnings` | array | Non-fatal warnings |
+| `metrics` | object | Cheap summary metrics |
+| `labels` | array | Tags for host-side filtering |
+
+### Manifest Example
+
+```json
+{
+ "protocol_version": "preview-bundle/v1",
+ "bundle_id": "20260419T104530Z_9f0a2c4b_quick",
+ "bundle_kind": "capture",
+ "software": "shotcut",
+ "recipe": "quick",
+ "status": "ok",
+ "created_at": "2026-04-19T10:45:30Z",
+ "generator": {
+ "entry_point": "cli-anything-shotcut",
+ "harness_version": "1.0.0",
+ "command": "cli-anything-shotcut --json -p demo.mlt preview capture --recipe quick"
+ },
+ "source": {
+ "project_path": "/work/demo.mlt",
+ "project_fingerprint": "sha256:3a0d6f...",
+ "session_id": "abc123"
+ },
+ "context": {
+ "timeline_duration_s": 42.1
+ },
+ "metrics": {
+ "video_tracks": 2,
+ "audio_tracks": 1,
+ "filters": 7
+ },
+ "summary_path": "summary.json",
+ "artifacts": [
+ {
+ "artifact_id": "hero",
+ "role": "hero",
+ "kind": "image",
+ "label": "Midpoint frame",
+ "media_type": "image/png",
+ "path": "artifacts/hero.png",
+ "width": 960,
+ "height": 540,
+ "bytes": 184220
+ },
+ {
+ "artifact_id": "clip",
+ "role": "preview-clip",
+ "kind": "clip",
+ "label": "Low-res preview render",
+ "media_type": "video/mp4",
+ "path": "artifacts/preview.mp4",
+ "width": 640,
+ "height": 360,
+ "duration_s": 6.0,
+ "bytes": 2419001
+ }
+ ]
+}
+```
+
+## Summary Schema
+
+`summary.json` should stay compact and cheap to parse.
+
+Recommended shape:
+
+```json
+{
+ "headline": "6-second quick preview rendered successfully",
+ "facts": {
+ "duration_s": 42.1,
+ "resolution": "640x360",
+ "recipe": "quick"
+ },
+ "warnings": [],
+ "next_actions": [
+ "Inspect the preview clip for pacing and transitions",
+ "Use final export only after timeline review passes"
+ ]
+}
+```
+
+The viewer should render `headline`, `facts`, and `warnings` first.
+
+## Artifact Descriptor
+
+Each artifact entry in `manifest.json` should use relative paths and carry enough
+metadata for a generic viewer to render a sensible page without probing files.
+
+Required artifact fields:
+
+| Field | Type | Notes |
+|---|---|---|
+| `artifact_id` | string | Unique inside bundle |
+| `role` | string | Semantic role |
+| `kind` | string | `image`, `clip`, `json`, `model`, `capture`, `text` |
+| `media_type` | string | MIME-like type |
+| `path` | string | Relative path from bundle root |
+| `label` | string | Short display label |
+
+Recommended fields:
+
+| Field | Type | Notes |
+|---|---|---|
+| `width` / `height` | int | For images and video |
+| `duration_s` | number | For clips |
+| `bytes` | int | For size display |
+| `view` | string | `iso`, `front`, `top`, `right`, etc. |
+| `event_id` | int | For RenderDoc-like outputs |
+| `tags` | array | Search/filter tags |
+
+## Standard Artifact Roles
+
+The role vocabulary matters more than the exact file type.
+
+Recommended roles:
+
+| Role | Meaning |
+|---|---|
+| `hero` | Best single preview artifact for quick inspection |
+| `gallery` | One of several related visual previews |
+| `preview-clip` | Short low-res video preview |
+| `before` | Baseline artifact in a diff bundle |
+| `after` | Target artifact in a diff bundle |
+| `diff-json` | Machine diff payload |
+| `pipeline-json` | Structured pipeline/debug state |
+| `viewport` | A specific camera/view output |
+| `render-output` | Output target or rendered frame |
+| `thumb` | Capture or media thumbnail |
+
+The viewer should not assume a bundle has only one artifact.
+
+## Performance Budget
+
+Previews should be cheap enough to generate inside an agent loop.
+
+Recommended defaults:
+
+- hero image: longest side <= 1280 px
+- gallery images: 3 to 8 images
+- preview clip: <= 8 seconds, <= 720p
+- bundle size target: <= 25 MB
+
+These are targets, not hard protocol limits. Larger bundles are allowed, but the
+default recipes should stay cheap.
+
+## Rendering Rule
+
+The same rendering rule as the rest of CLI-Anything still applies:
+
+- use the real software or real backend for rendering
+- use native project formats
+- do not quietly replace the app's renderer with a toy Python version
+
+What is allowed:
+
+- use the real app or backend to create a low-res preview
+- use `ffmpeg`, RenderDoc APIs, or similar native tools to extract frames or
+ dump outputs from a real render
+- package those results into a bundle
+
+What is not allowed:
+
+- inventing a fake renderer to approximate the app's preview behavior
+- screenshotting an unrelated GUI window as the only source of truth
+
+## Standard CLI Surface
+
+Participating harnesses should expose a top-level `preview` group.
+
+Recommended commands:
+
+### `preview recipes`
+
+Lists supported recipes and what each emits.
+
+Example:
+
+```bash
+cli-anything-shotcut preview recipes
+```
+
+### `preview capture`
+
+Generates a fresh or cached preview bundle.
+
+Recommended options:
+
+- `--recipe <name>`
+- `--output-dir <path>`
+- `--force`
+- `--label <text>`
+
+JSON mode should return at least:
+
+- `bundle_dir`
+- `manifest_path`
+- `status`
+- `artifact_count`
+
+### `preview latest`
+
+Returns the latest successful bundle for the current project and optional recipe.
+
+### `preview diff`
+
+Recommended for domains with meaningful before/after or event/event comparison.
+Not every harness must implement this in v1, but the protocol supports it.
+
+## Caching Rules
+
+`preview capture` may return a cached bundle if:
+
+- the project/capture fingerprint is unchanged
+- recipe and normalized preview args are unchanged
+- protocol version is unchanged
+- the bundle is still present on disk
+
+`--force` must bypass the cache and generate a new bundle.
+
+`preview latest` returns the newest successful bundle by timestamp.
+
+## Portability Rules
+
+- artifact paths in `manifest.json` must be relative to bundle root
+- bundle files must be immutable once written
+- `summary.json` and `manifest.json` must be UTF-8 JSON
+- absolute project paths are allowed in `source`, but viewer logic must not rely
+ on them to render the bundle
+
+## Host/Agent Contract
+
+The protocol solves the artifact contract. A host runtime may do more.
+
+Recommended host behavior:
+
+1. Read `manifest.json` first.
+2. Render `summary.json`.
+3. Prefer displaying, or attaching back into model context, artifacts in this
+ order:
+ - `hero`
+ - `gallery`
+ - `preview-clip`
+ - `before` / `after`
+ - `diff-json` / `pipeline-json`
+4. If binary attachment is unavailable, at least expose file paths and summary.
+
+This is the root simplification: the agent does not need app-specific preview
+logic. It only needs bundle-aware preview logic.
+
+## Generic Viewer
+
+The generic viewer should live in `cli-hub`.
+
+Minimal viewer commands for v1:
+
+- `cli-hub preview inspect <bundle-or-manifest>`
+- `cli-hub preview html <bundle-or-manifest> [-o output.html]`
+
+`inspect` prints:
+
+- bundle metadata
+- source identity
+- summary headline/facts/warnings
+- artifact table
+
+`html` writes a static HTML page that:
+
+- shows the summary first
+- renders image galleries from `hero` and `gallery` artifacts
+- embeds playable `<video>` elements for `preview-clip`
+- links to JSON artifacts for detailed inspection
+
+This viewer is intentionally generic. It does not know what Shotcut, FreeCAD,
+Blender, or RenderDoc "mean". It only knows bundle roles and artifact kinds.
+
+## Testing Requirements
+
+Any harness that adopts the protocol should add:
+
+### Unit Tests
+
+- bundle writer path normalization
+- manifest generation
+- recipe listing
+- cache key stability
+
+### E2E Tests
+
+- generate a real preview bundle with the real backend
+- verify `manifest.json` and `summary.json` exist
+- verify every artifact path listed in the manifest exists
+- verify at least one visual artifact exists
+- verify JSON output includes `manifest_path`
+
+For diff-capable harnesses:
+
+- verify diff bundle references source bundles or source refs
+- verify the diff JSON artifact exists
+
+## Implementation Pattern For Existing Harnesses
+
+This repo already has one proven "copy canonical helper into harness" pattern:
+`repl_skin.py`.
+
+The preview protocol should follow the same approach in v1:
+
+- canonical helper lives in `cli-anything-plugin/`
+- pilot harnesses vendor-copy a small helper as `utils/preview_bundle.py`
+- the helper handles:
+ - bundle directory creation
+ - manifest writing
+ - summary writing
+ - relative artifact descriptors
+ - cache key generation
+
+This avoids introducing a new shared runtime dependency across all harness
+packages.
+
+## Initial 4-PR Plan
+
+The first implementation should be split into four practical PRs.
+
+### PR1: Foundation - Protocol, Helper, and Generic Viewer
+
+Goal:
+
+- establish the protocol and a reusable bundle writer
+- make `cli-hub` able to inspect any compliant bundle
+
+Scope:
+
+- add this document
+- add canonical helper under `cli-anything-plugin/`
+- update `cli-anything-plugin/HARNESS.md` with preview requirements
+- add `cli-hub` preview inspection commands
+
+Concrete file plan:
+
+- `docs/PREVIEW_PROTOCOL.md`
+- `cli-anything-plugin/preview_bundle.py`
+- `cli-anything-plugin/HARNESS.md`
+- `cli-hub/cli_hub/preview.py`
+- `cli-hub/cli_hub/cli.py`
+- `cli-hub/tests/test_cli_hub.py`
+
+Concrete behavior:
+
+- `cli-hub preview inspect <bundle>`
+ prints manifest metadata, summary, and artifact inventory
+- `cli-hub preview html <bundle> -o page.html`
+ writes a static HTML page with summary + gallery + video embedding
+
+Why this works:
+
+- it does not depend on any specific harness
+- it gives immediate value as soon as the first pilot bundle exists
+
+Acceptance criteria:
+
+- a sample bundle can be inspected by `cli-hub`
+- the HTML viewer renders images and videos using only manifest metadata
+- `HARNESS.md` tells future harnesses how to adopt preview support
+
+Out of scope:
+
+- no live preview streaming
+- no harness-specific rendering logic here
+
+### PR2: Video Pilot - Shotcut and Openscreen
+
+Goal:
+
+- prove that video editors can produce standard preview bundles cheaply
+
+Scope:
+
+- add `preview` support to `shotcut`
+- add `preview` support to `openscreen`
+
+Concrete file plan:
+
+- `shotcut/agent-harness/cli_anything/shotcut/utils/preview_bundle.py`
+- `shotcut/agent-harness/cli_anything/shotcut/core/preview.py`
+- `shotcut/agent-harness/cli_anything/shotcut/shotcut_cli.py`
+- `shotcut/agent-harness/cli_anything/shotcut/tests/test_core.py`
+- `shotcut/agent-harness/cli_anything/shotcut/tests/test_full_e2e.py`
+- `openscreen/agent-harness/cli_anything/openscreen/utils/preview_bundle.py`
+- `openscreen/agent-harness/cli_anything/openscreen/core/preview.py`
+- `openscreen/agent-harness/cli_anything/openscreen/openscreen_cli.py`
+- `openscreen/agent-harness/cli_anything/openscreen/tests/test_core.py`
+- `openscreen/agent-harness/cli_anything/openscreen/tests/test_full_e2e.py`
+
+Shotcut workable MVP design:
+
+- command: `cli-anything-shotcut preview capture --recipe quick`
+- recipe `quick` does:
+ - low-res render using existing `core/export.py`
+ - default preset: `h264-fast`
+ - default size: `640x360`
+ - extract 5 PNG frames from the rendered clip at fixed percentages
+ - choose the midpoint frame as `hero`
+ - write summary with timeline duration, track counts, and filter counts
+- command: `preview recipes`
+ lists `quick`
+- command: `preview latest`
+ returns the latest bundle path
+
+Existing code it reuses:
+
+- render path in [core/export.py](/root/CLI-Anything/shotcut/agent-harness/cli_anything/shotcut/core/export.py:369)
+- thumbnail extraction in [core/media.py](/root/CLI-Anything/shotcut/agent-harness/cli_anything/shotcut/core/media.py:189)
+
+Openscreen workable MVP design:
+
+- command: `cli-anything-openscreen preview capture --recipe quick`
+- recipe `quick` does:
+ - low-res render via existing `core/export.render()`
+ - extract 5 PNG frames at 0%, 25%, 50%, 75%, and 95%
+ - midpoint frame becomes `hero`
+ - summary includes source duration, zoom region count, speed region count,
+ and trim region count
+
+Existing code it reuses:
+
+- export path in [core/export.py](/root/CLI-Anything/openscreen/agent-harness/cli_anything/openscreen/core/export.py:52)
+- frame extraction in [core/media.py](/root/CLI-Anything/openscreen/agent-harness/cli_anything/openscreen/core/media.py:41)
+
+Why this works:
+
+- both harnesses already have real render pipelines
+- both already know how to extract thumbnails
+- the only new layer is bundle assembly and command wiring
+
+Acceptance criteria:
+
+- both harnesses emit valid bundles for a real project
+- `cli-hub preview inspect` can read them
+- the HTML viewer shows the gallery and preview clip without app-specific code
+
+Out of scope:
+
+- no per-cut diffing in this PR
+- no contact-sheet composition requirement
+
+### PR3: 3D/CAD Pilot - Blender and FreeCAD
+
+Goal:
+
+- prove the protocol works for still renders, multiple standard views, and 3D
+ scene review
+
+Scope:
+
+- add `preview` support to `blender`
+- add `preview` support to `freecad`
+
+Concrete file plan:
+
+- `blender/agent-harness/cli_anything/blender/utils/preview_bundle.py`
+- `blender/agent-harness/cli_anything/blender/core/preview.py`
+- `blender/agent-harness/cli_anything/blender/blender_cli.py`
+- `blender/agent-harness/cli_anything/blender/tests/test_core.py`
+- `blender/agent-harness/cli_anything/blender/tests/test_full_e2e.py`
+- `freecad/agent-harness/cli_anything/freecad/utils/preview_bundle.py`
+- `freecad/agent-harness/cli_anything/freecad/core/preview.py`
+- `freecad/agent-harness/cli_anything/freecad/utils/freecad_backend.py`
+- `freecad/agent-harness/cli_anything/freecad/freecad_cli.py`
+- `freecad/agent-harness/cli_anything/freecad/tests/test_core.py`
+- `freecad/agent-harness/cli_anything/freecad/tests/test_full_e2e.py`
+
+Blender workable MVP design:
+
+- command: `cli-anything-blender preview capture --recipe quick`
+- recipe `quick` does:
+ - apply `eevee_preview` or `workbench` style render settings
+ - render one still image at low resolution
+ - use the current frame or an explicit `--frame`
+ - write summary with engine, resolution, active camera, object count
+
+Preferred implementation detail:
+
+- generate bpy script using existing render code
+- execute it with the real Blender backend, not just script generation
+
+Existing code it reuses:
+
+- render presets documented in [BLENDER.md](/root/CLI-Anything/blender/agent-harness/BLENDER.md:64)
+- render configuration in [core/scene.py](/root/CLI-Anything/blender/agent-harness/cli_anything/blender/core/scene.py:12)
+- script generation in [core/render.py](/root/CLI-Anything/blender/agent-harness/cli_anything/blender/core/render.py:182)
+- real headless execution in [utils/blender_backend.py](/root/CLI-Anything/blender/agent-harness/cli_anything/blender/utils/blender_backend.py:37)
+
+FreeCAD workable MVP design:
+
+- command: `cli-anything-freecad preview capture --recipe quick`
+- command: `cli-anything-freecad preview capture --recipe quad`
+- recipe `quick` does:
+ - export one low-res isometric PNG
+- recipe `quad` does:
+ - export four PNGs: `iso`, `front`, `top`, `right`
+ - mark `iso` as `hero`
+ - mark the four views as `gallery`
+ - write summary with document name, object count, and bounding-box metrics if
+ available
+
+Implementation detail:
+
+- extend the FreeCAD macro/backend path for `png` and `jpg` export with an
+ explicit standard-view option
+- do not add a GUI dependency; the macro should set the desired view itself
+
+Existing code it reuses:
+
+- image export support in [core/export.py](/root/CLI-Anything/freecad/agent-harness/cli_anything/freecad/core/export.py:86)
+- export CLI in [freecad_cli.py](/root/CLI-Anything/freecad/agent-harness/cli_anything/freecad/freecad_cli.py:1920)
+
+Why this works:
+
+- Blender already has low-cost preview presets
+- FreeCAD already exports rendered PNG/JPG
+- the viewer can show multi-view galleries without requiring an app-specific
+ viewport widget
+
+Acceptance criteria:
+
+- Blender quick preview emits a real PNG bundle
+- FreeCAD quick and quad previews emit real PNG bundles
+- the generic viewer shows Blender as a hero image and FreeCAD as a gallery
+
+Out of scope:
+
+- no fully interactive camera orbit viewer
+- no mesh viewer in the browser for v1
+
+### PR4: GPU Debug Pilot - RenderDoc
+
+Goal:
+
+- prove the protocol also works for non-DCC visual inspection workflows
+
+Scope:
+
+- add `preview capture` and `preview diff` to `renderdoc`
+
+Concrete file plan:
+
+- `renderdoc/agent-harness/cli_anything/renderdoc/utils/preview_bundle.py`
+- `renderdoc/agent-harness/cli_anything/renderdoc/core/preview.py`
+- `renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py`
+- `renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py`
+- `renderdoc/agent-harness/cli_anything/renderdoc/tests/test_full_e2e.py`
+
+RenderDoc workable MVP design:
+
+- command:
+ `cli-anything-renderdoc -c frame.rdc preview capture --event-id 123`
+- capture recipe does:
+ - extract capture thumbnail
+ - save render target outputs at the target event
+ - dump pipeline state JSON for the same event
+ - write summary with API, event id, output count, viewport size
+
+- command:
+ `cli-anything-renderdoc -c frame.rdc preview diff --event-a 100 --event-b 200`
+- diff recipe does:
+ - run existing pipeline diff JSON
+ - save output targets for `event-a`
+ - save output targets for `event-b`
+ - mark output images from A as `before`
+ - mark output images from B as `after`
+ - attach diff JSON as `diff-json`
+
+Existing code it reuses:
+
+- capture thumbnail in [renderdoc_cli.py](/root/CLI-Anything/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py:178)
+- output target dumping in [renderdoc_cli.py](/root/CLI-Anything/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py:340)
+- pipeline diff in [renderdoc_cli.py](/root/CLI-Anything/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py:761)
+
+Why this works:
+
+- RenderDoc already has the hard parts: thumbnail extraction, output saving, and
+ structured diff
+- the bundle simply packages these under one viewer-readable contract
+
+Acceptance criteria:
+
+- given a real `.rdc` file and event id, the harness emits a valid bundle
+- the viewer shows the thumbnail and output galleries
+- diff bundles include both sides plus the JSON diff payload
+
+Out of scope:
+
+- no shader-side visual heatmap generation in v1
+- no browser-side replay
+
+## Recommended Adoption Order After The First 4 PRs
+
+Once the four PRs above land, the next wave should target:
+
+- `kdenlive`, because it can reuse most of the Shotcut preview logic
+- `godot`, because it is already listed as a preview-capable provider in the
+ matrix
+- `krita`, because frame/image preview is already natural there
+
+## Decision Summary
+
+The protocol is intentionally simple:
+
+- standardize preview artifacts, not app-specific viewers
+- use real software for preview generation
+- make previews cheap, cacheable, and inspectable
+- centralize preview consumption in `cli-hub`
+
+That is the generic, compact, and practical path that should scale across the
+repo.
diff --git a/docs/scripts/freecad_live_preview_demo.py b/docs/scripts/freecad_live_preview_demo.py
new file mode 100644
index 000000000..188dce7c0
--- /dev/null
+++ b/docs/scripts/freecad_live_preview_demo.py
@@ -0,0 +1,4971 @@
+#!/usr/bin/env python3
+"""Collect and render a real FreeCAD live-preview demo video.
+
+This script has two phases:
+
+1. ``collect`` runs a real CLI trajectory against ``cli-anything-freecad``,
+ starts poll-mode live preview, waits for real preview bundles to update,
+ and saves a structured timeline plus copied preview snapshots.
+2. ``render`` turns that real timeline into an editable split-screen MP4:
+ terminal trajectory on the left, preview window on the right.
+
+The composition is programmatic, but the commands, outputs, timing, and preview
+artifacts are all captured from real execution.
+"""
+
+from __future__ import annotations
+
+import argparse
+import copy
+import json
+import math
+import os
+import shutil
+import subprocess
+import sys
+import textwrap
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from PIL import Image, ImageDraw, ImageFont
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+FREECAD_WORKDIR = REPO_ROOT / "freecad" / "agent-harness"
+CLI_HUB_WORKDIR = REPO_ROOT / "cli-hub"
+FREECAD_CLI = shutil.which("cli-anything-freecad") or "cli-anything-freecad"
+CLI_HUB = shutil.which("cli-hub") or "cli-hub"
+MONO_FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"
+MONO_BOLD_FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"
+SANS_FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
+DISPLAY_FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSansCondensed-Bold.ttf"
+
+VIDEO_W = 1600
+VIDEO_H = 900
+LEFT_W = 650
+RIGHT_W = VIDEO_W - LEFT_W
+FPS = 12
+HOLD_TAIL_S = 2.5
+DEFAULT_WAIT_TIMEOUT_S = 90.0
+SHOWCASE_FRAME_COUNT = 12
+SHOWCASE_DURATION_S = 7.0
+SHOWCASE_HOLD_S = 1.1
+TRUE_MOTION_DURATION_S = 6.0
+TRUE_MOTION_KEYFRAME_COUNT = 13
+SPIN_MOTION_DURATION_S = 7.0
+SPIN_MOTION_KEYFRAME_COUNT = 19
+COMBO_MOTION_DURATION_S = 9.0
+COMBO_MOTION_KEYFRAME_COUNT = 25
+
+COLORS = {
+ "bg_top": "#030b16",
+ "bg_bottom": "#081a2d",
+ "grid": "#14314d",
+ "grid_soft": "#0d2338",
+ "panel": "#0b1522",
+ "panel_soft": "#101d2f",
+ "panel_line": "#224667",
+ "panel_glow": "#2de2c5",
+ "terminal_bg": "#07111b",
+ "terminal_text": "#d9e7f5",
+ "terminal_muted": "#6d839c",
+ "terminal_success": "#8bf0c8",
+ "terminal_error": "#ff8f98",
+ "terminal_cmd": "#7ed6ff",
+ "terminal_json": "#f7d488",
+ "preview_shell": "#0b1220",
+ "preview_stage": "#efe7da",
+ "preview_stage_edge": "#cabca8",
+ "preview_text": "#f2f5f8",
+ "preview_muted": "#9fb2c8",
+ "chip_bg": "#11263a",
+ "chip_text": "#dfeaf5",
+ "accent": "#23d7bb",
+ "accent_warm": "#ff8a57",
+ "accent_soft": "#173f40",
+ "paper": "#f7f2ea",
+ "paper_line": "#d2c6b5",
+ "white": "#ffffff",
+}
+
+
+def _taipei_101_steps() -> List[Dict[str, Any]]:
+ """Return a more legible tiny Taipei 101 build trajectory."""
+ steps: List[Dict[str, Any]] = [
+ {
+ "id": "create-project",
+ "label": "Create FreeCAD project",
+ "argv": ["document", "new", "--name", "Taipei101", "-o", "{project_path}"],
+ "wait_preview": False,
+ },
+ {
+ "id": "start-live-preview",
+ "label": "Start poll-mode live preview",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "preview",
+ "live",
+ "start",
+ "--recipe",
+ "quick",
+ "--mode",
+ "poll",
+ "--source-poll-ms",
+ "500",
+ "--poll-ms",
+ "700",
+ "--root-dir",
+ "{live_root}",
+ ],
+ "wait_preview": True,
+ "manual_session_payload": True,
+ },
+ {
+ "id": "podium",
+ "label": "Add podium",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "Podium",
+ "-P",
+ "length=58",
+ "-P",
+ "width=46",
+ "-P",
+ "height=16",
+ "-pos",
+ "-29,-23,0",
+ ],
+ "wait_preview": True,
+ },
+ ]
+
+ z = 16.0
+ for index in range(8):
+ module_no = index + 1
+ core_len = 24.0 - index * 1.3
+ core_w = 15.0 - index * 0.5
+ core_h = 8.4
+ arm_w = max(5.0, core_w - 7.0)
+ arm_h = 1.8
+ arm_lo_len = core_len + 8.0
+ arm_hi_len = core_len + 12.0
+
+ steps.append(
+ {
+ "id": f"module-{module_no}",
+ "label": f"Add tower module {module_no}",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ f"Core{module_no}",
+ "-P",
+ f"length={core_len:.2f}",
+ "-P",
+ f"width={core_w:.2f}",
+ "-P",
+ f"height={core_h:.2f}",
+ "-pos",
+ f"{-core_len / 2:.2f},{-core_w / 2:.2f},{z:.2f}",
+ ],
+ "wait_preview": True,
+ }
+ )
+ steps.append(
+ {
+ "id": f"arm-low-{module_no}",
+ "label": f"Add lower shoulder {module_no}",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ f"ArmLo{module_no}",
+ "-P",
+ f"length={arm_lo_len:.2f}",
+ "-P",
+ f"width={arm_w:.2f}",
+ "-P",
+ f"height={arm_h:.2f}",
+ "-pos",
+ f"{-arm_lo_len / 2:.2f},{-arm_w / 2:.2f},{z + 2.0:.2f}",
+ ],
+ "wait_preview": True,
+ }
+ )
+ steps.append(
+ {
+ "id": f"arm-high-{module_no}",
+ "label": f"Add upper shoulder {module_no}",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ f"ArmHi{module_no}",
+ "-P",
+ f"length={arm_hi_len:.2f}",
+ "-P",
+ f"width={arm_w:.2f}",
+ "-P",
+ f"height={arm_h:.2f}",
+ "-pos",
+ f"{-arm_hi_len / 2:.2f},{-arm_w / 2:.2f},{z + 5.1:.2f}",
+ ],
+ "wait_preview": True,
+ }
+ )
+ z += core_h
+
+ steps.extend(
+ [
+ {
+ "id": "crown",
+ "label": "Add crown block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "Crown",
+ "-P",
+ "length=9",
+ "-P",
+ "width=9",
+ "-P",
+ "height=8",
+ "-pos",
+ f"-4.5,-4.5,{z:.2f}",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "spire-lower",
+ "label": "Add lower spire",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "SpireLower",
+ "-P",
+ "radius=1.8",
+ "-P",
+ "height=14",
+ "-pos",
+ f"0,0,{z + 8.0:.2f}",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "spire-upper",
+ "label": "Add upper spire",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "SpireUpper",
+ "-P",
+ "radius=1.0",
+ "-P",
+ "height=12",
+ "-pos",
+ f"0,0,{z + 22.0:.2f}",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "spire-tip",
+ "label": "Add spire tip",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cone",
+ "--name",
+ "SpireTip",
+ "-P",
+ "radius1=1.5",
+ "-P",
+ "radius2=0.18",
+ "-P",
+ "height=11",
+ "-pos",
+ f"0,0,{z + 34.0:.2f}",
+ ],
+ "wait_preview": True,
+ },
+ ]
+ )
+ return steps
+
+
+def _mars_rover_steps() -> List[Dict[str, Any]]:
+ """Return a modular Mars rover build trajectory tuned for live preview."""
+ return [
+ {
+ "id": "create-project",
+ "label": "Create FreeCAD project",
+ "argv": ["document", "new", "--name", "MarsRover", "-o", "{project_path}"],
+ "wait_preview": False,
+ },
+ {
+ "id": "start-live-preview",
+ "label": "Start poll-mode live preview",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "preview",
+ "live",
+ "start",
+ "--recipe",
+ "quick",
+ "--mode",
+ "poll",
+ "--source-poll-ms",
+ "500",
+ "--poll-ms",
+ "700",
+ "--root-dir",
+ "{live_root}",
+ ],
+ "wait_preview": True,
+ "manual_session_payload": True,
+ },
+ {
+ "id": "chassis-belly",
+ "label": "Add chassis belly",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "ChassisBelly",
+ "-P",
+ "length=72",
+ "-P",
+ "width=28",
+ "-P",
+ "height=6",
+ "-pos",
+ "-36,-14,24",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "deck-module",
+ "label": "Add upper deck module",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "DeckModule",
+ "-P",
+ "length=46",
+ "-P",
+ "width=24",
+ "-P",
+ "height=7",
+ "-pos",
+ "-14,-12,30",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "rear-power-pack",
+ "label": "Add rear power pack",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RearPowerPack",
+ "-P",
+ "length=24",
+ "-P",
+ "width=22",
+ "-P",
+ "height=14",
+ "-pos",
+ "-34,-11,37",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "front-bumper",
+ "label": "Add front bumper",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "FrontBumper",
+ "-P",
+ "length=12",
+ "-P",
+ "width=24",
+ "-P",
+ "height=3",
+ "-pos",
+ "28,-12,25",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-rocker",
+ "label": "Add left suspension beam",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftRocker",
+ "-P",
+ "length=72",
+ "-P",
+ "width=4",
+ "-P",
+ "height=3",
+ "-pos",
+ "-36,-17,20",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-front-wheel",
+ "label": "Add left front wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "LeftFrontWheel",
+ "-P",
+ "radius=12",
+ "-P",
+ "height=6",
+ "-pos",
+ "24,-20,12",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-mid-wheel",
+ "label": "Add left middle wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "LeftMidWheel",
+ "-P",
+ "radius=13",
+ "-P",
+ "height=6",
+ "-pos",
+ "0,-20,12",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-rear-wheel",
+ "label": "Add left rear wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "LeftRearWheel",
+ "-P",
+ "radius=12",
+ "-P",
+ "height=6",
+ "-pos",
+ "-26,-20,12",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-front-wheel",
+ "label": "Mirror right front wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "mirror",
+ "5",
+ "--plane",
+ "XZ",
+ "--name",
+ "RightFrontWheel",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-mid-wheel",
+ "label": "Mirror right middle wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "mirror",
+ "6",
+ "--plane",
+ "XZ",
+ "--name",
+ "RightMidWheel",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-rear-wheel",
+ "label": "Mirror right rear wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "mirror",
+ "7",
+ "--plane",
+ "XZ",
+ "--name",
+ "RightRearWheel",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-rocker",
+ "label": "Mirror right suspension beam",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "mirror",
+ "4",
+ "--plane",
+ "XZ",
+ "--name",
+ "RightRocker",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "mast-base",
+ "label": "Add mast base",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "MastBase",
+ "-P",
+ "radius=3.6",
+ "-P",
+ "height=12",
+ "-pos",
+ "8,0,37",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "mast-neck",
+ "label": "Add camera mast",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "MastNeck",
+ "-P",
+ "radius=1.7",
+ "-P",
+ "height=26",
+ "-pos",
+ "8,0,49",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "camera-head",
+ "label": "Add camera head",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "CameraHead",
+ "-P",
+ "length=16",
+ "-P",
+ "width=8",
+ "-P",
+ "height=7",
+ "-pos",
+ "0,-4,74",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "sensor-bar",
+ "label": "Add sensor bar",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "SensorBar",
+ "-P",
+ "length=24",
+ "-P",
+ "width=4",
+ "-P",
+ "height=3",
+ "-pos",
+ "-4,-2,81",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "antenna-mast",
+ "label": "Add high-gain antenna mast",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "AntennaMast",
+ "-P",
+ "radius=1.2",
+ "-P",
+ "height=12",
+ "-pos",
+ "-20,0,40",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "antenna-dish",
+ "label": "Add high-gain antenna dish",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "AntennaDish",
+ "-P",
+ "radius=7",
+ "-P",
+ "height=2",
+ "-pos",
+ "-21,0,48",
+ "-rot",
+ "0,90,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "science-boom",
+ "label": "Add science boom",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "ScienceBoom",
+ "-P",
+ "radius=1.4",
+ "-P",
+ "height=24",
+ "-pos",
+ "16,10,30",
+ "-rot",
+ "0,90,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "sample-head",
+ "label": "Add sample head",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "sphere",
+ "--name",
+ "SampleHead",
+ "-P",
+ "radius=4.5",
+ "-pos",
+ "42,10,30",
+ ],
+ "wait_preview": True,
+ },
+ ]
+
+
+def _curiosity_steps() -> List[Dict[str, Any]]:
+ """Return a higher-fidelity tiny Curiosity rover build trajectory."""
+ return [
+ {
+ "id": "create-project",
+ "label": "Create FreeCAD project",
+ "argv": ["document", "new", "--name", "Curiosity", "-o", "{project_path}"],
+ "wait_preview": False,
+ },
+ {
+ "id": "start-live-preview",
+ "label": "Start poll-mode live preview",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "preview",
+ "live",
+ "start",
+ "--recipe",
+ "quick",
+ "--mode",
+ "poll",
+ "--source-poll-ms",
+ "500",
+ "--poll-ms",
+ "700",
+ "--root-dir",
+ "{live_root}",
+ ],
+ "wait_preview": True,
+ "manual_session_payload": True,
+ },
+ {
+ "id": "lower-chassis",
+ "label": "Add lower chassis tub",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LowerChassis",
+ "-P",
+ "length=50",
+ "-P",
+ "width=34",
+ "-P",
+ "height=8",
+ "-pos",
+ "-10,-17,25",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "upper-deck",
+ "label": "Add upper instrument deck",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "UpperDeck",
+ "-P",
+ "length=34",
+ "-P",
+ "width=28",
+ "-P",
+ "height=8",
+ "-pos",
+ "-8,-14,33",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "front-avionics",
+ "label": "Add front avionics bay",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "FrontAvionics",
+ "-P",
+ "length=14",
+ "-P",
+ "width=26",
+ "-P",
+ "height=8",
+ "-pos",
+ "24,-13,31",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "rear-bridge",
+ "label": "Add rear bridge deck",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RearBridge",
+ "-P",
+ "length=14",
+ "-P",
+ "width=22",
+ "-P",
+ "height=5",
+ "-pos",
+ "-24,-11,33",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-rocker",
+ "label": "Add left rocker beam",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftRocker",
+ "-P",
+ "length=46",
+ "-P",
+ "width=3.5",
+ "-P",
+ "height=3",
+ "-pos",
+ "-8,-22,22",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-rocker",
+ "label": "Add right rocker beam",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightRocker",
+ "-P",
+ "length=46",
+ "-P",
+ "width=3.5",
+ "-P",
+ "height=3",
+ "-pos",
+ "-8,18.5,22",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-bogie",
+ "label": "Add left bogie beam",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftBogie",
+ "-P",
+ "length=34",
+ "-P",
+ "width=3",
+ "-P",
+ "height=3",
+ "-pos",
+ "-20,-22,18",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-bogie",
+ "label": "Add right bogie beam",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightBogie",
+ "-P",
+ "length=34",
+ "-P",
+ "width=3",
+ "-P",
+ "height=3",
+ "-pos",
+ "-20,19,18",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-front-link",
+ "label": "Add left front suspension link",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftFrontLink",
+ "-P",
+ "length=18",
+ "-P",
+ "width=3",
+ "-P",
+ "height=3",
+ "-pos",
+ "18,-22,19",
+ "-rot",
+ "0,0,-28",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-front-link",
+ "label": "Add right front suspension link",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightFrontLink",
+ "-P",
+ "length=18",
+ "-P",
+ "width=3",
+ "-P",
+ "height=3",
+ "-pos",
+ "18,19,19",
+ "-rot",
+ "0,0,28",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-rear-link",
+ "label": "Add left rear suspension link",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftRearLink",
+ "-P",
+ "length=16",
+ "-P",
+ "width=3",
+ "-P",
+ "height=3",
+ "-pos",
+ "-33,-22,18",
+ "-rot",
+ "0,0,30",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-rear-link",
+ "label": "Add right rear suspension link",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightRearLink",
+ "-P",
+ "length=16",
+ "-P",
+ "width=3",
+ "-P",
+ "height=3",
+ "-pos",
+ "-33,19,18",
+ "-rot",
+ "0,0,-30",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-front-wheel",
+ "label": "Add left front wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "LeftFrontWheel",
+ "-P",
+ "radius=12",
+ "-P",
+ "height=6",
+ "-pos",
+ "24,-25,12",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-mid-wheel",
+ "label": "Add left middle wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "LeftMidWheel",
+ "-P",
+ "radius=12",
+ "-P",
+ "height=6",
+ "-pos",
+ "-2,-25,10",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-rear-wheel",
+ "label": "Add left rear wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "LeftRearWheel",
+ "-P",
+ "radius=12",
+ "-P",
+ "height=6",
+ "-pos",
+ "-26,-25,12",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-front-wheel",
+ "label": "Add right front wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "RightFrontWheel",
+ "-P",
+ "radius=12",
+ "-P",
+ "height=6",
+ "-pos",
+ "24,19,12",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-mid-wheel",
+ "label": "Add right middle wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "RightMidWheel",
+ "-P",
+ "radius=12",
+ "-P",
+ "height=6",
+ "-pos",
+ "-2,19,10",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-rear-wheel",
+ "label": "Add right rear wheel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "RightRearWheel",
+ "-P",
+ "radius=12",
+ "-P",
+ "height=6",
+ "-pos",
+ "-26,19,12",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-front-wheel-outboard",
+ "label": "Push right front wheel to mirrored track width",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "15",
+ "0",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ "--dy",
+ "8.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-mid-wheel-outboard",
+ "label": "Push right middle wheel to mirrored track width",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "16",
+ "0",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ "--dy",
+ "8.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-rear-wheel-outboard",
+ "label": "Push right rear wheel to mirrored track width",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "17",
+ "0",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ "--dy",
+ "8.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-left-rocker-wheel-plane",
+ "label": "Seat left rocker into wheel plane",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "4",
+ "12",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-rocker-wheel-plane",
+ "label": "Seat right rocker into wheel plane",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "5",
+ "15",
+ "--y",
+ "max",
+ "--to-y",
+ "min",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-left-bogie-wheel-plane",
+ "label": "Seat left bogie into wheel plane",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "6",
+ "13",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-bogie-wheel-plane",
+ "label": "Seat right bogie into wheel plane",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "7",
+ "16",
+ "--y",
+ "max",
+ "--to-y",
+ "min",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-left-front-link-wheel-plane",
+ "label": "Seat left front link into wheel plane",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "8",
+ "12",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-front-link-wheel-plane",
+ "label": "Seat right front link into wheel plane",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "9",
+ "15",
+ "--y",
+ "max",
+ "--to-y",
+ "min",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-left-rear-link-wheel-plane",
+ "label": "Seat left rear link into wheel plane",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "10",
+ "14",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-rear-link-wheel-plane",
+ "label": "Seat right rear link into wheel plane",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "11",
+ "17",
+ "--y",
+ "max",
+ "--to-y",
+ "min",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-front-axle-block",
+ "label": "Add left front axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftFrontAxleBlock",
+ "-P",
+ "length=6",
+ "-P",
+ "width=8",
+ "-P",
+ "height=8",
+ "-pos",
+ "21,-24,16",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-left-front-axle-block",
+ "label": "Attach left front axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "18",
+ "12",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "1.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-mid-axle-block",
+ "label": "Add left middle axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftMidAxleBlock",
+ "-P",
+ "length=6",
+ "-P",
+ "width=8",
+ "-P",
+ "height=8",
+ "-pos",
+ "-5,-24,14",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-left-mid-axle-block",
+ "label": "Attach left middle axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "19",
+ "13",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "3.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-rear-axle-block",
+ "label": "Add left rear axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftRearAxleBlock",
+ "-P",
+ "length=6",
+ "-P",
+ "width=8",
+ "-P",
+ "height=8",
+ "-pos",
+ "-29,-24,16",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-left-rear-axle-block",
+ "label": "Attach left rear axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "20",
+ "14",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "min",
+ "--to-y",
+ "max",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "1.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-front-axle-block",
+ "label": "Add right front axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightFrontAxleBlock",
+ "-P",
+ "length=6",
+ "-P",
+ "width=8",
+ "-P",
+ "height=8",
+ "-pos",
+ "21,17,16",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-front-axle-block",
+ "label": "Attach right front axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "21",
+ "15",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "max",
+ "--to-y",
+ "min",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "1.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-mid-axle-block",
+ "label": "Add right middle axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightMidAxleBlock",
+ "-P",
+ "length=6",
+ "-P",
+ "width=8",
+ "-P",
+ "height=8",
+ "-pos",
+ "-5,17,14",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-mid-axle-block",
+ "label": "Attach right middle axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "22",
+ "16",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "max",
+ "--to-y",
+ "min",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "3.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-rear-axle-block",
+ "label": "Add right rear axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightRearAxleBlock",
+ "-P",
+ "length=6",
+ "-P",
+ "width=8",
+ "-P",
+ "height=8",
+ "-pos",
+ "-29,17,16",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-rear-axle-block",
+ "label": "Attach right rear axle block",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "23",
+ "17",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "max",
+ "--to-y",
+ "min",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "1.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-rocker-pivot-housing",
+ "label": "Add left rocker pivot housing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftRockerPivotHousing",
+ "-P",
+ "length=8",
+ "-P",
+ "width=8",
+ "-P",
+ "height=6",
+ "-pos",
+ "11,-22,21",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-left-rocker-pivot-housing",
+ "label": "Seat left rocker pivot housing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "24",
+ "4",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "min",
+ "--to-y",
+ "min",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "3.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-rocker-pivot-housing",
+ "label": "Add right rocker pivot housing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightRockerPivotHousing",
+ "-P",
+ "length=8",
+ "-P",
+ "width=8",
+ "-P",
+ "height=6",
+ "-pos",
+ "11,17,21",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-rocker-pivot-housing",
+ "label": "Seat right rocker pivot housing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "25",
+ "5",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "max",
+ "--to-y",
+ "max",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "3.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-bogie-pivot-housing",
+ "label": "Add left bogie pivot housing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftBogiePivotHousing",
+ "-P",
+ "length=8",
+ "-P",
+ "width=8",
+ "-P",
+ "height=6",
+ "-pos",
+ "-7,-22,17",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-left-bogie-pivot-housing",
+ "label": "Seat left bogie pivot housing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "26",
+ "6",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "min",
+ "--to-y",
+ "min",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "5.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-bogie-pivot-housing",
+ "label": "Add right bogie pivot housing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightBogiePivotHousing",
+ "-P",
+ "length=8",
+ "-P",
+ "width=8",
+ "-P",
+ "height=6",
+ "-pos",
+ "-7,17,17",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-bogie-pivot-housing",
+ "label": "Seat right bogie pivot housing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "27",
+ "7",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "max",
+ "--to-y",
+ "max",
+ "--z",
+ "max",
+ "--to-z",
+ "max",
+ "--dz",
+ "5.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "mast-pedestal",
+ "label": "Add mast pedestal",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "MastPedestal",
+ "-P",
+ "radius=3.8",
+ "-P",
+ "height=10",
+ "-pos",
+ "2,0,41",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "mast-column",
+ "label": "Add mast column",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "MastColumn",
+ "-P",
+ "radius=1.7",
+ "-P",
+ "height=28",
+ "-pos",
+ "2,0,51",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "camera-bar",
+ "label": "Add mast camera bridge",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "CameraBridge",
+ "-P",
+ "length=18",
+ "-P",
+ "width=4",
+ "-P",
+ "height=3",
+ "-pos",
+ "-5,-2,79",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "camera-pods",
+ "label": "Add stereo camera pods",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftCameraPod",
+ "-P",
+ "length=7",
+ "-P",
+ "width=6",
+ "-P",
+ "height=7",
+ "-pos",
+ "-11,-7,73",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "chemcam-barrel",
+ "label": "Add ChemCam barrel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "ChemCamBarrel",
+ "-P",
+ "radius=0.9",
+ "-P",
+ "height=9",
+ "-pos",
+ "-2,-0.5,75",
+ "-rot",
+ "0,90,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-camera-pod",
+ "label": "Add right camera pod",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightCameraPod",
+ "-P",
+ "length=7",
+ "-P",
+ "width=6",
+ "-P",
+ "height=7",
+ "-pos",
+ "4,1,73",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "rtg-body",
+ "label": "Add rear RTG body",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "RTGBody",
+ "-P",
+ "radius=6.5",
+ "-P",
+ "height=18",
+ "-pos",
+ "-28,13,35",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "rtg-cap",
+ "label": "Add RTG cap",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cone",
+ "--name",
+ "RTGCap",
+ "-P",
+ "radius1=6.2",
+ "-P",
+ "radius2=2.8",
+ "-P",
+ "height=6",
+ "-pos",
+ "-32,13,35",
+ "-rot",
+ "90,0,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "rtg-strut",
+ "label": "Add RTG support strut",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RTGStrut",
+ "-P",
+ "length=11",
+ "-P",
+ "width=3",
+ "-P",
+ "height=3",
+ "-pos",
+ "-20,11,35",
+ "-rot",
+ "0,0,-18",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "hga-stem",
+ "label": "Add high-gain antenna stem",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "HGAStem",
+ "-P",
+ "radius=1.2",
+ "-P",
+ "height=14",
+ "-pos",
+ "-1,11,43",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "hga-dish",
+ "label": "Add high-gain antenna dish",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "HGADish",
+ "-P",
+ "radius=6.3",
+ "-P",
+ "height=1.3",
+ "-pos",
+ "1,14,56",
+ "-rot",
+ "0,90,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "arm-shoulder",
+ "label": "Add robotic arm shoulder",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "ArmShoulder",
+ "-P",
+ "radius=2.4",
+ "-P",
+ "height=8",
+ "-pos",
+ "32,0,30",
+ "-rot",
+ "0,90,0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "arm-upper",
+ "label": "Add robotic arm upper segment",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "ArmUpper",
+ "-P",
+ "radius=1.6",
+ "-P",
+ "height=16",
+ "-pos",
+ "35,0,28",
+ "-rot",
+ "0,90,-26",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "arm-fore",
+ "label": "Add robotic forearm",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "ArmFore",
+ "-P",
+ "radius=1.4",
+ "-P",
+ "height=15",
+ "-pos",
+ "46,0,19",
+ "-rot",
+ "0,90,18",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "turret",
+ "label": "Add drill turret",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "sphere",
+ "--name",
+ "ToolTurret",
+ "-P",
+ "radius=4.1",
+ "-pos",
+ "56,0,13",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "deck-sensor-pack",
+ "label": "Add deck sensor pack",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "DeckSensorPack",
+ "-P",
+ "length=12",
+ "-P",
+ "width=7",
+ "-P",
+ "height=4",
+ "-pos",
+ "-10,-3,41",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-upper-deck",
+ "label": "Seat upper deck on chassis",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "1",
+ "0",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "min",
+ "--to-z",
+ "max",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-front-avionics",
+ "label": "Seat front avionics",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "2",
+ "1",
+ "--x",
+ "min",
+ "--to-x",
+ "max",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "min",
+ "--to-z",
+ "min",
+ "--dz",
+ "-2",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-rear-bridge",
+ "label": "Seat rear bridge",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "3",
+ "1",
+ "--x",
+ "max",
+ "--to-x",
+ "min",
+ "--dx",
+ "-1.5",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "min",
+ "--to-z",
+ "min",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-mast-column",
+ "label": "Attach mast column to pedestal",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "29",
+ "28",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "min",
+ "--to-z",
+ "max",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-camera-bridge",
+ "label": "Attach camera bridge to mast",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "30",
+ "29",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--dx",
+ "-1.0",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "min",
+ "--to-z",
+ "max",
+ "--dz",
+ "-3.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-camera-pods",
+ "label": "Hang camera pods under bridge",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "31",
+ "30",
+ "--x",
+ "center",
+ "--to-x",
+ "min",
+ "--dx",
+ "2.0",
+ "--z",
+ "max",
+ "--to-z",
+ "min",
+ "--dz",
+ "1.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-right-camera-pod",
+ "label": "Hang right camera pod under bridge",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "33",
+ "30",
+ "--x",
+ "center",
+ "--to-x",
+ "max",
+ "--dx",
+ "-2.0",
+ "--z",
+ "max",
+ "--to-z",
+ "min",
+ "--dz",
+ "1.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-chemcam",
+ "label": "Attach ChemCam barrel",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "32",
+ "30",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "center",
+ "--to-z",
+ "center",
+ "--dz",
+ "-2.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-rtg-body",
+ "label": "Attach RTG body to rear bridge",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "34",
+ "3",
+ "--x",
+ "max",
+ "--to-x",
+ "min",
+ "--dx",
+ "-2.0",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--dy",
+ "9.0",
+ "--z",
+ "center",
+ "--to-z",
+ "center",
+ "--dz",
+ "2.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-rtg-cap",
+ "label": "Cap the RTG body",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "35",
+ "34",
+ "--x",
+ "max",
+ "--to-x",
+ "min",
+ "--dx",
+ "0.5",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "center",
+ "--to-z",
+ "center",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-rtg-strut",
+ "label": "Support the RTG",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "36",
+ "34",
+ "--x",
+ "max",
+ "--to-x",
+ "max",
+ "--dx",
+ "8.0",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "center",
+ "--to-z",
+ "center",
+ "--dz",
+ "-3.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-hga-stem",
+ "label": "Attach antenna stem",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "37",
+ "1",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--dx",
+ "10.0",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--dy",
+ "11.0",
+ "--z",
+ "min",
+ "--to-z",
+ "max",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-hga-dish",
+ "label": "Attach antenna dish",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "38",
+ "37",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--dy",
+ "3.0",
+ "--z",
+ "min",
+ "--to-z",
+ "max",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-arm-shoulder",
+ "label": "Attach arm shoulder to front bay",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "39",
+ "2",
+ "--x",
+ "min",
+ "--to-x",
+ "max",
+ "--dx",
+ "-1.0",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "center",
+ "--to-z",
+ "center",
+ "--dz",
+ "-3.0",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-arm-upper",
+ "label": "Attach upper arm",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "40",
+ "39",
+ "--x",
+ "min",
+ "--to-x",
+ "max",
+ "--dx",
+ "-1.5",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "center",
+ "--to-z",
+ "center",
+ "--dz",
+ "-1.5",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-arm-fore",
+ "label": "Attach forearm",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "41",
+ "40",
+ "--x",
+ "min",
+ "--to-x",
+ "max",
+ "--dx",
+ "-1.5",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "center",
+ "--to-z",
+ "center",
+ "--dz",
+ "-2.5",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-turret",
+ "label": "Attach tool turret",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "42",
+ "41",
+ "--x",
+ "min",
+ "--to-x",
+ "max",
+ "--dx",
+ "-0.5",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "center",
+ "--to-z",
+ "center",
+ "--dz",
+ "-1.5",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "align-sensor-pack",
+ "label": "Seat sensor pack on deck",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "align",
+ "43",
+ "1",
+ "--x",
+ "center",
+ "--to-x",
+ "center",
+ "--dx",
+ "-7.0",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "min",
+ "--to-z",
+ "max",
+ ],
+ "wait_preview": True,
+ },
+ ]
+
+
+SCENARIOS: Dict[str, Dict[str, Any]] = {
+ "curiosity": {
+ "title": "Curiosity",
+ "subtitle": "high-fidelity tiny Curiosity rover built with cli-anything-freecad and live preview",
+ "project_name": "Curiosity",
+ "project_file": "curiosity.json",
+ "steps": _curiosity_steps(),
+ },
+ "mars-rover": {
+ "title": "Mars Rover",
+ "subtitle": "modular six-wheel rover built with cli-anything-freecad and live preview",
+ "project_name": "MarsRover",
+ "project_file": "mars_rover.json",
+ "steps": _mars_rover_steps(),
+ },
+ "orbital-relay": {
+ "title": "Orbital Relay",
+ "subtitle": "fictional sci-fi station built with FreeCAD primitives",
+ "project_name": "OrbitalRelay",
+ "project_file": "orbital_relay.json",
+ "steps": [
+ {
+ "id": "create-project",
+ "label": "Create FreeCAD project",
+ "argv": ["document", "new", "--name", "OrbitalRelay", "-o", "{project_path}"],
+ "wait_preview": False,
+ },
+ {
+ "id": "start-live-preview",
+ "label": "Start poll-mode live preview",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "preview",
+ "live",
+ "start",
+ "--recipe",
+ "quick",
+ "--mode",
+ "poll",
+ "--source-poll-ms",
+ "500",
+ "--poll-ms",
+ "700",
+ "--root-dir",
+ "{live_root}",
+ ],
+ "wait_preview": True,
+ "manual_session_payload": True,
+ },
+ {
+ "id": "base-deck",
+ "label": "Add base deck",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "BaseDeck",
+ "-P",
+ "length=60",
+ "-P",
+ "width=40",
+ "-P",
+ "height=8",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "core-spine",
+ "label": "Add core spine",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "CoreSpine",
+ "-P",
+ "radius=9",
+ "-P",
+ "height=24",
+ "-pos",
+ "0,0,8",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "tail-fin",
+ "label": "Add tail fin",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "TailFin",
+ "-P",
+ "length=10",
+ "-P",
+ "width=6",
+ "-P",
+ "height=24",
+ "-pos",
+ "0,-18,8",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "sensor-dome",
+ "label": "Add sensor dome",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "sphere",
+ "--name",
+ "SensorDome",
+ "-P",
+ "radius=12",
+ "-pos",
+ "0,0,34",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "port-wing",
+ "label": "Add port wing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "PortWing",
+ "-P",
+ "length=18",
+ "-P",
+ "width=28",
+ "-P",
+ "height=5",
+ "-pos",
+ "-28,0,14",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "starboard-wing",
+ "label": "Add starboard wing",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "StarboardWing",
+ "-P",
+ "length=18",
+ "-P",
+ "width=28",
+ "-P",
+ "height=5",
+ "-pos",
+ "28,0,14",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "beacon-cone",
+ "label": "Add beacon cone",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cone",
+ "--name",
+ "BeaconCone",
+ "-P",
+ "radius1=10",
+ "-P",
+ "radius2=3",
+ "-P",
+ "height=16",
+ "-pos",
+ "0,18,8",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "antenna",
+ "label": "Add antenna mast",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "AntennaMast",
+ "-P",
+ "radius=2",
+ "-P",
+ "height=18",
+ "-pos",
+ "0,0,48",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "halo-ring",
+ "label": "Add halo ring",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "torus",
+ "--name",
+ "HaloRing",
+ "-P",
+ "radius1=20",
+ "-P",
+ "radius2=2.5",
+ "-pos",
+ "0,0,28",
+ ],
+ "wait_preview": True,
+ },
+ ],
+ },
+ "empire-state-building": {
+ "title": "Empire State Building",
+ "subtitle": "tiny iconic skyscraper model built with cli-anything-freecad",
+ "project_name": "EmpireStateBuilding",
+ "project_file": "empire_state_building.json",
+ "steps": [
+ {
+ "id": "create-project",
+ "label": "Create FreeCAD project",
+ "argv": ["document", "new", "--name", "EmpireStateBuilding", "-o", "{project_path}"],
+ "wait_preview": False,
+ },
+ {
+ "id": "start-live-preview",
+ "label": "Start poll-mode live preview",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "preview",
+ "live",
+ "start",
+ "--recipe",
+ "quick",
+ "--mode",
+ "poll",
+ "--source-poll-ms",
+ "500",
+ "--poll-ms",
+ "700",
+ "--root-dir",
+ "{live_root}",
+ ],
+ "wait_preview": True,
+ "manual_session_payload": True,
+ },
+ {
+ "id": "podium",
+ "label": "Add podium base",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "Podium",
+ "-P",
+ "length=52",
+ "-P",
+ "width=88",
+ "-P",
+ "height=10",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "lower-mass",
+ "label": "Add lower tower mass",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LowerMass",
+ "-P",
+ "length=36",
+ "-P",
+ "width=64",
+ "-P",
+ "height=20",
+ "-pos",
+ "0,0,10",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "mid-mass",
+ "label": "Add mid setback mass",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "MidMass",
+ "-P",
+ "length=28",
+ "-P",
+ "width=44",
+ "-P",
+ "height=22",
+ "-pos",
+ "0,0,30",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "upper-shaft",
+ "label": "Add upper shaft",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "UpperShaft",
+ "-P",
+ "length=20",
+ "-P",
+ "width=28",
+ "-P",
+ "height=24",
+ "-pos",
+ "0,0,52",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "left-crown-pier",
+ "label": "Add left crown pier",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "LeftCrownPier",
+ "-P",
+ "length=16",
+ "-P",
+ "width=10",
+ "-P",
+ "height=26",
+ "-pos",
+ "-12,0,76",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "right-crown-pier",
+ "label": "Add right crown pier",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "RightCrownPier",
+ "-P",
+ "length=16",
+ "-P",
+ "width=10",
+ "-P",
+ "height=26",
+ "-pos",
+ "12,0,76",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "central-crown",
+ "label": "Add central crown tower",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "CentralCrown",
+ "-P",
+ "length=16",
+ "-P",
+ "width=16",
+ "-P",
+ "height=32",
+ "-pos",
+ "0,0,76",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "upper-crown",
+ "label": "Add upper crown",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "box",
+ "--name",
+ "UpperCrown",
+ "-P",
+ "length=10",
+ "-P",
+ "width=12",
+ "-P",
+ "height=18",
+ "-pos",
+ "0,0,108",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "mast-lower",
+ "label": "Add mast base",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "MastLower",
+ "-P",
+ "radius=2.2",
+ "-P",
+ "height=14",
+ "-pos",
+ "0,0,126",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "mast-upper",
+ "label": "Add upper antenna mast",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "MastUpper",
+ "-P",
+ "radius=1.3",
+ "-P",
+ "height=12",
+ "-pos",
+ "0,0,140",
+ ],
+ "wait_preview": True,
+ },
+ {
+ "id": "spire-tip",
+ "label": "Add spire tip",
+ "argv": [
+ "-p",
+ "{project_path}",
+ "part",
+ "add",
+ "cone",
+ "--name",
+ "SpireTip",
+ "-P",
+ "radius1=2.0",
+ "-P",
+ "radius2=0.2",
+ "-P",
+ "height=10",
+ "-pos",
+ "0,0,152",
+ ],
+ "wait_preview": True,
+ },
+ ],
+ },
+ "taipei-101": {
+ "title": "Taipei 101",
+ "subtitle": "tiny stacked-shoulder skyscraper model built with cli-anything-freecad",
+ "project_name": "Taipei101",
+ "project_file": "taipei_101.json",
+ "steps": _taipei_101_steps(),
+ },
+}
+
+
+def now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def get_scenario(name: str) -> Dict[str, Any]:
+ try:
+ return SCENARIOS[name]
+ except KeyError as exc:
+ raise ValueError(f"Unknown scenario: {name!r}. Available: {', '.join(sorted(SCENARIOS))}") from exc
+
+
+def ensure_clean_dir(path: Path) -> Path:
+ if path.exists():
+ shutil.rmtree(path)
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def load_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def write_json(path: Path, payload: Dict[str, Any]) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "w", encoding="utf-8") as fh:
+ json.dump(payload, fh, indent=2, ensure_ascii=False)
+ fh.write("\n")
+ return path
+
+
+def format_cmd(argv: List[str]) -> str:
+ return " ".join(shlex_quote(arg) for arg in argv)
+
+
+def shlex_quote(value: str) -> str:
+ if not value or any(c in value for c in " \t\n\"'`$&|;()[]{}<>"):
+ return "'" + value.replace("'", "'\"'\"'") + "'"
+ return value
+
+
+def run_cli(argv: List[str], *, timeout: int = 300) -> Dict[str, Any]:
+ cmd = [FREECAD_CLI, "--json"] + argv
+ started = time.time()
+ proc = subprocess.run(
+ cmd,
+ cwd=FREECAD_WORKDIR,
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ )
+ finished = time.time()
+ payload: Dict[str, Any] = {
+ "argv": cmd,
+ "display_cmd": format_cmd(cmd),
+ "returncode": proc.returncode,
+ "stdout": proc.stdout,
+ "stderr": proc.stderr,
+ "started_at": started,
+ "finished_at": finished,
+ "duration_s": round(finished - started, 3),
+ }
+ if proc.returncode != 0:
+ raise RuntimeError(
+ f"Command failed: {payload['display_cmd']}\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr}"
+ )
+ try:
+ payload["json"] = json.loads(proc.stdout) if proc.stdout.strip() else None
+ except json.JSONDecodeError:
+ payload["json"] = None
+ return payload
+
+
+def _load_motion_module():
+ if str(FREECAD_WORKDIR) not in sys.path:
+ sys.path.insert(0, str(FREECAD_WORKDIR))
+ from cli_anything.freecad.core import motion as motion_mod
+
+ return motion_mod
+
+
+def _is_noop_alignment(result: Dict[str, Any]) -> bool:
+ """Return True when a part-align command produced no placement delta."""
+ payload = result.get("json") or {}
+ delta = payload.get("delta")
+ if not isinstance(delta, dict):
+ return False
+ try:
+ return all(abs(float(delta.get(axis, 0.0))) <= 1e-9 for axis in ("x", "y", "z"))
+ except (TypeError, ValueError):
+ return False
+
+
+def wait_for_bundle_update(
+ session_path: Path,
+ expected_count: int,
+ timeout_s: float,
+ *,
+ previous_bundle_id: Optional[str] = None,
+) -> Dict[str, Any]:
+ deadline = time.time() + timeout_s
+ latest = None
+ while time.time() < deadline:
+ latest = load_json(session_path)
+ current_bundle_id = latest.get("current_bundle_id")
+ if latest.get("bundle_count", 0) >= expected_count:
+ return latest
+ if previous_bundle_id and current_bundle_id and current_bundle_id != previous_bundle_id:
+ return latest
+ time.sleep(0.4)
+ raise TimeoutError(
+ f"Timed out waiting for bundle update >= {expected_count} in {session_path}: {latest}"
+ )
+
+
+def extract_bundle_artifacts(session_payload: Dict[str, Any], snapshot_dir: Path) -> Dict[str, Any]:
+ current_manifest_path = Path(session_payload["current_manifest_path"]).resolve()
+ manifest = load_json(current_manifest_path)
+ bundle_dir = current_manifest_path.parent
+ summary_path = bundle_dir / manifest.get("summary_path", "summary.json")
+ if summary_path.is_file():
+ shutil.copy2(summary_path, snapshot_dir / "summary.json")
+ shutil.copy2(current_manifest_path, snapshot_dir / "manifest.json")
+ copied: Dict[str, str] = {}
+ for artifact in manifest.get("artifacts", []):
+ artifact_id = artifact.get("artifact_id")
+ artifact_src = (bundle_dir / artifact.get("path", "")).resolve()
+ if not artifact_id or not artifact_src.is_file():
+ continue
+ dest = snapshot_dir / f"{artifact_id}{artifact_src.suffix.lower()}"
+ shutil.copy2(artifact_src, dest)
+ copied[artifact_id] = str(dest)
+ return {
+ "bundle_id": manifest.get("bundle_id"),
+ "bundle_dir": str(bundle_dir),
+ "manifest_path": str(snapshot_dir / "manifest.json"),
+ "summary_path": str(snapshot_dir / "summary.json"),
+ "artifacts": copied,
+ }
+
+
+def generate_live_html(session_dir: Path, output_path: Path) -> None:
+ cmd = [CLI_HUB, "preview", "html", str(session_dir), "-o", str(output_path)]
+ subprocess.run(
+ cmd,
+ cwd=CLI_HUB_WORKDIR,
+ capture_output=True,
+ text=True,
+ timeout=180,
+ check=True,
+ )
+
+
+def collect_demo(output_dir: Path, scenario_name: str) -> Path:
+ scenario = get_scenario(scenario_name)
+ run_dir = ensure_clean_dir(output_dir)
+ snapshots_dir = run_dir / "snapshots"
+ snapshots_dir.mkdir(parents=True, exist_ok=True)
+ project_path = run_dir / scenario["project_file"]
+ live_root = run_dir / "live-root"
+
+ trajectory: Dict[str, Any] = {
+ "protocol": "freecad-live-demo/v1",
+ "created_at": now_iso(),
+ "scenario": scenario_name,
+ "scenario_title": scenario["title"],
+ "scenario_subtitle": scenario["subtitle"],
+ "repo_root": str(REPO_ROOT),
+ "freecad_workdir": str(FREECAD_WORKDIR),
+ "project_path": str(project_path),
+ "live_root": str(live_root),
+ "commands": [],
+ "preview_events": [],
+ "notes": [
+ "All commands were executed against the real cli-anything-freecad entry point.",
+ "All preview images came from the real FreeCAD live-preview poll session.",
+ "The final video is a programmatic composition of these real artifacts.",
+ ],
+ }
+
+ started_at = time.time()
+ session_path: Optional[Path] = None
+ session_dir: Optional[Path] = None
+ live_recipe = "quick"
+ expected_bundle_count = 0
+ failure: Optional[BaseException] = None
+ partial_timeline_path = run_dir / "trajectory.partial.json"
+
+ try:
+ for idx, step in enumerate(scenario["steps"]):
+ argv = [arg.format(project_path=project_path, live_root=live_root) for arg in step["argv"]]
+ result = run_cli(argv)
+ result["index"] = idx
+ result["id"] = step["id"]
+ result["label"] = step["label"]
+ result["timeline_start_s"] = round(result["started_at"] - started_at, 3)
+ result["timeline_end_s"] = round(result["finished_at"] - started_at, 3)
+ trajectory["commands"].append(result)
+ write_json(partial_timeline_path, trajectory)
+
+ if step.get("manual_session_payload"):
+ payload = result.get("json") or {}
+ session_path = Path(payload["_session_path"]).resolve()
+ session_dir = Path(payload["_session_dir"]).resolve()
+ expected_bundle_count = int(payload.get("bundle_count", 0))
+ preview_sequence = len(trajectory["preview_events"]) + 1
+ snapshot_dir = snapshots_dir / f"{preview_sequence:02d}_{step['id']}"
+ snapshot_dir.mkdir(parents=True, exist_ok=True)
+ copied = extract_bundle_artifacts(payload, snapshot_dir)
+ preview_event = {
+ "sequence_index": preview_sequence,
+ "step_index": idx,
+ "step_id": step["id"],
+ "step_label": step["label"],
+ "ready_at": time.time(),
+ "timeline_ready_s": round(time.time() - started_at, 3),
+ "latency_s": round(time.time() - result["finished_at"], 3),
+ "bundle_count": expected_bundle_count,
+ "publish_reason": (payload.get("source_state") or {}).get("last_publish_reason"),
+ "session_path": str(session_path),
+ "session_dir": str(session_dir),
+ "snapshot_dir": str(snapshot_dir),
+ "copied_bundle": copied,
+ }
+ trajectory["preview_events"].append(preview_event)
+ write_json(partial_timeline_path, trajectory)
+ continue
+
+ if step.get("wait_preview"):
+ if session_path is None or session_dir is None:
+ raise RuntimeError(f"Step {step['id']} expected an active live session")
+ if _is_noop_alignment(result):
+ continue
+ expected_bundle_count += 1
+ previous_bundle_id = trajectory["preview_events"][-1]["copied_bundle"]["bundle_id"] if trajectory["preview_events"] else None
+ payload = wait_for_bundle_update(
+ session_path,
+ expected_bundle_count,
+ DEFAULT_WAIT_TIMEOUT_S,
+ previous_bundle_id=previous_bundle_id,
+ )
+ observed_bundle_count = int(payload.get("bundle_count", expected_bundle_count))
+ expected_bundle_count = observed_bundle_count
+ preview_sequence = len(trajectory["preview_events"]) + 1
+ snapshot_dir = snapshots_dir / f"{preview_sequence:02d}_{step['id']}"
+ snapshot_dir.mkdir(parents=True, exist_ok=True)
+ copied = extract_bundle_artifacts(payload, snapshot_dir)
+ ready_at = time.time()
+ preview_event = {
+ "sequence_index": preview_sequence,
+ "step_index": idx,
+ "step_id": step["id"],
+ "step_label": step["label"],
+ "ready_at": ready_at,
+ "timeline_ready_s": round(ready_at - started_at, 3),
+ "latency_s": round(ready_at - result["finished_at"], 3),
+ "bundle_count": int(payload.get("bundle_count", 0)),
+ "publish_reason": (payload.get("source_state") or {}).get("last_publish_reason"),
+ "session_path": str(session_path),
+ "session_dir": str(session_dir),
+ "snapshot_dir": str(snapshot_dir),
+ "copied_bundle": copied,
+ }
+ trajectory["preview_events"].append(preview_event)
+ write_json(partial_timeline_path, trajectory)
+
+ if session_dir is not None:
+ generate_live_html(session_dir, run_dir / "live.html")
+ trajectory["final_session_dir"] = str(session_dir)
+ trajectory["final_session_path"] = str(session_dir / "session.json")
+ trajectory["final_live_html"] = str(run_dir / "live.html")
+ except Exception as exc:
+ failure = exc
+ trajectory["error"] = {
+ "type": type(exc).__name__,
+ "message": str(exc),
+ }
+ finally:
+ if project_path.is_file():
+ try:
+ stop_result = run_cli(
+ [
+ "-p",
+ str(project_path),
+ "preview",
+ "live",
+ "stop",
+ "--recipe",
+ live_recipe,
+ "--root-dir",
+ str(live_root),
+ ],
+ timeout=120,
+ )
+ trajectory["stop_command"] = {
+ "display_cmd": stop_result["display_cmd"],
+ "returncode": stop_result["returncode"],
+ "stdout": stop_result["stdout"],
+ "stderr": stop_result["stderr"],
+ }
+ except Exception as exc: # pragma: no cover - cleanup best effort
+ trajectory["stop_error"] = str(exc)
+
+ trajectory["completed_at"] = now_iso()
+ timeline_path = write_json(run_dir / "trajectory.json", trajectory)
+ if failure is not None:
+ raise RuntimeError(
+ f"collect_demo failed for scenario {scenario_name!r}; partial trajectory written to {timeline_path}"
+ ) from failure
+ return timeline_path
+
+
+def fit_image(img: Image.Image, box: tuple[int, int], *, background: str) -> Image.Image:
+ target_w, target_h = box
+ canvas = Image.new("RGB", (target_w, target_h), background)
+ src = img.convert("RGB")
+ scale = min(target_w / src.width, target_h / src.height)
+ new_size = (max(1, int(src.width * scale)), max(1, int(src.height * scale)))
+ resized = src.resize(new_size, Image.Resampling.LANCZOS)
+ x = (target_w - resized.width) // 2
+ y = (target_h - resized.height) // 2
+ canvas.paste(resized, (x, y))
+ return canvas
+
+
+def _make_box_part(
+ *,
+ part_id: int,
+ name: str,
+ length: float,
+ width: float,
+ height: float,
+ position: List[float],
+) -> Dict[str, Any]:
+ return {
+ "id": part_id,
+ "name": name,
+ "type": "box",
+ "params": {
+ "length": float(length),
+ "width": float(width),
+ "height": float(height),
+ },
+ "placement": {
+ "position": [float(v) for v in position],
+ "rotation": [0.0, 0.0, 0.0],
+ },
+ "material_index": None,
+ "visible": True,
+ }
+
+
+def _curiosity_showcase_project(base_project: Dict[str, Any]) -> Dict[str, Any]:
+ project = copy.deepcopy(base_project)
+ parts = [part for part in project.get("parts", []) if not str(part.get("name", "")).startswith("Showcase")]
+ next_id = max((int(part.get("id", 0)) for part in parts), default=0) + 1
+ extras = [
+ _make_box_part(
+ part_id=next_id,
+ name="ShowcaseGround",
+ length=184.0,
+ width=96.0,
+ height=4.0,
+ position=[-72.0, -48.0, -4.0],
+ ),
+ _make_box_part(
+ part_id=next_id + 1,
+ name="ShowcaseMarkerA",
+ length=12.0,
+ width=8.0,
+ height=2.0,
+ position=[-18.0, -10.0, 0.0],
+ ),
+ _make_box_part(
+ part_id=next_id + 2,
+ name="ShowcaseMarkerB",
+ length=16.0,
+ width=10.0,
+ height=3.0,
+ position=[24.0, 10.0, 0.0],
+ ),
+ _make_box_part(
+ part_id=next_id + 3,
+ name="ShowcaseMarkerC",
+ length=18.0,
+ width=8.0,
+ height=2.0,
+ position=[58.0, -4.0, 0.0],
+ ),
+ ]
+ project["parts"] = parts + extras
+ return project
+
+
+def _apply_curiosity_showcase_pose(project: Dict[str, Any], progress: float) -> Dict[str, Any]:
+ rover_shift_x = -38.0 + 78.0 * progress
+ rover_shift_y = -7.0 + 11.0 * progress
+ bump_a = math.exp(-((progress - 0.32) ** 2) / (2 * 0.12 ** 2))
+ bump_b = math.exp(-((progress - 0.74) ** 2) / (2 * 0.10 ** 2))
+ rover_shift_z = 1.2 + 0.55 * math.sin(progress * math.tau) + 0.85 * bump_a + 0.65 * bump_b
+ arm_sway = 0.75 * math.sin(progress * math.tau)
+ mast_sway = 0.35 * math.cos(progress * math.pi)
+ dish_sway = 0.55 * math.cos(progress * math.tau)
+
+ for part in project.get("parts", []):
+ name = str(part.get("name", ""))
+ if name.startswith("Showcase"):
+ continue
+ placement = part.setdefault("placement", {})
+ position = placement.setdefault("position", [0.0, 0.0, 0.0])
+ while len(position) < 3:
+ position.append(0.0)
+ position[0] = float(position[0]) + rover_shift_x
+ position[1] = float(position[1]) + rover_shift_y
+ position[2] = float(position[2]) + rover_shift_z
+
+ if name in {"ArmFore", "ToolTurret"}:
+ position[1] += arm_sway
+ position[2] += 0.35 * arm_sway
+ elif name in {"ArmUpper", "ArmShoulder"}:
+ position[1] += 0.35 * arm_sway
+ elif name in {"HGADish", "HGAStem"}:
+ position[1] += dish_sway
+ elif name in {"MastColumn", "CameraBridge", "LeftCameraPod", "RightCameraPod", "ChemCamBarrel"}:
+ position[1] += mast_sway
+ return project
+
+
+def generate_curiosity_showcase_sequence(trajectory: Dict[str, Any], run_dir: Path) -> Optional[Dict[str, Any]]:
+ if trajectory.get("scenario") != "curiosity":
+ return None
+
+ showcase_dir = run_dir / "showcase"
+ manifest_path = showcase_dir / "sequence.json"
+ if manifest_path.is_file():
+ cached = load_json(manifest_path)
+ frames = cached.get("frames") or []
+ if frames and all(Path(frame.get("hero_path", "")).is_file() for frame in frames):
+ return cached
+
+ source_project_path = Path(trajectory["project_path"]).expanduser().resolve()
+ if not source_project_path.is_file():
+ return None
+
+ ensure_clean_dir(showcase_dir)
+ projects_dir = ensure_clean_dir(showcase_dir / "projects")
+ captures_root = ensure_clean_dir(showcase_dir / "captures")
+
+ base_project = _curiosity_showcase_project(load_json(source_project_path))
+ write_json(projects_dir / "showcase_base.json", base_project)
+
+ frames: List[Dict[str, Any]] = []
+ for idx in range(SHOWCASE_FRAME_COUNT):
+ progress = idx / max(1, SHOWCASE_FRAME_COUNT - 1)
+ posed_project = _apply_curiosity_showcase_pose(copy.deepcopy(base_project), progress)
+ posed_path = write_json(projects_dir / f"pose_{idx:02d}.json", posed_project)
+ capture = run_cli(
+ ["-p", str(posed_path), "preview", "capture", "--root-dir", str(captures_root)],
+ timeout=180,
+ )
+ payload = capture.get("json") or {}
+ bundle_dir = Path(payload.get("_bundle_dir", "")).expanduser()
+ hero_path = bundle_dir / "artifacts" / "hero.png"
+ if not hero_path.is_file():
+ raise RuntimeError(f"Missing hero artifact for showcase frame {idx}: {bundle_dir}")
+ frames.append(
+ {
+ "index": idx,
+ "progress": round(progress, 4),
+ "project_path": str(posed_path),
+ "bundle_dir": str(bundle_dir),
+ "hero_path": str(hero_path),
+ "capture_cmd": capture["display_cmd"],
+ }
+ )
+
+ manifest = {
+ "protocol": "freecad-showcase-sequence/v1",
+ "created_at": now_iso(),
+ "scenario": "curiosity",
+ "title": "Curiosity Showcase Drive",
+ "subtitle": "real extra FreeCAD hero captures generated from the final Curiosity v6 project",
+ "source_timeline": str(run_dir / "trajectory.json"),
+ "source_project_path": str(source_project_path),
+ "duration_s": SHOWCASE_DURATION_S,
+ "hold_s": SHOWCASE_HOLD_S,
+ "frames": frames,
+ "notes": [
+ "The ending showcase uses real preview captures from the final Curiosity v6 project.",
+ "A staged ground and marker bed are added as extra geometry so whole-rover translation reads visually in hero view.",
+ "No GUI screen recording or synthetic CAD viewport frames are used.",
+ ],
+ }
+ write_json(manifest_path, manifest)
+ return manifest
+
+
+def _apply_curiosity_true_motion_pose(project: Dict[str, Any], progress: float) -> Dict[str, Any]:
+ drive_x = -46.0 + 96.0 * progress
+ drive_y = -10.0 + 15.0 * progress + 2.2 * math.sin(progress * math.pi * 1.2)
+ bump_a = math.exp(-((progress - 0.28) ** 2) / (2 * 0.11 ** 2))
+ bump_b = math.exp(-((progress - 0.71) ** 2) / (2 * 0.10 ** 2))
+ body_heave = 1.15 + 0.45 * math.sin(progress * math.tau) + 0.85 * bump_a + 0.65 * bump_b
+ arm_sway = 0.9 * math.sin(progress * math.tau)
+ mast_sway = 0.45 * math.cos(progress * math.pi)
+ dish_sway = 0.65 * math.cos(progress * math.tau)
+
+ for part in project.get("parts", []):
+ name = str(part.get("name", ""))
+ if name.startswith("Showcase"):
+ continue
+ placement = part.setdefault("placement", {})
+ position = placement.setdefault("position", [0.0, 0.0, 0.0])
+ while len(position) < 3:
+ position.append(0.0)
+
+ position[0] = float(position[0]) + drive_x
+ position[1] = float(position[1]) + drive_y
+ position[2] = float(position[2]) + body_heave
+
+ if name in {"ArmFore", "ToolTurret"}:
+ position[1] += arm_sway
+ position[2] += 0.35 * arm_sway
+ elif name in {"ArmUpper", "ArmShoulder"}:
+ position[1] += 0.35 * arm_sway
+ elif name in {"HGADish", "HGAStem"}:
+ position[1] += dish_sway
+ position[2] += 0.18 * dish_sway
+ elif name in {"MastColumn", "CameraBridge", "LeftCameraPod", "RightCameraPod", "ChemCamBarrel"}:
+ position[1] += mast_sway
+ position[2] += 0.12 * mast_sway
+ return project
+
+
+def _curiosity_motion_pivot(project: Dict[str, Any]) -> List[float]:
+ xs: List[float] = []
+ ys: List[float] = []
+ zs: List[float] = []
+ for part in project.get("parts", []):
+ name = str(part.get("name", ""))
+ if name.startswith("Showcase"):
+ continue
+ placement = part.get("placement") or {}
+ position = placement.get("position") or [0.0, 0.0, 0.0]
+ if len(position) >= 3:
+ xs.append(float(position[0]))
+ ys.append(float(position[1]))
+ zs.append(float(position[2]))
+ if not xs:
+ return [0.0, 0.0, 0.0]
+ return [
+ (min(xs) + max(xs)) / 2.0,
+ (min(ys) + max(ys)) / 2.0,
+ (min(zs) + max(zs)) / 2.0,
+ ]
+
+
+def _rotate_xy(x: float, y: float, cx: float, cy: float, angle_deg: float) -> List[float]:
+ angle = math.radians(angle_deg)
+ dx = x - cx
+ dy = y - cy
+ cos_a = math.cos(angle)
+ sin_a = math.sin(angle)
+ return [
+ cx + dx * cos_a - dy * sin_a,
+ cy + dx * sin_a + dy * cos_a,
+ ]
+
+
+def _apply_curiosity_spin_motion_pose(project: Dict[str, Any], progress: float) -> Dict[str, Any]:
+ pivot = _curiosity_motion_pivot(project)
+ target_center_x = 10.0
+ target_center_y = 0.0
+ shift_x = target_center_x - pivot[0]
+ shift_y = target_center_y - pivot[1]
+ spin_deg = -20.0 + 380.0 * progress
+ body_heave = 1.05 + 0.25 * math.sin(progress * math.tau * 2.0)
+ mast_sway = 0.35 * math.cos(progress * math.tau)
+ arm_sway = 0.75 * math.sin(progress * math.tau * 1.5)
+ dish_sway = 0.45 * math.sin(progress * math.tau + math.pi / 6.0)
+
+ for part in project.get("parts", []):
+ name = str(part.get("name", ""))
+ if name.startswith("Showcase"):
+ continue
+ placement = part.setdefault("placement", {})
+ position = placement.setdefault("position", [0.0, 0.0, 0.0])
+ rotation = placement.setdefault("rotation", [0.0, 0.0, 0.0])
+ while len(position) < 3:
+ position.append(0.0)
+ while len(rotation) < 3:
+ rotation.append(0.0)
+
+ base_x = float(position[0]) + shift_x
+ base_y = float(position[1]) + shift_y
+ rotated_x, rotated_y = _rotate_xy(base_x, base_y, target_center_x, target_center_y, spin_deg)
+ position[0] = rotated_x
+ position[1] = rotated_y
+ position[2] = float(position[2]) + body_heave
+
+ rotation[2] = float(rotation[2]) + spin_deg
+
+ if name in {"ArmFore", "ToolTurret"}:
+ position[1] += 0.6 * arm_sway
+ position[2] += 0.25 * arm_sway
+ elif name in {"ArmUpper", "ArmShoulder"}:
+ position[1] += 0.3 * arm_sway
+ elif name in {"HGADish", "HGAStem"}:
+ position[1] += 0.35 * dish_sway
+ position[2] += 0.12 * dish_sway
+ elif name in {"MastColumn", "CameraBridge", "LeftCameraPod", "RightCameraPod", "ChemCamBarrel"}:
+ position[1] += 0.3 * mast_sway
+ position[2] += 0.10 * mast_sway
+ return project
+
+
+def _apply_curiosity_combo_motion_pose(project: Dict[str, Any], progress: float) -> Dict[str, Any]:
+ pivot = _curiosity_motion_pivot(project)
+ target_center_x = 10.0
+ target_center_y = 0.0
+ shift_x = target_center_x - pivot[0]
+ shift_y = target_center_y - pivot[1]
+
+ spin_phase = min(1.0, progress / 0.56)
+ drive_phase = 0.0 if progress <= 0.56 else min(1.0, (progress - 0.56) / 0.44)
+ spin_deg = -18.0 + 360.0 * spin_phase
+ drive_ease = 1.0 - pow(1.0 - drive_phase, 2.2)
+ drive_dx = 28.0 * drive_ease
+ drive_dy = -11.0 * drive_ease
+ body_heave = 0.95 + 0.18 * math.sin(progress * math.tau * 2.5)
+ mast_sway = 0.25 * math.cos(progress * math.tau * 1.25)
+ arm_sway = 0.42 * math.sin(progress * math.tau * 1.7)
+ dish_sway = 0.24 * math.sin(progress * math.tau + math.pi / 5.0)
+
+ for part in project.get("parts", []):
+ name = str(part.get("name", ""))
+ if name.startswith("Showcase"):
+ continue
+ placement = part.setdefault("placement", {})
+ position = placement.setdefault("position", [0.0, 0.0, 0.0])
+ rotation = placement.setdefault("rotation", [0.0, 0.0, 0.0])
+ while len(position) < 3:
+ position.append(0.0)
+ while len(rotation) < 3:
+ rotation.append(0.0)
+
+ base_x = float(position[0]) + shift_x
+ base_y = float(position[1]) + shift_y
+ rotated_x, rotated_y = _rotate_xy(base_x, base_y, target_center_x, target_center_y, spin_deg)
+ position[0] = rotated_x + drive_dx
+ position[1] = rotated_y + drive_dy
+ position[2] = float(position[2]) + body_heave
+
+ rotation[2] = float(rotation[2]) + spin_deg
+
+ if name in {"ArmFore", "ToolTurret"}:
+ position[1] += 0.35 * arm_sway
+ position[2] += 0.20 * arm_sway
+ elif name in {"ArmUpper", "ArmShoulder"}:
+ position[1] += 0.18 * arm_sway
+ elif name in {"HGADish", "HGAStem"}:
+ position[1] += 0.18 * dish_sway
+ position[2] += 0.10 * dish_sway
+ elif name in {"MastColumn", "CameraBridge", "LeftCameraPod", "RightCameraPod", "ChemCamBarrel"}:
+ position[1] += 0.18 * mast_sway
+ position[2] += 0.08 * mast_sway
+ return project
+
+
+def generate_curiosity_true_motion_showcase(
+ timeline_path: Path,
+ output_dir: Path,
+ *,
+ fps: int = FPS,
+ keep_frames: bool = True,
+ motion_style: str = "drive",
+) -> Dict[str, Any]:
+ trajectory = load_json(timeline_path)
+ if trajectory.get("scenario") != "curiosity":
+ raise ValueError("True motion showcase is currently implemented for the curiosity scenario only.")
+ if motion_style not in {"drive", "spin", "combo"}:
+ raise ValueError("motion_style must be 'drive', 'spin', or 'combo'")
+
+ motion_mod = _load_motion_module()
+ output_dir = output_dir.expanduser().resolve()
+ ensure_clean_dir(output_dir)
+ stills_dir = ensure_clean_dir(output_dir / "stills")
+ source_project_path = Path(trajectory["project_path"]).expanduser().resolve()
+ if not source_project_path.is_file():
+ raise FileNotFoundError(f"Missing Curiosity project: {source_project_path}")
+
+ base_project = _curiosity_showcase_project(load_json(source_project_path))
+ motion_project = copy.deepcopy(base_project)
+ if motion_style == "drive":
+ duration_s = TRUE_MOTION_DURATION_S
+ keyframe_count = TRUE_MOTION_KEYFRAME_COUNT
+ motion_name = "CuriosityTrueDrive"
+ motion_title = "Curiosity True Motion Showcase"
+ motion_subtitle = "real frame-by-frame FreeCAD motion render from the final Curiosity v6 project"
+ apply_pose = _apply_curiosity_true_motion_pose
+ project_stem = "curiosity_true_motion"
+ video_name = "curiosity_true_motion.mp4"
+ elif motion_style == "spin":
+ duration_s = SPIN_MOTION_DURATION_S
+ keyframe_count = SPIN_MOTION_KEYFRAME_COUNT
+ motion_name = "CuriosityTurntable"
+ motion_title = "Curiosity Turntable Motion"
+ motion_subtitle = "real frame-by-frame FreeCAD turntable render from the final Curiosity v6 project"
+ apply_pose = _apply_curiosity_spin_motion_pose
+ project_stem = "curiosity_turntable_motion"
+ video_name = "curiosity_turntable_motion.mp4"
+ else:
+ duration_s = COMBO_MOTION_DURATION_S
+ keyframe_count = COMBO_MOTION_KEYFRAME_COUNT
+ motion_name = "CuriosityComboShowcase"
+ motion_title = "Curiosity Rotation + Drive Motion"
+ motion_subtitle = "real frame-by-frame FreeCAD combo motion: one full turntable rotation followed by forward travel"
+ apply_pose = _apply_curiosity_combo_motion_pose
+ project_stem = "curiosity_combo_motion"
+ video_name = "curiosity_combo_motion.mp4"
+
+ motion_mod.create_motion(
+ motion_project,
+ name=motion_name,
+ duration=duration_s,
+ fps=int(fps),
+ camera="hero",
+ width=1600,
+ height=900,
+ background="White",
+ fit_mode="initial",
+ )
+ motion_index = len(motion_project.get("motions", [])) - 1
+
+ keyframes: List[Dict[str, Any]] = []
+ for idx in range(keyframe_count):
+ progress = idx / max(1, keyframe_count - 1)
+ time_value = round(progress * duration_s, 4)
+ posed_project = apply_pose(copy.deepcopy(base_project), progress)
+ for part_index, part in enumerate(posed_project.get("parts", [])):
+ placement = part.get("placement") or {}
+ motion_mod.add_keyframe(
+ motion_project,
+ motion_index,
+ target_kind="part",
+ target_index=part_index,
+ time_value=time_value,
+ position=placement.get("position"),
+ rotation=placement.get("rotation"),
+ )
+ keyframes.append(
+ {
+ "index": idx,
+ "progress": round(progress, 4),
+ "time": time_value,
+ }
+ )
+
+ project_path = write_json(output_dir / f"{project_stem}.json", motion_project)
+ frames_dir = output_dir / "frames"
+ video_path = output_dir / video_name
+ cli_args = [
+ "-p",
+ str(project_path),
+ "motion",
+ "render-video",
+ str(motion_index),
+ str(video_path),
+ "--overwrite",
+ ]
+ if keep_frames:
+ cli_args += ["--frames-dir", str(frames_dir)]
+ render = run_cli(cli_args, timeout=600)
+ render_payload = render.get("json") or {}
+
+ sequence_path = Path(render_payload.get("sequence_path", "")).expanduser()
+ sequence: Dict[str, Any] = {}
+ if sequence_path and sequence_path.is_file():
+ sequence = load_json(sequence_path)
+ frames = sequence.get("frames", [])
+ if frames:
+ still_indices = {
+ "start": 0,
+ "mid": len(frames) // 2,
+ "final": len(frames) - 1,
+ }
+ for label, frame_index in still_indices.items():
+ rel_path = frames[frame_index]["path"]
+ source = sequence_path.parent / rel_path
+ shutil.copy2(source, stills_dir / f"{label}.png")
+
+ manifest = {
+ "protocol": "freecad-true-motion-showcase/v1",
+ "created_at": now_iso(),
+ "scenario": "curiosity",
+ "motion_style": motion_style,
+ "title": motion_title,
+ "subtitle": motion_subtitle,
+ "source_timeline": str(timeline_path),
+ "source_project_path": str(source_project_path),
+ "motion_project_path": str(project_path),
+ "video_path": str(video_path),
+ "frames_dir": str(frames_dir) if keep_frames else None,
+ "sequence_path": render_payload.get("sequence_path"),
+ "duration_s": duration_s,
+ "fps": int(fps),
+ "keyframe_count": keyframe_count,
+ "render": render_payload,
+ "sequence": sequence,
+ "keyframes": keyframes,
+ "notes": [
+ "This sequence uses the final Curiosity v6 project as source geometry.",
+ "Motion is rendered frame-by-frame through cli-anything-freecad motion render-video.",
+ "No synthetic in-between frames or blend-based motion are used.",
+ ],
+ }
+ write_json(output_dir / "motion_manifest.json", manifest)
+ return manifest
+
+
+def load_font(path: str, size: int) -> ImageFont.FreeTypeFont:
+ return ImageFont.truetype(path, size=size)
+
+
+def _hex_rgb(value: str) -> tuple[int, int, int]:
+ value = value.lstrip("#")
+ return tuple(int(value[idx:idx + 2], 16) for idx in (0, 2, 4))
+
+
+def _rgba(value: str, alpha: int = 255) -> tuple[int, int, int, int]:
+ r, g, b = _hex_rgb(value)
+ return (r, g, b, alpha)
+
+
+def _mix(color_a: str, color_b: str, t: float) -> tuple[int, int, int]:
+ a = _hex_rgb(color_a)
+ b = _hex_rgb(color_b)
+ t = max(0.0, min(1.0, t))
+ return tuple(int(a[idx] + (b[idx] - a[idx]) * t) for idx in range(3))
+
+
+def _trim_middle(text: str, max_len: int) -> str:
+ if len(text) <= max_len:
+ return text
+ keep = max(4, (max_len - 1) // 2)
+ return f"{text[:keep]}…{text[-keep:]}"
+
+
+def _wrap_trimmed(text: str, *, width_chars: int, max_lines: int) -> List[str]:
+ wrapped = textwrap.wrap(text, width=width_chars, replace_whitespace=False, drop_whitespace=False) or [text]
+ if len(wrapped) > max_lines:
+ wrapped = wrapped[:max_lines]
+ wrapped[-1] = _trim_middle(wrapped[-1].strip(), width_chars)
+ return [line.rstrip() for line in wrapped]
+
+
+def _readable_command_text(cmd_text: str) -> str:
+ normalized = cmd_text.strip()
+ replacements = {
+ str(Path(FREECAD_CLI)): "cli-anything-freecad",
+ str(Path(CLI_HUB)): "cli-hub",
+ "/root/miniconda3/bin/cli-anything-freecad": "cli-anything-freecad",
+ "/root/miniconda3/bin/cli-hub": "cli-hub",
+ }
+ for source, target in replacements.items():
+ normalized = normalized.replace(source, target)
+ return normalized
+
+
+def _draw_text_right(
+ draw: ImageDraw.ImageDraw,
+ x: int,
+ y: int,
+ text: str,
+ *,
+ font: ImageFont.FreeTypeFont,
+ fill: str,
+) -> None:
+ bbox = draw.textbbox((0, 0), text, font=font)
+ draw.text((x - (bbox[2] - bbox[0]), y), text, fill=fill, font=font)
+
+
+def _alpha_box(
+ canvas: Image.Image,
+ area: tuple[int, int, int, int],
+ *,
+ radius: int,
+ fill: tuple[int, int, int, int],
+ outline: Optional[tuple[int, int, int, int]] = None,
+ width: int = 1,
+) -> None:
+ overlay = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(overlay)
+ draw.rounded_rectangle(area, radius=radius, fill=fill, outline=outline, width=width)
+ canvas.alpha_composite(overlay)
+
+
+def _draw_panel(
+ canvas: Image.Image,
+ area: tuple[int, int, int, int],
+ *,
+ radius: int,
+ fill: str,
+ outline: str,
+ accent: Optional[str] = None,
+) -> None:
+ x0, y0, x1, y1 = area
+ shadow = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(shadow)
+ for offset, alpha in ((20, 24), (10, 40), (4, 72)):
+ draw.rounded_rectangle(
+ (x0 + offset, y0 + offset, x1 + offset, y1 + offset),
+ radius=radius,
+ fill=(0, 0, 0, alpha),
+ )
+ canvas.alpha_composite(shadow)
+ _alpha_box(canvas, area, radius=radius, fill=_rgba(fill, 238), outline=_rgba(outline, 255), width=2)
+ if accent:
+ _alpha_box(canvas, (x0 + 14, y0 + 12, x1 - 14, y0 + 18), radius=6, fill=_rgba(accent, 220))
+
+
+def _draw_chip(
+ canvas: Image.Image,
+ box: tuple[int, int, int, int],
+ *,
+ text: str,
+ font: ImageFont.FreeTypeFont,
+ fill: str,
+ text_fill: str,
+ outline: Optional[str] = None,
+) -> None:
+ x0, y0, x1, y1 = box
+ _alpha_box(
+ canvas,
+ box,
+ radius=min(14, (y1 - y0) // 2),
+ fill=_rgba(fill, 245),
+ outline=_rgba(outline or fill, 255),
+ width=1,
+ )
+ draw = ImageDraw.Draw(canvas)
+ bbox = draw.textbbox((0, 0), text, font=font)
+ tw = bbox[2] - bbox[0]
+ th = bbox[3] - bbox[1]
+ draw.text((x0 + ((x1 - x0) - tw) / 2, y0 + ((y1 - y0) - th) / 2 - 1), text, fill=text_fill, font=font)
+
+
+def _draw_segment_bar(
+ canvas: Image.Image,
+ box: tuple[int, int, int, int],
+ *,
+ done: int,
+ total: int,
+ fill: str,
+ empty: str,
+) -> None:
+ x0, y0, x1, y1 = box
+ if total <= 0:
+ return
+ available_w = max(1, x1 - x0)
+ min_seg_w = 1 if total > 28 else 2
+ target_gap = 4 if total <= 18 else 2
+ if total > 1:
+ max_gap = max(0, (available_w - total * min_seg_w) // (total - 1))
+ gap = min(target_gap, max_gap)
+ else:
+ gap = 0
+ seg_w = max(min_seg_w, int((available_w - gap * (total - 1)) / total))
+ overlay = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(overlay)
+ for idx in range(total):
+ sx0 = x0 + idx * (seg_w + gap)
+ if sx0 >= x1:
+ break
+ sx1 = min(x1, max(sx0 + 1, sx0 + seg_w))
+ color = fill if idx < done else empty
+ alpha = 235 if idx < done else 125
+ draw.rounded_rectangle((sx0, y0, sx1, y1), radius=4, fill=_rgba(color, alpha))
+ canvas.alpha_composite(overlay)
+
+
+def _draw_soft_glow(
+ canvas: Image.Image,
+ *,
+ center: tuple[int, int],
+ radius: int,
+ color: str,
+ strength: int,
+) -> None:
+ overlay = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(overlay)
+ cx, cy = center
+ for idx, scale in enumerate((1.0, 0.72, 0.45)):
+ r = int(radius * scale)
+ alpha = max(0, strength - idx * (strength // 3))
+ draw.ellipse((cx - r, cy - r, cx + r, cy + r), fill=_rgba(color, alpha))
+ canvas.alpha_composite(overlay)
+
+
+def build_static_backdrop() -> Image.Image:
+ image = Image.new("RGBA", (VIDEO_W, VIDEO_H), _rgba(COLORS["bg_bottom"]))
+ pixels = image.load()
+ for y in range(VIDEO_H):
+ row = _mix(COLORS["bg_top"], COLORS["bg_bottom"], y / max(1, VIDEO_H - 1))
+ for x in range(VIDEO_W):
+ pixels[x, y] = (*row, 255)
+
+ overlay = Image.new("RGBA", image.size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(overlay)
+
+ for x in range(0, VIDEO_W, 42):
+ draw.line((x, 0, x, VIDEO_H), fill=_rgba(COLORS["grid_soft"], 48), width=1)
+ for y in range(0, VIDEO_H, 42):
+ draw.line((0, y, VIDEO_W, y), fill=_rgba(COLORS["grid_soft"], 40), width=1)
+
+ for x in range(0, VIDEO_W, 168):
+ draw.line((x, 0, x, VIDEO_H), fill=_rgba(COLORS["grid"], 42), width=1)
+ for y in range(0, VIDEO_H, 168):
+ draw.line((0, y, VIDEO_W, y), fill=_rgba(COLORS["grid"], 38), width=1)
+
+ draw.arc((-180, 560, 430, 1170), start=272, end=18, fill=_rgba(COLORS["accent"], 46), width=2)
+ draw.arc((1180, -220, 1840, 420), start=156, end=292, fill=_rgba(COLORS["accent_warm"], 38), width=2)
+ draw.line((0, VIDEO_H - 88, VIDEO_W, VIDEO_H - 88), fill=_rgba(COLORS["grid"], 55), width=1)
+ draw.line((0, 74, VIDEO_W, 74), fill=_rgba(COLORS["grid"], 32), width=1)
+ image.alpha_composite(overlay)
+
+ _draw_soft_glow(image, center=(270, 180), radius=180, color=COLORS["accent"], strength=26)
+ _draw_soft_glow(image, center=(1310, 160), radius=240, color=COLORS["accent_warm"], strength=22)
+ _draw_soft_glow(image, center=(1130, 710), radius=200, color=COLORS["panel_glow"], strength=16)
+ return image
+
+
+def text_lines(text: str, width_chars: int) -> List[str]:
+ lines: List[str] = []
+ for raw in text.splitlines():
+ if not raw:
+ lines.append("")
+ continue
+ wrapped = textwrap.wrap(raw, width=width_chars, replace_whitespace=False, drop_whitespace=False)
+ lines.extend(wrapped or [""])
+ return lines
+
+
+def build_terminal_lines(trajectory: Dict[str, Any], t_real: float, *, width_chars: int) -> List[Dict[str, str]]:
+ lines: List[Dict[str, str]] = []
+ active_cmd: Optional[Dict[str, Any]] = None
+
+ for cmd in trajectory["commands"]:
+ if cmd["timeline_start_s"] > t_real:
+ break
+ lines.append({"text": f"$ {cmd['display_cmd']}", "kind": "cmd"})
+ if t_real < cmd["timeline_end_s"]:
+ active_cmd = cmd
+ dots = "." * (1 + (int(t_real * 3) % 3))
+ lines.append({"text": f"# running{dots}", "kind": "muted"})
+ break
+ stdout = cmd.get("stdout", "")
+ stderr = cmd.get("stderr", "")
+ if stdout.strip():
+ for line in text_lines(stdout.rstrip(), width_chars):
+ stripped = line.strip()
+ kind = "json" if stripped.startswith(("{", "}", "[", "]", "\"")) else "out"
+ lines.append({"text": line, "kind": kind})
+ if stderr.strip():
+ for line in text_lines(stderr.rstrip(), width_chars):
+ lines.append({"text": line, "kind": "err"})
+ lines.append({"text": "", "kind": "out"})
+
+ if active_cmd is None and trajectory["commands"]:
+ last_cmd = trajectory["commands"][-1]
+ if t_real > last_cmd["timeline_end_s"] + 0.8:
+ lines.append({"text": "# trajectory complete", "kind": "success"})
+ return lines[-30:]
+
+
+def pick_preview_event(trajectory: Dict[str, Any], t_real: float) -> Optional[Dict[str, Any]]:
+ latest = None
+ for event in trajectory["preview_events"]:
+ if event["timeline_ready_s"] <= t_real:
+ latest = event
+ else:
+ break
+ return latest
+
+
+def progress_snapshot(trajectory: Dict[str, Any], t_real: float) -> Dict[str, Any]:
+ completed_cmds = sum(1 for cmd in trajectory["commands"] if cmd["timeline_end_s"] <= t_real)
+ completed_previews = sum(1 for event in trajectory["preview_events"] if event["timeline_ready_s"] <= t_real)
+ active_cmd = None
+ for cmd in trajectory["commands"]:
+ if cmd["timeline_start_s"] <= t_real < cmd["timeline_end_s"]:
+ active_cmd = cmd
+ break
+ return {
+ "completed_cmds": completed_cmds,
+ "total_cmds": len(trajectory["commands"]),
+ "completed_previews": completed_previews,
+ "total_previews": len(trajectory["preview_events"]),
+ "active_cmd": active_cmd,
+ "current_event": pick_preview_event(trajectory, t_real),
+ }
+
+
+def build_command_cards(trajectory: Dict[str, Any], t_real: float, *, max_cards: int = 6) -> List[Dict[str, Any]]:
+ commands = trajectory.get("commands", [])
+ if not commands:
+ return []
+
+ active_idx: Optional[int] = None
+ completed = 0
+ for idx, cmd in enumerate(commands):
+ if t_real >= cmd["timeline_end_s"]:
+ completed += 1
+ elif cmd["timeline_start_s"] <= t_real < cmd["timeline_end_s"]:
+ active_idx = idx
+ break
+
+ if active_idx is None:
+ focus_idx = min(len(commands) - 1, completed)
+ else:
+ focus_idx = active_idx
+
+ start = max(0, focus_idx - 2)
+ start = min(start, max(0, len(commands) - max_cards))
+ selected = commands[start:start + max_cards]
+
+ cards: List[Dict[str, Any]] = []
+ for idx, cmd in enumerate(selected, start=start):
+ if t_real >= cmd["timeline_end_s"]:
+ status = "done"
+ elif cmd["timeline_start_s"] <= t_real < cmd["timeline_end_s"]:
+ status = "live"
+ else:
+ status = "queued"
+
+ cards.append(
+ {
+ "index": idx,
+ "status": status,
+ "label": cmd.get("label") or cmd.get("id") or f"Step {idx + 1}",
+ "command": _readable_command_text(cmd.get("display_cmd", "")),
+ "duration_s": float(cmd.get("duration_s") or 0.0),
+ }
+ )
+ return cards
+
+
+def draw_global_header(
+ canvas: Image.Image,
+ trajectory: Dict[str, Any],
+ t_real: float,
+ fonts: Dict[str, ImageFont.FreeTypeFont],
+) -> None:
+ draw = ImageDraw.Draw(canvas)
+ snapshot = progress_snapshot(trajectory, t_real)
+ title = trajectory.get("scenario_title", "FreeCAD Live Demo").upper()
+ subtitle = trajectory.get("scenario_subtitle", "real CLI trajectory + real preview bundles")
+
+ draw.text((34, 20), "CLI-ANYTHING / FREECAD / LIVE PREVIEW PROTOCOL", fill="#88a9c8", font=fonts["small"])
+ draw.text((34, 36), title, fill=COLORS["white"], font=fonts["display"])
+ draw.text((34, 68), subtitle, fill="#97abc2", font=fonts["body"])
+
+ chip_y = 20
+ chips = [
+ f"T+ {t_real:05.1f}s",
+ f"{snapshot['completed_cmds']:02d}/{snapshot['total_cmds']:02d} cmds",
+ f"{snapshot['completed_previews']:02d}/{snapshot['total_previews']:02d} bundles",
+ ]
+ x = VIDEO_W - 34
+ for text in reversed(chips):
+ bbox = draw.textbbox((0, 0), text, font=fonts["mono_small"])
+ chip_w = (bbox[2] - bbox[0]) + 26
+ _draw_chip(
+ canvas,
+ (x - chip_w, chip_y, x, chip_y + 26),
+ text=text,
+ font=fonts["mono_small"],
+ fill=COLORS["chip_bg"],
+ text_fill=COLORS["chip_text"],
+ outline=COLORS["panel_line"],
+ )
+ x -= chip_w + 10
+
+ draw.line((30, 98, VIDEO_W - 30, 98), fill=_rgba(COLORS["grid"], 120), width=1)
+
+
+def draw_terminal_panel(
+ canvas: Image.Image,
+ area: tuple[int, int, int, int],
+ trajectory: Dict[str, Any],
+ t_real: float,
+ fonts: Dict[str, ImageFont.FreeTypeFont],
+) -> None:
+ x0, y0, x1, y1 = area
+ draw = ImageDraw.Draw(canvas)
+ snapshot = progress_snapshot(trajectory, t_real)
+ _draw_panel(canvas, area, radius=30, fill=COLORS["panel"], outline=COLORS["panel_line"], accent=COLORS["accent"])
+
+ draw.text((x0 + 24, y0 + 24), "Agent Command Stream", fill=COLORS["white"], font=fonts["title"])
+ _draw_chip(
+ canvas,
+ (x1 - 190, y0 + 24, x1 - 24, y0 + 50),
+ text="REAL COMMAND TRACE",
+ font=fonts["mono_small"],
+ fill=COLORS["accent_soft"],
+ text_fill=COLORS["accent"],
+ outline=COLORS["accent"],
+ )
+
+ active_label = snapshot["active_cmd"]["label"] if snapshot["active_cmd"] else (
+ snapshot["current_event"]["step_label"] if snapshot["current_event"] else "waiting for first command"
+ )
+ draw.text((x0 + 24, y0 + 58), _trim_middle(active_label, 46), fill="#9bb4ce", font=fonts["body"])
+ _draw_segment_bar(
+ canvas,
+ (x0 + 24, y0 + 90, x1 - 24, y0 + 101),
+ done=snapshot["completed_cmds"],
+ total=max(1, snapshot["total_cmds"]),
+ fill=COLORS["accent"],
+ empty=COLORS["panel_line"],
+ )
+
+ chip_y = y0 + 116
+ chip_specs = [
+ (f"cmd {snapshot['completed_cmds']:02d}/{snapshot['total_cmds']:02d}", COLORS["chip_bg"], COLORS["chip_text"]),
+ (f"preview {snapshot['completed_previews']:02d}/{snapshot['total_previews']:02d}", COLORS["chip_bg"], COLORS["chip_text"]),
+ ("poll-mode live", COLORS["accent_soft"], COLORS["accent"]),
+ ]
+ chip_x = x0 + 24
+ for text, fill, text_fill in chip_specs:
+ bbox = draw.textbbox((0, 0), text, font=fonts["mono_small"])
+ chip_w = (bbox[2] - bbox[0]) + 24
+ _draw_chip(canvas, (chip_x, chip_y, chip_x + chip_w, chip_y + 24), text=text, font=fonts["mono_small"], fill=fill, text_fill=text_fill, outline=COLORS["panel_line"])
+ chip_x += chip_w + 10
+
+ body_area = (x0 + 16, y0 + 154, x1 - 16, y1 - 44)
+ _alpha_box(canvas, body_area, radius=22, fill=_rgba(COLORS["terminal_bg"], 246), outline=_rgba(COLORS["panel_line"], 255), width=1)
+
+ draw.text((body_area[0] + 18, body_area[1] + 16), "Recent commands", fill=COLORS["white"], font=fonts["body"])
+ draw.text((body_area[2] - 168, body_area[1] + 16), "normalized real CLI", fill=COLORS["terminal_muted"], font=fonts["small"])
+
+ cards = build_command_cards(trajectory, t_real, max_cards=6)
+ card_gap = 10
+ card_height = 82
+ card_x0 = body_area[0] + 14
+ card_x1 = body_area[2] - 14
+ card_y = body_area[1] + 48
+ for card in cards:
+ status = card["status"]
+ if status == "live":
+ fill = "#0d2630"
+ outline = COLORS["accent"]
+ status_fill = COLORS["accent_soft"]
+ status_text = COLORS["accent"]
+ label_fill = COLORS["white"]
+ elif status == "done":
+ fill = "#0e1826"
+ outline = COLORS["panel_line"]
+ status_fill = "#123648"
+ status_text = "#9ddfff"
+ label_fill = "#dbe6f3"
+ else:
+ fill = "#0a111a"
+ outline = "#173049"
+ status_fill = "#111f30"
+ status_text = "#6f87a2"
+ label_fill = "#9bb0c7"
+
+ box = (card_x0, card_y, card_x1, card_y + card_height)
+ _alpha_box(canvas, box, radius=18, fill=_rgba(fill, 248), outline=_rgba(outline, 255), width=2 if status == "live" else 1)
+ _alpha_box(canvas, (box[0] + 10, box[1] + 10, box[0] + 14, box[3] - 10), radius=2, fill=_rgba(outline, 255))
+ if status == "live":
+ _draw_soft_glow(canvas, center=(box[2] - 34, box[1] + 24), radius=26, color=COLORS["accent"], strength=34)
+
+ _draw_chip(
+ canvas,
+ (box[0] + 22, box[1] + 12, box[0] + 74, box[1] + 34),
+ text=f"{card['index'] + 1:02d}",
+ font=fonts["mono_small"],
+ fill=COLORS["chip_bg"],
+ text_fill=COLORS["chip_text"],
+ outline=COLORS["panel_line"],
+ )
+ _draw_chip(
+ canvas,
+ (box[2] - 114, box[1] + 12, box[2] - 18, box[1] + 34),
+ text=status.upper(),
+ font=fonts["mono_small"],
+ fill=status_fill,
+ text_fill=status_text,
+ outline=outline,
+ )
+ draw.text((box[0] + 84, box[1] + 10), _trim_middle(card["label"], 38), fill=label_fill, font=fonts["body"])
+ draw.text((box[2] - 182, box[3] - 26), f"{card['duration_s']:.2f}s", fill=COLORS["terminal_muted"], font=fonts["mono_small"])
+
+ command_lines = _wrap_trimmed(card["command"], width_chars=54, max_lines=2)
+ cmd_y = box[1] + 38
+ for line in command_lines:
+ draw.text((box[0] + 22, cmd_y), line, fill=COLORS["terminal_cmd"] if status != "queued" else "#6e8aa6", font=fonts["mono_small"])
+ cmd_y += 17
+
+ card_y += card_height + card_gap
+
+ footer = "Real command strings from the captured trajectory, styled as an agent operations panel."
+ draw.text((x0 + 24, y1 - 28), footer, fill=COLORS["terminal_muted"], font=fonts["small"])
+
+
+def _paste_preview_card(
+ canvas: Image.Image,
+ box: tuple[int, int, int, int],
+ *,
+ img_path: Optional[str],
+ label: str,
+ fonts: Dict[str, ImageFont.FreeTypeFont],
+ main: bool = False,
+) -> None:
+ x0, y0, x1, y1 = box
+ _alpha_box(canvas, box, radius=18 if main else 14, fill=_rgba(COLORS["paper"], 255), outline=_rgba(COLORS["paper_line"], 255), width=2)
+ if img_path and Path(img_path).is_file():
+ fit = fit_image(Image.open(img_path), (max(1, x1 - x0 - 18), max(1, y1 - y0 - 18)), background=COLORS["paper"])
+ canvas.paste(fit.convert("RGBA"), (x0 + 9, y0 + 9))
+ _draw_chip(
+ canvas,
+ (x0 + 12, y0 + 12, x0 + 100, y0 + 36),
+ text=label,
+ font=fonts["mono_small"],
+ fill="#fffaf3",
+ text_fill="#5b5145",
+ outline=COLORS["paper_line"],
+ )
+ overlay = Image.new("RGBA", canvas.size, (0, 0, 0, 0))
+ draw = ImageDraw.Draw(overlay)
+ draw.line((x0 + 10, y0 + 10, x0 + 30, y0 + 10), fill=_rgba(COLORS["accent_warm"], 160), width=2)
+ draw.line((x0 + 10, y0 + 10, x0 + 10, y0 + 30), fill=_rgba(COLORS["accent_warm"], 160), width=2)
+ draw.line((x1 - 10, y1 - 10, x1 - 30, y1 - 10), fill=_rgba(COLORS["accent"], 160), width=2)
+ draw.line((x1 - 10, y1 - 10, x1 - 10, y1 - 30), fill=_rgba(COLORS["accent"], 160), width=2)
+ canvas.alpha_composite(overlay)
+
+
+def compose_preview_dashboard(
+ event: Dict[str, Any],
+ size: tuple[int, int],
+ *,
+ scenario: str,
+ fonts: Dict[str, ImageFont.FreeTypeFont],
+) -> Image.Image:
+ width, height = size
+ canvas = Image.new("RGBA", size, _rgba(COLORS["preview_shell"], 255))
+ _alpha_box(canvas, (0, 0, width - 1, height - 1), radius=22, fill=_rgba(COLORS["preview_shell"], 255), outline=_rgba(COLORS["panel_line"], 255), width=2)
+
+ copied = event["copied_bundle"]["artifacts"]
+ primary = "front" if scenario in {"empire-state-building", "taipei-101"} else "hero"
+ secondary = ["hero", "right", "top"] if primary == "front" else ["front", "top", "right"]
+
+ main_box = (18, 18, width - 18, int(height * 0.74))
+ _paste_preview_card(canvas, main_box, img_path=copied.get(primary), label=primary.upper(), fonts=fonts, main=True)
+
+ thumb_y = int(height * 0.77)
+ thumb_h = height - thumb_y - 18
+ thumb_w = (width - 48) // len(secondary)
+ for idx, key in enumerate(secondary):
+ x0 = 18 + idx * (thumb_w + 6)
+ _paste_preview_card(
+ canvas,
+ (x0, thumb_y, x0 + thumb_w, thumb_y + thumb_h),
+ img_path=copied.get(key),
+ label=key.upper(),
+ fonts=fonts,
+ )
+ return canvas
+
+
+def draw_preview_panel(
+ canvas: Image.Image,
+ area: tuple[int, int, int, int],
+ trajectory: Dict[str, Any],
+ t_real: float,
+ fonts: Dict[str, ImageFont.FreeTypeFont],
+) -> None:
+ x0, y0, x1, y1 = area
+ draw = ImageDraw.Draw(canvas)
+ _draw_panel(canvas, area, radius=30, fill=COLORS["panel"], outline=COLORS["panel_line"], accent=COLORS["accent_warm"])
+ draw.text((x0 + 24, y0 + 24), "Preview Monitor", fill=COLORS["white"], font=fonts["title"])
+ _draw_chip(
+ canvas,
+ (x1 - 140, y0 + 24, x1 - 24, y0 + 50),
+ text="POLL MODE",
+ font=fonts["mono_small"],
+ fill="#351d17",
+ text_fill=COLORS["accent_warm"],
+ outline=COLORS["accent_warm"],
+ )
+ draw.text((x0 + 24, y0 + 58), "Bundle stream from the active FreeCAD live session", fill=COLORS["preview_muted"], font=fonts["body"])
+
+ event = pick_preview_event(trajectory, t_real)
+ if event is None:
+ draw.text((x0 + 28, y0 + 96), "Waiting for first live preview bundle...", fill=COLORS["preview_muted"], font=fonts["body"])
+ return
+
+ command = trajectory["commands"][event["step_index"]]
+ info_w = 246
+ stage_area = (x0 + 20, y0 + 96, x1 - info_w - 18, y1 - 20)
+ info_area = (x1 - info_w, y0 + 96, x1 - 20, y1 - 20)
+ _alpha_box(canvas, info_area, radius=20, fill=_rgba(COLORS["panel_soft"], 252), outline=_rgba(COLORS["panel_line"], 255), width=1)
+
+ scenario = trajectory.get("scenario")
+ stage = compose_preview_dashboard(
+ event,
+ (stage_area[2] - stage_area[0], stage_area[3] - stage_area[1]),
+ scenario=scenario or "",
+ fonts=fonts,
+ )
+ canvas.paste(stage, (stage_area[0], stage_area[1]))
+
+ meta_lines = [
+ ("STEP", event["step_label"]),
+ ("BUNDLE", _trim_middle(event["copied_bundle"]["bundle_id"], 18)),
+ ("CAUSE", event.get("publish_reason") or "n/a"),
+ ("LATENCY", f"{event['latency_s']:.2f}s"),
+ ("CMD TIME", f"{command['duration_s']:.2f}s"),
+ ("STREAM", f"{event.get('sequence_index', event['bundle_count']):02d}/{len(trajectory['preview_events']):02d}"),
+ ]
+
+ draw.text((info_area[0] + 16, info_area[1] + 16), "Telemetry", fill=COLORS["white"], font=fonts["body"])
+ meta_y = info_area[1] + 46
+ for label, value in meta_lines:
+ _draw_chip(
+ canvas,
+ (info_area[0] + 16, meta_y, info_area[2] - 16, meta_y + 28),
+ text=label,
+ font=fonts["mono_small"],
+ fill=COLORS["chip_bg"],
+ text_fill=COLORS["chip_text"],
+ outline=COLORS["panel_line"],
+ )
+ draw.text((info_area[0] + 18, meta_y + 36), value, fill=COLORS["white"], font=fonts["body"])
+ meta_y += 74
+
+ step_progress = event.get("sequence_index", event["bundle_count"])
+ _draw_segment_bar(
+ canvas,
+ (info_area[0] + 16, info_area[3] - 52, info_area[2] - 16, info_area[3] - 38),
+ done=step_progress,
+ total=max(1, len(trajectory["preview_events"])),
+ fill=COLORS["accent_warm"],
+ empty=COLORS["panel_line"],
+ )
+ draw.text((info_area[0] + 16, info_area[3] - 80), "Real preview artifacts only. No synthetic viewport frames.", fill=COLORS["preview_muted"], font=fonts["small"])
+
+
+def compose_showcase_frame(
+ trajectory: Dict[str, Any],
+ showcase: Dict[str, Any],
+ showcase_t: float,
+ final_t_real: float,
+ fonts: Dict[str, ImageFont.FreeTypeFont],
+ backdrop: Image.Image,
+ image_cache: Dict[int, Image.Image],
+) -> Image.Image:
+ sequence = showcase.get("sequence") or {}
+ frames = sequence.get("frames") or []
+ if not frames:
+ raise RuntimeError("Showcase sequence is empty")
+
+ total_duration = float(showcase.get("duration_s") or 0.0)
+ if total_duration <= 0.0:
+ last_time = float(frames[-1].get("time") or 0.0)
+ fps = int(sequence.get("fps") or FPS)
+ total_duration = last_time if last_time > 0 else max(0.01, (len(frames) - 1) / max(1, fps))
+ clamped_t = max(0.0, min(showcase_t, total_duration))
+ sequence_pos = (clamped_t / max(0.01, total_duration)) * (len(frames) - 1)
+ frame_index = min(len(frames) - 1, int(round(sequence_pos)))
+
+ stage_size = (VIDEO_W - 180, VIDEO_H - 250)
+
+ def _stage_image(idx: int) -> Image.Image:
+ cached = image_cache.get(idx)
+ if cached is not None:
+ return cached
+ sequence_path = Path(showcase["sequence_path"]).expanduser().resolve()
+ source_path = sequence_path.parent / frames[idx]["path"]
+ stage = fit_image(Image.open(source_path), stage_size, background=COLORS["paper"])
+ cached = stage.convert("RGBA")
+ image_cache[idx] = cached
+ return cached
+
+ stage = _stage_image(frame_index)
+
+ canvas = backdrop.copy()
+ overlay = Image.new("RGBA", canvas.size, _rgba("#050913", 138))
+ canvas.alpha_composite(overlay)
+ draw_global_header(canvas, trajectory, final_t_real, fonts)
+
+ panel = (54, 118, VIDEO_W - 54, VIDEO_H - 54)
+ _draw_panel(canvas, panel, radius=34, fill=COLORS["panel"], outline=COLORS["panel_line"], accent=COLORS["accent_warm"])
+
+ draw = ImageDraw.Draw(canvas)
+ draw.text((panel[0] + 26, panel[1] + 24), "Final Showcase", fill=COLORS["white"], font=fonts["title"])
+ _draw_chip(
+ canvas,
+ (panel[2] - 246, panel[1] + 22, panel[2] - 24, panel[1] + 50),
+ text="TRUE FREECAD MOTION",
+ font=fonts["mono_small"],
+ fill="#351d17",
+ text_fill=COLORS["accent_warm"],
+ outline=COLORS["accent_warm"],
+ )
+
+ subtitle = showcase.get("subtitle") or "real frame-by-frame FreeCAD motion render from the final project"
+ draw.text((panel[0] + 26, panel[1] + 56), subtitle, fill=COLORS["preview_muted"], font=fonts["body"])
+
+ stage_box = (panel[0] + 26, panel[1] + 92, panel[2] - 26, panel[3] - 88)
+ _alpha_box(canvas, stage_box, radius=28, fill=_rgba(COLORS["preview_shell"], 255), outline=_rgba(COLORS["panel_line"], 255), width=2)
+ inset = (stage_box[0] + 16, stage_box[1] + 16)
+ canvas.paste(stage, inset, stage)
+
+ frame_label = f"frame {frame_index + 1:03d}/{len(frames):03d}"
+ progress_label = f"showcase {showcase_t:04.1f}s / {total_duration:04.1f}s"
+ _draw_chip(
+ canvas,
+ (stage_box[0] + 20, stage_box[1] + 18, stage_box[0] + 150, stage_box[1] + 42),
+ text=frame_label.upper(),
+ font=fonts["mono_small"],
+ fill="#fffaf3",
+ text_fill="#5b5145",
+ outline=COLORS["paper_line"],
+ )
+ _draw_chip(
+ canvas,
+ (stage_box[2] - 190, stage_box[1] + 18, stage_box[2] - 20, stage_box[1] + 42),
+ text=progress_label.upper(),
+ font=fonts["mono_small"],
+ fill=COLORS["chip_bg"],
+ text_fill=COLORS["chip_text"],
+ outline=COLORS["panel_line"],
+ )
+
+ _draw_segment_bar(
+ canvas,
+ (panel[0] + 26, panel[3] - 52, panel[2] - 26, panel[3] - 38),
+ done=max(1, frame_index + 1),
+ total=max(1, len(frames)),
+ fill=COLORS["accent_warm"],
+ empty=COLORS["panel_line"],
+ )
+
+ footer = "Real ending sequence: final project JSON + cli-anything-freecad motion render-video + programmatic composition"
+ draw.text((panel[0] + 26, panel[3] - 74), footer, fill=COLORS["preview_muted"], font=fonts["small"])
+ return canvas
+
+
+def render_video(timeline_path: Path, *, output_path: Optional[Path] = None, fps: int = FPS, speed: float = 1.0, keep_frames: bool = True) -> Path:
+ trajectory = load_json(timeline_path)
+ run_dir = timeline_path.parent
+ output_file = output_path or (run_dir / "demo.mp4")
+ output_file.parent.mkdir(parents=True, exist_ok=True)
+ frames_dir = run_dir / "frames"
+ ensure_clean_dir(frames_dir)
+
+ fonts = {
+ "display": load_font(DISPLAY_FONT_PATH, 38),
+ "title": load_font(DISPLAY_FONT_PATH, 24),
+ "body": load_font(SANS_FONT_PATH, 17),
+ "small": load_font(SANS_FONT_PATH, 13),
+ "mono": load_font(MONO_FONT_PATH, 15),
+ "mono_small": load_font(MONO_BOLD_FONT_PATH, 12),
+ }
+ backdrop = build_static_backdrop()
+ if trajectory.get("scenario") == "curiosity":
+ showcase = generate_curiosity_true_motion_showcase(
+ timeline_path,
+ run_dir / "showcase-motion",
+ fps=fps,
+ keep_frames=True,
+ motion_style="combo",
+ )
+ else:
+ showcase = generate_curiosity_showcase_sequence(trajectory, run_dir)
+ showcase_cache: Dict[int, Image.Image] = {}
+
+ last_t = 0.0
+ if trajectory["commands"]:
+ last_t = max(last_t, max(cmd["timeline_end_s"] for cmd in trajectory["commands"]))
+ if trajectory["preview_events"]:
+ last_t = max(last_t, max(event["timeline_ready_s"] for event in trajectory["preview_events"]))
+ main_duration_s = (last_t + HOLD_TAIL_S) / max(speed, 0.01)
+ showcase_duration_s = float(showcase.get("duration_s", SHOWCASE_DURATION_S)) if showcase else 0.0
+ duration_s = main_duration_s + showcase_duration_s
+ frame_count = int(math.ceil(duration_s * fps))
+
+ for frame_idx in range(frame_count):
+ t_display = frame_idx / fps
+ if showcase and t_display >= main_duration_s:
+ showcase_t = t_display - main_duration_s
+ image = compose_showcase_frame(
+ trajectory,
+ showcase,
+ showcase_t,
+ last_t + HOLD_TAIL_S,
+ fonts,
+ backdrop,
+ showcase_cache,
+ )
+ footer_left = "REAL CLI trajectory · REAL live preview bundles · REAL FreeCAD motion ending"
+ else:
+ t_real = t_display * speed
+ image = backdrop.copy()
+ draw_global_header(image, trajectory, t_real, fonts)
+ draw_terminal_panel(image, (26, 116, LEFT_W - 14, VIDEO_H - 34), trajectory, t_real, fonts)
+ draw_preview_panel(image, (LEFT_W + 10, 116, VIDEO_W - 26, VIDEO_H - 34), trajectory, t_real, fonts)
+ footer_left = "REAL CLI trajectory · REAL live preview bundles · programmatic composition"
+
+ draw = ImageDraw.Draw(image)
+ footer_right = _trim_middle(str(timeline_path), 56)
+ draw.text((34, VIDEO_H - 26), footer_left, fill="#7891ab", font=fonts["small"])
+ _draw_text_right(draw, VIDEO_W - 34, VIDEO_H - 26, footer_right, font=fonts["mono_small"], fill="#7891ab")
+
+ image.convert("RGB").save(frames_dir / f"frame_{frame_idx:05d}.png")
+
+ ffmpeg_cmd = [
+ shutil.which("ffmpeg") or "ffmpeg",
+ "-y",
+ "-framerate",
+ str(fps),
+ "-i",
+ str(frames_dir / "frame_%05d.png"),
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ str(output_file),
+ ]
+ subprocess.run(ffmpeg_cmd, cwd=run_dir, capture_output=True, text=True, timeout=600, check=True)
+
+ if not keep_frames:
+ shutil.rmtree(frames_dir)
+ return output_file
+
+
+def parse_args() -> argparse.Namespace:
+ today = datetime.now(timezone.utc).strftime("%Y%m%d")
+ default_output = Path.home() / "preview-artifacts" / today / "freecad-live-video"
+
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "mode",
+ choices=["collect", "render", "run-all", "motion-showcase"],
+ help="Collect a real trajectory, render a video from an existing trajectory, or do both.",
+ )
+ parser.add_argument(
+ "--output-dir",
+ default=str(default_output),
+ help="Directory for collected artifacts and rendered video.",
+ )
+ parser.add_argument(
+ "--scenario",
+ default="orbital-relay",
+ choices=sorted(SCENARIOS),
+ help="Demo scenario to collect.",
+ )
+ parser.add_argument(
+ "--timeline",
+ default=None,
+ help="Existing trajectory.json path for render mode.",
+ )
+ parser.add_argument("--fps", type=int, default=FPS, help="Output video framerate.")
+ parser.add_argument("--speed", type=float, default=1.0, help="Playback speed multiplier.")
+ parser.add_argument("--no-frames", action="store_true", help="Delete intermediate frame PNGs after encoding.")
+ parser.add_argument(
+ "--motion-style",
+ default="drive",
+ choices=["drive", "spin", "combo"],
+ help="Motion showcase style for motion-showcase mode.",
+ )
+ return parser.parse_args()
+
+
+def main() -> int:
+ args = parse_args()
+ output_dir = Path(args.output_dir).expanduser().resolve()
+
+ if args.mode == "collect":
+ timeline = collect_demo(output_dir, args.scenario)
+ print(timeline)
+ return 0
+
+ if args.mode == "render":
+ if not args.timeline:
+ raise SystemExit("--timeline is required for render mode")
+ output_path = render_video(
+ Path(args.timeline).expanduser().resolve(),
+ fps=args.fps,
+ speed=args.speed,
+ keep_frames=not args.no_frames,
+ )
+ print(output_path)
+ return 0
+
+ if args.mode == "motion-showcase":
+ if not args.timeline:
+ raise SystemExit("--timeline is required for motion-showcase mode")
+ manifest = generate_curiosity_true_motion_showcase(
+ Path(args.timeline).expanduser().resolve(),
+ output_dir,
+ fps=args.fps,
+ keep_frames=not args.no_frames,
+ motion_style=args.motion_style,
+ )
+ print(json.dumps(manifest, indent=2))
+ return 0
+
+ timeline = collect_demo(output_dir, args.scenario)
+ output_path = render_video(
+ timeline,
+ fps=args.fps,
+ speed=args.speed,
+ keep_frames=not args.no_frames,
+ )
+ print(json.dumps({"timeline": str(timeline), "video": str(output_path)}, indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/freecad/agent-harness/cli_anything/freecad/core/body.py b/freecad/agent-harness/cli_anything/freecad/core/body.py
index 2d54b9941..a55c800de 100644
--- a/freecad/agent-harness/cli_anything/freecad/core/body.py
+++ b/freecad/agent-harness/cli_anything/freecad/core/body.py
@@ -97,6 +97,30 @@ def _validate_sketch_index(project: Dict[str, Any], sketch_index: int) -> Dict[s
return sketches[sketch_index]
+def _validate_vec3(value: Optional[List[float]], label: str) -> Optional[List[float]]:
+ """Validate and normalize a 3-component vector."""
+ if value is None:
+ return None
+ if not isinstance(value, (list, tuple)) or len(value) != 3:
+ raise ValueError(f"{label} must be a list of 3 numbers")
+ return [float(component) for component in value]
+
+
+def _normalize_feature_placement(
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Optional[Dict[str, List[float]]]:
+ """Normalize optional position/rotation into a placement payload."""
+ pos = _validate_vec3(position, "position")
+ rot = _validate_vec3(rotation, "rotation")
+ if pos is None and rot is None:
+ return None
+ return {
+ "position": pos or [0.0, 0.0, 0.0],
+ "rotation": rot or [0.0, 0.0, 0.0],
+ }
+
+
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
@@ -637,6 +661,8 @@ def _additive_primitive(
body_index: int,
primitive_type: str,
params: Dict[str, Any],
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Internal helper to add an additive primitive feature."""
_validate_project(project)
@@ -647,6 +673,9 @@ def _additive_primitive(
"type": f"additive_{primitive_type}",
}
feature.update(params)
+ placement = _normalize_feature_placement(position=position, rotation=rotation)
+ if placement is not None:
+ feature["placement"] = placement
body["features"].append(feature)
return feature
@@ -658,6 +687,8 @@ def additive_box(
length: float = 10.0,
width: float = 10.0,
height: float = 10.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add an additive box primitive to a body.
@@ -683,9 +714,14 @@ def additive_box(
for name, val in [("length", length), ("width", width), ("height", height)]:
if val <= 0:
raise ValueError(f"Box {name} must be positive, got {val}")
- return _additive_primitive(project, body_index, "box", {
- "length": length, "width": width, "height": height,
- })
+ return _additive_primitive(
+ project,
+ body_index,
+ "box",
+ {"length": length, "width": width, "height": height},
+ position=position,
+ rotation=rotation,
+ )
def additive_cylinder(
@@ -693,6 +729,8 @@ def additive_cylinder(
body_index: int,
radius: float = 5.0,
height: float = 10.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add an additive cylinder primitive to a body.
@@ -717,15 +755,22 @@ def additive_cylinder(
raise ValueError(f"Cylinder radius must be positive, got {radius}")
if height <= 0:
raise ValueError(f"Cylinder height must be positive, got {height}")
- return _additive_primitive(project, body_index, "cylinder", {
- "radius": radius, "height": height,
- })
+ return _additive_primitive(
+ project,
+ body_index,
+ "cylinder",
+ {"radius": radius, "height": height},
+ position=position,
+ rotation=rotation,
+ )
def additive_sphere(
project: Dict[str, Any],
body_index: int,
radius: float = 5.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add an additive sphere primitive to a body.
@@ -746,7 +791,14 @@ def additive_sphere(
radius = float(radius)
if radius <= 0:
raise ValueError(f"Sphere radius must be positive, got {radius}")
- return _additive_primitive(project, body_index, "sphere", {"radius": radius})
+ return _additive_primitive(
+ project,
+ body_index,
+ "sphere",
+ {"radius": radius},
+ position=position,
+ rotation=rotation,
+ )
def additive_cone(
@@ -755,6 +807,8 @@ def additive_cone(
radius1: float = 5.0,
radius2: float = 0.0,
height: float = 10.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add an additive cone primitive to a body.
@@ -783,9 +837,14 @@ def additive_cone(
raise ValueError(f"Cone radius2 must be non-negative, got {radius2}")
if height <= 0:
raise ValueError(f"Cone height must be positive, got {height}")
- return _additive_primitive(project, body_index, "cone", {
- "radius1": radius1, "radius2": radius2, "height": height,
- })
+ return _additive_primitive(
+ project,
+ body_index,
+ "cone",
+ {"radius1": radius1, "radius2": radius2, "height": height},
+ position=position,
+ rotation=rotation,
+ )
def additive_torus(
@@ -793,6 +852,8 @@ def additive_torus(
body_index: int,
radius1: float = 10.0,
radius2: float = 2.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add an additive torus primitive to a body.
@@ -817,9 +878,14 @@ def additive_torus(
raise ValueError(f"Torus major radius must be positive, got {radius1}")
if radius2 <= 0:
raise ValueError(f"Torus minor radius must be positive, got {radius2}")
- return _additive_primitive(project, body_index, "torus", {
- "radius1": radius1, "radius2": radius2,
- })
+ return _additive_primitive(
+ project,
+ body_index,
+ "torus",
+ {"radius1": radius1, "radius2": radius2},
+ position=position,
+ rotation=rotation,
+ )
def additive_wedge(
@@ -835,6 +901,8 @@ def additive_wedge(
x2max: float = 8.0,
z2min: float = 2.0,
z2max: float = 8.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add an additive wedge primitive to a body.
@@ -854,13 +922,25 @@ def additive_wedge(
Dict[str, Any]
The newly created additive wedge feature dictionary.
"""
- return _additive_primitive(project, body_index, "wedge", {
- "xmin": float(xmin), "xmax": float(xmax),
- "ymin": float(ymin), "ymax": float(ymax),
- "zmin": float(zmin), "zmax": float(zmax),
- "x2min": float(x2min), "x2max": float(x2max),
- "z2min": float(z2min), "z2max": float(z2max),
- })
+ return _additive_primitive(
+ project,
+ body_index,
+ "wedge",
+ {
+ "xmin": float(xmin),
+ "xmax": float(xmax),
+ "ymin": float(ymin),
+ "ymax": float(ymax),
+ "zmin": float(zmin),
+ "zmax": float(zmax),
+ "x2min": float(x2min),
+ "x2max": float(x2max),
+ "z2min": float(z2min),
+ "z2max": float(z2max),
+ },
+ position=position,
+ rotation=rotation,
+ )
# ---------------------------------------------------------------------------
@@ -1100,6 +1180,8 @@ def _subtractive_primitive(
body_index: int,
primitive_type: str,
params: Dict[str, Any],
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Internal helper to add a subtractive primitive feature."""
_validate_project(project)
@@ -1115,6 +1197,9 @@ def _subtractive_primitive(
"type": f"subtractive_{primitive_type}",
}
feature.update(params)
+ placement = _normalize_feature_placement(position=position, rotation=rotation)
+ if placement is not None:
+ feature["placement"] = placement
body["features"].append(feature)
return feature
@@ -1126,6 +1211,8 @@ def subtractive_box(
length: float = 10.0,
width: float = 10.0,
height: float = 10.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add a subtractive box primitive to a body.
@@ -1151,9 +1238,14 @@ def subtractive_box(
for name, val in [("length", length), ("width", width), ("height", height)]:
if val <= 0:
raise ValueError(f"Box {name} must be positive, got {val}")
- return _subtractive_primitive(project, body_index, "box", {
- "length": length, "width": width, "height": height,
- })
+ return _subtractive_primitive(
+ project,
+ body_index,
+ "box",
+ {"length": length, "width": width, "height": height},
+ position=position,
+ rotation=rotation,
+ )
def subtractive_cylinder(
@@ -1161,6 +1253,8 @@ def subtractive_cylinder(
body_index: int,
radius: float = 5.0,
height: float = 10.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add a subtractive cylinder primitive to a body.
@@ -1185,15 +1279,22 @@ def subtractive_cylinder(
raise ValueError(f"Cylinder radius must be positive, got {radius}")
if height <= 0:
raise ValueError(f"Cylinder height must be positive, got {height}")
- return _subtractive_primitive(project, body_index, "cylinder", {
- "radius": radius, "height": height,
- })
+ return _subtractive_primitive(
+ project,
+ body_index,
+ "cylinder",
+ {"radius": radius, "height": height},
+ position=position,
+ rotation=rotation,
+ )
def subtractive_sphere(
project: Dict[str, Any],
body_index: int,
radius: float = 5.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add a subtractive sphere primitive to a body.
@@ -1214,7 +1315,14 @@ def subtractive_sphere(
radius = float(radius)
if radius <= 0:
raise ValueError(f"Sphere radius must be positive, got {radius}")
- return _subtractive_primitive(project, body_index, "sphere", {"radius": radius})
+ return _subtractive_primitive(
+ project,
+ body_index,
+ "sphere",
+ {"radius": radius},
+ position=position,
+ rotation=rotation,
+ )
def subtractive_cone(
@@ -1223,6 +1331,8 @@ def subtractive_cone(
radius1: float = 5.0,
radius2: float = 0.0,
height: float = 10.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add a subtractive cone primitive to a body.
@@ -1251,9 +1361,14 @@ def subtractive_cone(
raise ValueError(f"Cone radius2 must be non-negative, got {radius2}")
if height <= 0:
raise ValueError(f"Cone height must be positive, got {height}")
- return _subtractive_primitive(project, body_index, "cone", {
- "radius1": radius1, "radius2": radius2, "height": height,
- })
+ return _subtractive_primitive(
+ project,
+ body_index,
+ "cone",
+ {"radius1": radius1, "radius2": radius2, "height": height},
+ position=position,
+ rotation=rotation,
+ )
def subtractive_torus(
@@ -1261,6 +1376,8 @@ def subtractive_torus(
body_index: int,
radius1: float = 10.0,
radius2: float = 2.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add a subtractive torus primitive to a body.
@@ -1285,9 +1402,14 @@ def subtractive_torus(
raise ValueError(f"Torus major radius must be positive, got {radius1}")
if radius2 <= 0:
raise ValueError(f"Torus minor radius must be positive, got {radius2}")
- return _subtractive_primitive(project, body_index, "torus", {
- "radius1": radius1, "radius2": radius2,
- })
+ return _subtractive_primitive(
+ project,
+ body_index,
+ "torus",
+ {"radius1": radius1, "radius2": radius2},
+ position=position,
+ rotation=rotation,
+ )
def subtractive_wedge(
@@ -1303,6 +1425,8 @@ def subtractive_wedge(
x2max: float = 8.0,
z2min: float = 2.0,
z2max: float = 8.0,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
) -> Dict[str, Any]:
"""Add a subtractive wedge primitive to a body.
@@ -1322,13 +1446,25 @@ def subtractive_wedge(
Dict[str, Any]
The newly created subtractive wedge feature dictionary.
"""
- return _subtractive_primitive(project, body_index, "wedge", {
- "xmin": float(xmin), "xmax": float(xmax),
- "ymin": float(ymin), "ymax": float(ymax),
- "zmin": float(zmin), "zmax": float(zmax),
- "x2min": float(x2min), "x2max": float(x2max),
- "z2min": float(z2min), "z2max": float(z2max),
- })
+ return _subtractive_primitive(
+ project,
+ body_index,
+ "wedge",
+ {
+ "xmin": float(xmin),
+ "xmax": float(xmax),
+ "ymin": float(ymin),
+ "ymax": float(ymax),
+ "zmin": float(zmin),
+ "zmax": float(zmax),
+ "x2min": float(x2min),
+ "x2max": float(x2max),
+ "z2min": float(z2min),
+ "z2max": float(z2max),
+ },
+ position=position,
+ rotation=rotation,
+ )
# ---------------------------------------------------------------------------
diff --git a/freecad/agent-harness/cli_anything/freecad/core/document.py b/freecad/agent-harness/cli_anything/freecad/core/document.py
index 67bc7b91b..ecc4020bf 100644
--- a/freecad/agent-harness/cli_anything/freecad/core/document.py
+++ b/freecad/agent-harness/cli_anything/freecad/core/document.py
@@ -62,6 +62,7 @@ _REQUIRED_COLLECTIONS = ("parts", "sketches", "bodies", "materials")
_OPTIONAL_COLLECTIONS = (
"assemblies", "meshes", "techdraw_pages", "draft_objects",
"measurements", "surfaces", "fem_analyses", "cam_jobs", "spreadsheets",
+ "motions",
)
ALL_COLLECTIONS = _REQUIRED_COLLECTIONS + _OPTIONAL_COLLECTIONS
@@ -165,6 +166,7 @@ def create_document(
"fem_analyses": [],
"cam_jobs": [],
"spreadsheets": [],
+ "motions": [],
"metadata": {
"created": now,
"modified": now,
diff --git a/freecad/agent-harness/cli_anything/freecad/core/motion.py b/freecad/agent-harness/cli_anything/freecad/core/motion.py
new file mode 100644
index 000000000..bcff69f3a
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/motion.py
@@ -0,0 +1,707 @@
+"""Motion sequencing and real frame rendering for the FreeCAD CLI harness."""
+
+from __future__ import annotations
+
+import copy
+import json
+import math
+import os
+import shutil
+import subprocess
+import tempfile
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+
+from cli_anything.freecad.utils import freecad_backend
+from cli_anything.freecad.utils import freecad_macro_gen as macro_gen
+
+from .document import ensure_collection
+from .parts import get_part
+
+
+CAMERA_PRESETS: Dict[str, Dict[str, str]] = {
+ "hero": {"method": "viewIsometric", "description": "Isometric overview"},
+ "front": {"method": "viewFront", "description": "Front view"},
+ "top": {"method": "viewTop", "description": "Top view"},
+ "right": {"method": "viewRight", "description": "Right view"},
+}
+
+FIT_MODES = {"initial", "per-frame"}
+TARGET_KINDS = {"part"}
+_COLLECTION_KEY = "motions"
+
+
+def _now_iso() -> str:
+ return datetime.now().isoformat()
+
+
+def _next_id(project: Dict[str, Any]) -> int:
+ items = ensure_collection(project, _COLLECTION_KEY)
+ if not items:
+ return 1
+ return max(int(item["id"]) for item in items) + 1
+
+
+def _unique_name(project: Dict[str, Any], base: str) -> str:
+ items = ensure_collection(project, _COLLECTION_KEY)
+ existing = {item["name"] for item in items}
+ if base not in existing:
+ return base
+ counter = 2
+ while f"{base}_{counter}" in existing:
+ counter += 1
+ return f"{base}_{counter}"
+
+
+def _validate_vec3(value: Optional[List[float]], label: str) -> Optional[List[float]]:
+ if value is None:
+ return None
+ if not isinstance(value, (list, tuple)) or len(value) != 3:
+ raise ValueError(f"{label} must be a list of 3 numbers")
+ try:
+ return [float(component) for component in value]
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} elements must be numeric: {exc}") from exc
+
+
+def _validate_time(value: float, duration: float) -> float:
+ numeric = float(value)
+ if numeric < 0.0 or numeric > float(duration):
+ raise ValueError(f"time must be within [0, {duration}], got {numeric}")
+ return numeric
+
+
+def _validate_motion_index(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ items = ensure_collection(project, _COLLECTION_KEY)
+ if not isinstance(index, int) or index < 0 or index >= len(items):
+ raise IndexError(f"Motion index {index} out of range (0..{len(items) - 1})")
+ return items[index]
+
+
+def _track_summary(track: Dict[str, Any]) -> Dict[str, Any]:
+ keyframes = track.get("keyframes", [])
+ return {
+ "target": dict(track.get("target", {})),
+ "keyframe_count": len(keyframes),
+ "time_range": [
+ float(keyframes[0]["time"]) if keyframes else 0.0,
+ float(keyframes[-1]["time"]) if keyframes else 0.0,
+ ],
+ }
+
+
+def _normalize_target(project: Dict[str, Any], target_kind: str, target_index: int) -> Tuple[Dict[str, Any], Dict[str, Any]]:
+ if target_kind not in TARGET_KINDS:
+ raise ValueError(f"Unsupported target_kind '{target_kind}'. Valid: {', '.join(sorted(TARGET_KINDS))}")
+ if target_kind == "part":
+ part = get_part(project, target_index)
+ return (
+ {
+ "kind": "part",
+ "index": int(target_index),
+ "part_id": int(part["id"]),
+ "name": part["name"],
+ },
+ part,
+ )
+ raise ValueError(f"Unsupported target_kind '{target_kind}'")
+
+
+def _resolve_target_part(project: Dict[str, Any], target: Dict[str, Any]) -> Dict[str, Any]:
+ if target.get("kind") != "part":
+ raise ValueError(f"Unsupported motion target: {target}")
+ parts = project.get("parts", [])
+ index = int(target.get("index", -1))
+ part_id = target.get("part_id")
+ if 0 <= index < len(parts) and parts[index].get("id") == part_id:
+ return parts[index]
+ for part in parts:
+ if part.get("id") == part_id:
+ return part
+ raise ValueError(f"Motion target part could not be resolved: {target}")
+
+
+def _find_track(motion: Dict[str, Any], target: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ for track in motion.get("tracks", []):
+ existing = track.get("target", {})
+ if existing.get("kind") == target.get("kind") and existing.get("part_id") == target.get("part_id"):
+ return track
+ return None
+
+
+def _sorted_keyframes(keyframes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ return sorted(keyframes, key=lambda item: (float(item["time"]), json.dumps(item, sort_keys=True)))
+
+
+def _interpolate_vec3(a: List[float], b: List[float], alpha: float) -> List[float]:
+ return [
+ float(a[i]) + (float(b[i]) - float(a[i])) * alpha
+ for i in range(3)
+ ]
+
+
+def _track_state_at_time(track: Dict[str, Any], time_value: float) -> Dict[str, Any]:
+ keyframes = _sorted_keyframes(track.get("keyframes", []))
+ if not keyframes:
+ raise ValueError(f"Track has no keyframes: {track.get('target')}")
+
+ if time_value <= float(keyframes[0]["time"]):
+ first = keyframes[0]
+ return {
+ "position": list(first["position"]),
+ "rotation": list(first["rotation"]),
+ }
+ if time_value >= float(keyframes[-1]["time"]):
+ last = keyframes[-1]
+ return {
+ "position": list(last["position"]),
+ "rotation": list(last["rotation"]),
+ }
+
+ for left, right in zip(keyframes, keyframes[1:]):
+ left_time = float(left["time"])
+ right_time = float(right["time"])
+ if left_time <= time_value <= right_time:
+ if right_time == left_time:
+ alpha = 0.0
+ else:
+ alpha = (time_value - left_time) / (right_time - left_time)
+ return {
+ "position": _interpolate_vec3(left["position"], right["position"], alpha),
+ "rotation": _interpolate_vec3(left["rotation"], right["rotation"], alpha),
+ }
+ last = keyframes[-1]
+ return {
+ "position": list(last["position"]),
+ "rotation": list(last["rotation"]),
+ }
+
+
+def _frame_times(duration: float, fps: int) -> List[float]:
+ if fps <= 0:
+ raise ValueError("fps must be positive")
+ frame_count = max(2, int(round(float(duration) * int(fps))) + 1)
+ return [min(float(duration), i / float(fps)) for i in range(frame_count)]
+
+
+def _safe_path(path: str) -> str:
+ return path.replace("\\", "/")
+
+
+def _ensure_empty_dir(path: str, overwrite: bool) -> str:
+ resolved = os.path.abspath(path)
+ if os.path.isdir(resolved):
+ if os.listdir(resolved):
+ if not overwrite:
+ raise FileExistsError(
+ f"Output directory already exists and is not empty: {resolved}. "
+ "Use overwrite=True to replace it."
+ )
+ shutil.rmtree(resolved)
+ elif os.path.exists(resolved):
+ raise FileExistsError(f"Output path exists and is not a directory: {resolved}")
+ os.makedirs(resolved, exist_ok=True)
+ return resolved
+
+
+def _ffmpeg_path() -> str:
+ ffmpeg = shutil.which("ffmpeg")
+ if ffmpeg:
+ return ffmpeg
+ raise RuntimeError("ffmpeg is required for motion video export but was not found on PATH")
+
+
+def create_motion(
+ project: Dict[str, Any],
+ name: Optional[str] = None,
+ *,
+ duration: float = 2.0,
+ fps: int = 24,
+ camera: str = "hero",
+ width: int = 1280,
+ height: int = 960,
+ background: str = "White",
+ fit_mode: str = "initial",
+) -> Dict[str, Any]:
+ """Create a new motion sequence attached to the project."""
+ items = ensure_collection(project, _COLLECTION_KEY)
+ if float(duration) <= 0:
+ raise ValueError("duration must be greater than 0")
+ if int(fps) <= 0:
+ raise ValueError("fps must be positive")
+ if camera not in CAMERA_PRESETS:
+ raise ValueError(f"Unknown camera '{camera}'. Valid: {', '.join(sorted(CAMERA_PRESETS))}")
+ if fit_mode not in FIT_MODES:
+ raise ValueError(f"Unknown fit_mode '{fit_mode}'. Valid: {', '.join(sorted(FIT_MODES))}")
+ if int(width) <= 0 or int(height) <= 0:
+ raise ValueError("width and height must be positive")
+
+ motion = {
+ "id": _next_id(project),
+ "name": _unique_name(project, name or "Motion"),
+ "duration": float(duration),
+ "fps": int(fps),
+ "camera": camera,
+ "width": int(width),
+ "height": int(height),
+ "background": str(background),
+ "fit_mode": fit_mode,
+ "tracks": [],
+ "metadata": {
+ "created": _now_iso(),
+ "modified": _now_iso(),
+ },
+ }
+ items.append(motion)
+ return motion
+
+
+def list_motions(project: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return summary info for all motion sequences."""
+ items = ensure_collection(project, _COLLECTION_KEY)
+ result = []
+ for index, motion in enumerate(items):
+ keyframe_count = sum(len(track.get("keyframes", [])) for track in motion.get("tracks", []))
+ result.append(
+ {
+ "index": index,
+ "id": motion.get("id"),
+ "name": motion.get("name"),
+ "duration": motion.get("duration"),
+ "fps": motion.get("fps"),
+ "camera": motion.get("camera"),
+ "track_count": len(motion.get("tracks", [])),
+ "keyframe_count": keyframe_count,
+ }
+ )
+ return result
+
+
+def get_motion(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Return a single motion sequence."""
+ return _validate_motion_index(project, index)
+
+
+def delete_motion(project: Dict[str, Any], index: int) -> Dict[str, Any]:
+ """Delete and return a motion sequence."""
+ items = ensure_collection(project, _COLLECTION_KEY)
+ _validate_motion_index(project, index)
+ return items.pop(index)
+
+
+def add_keyframe(
+ project: Dict[str, Any],
+ motion_index: int,
+ *,
+ target_kind: str,
+ target_index: int,
+ time_value: float,
+ position: Optional[List[float]] = None,
+ rotation: Optional[List[float]] = None,
+) -> Dict[str, Any]:
+ """Insert or replace a keyframe on a motion track."""
+ motion = _validate_motion_index(project, motion_index)
+ target, source_obj = _normalize_target(project, target_kind, target_index)
+ placement = source_obj.get("placement", {})
+ resolved_position = _validate_vec3(position, "position") or list(placement.get("position", [0.0, 0.0, 0.0]))
+ resolved_rotation = _validate_vec3(rotation, "rotation") or list(placement.get("rotation", [0.0, 0.0, 0.0]))
+ keyframe = {
+ "time": _validate_time(time_value, float(motion["duration"])),
+ "position": resolved_position,
+ "rotation": resolved_rotation,
+ }
+
+ track = _find_track(motion, target)
+ if track is None:
+ track = {"target": target, "keyframes": []}
+ motion["tracks"].append(track)
+
+ replaced = False
+ updated_keyframes: List[Dict[str, Any]] = []
+ for existing in track["keyframes"]:
+ if math.isclose(float(existing["time"]), keyframe["time"], abs_tol=1e-9):
+ updated_keyframes.append(keyframe)
+ replaced = True
+ else:
+ updated_keyframes.append(existing)
+ if not replaced:
+ updated_keyframes.append(keyframe)
+
+ track["keyframes"] = _sorted_keyframes(updated_keyframes)
+ motion["metadata"]["modified"] = _now_iso()
+ return {
+ "motion": motion["name"],
+ "track": _track_summary(track),
+ "keyframe": keyframe,
+ "replaced": replaced,
+ }
+
+
+def sample_motion(project: Dict[str, Any], motion_index: int, time_value: float) -> Dict[str, Any]:
+ """Evaluate a motion sequence at an arbitrary time."""
+ motion = _validate_motion_index(project, motion_index)
+ resolved_time = _validate_time(time_value, float(motion["duration"]))
+ placements = []
+ for track in motion.get("tracks", []):
+ state = _track_state_at_time(track, resolved_time)
+ placements.append(
+ {
+ "target": dict(track["target"]),
+ "position": state["position"],
+ "rotation": state["rotation"],
+ }
+ )
+ return {
+ "motion": motion["name"],
+ "time": resolved_time,
+ "camera": motion["camera"],
+ "placements": placements,
+ }
+
+
+def apply_motion(project: Dict[str, Any], motion_index: int, time_value: float) -> Dict[str, Any]:
+ """Return a deep-copied project with interpolated placements applied."""
+ sampled = sample_motion(project, motion_index, time_value)
+ project_copy = copy.deepcopy(project)
+ for placement in sampled["placements"]:
+ target = placement["target"]
+ if target["kind"] != "part":
+ continue
+ part = _resolve_target_part(project_copy, target)
+ part.setdefault("placement", {})
+ part["placement"]["position"] = list(placement["position"])
+ part["placement"]["rotation"] = list(placement["rotation"])
+ return project_copy
+
+
+def _motion_frames(project: Dict[str, Any], motion: Dict[str, Any], output_dir: str) -> Dict[str, Any]:
+ frames: List[Dict[str, Any]] = []
+ unsupported_targets: List[Dict[str, Any]] = []
+ unsupported_seen = set()
+
+ times = _frame_times(float(motion["duration"]), int(motion["fps"]))
+ for frame_index, time_value in enumerate(times):
+ placements: Dict[str, Dict[str, List[float]]] = {}
+ for track in motion.get("tracks", []):
+ target = dict(track["target"])
+ part = _resolve_target_part(project, target)
+ render_spec = macro_gen._render_spec_for_part(project, part)
+ if render_spec is None:
+ signature = (target.get("kind"), target.get("part_id"))
+ if signature not in unsupported_seen:
+ unsupported_seen.add(signature)
+ unsupported_targets.append(target)
+ continue
+ state = _track_state_at_time(track, time_value)
+ placements[str(target["part_id"])] = {
+ "position": state["position"],
+ "rotation": state["rotation"],
+ }
+ frame_path = os.path.join(output_dir, f"frame_{frame_index:05d}.png")
+ frames.append(
+ {
+ "index": frame_index,
+ "time": time_value,
+ "path": frame_path,
+ "placements": placements,
+ }
+ )
+ return {
+ "frames": frames,
+ "unsupported_targets": unsupported_targets,
+ }
+
+
+def _generate_motion_macro(
+ project: Dict[str, Any],
+ *,
+ frames: List[Dict[str, Any]],
+ camera: str,
+ width: int,
+ height: int,
+ background: str,
+ fit_mode: str,
+) -> str:
+ if camera not in CAMERA_PRESETS:
+ raise ValueError(f"Unknown camera '{camera}'")
+ if fit_mode not in FIT_MODES:
+ raise ValueError(f"Unknown fit_mode '{fit_mode}'")
+
+ part_object_items = []
+ for part in project.get("parts", []):
+ render_spec = macro_gen._render_spec_for_part(project, part)
+ if render_spec is None:
+ continue
+ safe_name = macro_gen._safe_name(part.get("name", f"Part_{part.get('id', 'unknown')}"))
+ part_object_items.append(f" '{int(part['id'])}': obj_{safe_name},")
+
+ lines: List[str] = []
+ lines.extend(macro_gen._gen_header())
+ lines.extend(macro_gen._gen_parts(project))
+ lines.extend(macro_gen._gen_boolean_ops(project))
+ lines.extend(macro_gen._gen_bodies(project))
+ lines.extend(macro_gen._gen_placements(project))
+ lines.extend(
+ [
+ "doc.recompute()",
+ "",
+ "try:",
+ " import FreeCADGui",
+ "except ImportError as exc:",
+ " raise RuntimeError('FreeCADGui is required for motion rendering') from exc",
+ "",
+ "try:",
+ " FreeCADGui.showMainWindow()",
+ "except Exception:",
+ " pass",
+ "",
+ "gui_doc = FreeCADGui.getDocument(doc.Name)",
+ "if gui_doc is None:",
+ " raise RuntimeError(f'Could not acquire GUI document for {doc.Name}')",
+ "FreeCADGui.ActiveDocument = gui_doc",
+ "view = getattr(FreeCADGui.ActiveDocument, 'ActiveView', None)",
+ "if view is None:",
+ " view = FreeCADGui.ActiveDocument.activeView()",
+ "if view is None:",
+ " raise RuntimeError('FreeCAD active view is not available')",
+ "try:",
+ " view.setAnimationEnabled(False)",
+ "except Exception:",
+ " pass",
+ "",
+ "part_objects = {",
+ *part_object_items,
+ "}",
+ f"frames = {repr(frames)}",
+ "",
+ f"getattr(view, '{CAMERA_PRESETS[camera]['method']}')()",
+ "try:",
+ " view.fitAll()",
+ "except Exception:",
+ " pass",
+ "try:",
+ " FreeCADGui.updateGui()",
+ "except Exception:",
+ " pass",
+ "",
+ "for frame in frames:",
+ " for part_id, placement in frame['placements'].items():",
+ " obj = part_objects.get(str(part_id))",
+ " if obj is None:",
+ " continue",
+ " pos = placement['position']",
+ " rot = placement['rotation']",
+ " obj.Placement = FreeCAD.Placement(",
+ " FreeCAD.Vector(float(pos[0]), float(pos[1]), float(pos[2])),",
+ " FreeCAD.Rotation(float(rot[2]), float(rot[1]), float(rot[0])),",
+ " )",
+ " doc.recompute()",
+ " try:",
+ " FreeCADGui.updateGui()",
+ " except Exception:",
+ " pass",
+ ]
+ )
+ if fit_mode == "per-frame":
+ lines.extend(
+ [
+ " try:",
+ " view.fitAll()",
+ " except Exception:",
+ " pass",
+ ]
+ )
+ lines.extend(
+ [
+ f" view.saveImage(frame['path'], {int(width)}, {int(height)}, '{background}')",
+ "",
+ "try:",
+ " FreeCAD.closeDocument(doc.Name)",
+ "except Exception:",
+ " pass",
+ "import os as _motion_os",
+ "_motion_os._exit(0)",
+ "",
+ ]
+ )
+ return "\n".join(lines)
+
+
+def render_frames(
+ project: Dict[str, Any],
+ motion_index: int,
+ output_dir: str,
+ *,
+ overwrite: bool = False,
+ camera: Optional[str] = None,
+ width: Optional[int] = None,
+ height: Optional[int] = None,
+ background: Optional[str] = None,
+ fit_mode: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Render a motion sequence to a real frame directory via FreeCAD GUI capture."""
+ motion = _validate_motion_index(project, motion_index)
+ resolved_camera = camera or motion.get("camera", "hero")
+ resolved_width = int(width or motion.get("width", 1280))
+ resolved_height = int(height or motion.get("height", 960))
+ resolved_background = str(background or motion.get("background", "White"))
+ resolved_fit_mode = fit_mode or motion.get("fit_mode", "initial")
+ if resolved_camera not in CAMERA_PRESETS:
+ raise ValueError(f"Unknown camera '{resolved_camera}'")
+ if resolved_fit_mode not in FIT_MODES:
+ raise ValueError(f"Unknown fit_mode '{resolved_fit_mode}'")
+
+ resolved_output_dir = _ensure_empty_dir(output_dir, overwrite=overwrite)
+ frame_payload = _motion_frames(project, motion, resolved_output_dir)
+ frames = frame_payload["frames"]
+ if not frames:
+ raise RuntimeError("Motion sequence produced no frames")
+
+ macro = _generate_motion_macro(
+ project,
+ frames=frames,
+ camera=resolved_camera,
+ width=resolved_width,
+ height=resolved_height,
+ background=resolved_background,
+ fit_mode=resolved_fit_mode,
+ )
+ result = freecad_backend.run_macro_content(
+ macro,
+ timeout=max(240, len(frames) * 8),
+ gui_required=True,
+ env={"QT_QPA_PLATFORM": "offscreen"},
+ )
+ if result["returncode"] != 0:
+ raise RuntimeError(
+ f"FreeCAD motion render failed (exit code {result['returncode']}): {result['stderr']}"
+ )
+
+ missing = [frame["path"] for frame in frames if not os.path.isfile(frame["path"])]
+ if missing:
+ raise RuntimeError(f"Motion render completed but {len(missing)} frame(s) are missing: {missing[:3]}")
+
+ sequence_path = os.path.join(resolved_output_dir, "sequence.json")
+ sequence = {
+ "motion_name": motion["name"],
+ "motion_index": motion_index,
+ "duration": motion["duration"],
+ "fps": motion["fps"],
+ "camera": resolved_camera,
+ "width": resolved_width,
+ "height": resolved_height,
+ "background": resolved_background,
+ "fit_mode": resolved_fit_mode,
+ "frame_count": len(frames),
+ "frames": [
+ {
+ "index": frame["index"],
+ "time": frame["time"],
+ "path": os.path.relpath(frame["path"], resolved_output_dir),
+ }
+ for frame in frames
+ ],
+ "unsupported_targets": frame_payload["unsupported_targets"],
+ "method": "freecad-gui-sequence",
+ }
+ with open(sequence_path, "w", encoding="utf-8") as fh:
+ json.dump(sequence, fh, indent=2, ensure_ascii=False)
+ fh.write("\n")
+
+ return {
+ "motion": motion["name"],
+ "output_dir": resolved_output_dir,
+ "sequence_path": sequence_path,
+ "frame_count": len(frames),
+ "first_frame": frames[0]["path"],
+ "last_frame": frames[-1]["path"],
+ "camera": resolved_camera,
+ "fit_mode": resolved_fit_mode,
+ "method": "freecad-gui-sequence",
+ "unsupported_targets": frame_payload["unsupported_targets"],
+ }
+
+
+def render_video(
+ project: Dict[str, Any],
+ motion_index: int,
+ output_path: str,
+ *,
+ overwrite: bool = False,
+ frames_dir: Optional[str] = None,
+ keep_frames: bool = False,
+ camera: Optional[str] = None,
+ width: Optional[int] = None,
+ height: Optional[int] = None,
+ background: Optional[str] = None,
+ fit_mode: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Render a motion sequence to PNG frames and encode an MP4/WebM/GIF video."""
+ resolved_output_path = os.path.abspath(output_path)
+ output_dirname = os.path.dirname(resolved_output_path) or "."
+ os.makedirs(output_dirname, exist_ok=True)
+ if os.path.exists(resolved_output_path) and not overwrite:
+ raise FileExistsError(
+ f"Output file already exists: {resolved_output_path}. Use overwrite=True to replace it."
+ )
+ ext = Path(resolved_output_path).suffix.lower()
+ if ext not in {".mp4", ".webm", ".gif"}:
+ raise ValueError("motion render-video currently supports .mp4, .webm, and .gif outputs")
+
+ temp_dir: Optional[str] = None
+ if frames_dir:
+ resolved_frames_dir = os.path.abspath(frames_dir)
+ elif keep_frames:
+ stem = Path(resolved_output_path).stem
+ resolved_frames_dir = os.path.join(output_dirname, f"{stem}_frames")
+ else:
+ temp_dir = tempfile.mkdtemp(prefix="freecad_motion_frames_")
+ resolved_frames_dir = temp_dir
+
+ frame_result = render_frames(
+ project,
+ motion_index,
+ resolved_frames_dir,
+ overwrite=True,
+ camera=camera,
+ width=width,
+ height=height,
+ background=background,
+ fit_mode=fit_mode,
+ )
+ motion = _validate_motion_index(project, motion_index)
+ ffmpeg = _ffmpeg_path()
+
+ input_pattern = os.path.join(frame_result["output_dir"], "frame_%05d.png")
+ command = [ffmpeg, "-y", "-framerate", str(int(motion["fps"])), "-i", input_pattern]
+ if ext == ".mp4":
+ command.extend(["-c:v", "libx264", "-pix_fmt", "yuv420p", resolved_output_path])
+ elif ext == ".webm":
+ command.extend(["-c:v", "libvpx-vp9", "-pix_fmt", "yuv420p", resolved_output_path])
+ else:
+ command.extend(["-vf", "split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse", resolved_output_path])
+
+ proc = subprocess.run(command, capture_output=True, text=True)
+ if proc.returncode != 0 or not os.path.isfile(resolved_output_path):
+ raise RuntimeError(
+ f"ffmpeg video encode failed (exit code {proc.returncode}): {proc.stderr.strip()}"
+ )
+
+ result = {
+ "motion": motion["name"],
+ "output": resolved_output_path,
+ "format": ext.lstrip("."),
+ "file_size": os.path.getsize(resolved_output_path),
+ "frame_count": frame_result["frame_count"],
+ "fps": motion["fps"],
+ "frames_dir": frame_result["output_dir"],
+ "sequence_path": frame_result["sequence_path"],
+ "method": "freecad-gui-sequence+ffmpeg",
+ "ffmpeg_command": command,
+ }
+ if temp_dir and not keep_frames:
+ shutil.rmtree(temp_dir, ignore_errors=True)
+ result["frames_dir"] = None
+ result["sequence_path"] = None
+ return result
diff --git a/freecad/agent-harness/cli_anything/freecad/core/parts.py b/freecad/agent-harness/cli_anything/freecad/core/parts.py
index 51aeef8ef..6b6c8e7f6 100644
--- a/freecad/agent-harness/cli_anything/freecad/core/parts.py
+++ b/freecad/agent-harness/cli_anything/freecad/core/parts.py
@@ -136,6 +136,188 @@ def _validate_vec3(value: Any, label: str) -> List[float]:
raise ValueError(f"{label} elements must be numeric: {exc}") from exc
+def _rotation_matrix(rotation: List[float]) -> List[List[float]]:
+ """Return a simple XYZ Euler rotation matrix for *rotation* in degrees."""
+ rx, ry, rz = [math.radians(float(v)) for v in rotation]
+ cx, sx = math.cos(rx), math.sin(rx)
+ cy, sy = math.cos(ry), math.sin(ry)
+ cz, sz = math.cos(rz), math.sin(rz)
+
+ mx = [
+ [1.0, 0.0, 0.0],
+ [0.0, cx, -sx],
+ [0.0, sx, cx],
+ ]
+ my = [
+ [cy, 0.0, sy],
+ [0.0, 1.0, 0.0],
+ [-sy, 0.0, cy],
+ ]
+ mz = [
+ [cz, -sz, 0.0],
+ [sz, cz, 0.0],
+ [0.0, 0.0, 1.0],
+ ]
+
+ def _matmul(a: List[List[float]], b: List[List[float]]) -> List[List[float]]:
+ return [
+ [
+ sum(a[row][k] * b[k][col] for k in range(3))
+ for col in range(3)
+ ]
+ for row in range(3)
+ ]
+
+ return _matmul(mz, _matmul(my, mx))
+
+
+def _transform_point(point: List[float], rotation: List[float], translation: List[float]) -> List[float]:
+ """Apply an XYZ Euler rotation and translation to a point."""
+ matrix = _rotation_matrix(rotation)
+ x, y, z = point
+ tx, ty, tz = translation
+ return [
+ matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z + tx,
+ matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z + ty,
+ matrix[2][0] * x + matrix[2][1] * y + matrix[2][2] * z + tz,
+ ]
+
+
+def _bbox_from_points(points: List[List[float]]) -> Dict[str, Dict[str, float]]:
+ """Build min/max/size/center dictionaries from transformed points."""
+ xs = [point[0] for point in points]
+ ys = [point[1] for point in points]
+ zs = [point[2] for point in points]
+ min_corner = {"x": min(xs), "y": min(ys), "z": min(zs)}
+ max_corner = {"x": max(xs), "y": max(ys), "z": max(zs)}
+ return {
+ "min": min_corner,
+ "max": max_corner,
+ "size": {
+ axis: max_corner[axis] - min_corner[axis]
+ for axis in ("x", "y", "z")
+ },
+ "center": {
+ axis: (min_corner[axis] + max_corner[axis]) / 2.0
+ for axis in ("x", "y", "z")
+ },
+ }
+
+
+def _local_bounds(part_type: str, params: Dict[str, Any]) -> Optional[Dict[str, Dict[str, float]]]:
+ """Return a primitive-local bounding box for supported part types."""
+ if part_type == "box":
+ return {
+ "min": {"x": 0.0, "y": 0.0, "z": 0.0},
+ "max": {
+ "x": float(params["length"]),
+ "y": float(params["width"]),
+ "z": float(params["height"]),
+ },
+ }
+
+ if part_type == "cylinder":
+ radius = float(params["radius"])
+ height = float(params["height"])
+ return {
+ "min": {"x": -radius, "y": -radius, "z": 0.0},
+ "max": {"x": radius, "y": radius, "z": height},
+ }
+
+ if part_type == "sphere":
+ radius = float(params["radius"])
+ return {
+ "min": {"x": -radius, "y": -radius, "z": -radius},
+ "max": {"x": radius, "y": radius, "z": radius},
+ }
+
+ if part_type == "cone":
+ radius = max(float(params["radius1"]), float(params["radius2"]))
+ height = float(params["height"])
+ return {
+ "min": {"x": -radius, "y": -radius, "z": 0.0},
+ "max": {"x": radius, "y": radius, "z": height},
+ }
+
+ if part_type == "torus":
+ radius1 = float(params["radius1"])
+ radius2 = float(params["radius2"])
+ major = radius1 + radius2
+ return {
+ "min": {"x": -major, "y": -major, "z": -radius2},
+ "max": {"x": major, "y": major, "z": radius2},
+ }
+
+ if part_type == "wedge":
+ return {
+ "min": {
+ "x": min(float(params["xmin"]), float(params["x2min"])),
+ "y": float(params["ymin"]),
+ "z": min(float(params["zmin"]), float(params["z2min"])),
+ },
+ "max": {
+ "x": max(float(params["xmax"]), float(params["x2max"])),
+ "y": float(params["ymax"]),
+ "z": max(float(params["zmax"]), float(params["z2max"])),
+ },
+ }
+
+ if part_type == "plane":
+ return {
+ "min": {"x": 0.0, "y": 0.0, "z": 0.0},
+ "max": {"x": float(params["length"]), "y": float(params["width"]), "z": 0.0},
+ }
+
+ if part_type == "polygon_3d":
+ radius = float(params["radius"])
+ return {
+ "min": {"x": -radius, "y": -radius, "z": 0.0},
+ "max": {"x": radius, "y": radius, "z": 0.0},
+ }
+
+ return None
+
+
+def _world_bounds(part: Dict[str, Any]) -> Optional[Dict[str, Dict[str, float]]]:
+ """Return a world-space bounding box for supported primitive parts."""
+ local = _local_bounds(str(part.get("type", "")).lower(), part.get("params", {}))
+ if local is None:
+ return None
+
+ min_corner = local["min"]
+ max_corner = local["max"]
+ corners = []
+ for x in (min_corner["x"], max_corner["x"]):
+ for y in (min_corner["y"], max_corner["y"]):
+ for z in (min_corner["z"], max_corner["z"]):
+ corners.append([x, y, z])
+
+ placement = part.get("placement", {})
+ position = _validate_vec3(placement.get("position", [0.0, 0.0, 0.0]), "position")
+ rotation = _validate_vec3(placement.get("rotation", [0.0, 0.0, 0.0]), "rotation")
+ return _bbox_from_points([_transform_point(point, rotation, position) for point in corners])
+
+
+def _anchor_value(bounds: Dict[str, Dict[str, float]], axis: str, anchor: str) -> float:
+ """Resolve an axis anchor string against a bounds payload."""
+ aliases = {
+ "min": "min",
+ "max": "max",
+ "center": "center",
+ "left": "min",
+ "right": "max",
+ "bottom": "min",
+ "top": "max",
+ "front": "min",
+ "back": "max",
+ "mid": "center",
+ }
+ normalized = aliases.get(anchor.lower())
+ if normalized is None:
+ raise ValueError(f"Unknown anchor '{anchor}'. Valid: min, center, max")
+ return float(bounds[normalized][axis])
+
+
# ---------------------------------------------------------------------------
# Core functions
# ---------------------------------------------------------------------------
@@ -1311,6 +1493,90 @@ def _estimate_geometry(part_type: str, params: Dict[str, Any]) -> Dict[str, Any]
}
+def part_bounds(
+ project: Dict[str, Any],
+ index: int,
+) -> Dict[str, Any]:
+ """Return local and world bounding-box data for a part."""
+ part = get_part(project, index)
+ local = _local_bounds(str(part["type"]).lower(), part.get("params", {}))
+ world = _world_bounds(part)
+ return {
+ "id": part["id"],
+ "name": part["name"],
+ "type": part["type"],
+ "local_bounding_box": local,
+ "world_bounding_box": world,
+ }
+
+
+def align_part(
+ project: Dict[str, Any],
+ index: int,
+ target_index: int,
+ *,
+ x: Optional[str] = None,
+ to_x: Optional[str] = None,
+ dx: float = 0.0,
+ y: Optional[str] = None,
+ to_y: Optional[str] = None,
+ dy: float = 0.0,
+ z: Optional[str] = None,
+ to_z: Optional[str] = None,
+ dz: float = 0.0,
+) -> Dict[str, Any]:
+ """Move a part so selected bbox anchors match another part's anchors."""
+ part = get_part(project, index)
+ target = get_part(project, target_index)
+ source_bounds = _world_bounds(part)
+ target_bounds = _world_bounds(target)
+ if source_bounds is None:
+ raise ValueError(
+ f"Part #{index} ({part['name']}) does not support bounding-box alignment for type '{part['type']}'"
+ )
+ if target_bounds is None:
+ raise ValueError(
+ f"Target part #{target_index} ({target['name']}) does not support bounding-box alignment for type '{target['type']}'"
+ )
+
+ updates = {
+ "x": (x, to_x, float(dx)),
+ "y": (y, to_y, float(dy)),
+ "z": (z, to_z, float(dz)),
+ }
+ if not any(source_anchor or target_anchor for source_anchor, target_anchor, _ in updates.values()):
+ raise ValueError("At least one axis alignment must be specified")
+
+ position = _validate_vec3(part["placement"]["position"], "position")
+ delta = [0.0, 0.0, 0.0]
+ axis_to_index = {"x": 0, "y": 1, "z": 2}
+
+ for axis, (source_anchor, target_anchor, offset) in updates.items():
+ if source_anchor is None and target_anchor is None:
+ continue
+ if source_anchor is None or target_anchor is None:
+ raise ValueError(f"Axis '{axis}' requires both source and target anchors")
+ shift = (
+ _anchor_value(target_bounds, axis, target_anchor)
+ + offset
+ - _anchor_value(source_bounds, axis, source_anchor)
+ )
+ delta[axis_to_index[axis]] = shift
+ position[axis_to_index[axis]] += shift
+
+ part["placement"]["position"] = position
+ updated_bounds = _world_bounds(part)
+ return {
+ "part_index": index,
+ "target_index": target_index,
+ "part_name": part["name"],
+ "target_name": target["name"],
+ "delta": {"x": delta[0], "y": delta[1], "z": delta[2]},
+ "placement": deepcopy(part["placement"]),
+ "world_bounding_box": updated_bounds,
+ }
+
+
def part_info(
project: Dict[str, Any],
index: int,
@@ -1331,6 +1597,7 @@ def part_info(
"""
part = get_part(project, index)
geo = _estimate_geometry(part["type"], part.get("params", {}))
+ world = _world_bounds(part)
return {
"id": part["id"],
@@ -1343,4 +1610,5 @@ def part_info(
"volume": geo["volume"],
"area": geo["area"],
"bounding_box": geo["bounding_box"],
+ "world_bounding_box": world,
}
diff --git a/freecad/agent-harness/cli_anything/freecad/core/preview.py b/freecad/agent-harness/cli_anything/freecad/core/preview.py
new file mode 100644
index 000000000..a6eed0872
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/core/preview.py
@@ -0,0 +1,835 @@
+"""Preview bundle generation and live polling for the FreeCAD harness."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import signal
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from cli_anything.freecad.utils import freecad_backend
+from cli_anything.freecad.utils import freecad_macro_gen as macro_gen
+from cli_anything.freecad.utils.preview_bundle import (
+ artifact_record,
+ finalize_bundle,
+ find_latest_manifest,
+ fingerprint_data,
+ fingerprint_file,
+ prepare_bundle,
+)
+
+from . import document as doc_mod
+from .session import Session
+
+HARNESS_VERSION = "1.0.0"
+LIVE_PROTOCOL_VERSION = "preview-live/v1"
+DEFAULT_REFRESH_HINT_MS = 1500
+DEFAULT_SOURCE_POLL_MS = 500
+MIN_SOURCE_POLL_MS = 250
+
+RECIPES: Dict[str, Dict[str, Any]] = {
+ "quick": {
+ "description": "Isometric plus orthographic snapshots",
+ "width": 1280,
+ "height": 960,
+ "views": [
+ ("hero", "viewIsometric", "Isometric overview"),
+ ("front", "viewFront", "Front view"),
+ ("top", "viewTop", "Top view"),
+ ("right", "viewRight", "Right view"),
+ ],
+ "background": "White",
+ },
+}
+
+
+def list_recipes() -> List[Dict[str, Any]]:
+ """Return available preview recipes."""
+ return [
+ {
+ "name": name,
+ "description": config["description"],
+ "bundle_kind": "capture",
+ "artifacts": ["hero", "gallery"],
+ "views": [item[0] for item in config["views"]],
+ }
+ for name, config in RECIPES.items()
+ ]
+
+
+def _project_fingerprint(session: Session) -> str:
+ project = session.get_project()
+ payload: Dict[str, Any] = {
+ "project": project,
+ "project_path": os.path.abspath(session.project_path) if session.project_path else "",
+ }
+ if not session.project_path:
+ metadata = project.get("metadata") or {}
+ payload["project_created"] = metadata.get("created")
+ return fingerprint_data(payload)
+
+
+def _safe_path(path: str) -> str:
+ return path.replace("\\", "/")
+
+
+def _slug(value: str) -> str:
+ text = (value or "preview").strip().lower()
+ text = re.sub(r"[^a-z0-9]+", "-", text)
+ text = re.sub(r"-{2,}", "-", text).strip("-")
+ return text or "preview"
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def _normalize_poll_ms(value: Optional[int]) -> int:
+ try:
+ numeric = int(value or DEFAULT_SOURCE_POLL_MS)
+ except (TypeError, ValueError):
+ numeric = DEFAULT_SOURCE_POLL_MS
+ return max(MIN_SOURCE_POLL_MS, numeric)
+
+
+def _project_file_fingerprint(project_path: Optional[str]) -> Optional[str]:
+ if not project_path:
+ return None
+ resolved = os.path.abspath(project_path)
+ if not os.path.isfile(resolved):
+ return None
+ return fingerprint_file(resolved)
+
+
+def _preview_base_dir(project_path: Optional[str] = None, root_dir: Optional[str] = None) -> Path:
+ if root_dir:
+ return Path(root_dir).expanduser().resolve() / "freecad"
+ if project_path:
+ return Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews" / "freecad"
+ return Path.home() / ".cli-anything" / "previews" / "freecad"
+
+
+def _live_session_name(session: Session, recipe: str) -> str:
+ project = session.get_project()
+ project_name = Path(session.project_path).stem if session.project_path else project.get("name", "untitled")
+ if session.project_path:
+ fingerprint_source: Dict[str, Any] = {
+ "project_path": os.path.abspath(session.project_path),
+ "recipe": recipe,
+ }
+ else:
+ metadata = project.get("metadata") or {}
+ fingerprint_source = {
+ "project_name": project_name,
+ "project_created": metadata.get("created"),
+ "recipe": recipe,
+ }
+ suffix = fingerprint_data(fingerprint_source).split(":", 1)[-1][:8]
+ return f"{_slug(project_name)}-{suffix}-{_slug(recipe)}"
+
+
+def _live_session_dir(session: Session, recipe: str, root_dir: Optional[str] = None) -> Path:
+ return _preview_base_dir(session.project_path, root_dir=root_dir) / "live" / _live_session_name(session, recipe)
+
+
+def _read_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def _write_json(path: Path, payload: Dict[str, Any]) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "w", encoding="utf-8") as fh:
+ json.dump(payload, fh, indent=2, ensure_ascii=False, default=str)
+ fh.write("\n")
+ return path
+
+
+def _merge_nested_dict(base: Dict[str, Any], updates: Dict[str, Any]) -> Dict[str, Any]:
+ for key, value in updates.items():
+ if isinstance(value, dict) and isinstance(base.get(key), dict):
+ _merge_nested_dict(base[key], value)
+ else:
+ base[key] = value
+ return base
+
+
+def _pid_is_running(pid: Any) -> bool:
+ try:
+ numeric = int(pid)
+ except (TypeError, ValueError):
+ return False
+ if numeric <= 0:
+ return False
+ try:
+ os.kill(numeric, 0)
+ return True
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+
+
+def _terminate_pid(pid: Any) -> bool:
+ try:
+ numeric = int(pid)
+ except (TypeError, ValueError):
+ return False
+ if numeric <= 0:
+ return False
+ try:
+ os.kill(numeric, signal.SIGTERM)
+ return True
+ except ProcessLookupError:
+ return False
+
+
+def _with_live_refs(session_dir: Path, payload: Dict[str, Any]) -> Dict[str, Any]:
+ payload["_session_dir"] = str(session_dir.resolve())
+ payload["_session_path"] = str((session_dir / "session.json").resolve())
+ return payload
+
+
+def _load_existing_live_session(session_dir: Path) -> Dict[str, Any]:
+ session_path = session_dir / "session.json"
+ if session_path.is_file():
+ return _read_json(session_path)
+ return {}
+
+
+def _write_live_session_updates(session_dir: Path, updates: Dict[str, Any]) -> Dict[str, Any]:
+ payload = _load_existing_live_session(session_dir)
+ if not payload:
+ raise FileNotFoundError(f"Live preview session not found: {session_dir}")
+ _merge_nested_dict(payload, updates)
+ payload["updated_at"] = updates.get("updated_at", _now_iso())
+ _write_json(session_dir / "session.json", payload)
+ return _with_live_refs(session_dir, payload)
+
+
+def _update_current_symlink(session_dir: Path, bundle_dir: str) -> Path:
+ current_link = session_dir / "current"
+ if current_link.is_symlink() or current_link.exists():
+ if current_link.is_dir() and not current_link.is_symlink():
+ raise RuntimeError(f"Live preview current path is unexpectedly a directory: {current_link}")
+ current_link.unlink()
+ target = os.path.relpath(Path(bundle_dir).resolve(), session_dir)
+ os.symlink(target, current_link, target_is_directory=True)
+ return current_link
+
+
+def _history_item(bundle_manifest: Dict[str, Any]) -> Dict[str, Any]:
+ return {
+ "bundle_id": bundle_manifest.get("bundle_id"),
+ "bundle_dir": bundle_manifest.get("_bundle_dir"),
+ "manifest_path": bundle_manifest.get("_manifest_path"),
+ "summary_path": bundle_manifest.get("_summary_path"),
+ "created_at": bundle_manifest.get("created_at"),
+ "status": bundle_manifest.get("status"),
+ "cached": bool(bundle_manifest.get("cached")),
+ }
+
+
+def _generate_preview_macro(
+ project: Dict[str, Any],
+ outputs: List[Dict[str, str]],
+ *,
+ width: int,
+ height: int,
+ background: str,
+) -> str:
+ lines: List[str] = []
+ lines.extend(macro_gen._gen_header())
+ lines.extend(macro_gen._gen_parts(project))
+ lines.extend(macro_gen._gen_boolean_ops(project))
+ lines.extend(macro_gen._gen_bodies(project))
+ lines.extend(macro_gen._gen_placements(project))
+ lines.extend(
+ [
+ "doc.recompute()",
+ "",
+ "try:",
+ " import FreeCADGui",
+ "except ImportError as exc:",
+ " raise RuntimeError('FreeCADGui is required for preview capture') from exc",
+ "",
+ "try:",
+ " FreeCADGui.showMainWindow()",
+ "except Exception:",
+ " pass",
+ "",
+ "gui_doc = FreeCADGui.getDocument(doc.Name)",
+ "if gui_doc is None:",
+ " raise RuntimeError(f'Could not acquire GUI document for {doc.Name}')",
+ "FreeCADGui.ActiveDocument = gui_doc",
+ "view = getattr(FreeCADGui.ActiveDocument, 'ActiveView', None)",
+ "if view is None:",
+ " view = FreeCADGui.ActiveDocument.activeView()",
+ "if view is None:",
+ " raise RuntimeError('FreeCAD active view is not available')",
+ "try:",
+ " view.setAnimationEnabled(False)",
+ "except Exception:",
+ " pass",
+ "",
+ "def _capture(method_name, path):",
+ " getattr(view, method_name)()",
+ " try:",
+ " view.fitAll()",
+ " except Exception:",
+ " pass",
+ " try:",
+ " FreeCADGui.updateGui()",
+ " except Exception:",
+ " pass",
+ f" view.saveImage(path, {width}, {height}, '{background}')",
+ "",
+ ]
+ )
+ for output in outputs:
+ lines.append(f"_capture('{output['method']}', '{_safe_path(output['path'])}')")
+ lines.extend(
+ [
+ "",
+ "try:",
+ " FreeCAD.closeDocument(doc.Name)",
+ "except Exception:",
+ " pass",
+ "",
+ "# FreeCAD AppImage + GUI teardown is unstable in headless CI; exit",
+ "# immediately after the images are flushed to disk.",
+ "import os as _preview_os",
+ "_preview_os._exit(0)",
+ "",
+ ]
+ )
+ return "\n".join(lines)
+
+
+def capture(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ command: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Render a preview bundle for the active FreeCAD project."""
+ if session.project is None:
+ raise RuntimeError("No project is currently loaded.")
+ if recipe not in RECIPES:
+ raise ValueError(
+ f"Unknown preview recipe: {recipe!r}. Available: {', '.join(sorted(RECIPES))}"
+ )
+
+ project = session.get_project()
+ config = RECIPES[recipe]
+ source_fingerprint = _project_fingerprint(session)
+ prepared = prepare_bundle(
+ software="freecad",
+ recipe=recipe,
+ bundle_kind="capture",
+ source_fingerprint=source_fingerprint,
+ options=config,
+ harness_version=HARNESS_VERSION,
+ project_path=session.project_path,
+ root_dir=root_dir,
+ force=force,
+ )
+ if prepared["cached"]:
+ manifest = dict(prepared["manifest"])
+ manifest["cached"] = True
+ return manifest
+
+ bundle_dir = prepared["bundle_dir"]
+ artifacts_dir = prepared["artifacts_dir"]
+ outputs: List[Dict[str, str]] = []
+ for artifact_id, method_name, label in config["views"]:
+ filename = f"{artifact_id}.png"
+ outputs.append(
+ {
+ "artifact_id": artifact_id,
+ "method": method_name,
+ "label": label,
+ "path": os.path.join(artifacts_dir, filename),
+ }
+ )
+
+ warnings: List[str] = []
+ if not project.get("parts") and not project.get("bodies"):
+ warnings.append("Project has no parts or bodies; preview may be empty.")
+
+ macro_content = _generate_preview_macro(
+ project,
+ outputs,
+ width=config["width"],
+ height=config["height"],
+ background=config["background"],
+ )
+ result = freecad_backend.run_macro_content(
+ macro_content,
+ timeout=240,
+ gui_required=True,
+ env={"QT_QPA_PLATFORM": "offscreen"},
+ )
+ if result["returncode"] != 0:
+ raise RuntimeError(
+ f"FreeCAD preview failed (exit code {result['returncode']}): {result['stderr']}"
+ )
+
+ artifacts = []
+ for output in outputs:
+ if not os.path.isfile(output["path"]):
+ warnings.append(f"missing preview image: {os.path.basename(output['path'])}")
+ continue
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ output["path"],
+ artifact_id=output["artifact_id"],
+ role="hero" if output["artifact_id"] == "hero" else "gallery",
+ kind="image",
+ label=output["label"],
+ width=config["width"],
+ height=config["height"],
+ view_method=output["method"],
+ )
+ )
+
+ metrics = {
+ "parts_count": len(project.get("parts", [])),
+ "bodies_count": len(project.get("bodies", [])),
+ "sketches_count": len(project.get("sketches", [])),
+ "materials_count": len(project.get("materials", [])),
+ "assemblies_count": len(project.get("assemblies", [])),
+ }
+ summary = {
+ "headline": f"FreeCAD {recipe} preview rendered with {len(artifacts)} views",
+ "facts": {
+ "recipe": recipe,
+ "units": project.get("units", "mm"),
+ "resolution": f"{config['width']}x{config['height']}",
+ **metrics,
+ },
+ "warnings": warnings,
+ "next_actions": [
+ "Inspect the isometric hero image for overall form and placement.",
+ "Inspect front/top/right views for dimensional and alignment issues.",
+ ],
+ }
+
+ manifest = finalize_bundle(
+ bundle_dir=bundle_dir,
+ bundle_id=prepared["bundle_id"],
+ bundle_kind="capture",
+ software="freecad",
+ recipe=recipe,
+ source={
+ "project_path": session.project_path,
+ "project_name": os.path.basename(session.project_path) if session.project_path else project.get("name"),
+ "project_fingerprint": source_fingerprint,
+ },
+ artifacts=artifacts,
+ summary=summary,
+ cache_key=prepared["cache_key"],
+ generator={
+ "entry_point": "cli-anything-freecad",
+ "harness_version": HARNESS_VERSION,
+ "command": command or f"cli-anything-freecad preview capture --recipe {recipe}",
+ },
+ status="partial" if warnings else "ok",
+ warnings=warnings or None,
+ context={"views": [item[0] for item in config["views"]]},
+ metrics=metrics,
+ labels=["cad", "3d", "preview"],
+ )
+ manifest["cached"] = False
+ return manifest
+
+
+def latest(
+ *,
+ project_path: Optional[str] = None,
+ recipe: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Return the latest preview bundle manifest for FreeCAD."""
+ manifest = find_latest_manifest(
+ software="freecad",
+ recipe=recipe,
+ bundle_kind="capture",
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if manifest is None:
+ raise FileNotFoundError("No FreeCAD preview bundle found")
+ return manifest
+
+
+def _publish_live_session(
+ session: Session,
+ bundle_manifest: Dict[str, Any],
+ *,
+ recipe: str,
+ root_dir: Optional[str] = None,
+ refresh_hint_ms: int = DEFAULT_REFRESH_HINT_MS,
+ live_mode: Optional[str] = None,
+ source_poll_ms: int = DEFAULT_SOURCE_POLL_MS,
+ publish_reason: str = "manual",
+) -> Dict[str, Any]:
+ session_dir = _live_session_dir(session, recipe, root_dir=root_dir)
+ session_dir.mkdir(parents=True, exist_ok=True)
+ _update_current_symlink(session_dir, bundle_manifest["_bundle_dir"])
+
+ existing = _load_existing_live_session(session_dir)
+ now = _now_iso()
+ current_item = _history_item(bundle_manifest)
+ history = [current_item]
+ for item in existing.get("history", []):
+ if item.get("bundle_id") == current_item["bundle_id"]:
+ continue
+ history.append(item)
+ history = history[:12]
+
+ current_live_mode = live_mode or existing.get("live_mode") or "manual"
+ current_source_poll_ms = _normalize_poll_ms(
+ source_poll_ms if live_mode is not None or "source_poll_ms" not in existing else existing.get("source_poll_ms")
+ )
+ root_flag = f" --root-dir {root_dir}" if root_dir else ""
+ project_flag = f" -p {session.project_path}" if session.project_path else ""
+ poller = dict(existing.get("poller") or {})
+ poller["running"] = _pid_is_running(poller.get("pid"))
+ project_file_fingerprint = _project_file_fingerprint(session.project_path)
+ project = session.get_project()
+ source_state = dict(existing.get("source_state") or {})
+ if session.project_path:
+ source_state["source_type"] = "project-file"
+ source_state["project_path"] = session.project_path
+ source_state["project_name"] = project.get("name")
+ if project_file_fingerprint:
+ source_state["last_seen_fingerprint"] = project_file_fingerprint
+ source_state["last_rendered_fingerprint"] = project_file_fingerprint
+ source_state["last_rendered_at"] = now
+ source_state["last_publish_reason"] = publish_reason
+
+ payload = {
+ "protocol_version": LIVE_PROTOCOL_VERSION,
+ "software": "freecad",
+ "recipe": recipe,
+ "status": "active",
+ "live_mode": current_live_mode,
+ "session_name": session_dir.name,
+ "project_path": session.project_path,
+ "project_name": Path(session.project_path).name if session.project_path else project.get("name", "Untitled"),
+ "created_at": existing.get("created_at", now),
+ "updated_at": now,
+ "refresh_hint_ms": int(refresh_hint_ms),
+ "source_poll_ms": current_source_poll_ms,
+ "preview_root_dir": root_dir,
+ "current_link": "current",
+ "current_bundle_id": bundle_manifest.get("bundle_id"),
+ "current_bundle_dir": bundle_manifest.get("_bundle_dir"),
+ "current_manifest_path": bundle_manifest.get("_manifest_path"),
+ "current_summary_path": bundle_manifest.get("_summary_path"),
+ "current_cached": bool(bundle_manifest.get("cached")),
+ "bundle_count": len(history),
+ "history": history,
+ "source_state": source_state,
+ "poller": poller,
+ "publish_command": (
+ f"cli-anything-freecad{project_flag} preview live push --recipe {recipe}{root_flag}"
+ ).strip(),
+ "watch_command": (
+ f"cli-hub preview watch {session_dir} --open --poll-ms {int(refresh_hint_ms)}"
+ ),
+ "inspect_command": f"cli-hub preview inspect {session_dir}",
+ "html_command": f"cli-hub preview html {session_dir}",
+ "start_command": (
+ f"cli-anything-freecad{project_flag} preview live start --recipe {recipe} "
+ f"--mode {current_live_mode} --source-poll-ms {current_source_poll_ms}{root_flag}"
+ ).strip(),
+ "monitor_command": (
+ f"cli-anything-freecad preview live monitor --session-dir {session_dir}"
+ ),
+ }
+ _write_json(session_dir / "session.json", payload)
+ return _with_live_refs(session_dir, payload)
+
+
+def live_start(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ refresh_hint_ms: int = DEFAULT_REFRESH_HINT_MS,
+ live_mode: str = "poll",
+ source_poll_ms: int = DEFAULT_SOURCE_POLL_MS,
+ command: Optional[str] = None,
+ publish_reason: str = "live-start",
+) -> Dict[str, Any]:
+ """Capture a preview and publish it into a live session."""
+ if live_mode not in {"poll", "manual"}:
+ raise ValueError("live_mode must be 'poll' or 'manual'")
+ if live_mode == "poll" and not session.project_path:
+ raise RuntimeError("Poll mode requires a saved project path")
+
+ bundle_manifest = capture(
+ session,
+ recipe=recipe,
+ root_dir=root_dir,
+ force=force,
+ command=command,
+ )
+ live_payload = _publish_live_session(
+ session,
+ bundle_manifest,
+ recipe=recipe,
+ root_dir=root_dir,
+ refresh_hint_ms=refresh_hint_ms,
+ live_mode=live_mode,
+ source_poll_ms=source_poll_ms,
+ publish_reason=publish_reason,
+ )
+ live_payload["bundle"] = {
+ "bundle_id": bundle_manifest.get("bundle_id"),
+ "bundle_dir": bundle_manifest.get("_bundle_dir"),
+ "manifest_path": bundle_manifest.get("_manifest_path"),
+ "cached": bool(bundle_manifest.get("cached")),
+ }
+ return live_payload
+
+
+def live_push(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ refresh_hint_ms: int = DEFAULT_REFRESH_HINT_MS,
+ source_poll_ms: int = DEFAULT_SOURCE_POLL_MS,
+ command: Optional[str] = None,
+ publish_reason: str = "manual-push",
+) -> Dict[str, Any]:
+ """Publish a fresh preview bundle into the current live session."""
+ existing_mode: Optional[str] = None
+ try:
+ existing_mode = live_status(session, recipe=recipe, root_dir=root_dir).get("live_mode")
+ except FileNotFoundError:
+ existing_mode = "manual"
+ return live_start(
+ session,
+ recipe=recipe,
+ root_dir=root_dir,
+ force=force,
+ refresh_hint_ms=refresh_hint_ms,
+ live_mode=existing_mode or "manual",
+ source_poll_ms=source_poll_ms,
+ command=command,
+ publish_reason=publish_reason,
+ )
+
+
+def live_status(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Return the live session metadata for the active project."""
+ session_dir = _live_session_dir(session, recipe, root_dir=root_dir)
+ session_path = session_dir / "session.json"
+ if not session_path.is_file():
+ raise FileNotFoundError("No FreeCAD live preview session found")
+ payload = _read_json(session_path)
+ poller = dict(payload.get("poller") or {})
+ if poller:
+ poller["running"] = _pid_is_running(poller.get("pid"))
+ payload["poller"] = poller
+ return _with_live_refs(session_dir, payload)
+
+
+def live_stop(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Mark a live preview session as stopped while preserving its latest bundle."""
+ payload = live_status(session, recipe=recipe, root_dir=root_dir)
+ now = _now_iso()
+ poller = dict(payload.get("poller") or {})
+ terminated = _terminate_pid(poller.get("pid"))
+ poller["running"] = False
+ poller["stopped_at"] = now
+ poller["last_exit_reason"] = "manual-stop"
+ poller["terminated"] = terminated
+ payload["status"] = "stopped"
+ payload["stopped_at"] = now
+ payload["poller"] = poller
+ session_dir = Path(payload["_session_dir"])
+ _write_json(session_dir / "session.json", {k: v for k, v in payload.items() if not k.startswith("_")})
+ return _with_live_refs(session_dir, payload)
+
+
+def record_live_poller_spawn(
+ session_dir: str,
+ *,
+ pid: int,
+ command: List[str],
+ log_path: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Persist initial poller spawn metadata before the worker heartbeat lands."""
+ session_path = Path(session_dir).expanduser().resolve()
+ return _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": int(pid),
+ "running": True,
+ "spawned_at": _now_iso(),
+ "command": command,
+ "log_path": log_path,
+ }
+ },
+ )
+
+
+def poll_live_session_once(session_dir: str) -> Dict[str, Any]:
+ """Run one poll cycle for a live session and capture if the source changed."""
+ session_path = Path(session_dir).expanduser().resolve()
+ payload = _load_existing_live_session(session_path)
+ now = _now_iso()
+ if not payload:
+ return {"action": "exit", "reason": "missing-session"}
+
+ if payload.get("status") != "active":
+ _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": os.getpid(),
+ "running": False,
+ "last_heartbeat": now,
+ "last_exit_reason": f"session-status:{payload.get('status')}",
+ }
+ },
+ )
+ return {"action": "exit", "reason": f"status:{payload.get('status')}"}
+
+ if payload.get("live_mode") != "poll":
+ _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": os.getpid(),
+ "running": False,
+ "last_heartbeat": now,
+ "last_exit_reason": f"live-mode:{payload.get('live_mode')}",
+ }
+ },
+ )
+ return {"action": "exit", "reason": f"mode:{payload.get('live_mode')}"}
+
+ project_path = payload.get("project_path")
+ current_fingerprint = _project_file_fingerprint(project_path)
+ base_updates: Dict[str, Any] = {
+ "poller": {
+ "pid": os.getpid(),
+ "running": True,
+ "last_heartbeat": now,
+ },
+ "source_state": {
+ "source_type": "project-file",
+ "project_path": project_path,
+ },
+ }
+ if current_fingerprint:
+ base_updates["source_state"]["last_seen_fingerprint"] = current_fingerprint
+
+ last_rendered = (payload.get("source_state") or {}).get("last_rendered_fingerprint")
+ if not project_path or not os.path.isfile(project_path):
+ base_updates["source_state"]["last_error"] = f"Project path unavailable: {project_path or '(none)'}"
+ base_updates["source_state"]["last_error_at"] = now
+ _write_live_session_updates(session_path, base_updates)
+ return {"action": "idle", "reason": "missing-project", "project_path": project_path}
+
+ if current_fingerprint and current_fingerprint == last_rendered:
+ _write_live_session_updates(session_path, base_updates)
+ return {"action": "idle", "fingerprint": current_fingerprint}
+
+ try:
+ session = Session()
+ project = doc_mod.open_document(project_path)
+ session.set_project(project, path=project_path)
+ live_payload = live_start(
+ session,
+ recipe=str(payload.get("recipe") or "quick"),
+ root_dir=payload.get("preview_root_dir"),
+ force=False,
+ refresh_hint_ms=int(payload.get("refresh_hint_ms") or DEFAULT_REFRESH_HINT_MS),
+ live_mode="poll",
+ source_poll_ms=int(payload.get("source_poll_ms") or DEFAULT_SOURCE_POLL_MS),
+ command=str(payload.get("monitor_command") or f"cli-anything-freecad preview live monitor --session-dir {session_path}"),
+ publish_reason="auto-poll",
+ )
+ _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": os.getpid(),
+ "running": True,
+ "last_heartbeat": now,
+ "last_capture_status": "ok",
+ "last_capture_finished_at": _now_iso(),
+ },
+ "source_state": {
+ "last_seen_fingerprint": current_fingerprint,
+ "last_rendered_fingerprint": current_fingerprint,
+ "last_rendered_at": _now_iso(),
+ "last_error": None,
+ "last_error_at": None,
+ },
+ },
+ )
+ return {
+ "action": "captured",
+ "bundle_id": live_payload.get("current_bundle_id"),
+ "fingerprint": current_fingerprint,
+ }
+ except Exception as exc:
+ _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": os.getpid(),
+ "running": True,
+ "last_heartbeat": now,
+ "last_capture_status": "error",
+ "last_capture_error": str(exc),
+ "last_capture_error_at": _now_iso(),
+ },
+ "source_state": {
+ "last_seen_fingerprint": current_fingerprint,
+ "last_error": str(exc),
+ "last_error_at": _now_iso(),
+ },
+ },
+ )
+ return {"action": "error", "error": str(exc), "fingerprint": current_fingerprint}
+
+
+def run_live_poller(session_dir: str) -> Dict[str, Any]:
+ """Run the long-lived poll loop for a live session."""
+ session_path = Path(session_dir).expanduser().resolve()
+ while True:
+ result = poll_live_session_once(str(session_path))
+ if result.get("action") == "exit":
+ return result
+ payload = _load_existing_live_session(session_path)
+ poll_ms = _normalize_poll_ms((payload or {}).get("source_poll_ms"))
+ time.sleep(poll_ms / 1000.0)
diff --git a/freecad/agent-harness/cli_anything/freecad/freecad_cli.py b/freecad/agent-harness/cli_anything/freecad/freecad_cli.py
index d940c6884..63b97a38a 100644
--- a/freecad/agent-harness/cli_anything/freecad/freecad_cli.py
+++ b/freecad/agent-harness/cli_anything/freecad/freecad_cli.py
@@ -9,6 +9,8 @@ from __future__ import annotations
import json
import os
+import shutil
+import subprocess
import sys
from functools import wraps
from typing import Any, Optional
@@ -22,6 +24,8 @@ from cli_anything.freecad.core import (
body as body_mod,
materials as mat_mod,
export as export_mod,
+ motion as motion_mod,
+ preview as preview_mod,
measure as measure_mod,
spreadsheet as spread_mod,
mesh as mesh_mod,
@@ -77,6 +81,77 @@ def output(data: Any, message: str = "") -> None:
click.echo(f" [{i}] {item}")
+def _spawn_live_viewer(session_dir: str, poll_ms: int) -> dict:
+ """Launch cli-hub live preview watcher when available."""
+ hub = shutil.which("cli-hub")
+ command = [
+ hub or "cli-hub",
+ "preview",
+ "watch",
+ session_dir,
+ "--open",
+ "--poll-ms",
+ str(int(poll_ms)),
+ ]
+ if hub is None:
+ return {
+ "launched": False,
+ "command": command,
+ "reason": "cli-hub not found on PATH",
+ }
+ process = subprocess.Popen(
+ command,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ return {
+ "launched": True,
+ "pid": process.pid,
+ "command": command,
+ }
+
+
+def _spawn_live_poller(session_dir: str) -> dict:
+ """Launch the FreeCAD live preview poller in the background."""
+ cli_path = shutil.which("cli-anything-freecad")
+ if cli_path:
+ command = [cli_path, "preview", "live", "monitor", "--session-dir", session_dir]
+ else:
+ command = [
+ sys.executable,
+ "-m",
+ "cli_anything.freecad.freecad_cli",
+ "preview",
+ "live",
+ "monitor",
+ "--session-dir",
+ session_dir,
+ ]
+ log_path = os.path.join(session_dir, "poller.log")
+ log_fh = open(log_path, "ab")
+ process = subprocess.Popen(
+ command,
+ stdout=log_fh,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ close_fds=True,
+ )
+ log_fh.close()
+ preview_mod.record_live_poller_spawn(
+ session_dir,
+ pid=process.pid,
+ command=command,
+ log_path=log_path,
+ )
+ return {
+ "launched": True,
+ "pid": process.pid,
+ "command": command,
+ "log_path": log_path,
+ }
+
+
def handle_error(f):
"""Decorator to handle errors gracefully in CLI and REPL modes."""
@wraps(f)
@@ -660,6 +735,64 @@ def part_info(index: int) -> None:
output_fn(result, f"Part #{index} info:")
+@part_group.command("bounds")
[email protected]("index", type=int)
+@handle_error
+def part_bounds(index: int) -> None:
+ """Get local and world bounding boxes for a part."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = parts_mod.part_bounds(proj, index)
+ output_fn(result, f"Part #{index} bounds:")
+
+
+@part_group.command("align")
[email protected]("index", type=int)
[email protected]("target_index", type=int)
[email protected]("--x", "x_anchor", type=str, help="Source anchor on x axis (min|center|max).")
[email protected]("--to-x", "to_x_anchor", type=str, help="Target anchor on x axis (min|center|max).")
[email protected]("--dx", default=0.0, type=float, help="Additional x offset after alignment.")
[email protected]("--y", "y_anchor", type=str, help="Source anchor on y axis (min|center|max).")
[email protected]("--to-y", "to_y_anchor", type=str, help="Target anchor on y axis (min|center|max).")
[email protected]("--dy", default=0.0, type=float, help="Additional y offset after alignment.")
[email protected]("--z", "z_anchor", type=str, help="Source anchor on z axis (min|center|max).")
[email protected]("--to-z", "to_z_anchor", type=str, help="Target anchor on z axis (min|center|max).")
[email protected]("--dz", default=0.0, type=float, help="Additional z offset after alignment.")
+@handle_error
+def part_align(
+ index: int,
+ target_index: int,
+ x_anchor: Optional[str],
+ to_x_anchor: Optional[str],
+ dx: float,
+ y_anchor: Optional[str],
+ to_y_anchor: Optional[str],
+ dy: float,
+ z_anchor: Optional[str],
+ to_z_anchor: Optional[str],
+ dz: float,
+) -> None:
+ """Align a part to another part using world bounding-box anchors."""
+ sess = get_session()
+ sess.snapshot(f"Align part #{index} to #{target_index}")
+ proj = sess.get_project()
+ result = parts_mod.align_part(
+ proj,
+ index,
+ target_index,
+ x=x_anchor,
+ to_x=to_x_anchor,
+ dx=dx,
+ y=y_anchor,
+ to_y=to_y_anchor,
+ dy=dy,
+ z=z_anchor,
+ to_z=to_z_anchor,
+ dz=dz,
+ )
+ output_fn(result, f"Aligned part #{index} to #{target_index}")
+
+
# ── Sketch commands ──────────────────────────────────────────────────
@cli.group("sketch")
@@ -1358,15 +1491,27 @@ def body_subtractive_helix(body_index: int, sketch_index: int, pitch: float,
@click.option("--length", "-l", default=10.0, type=float)
@click.option("--width", "-w", default=10.0, type=float)
@click.option("--height", "-h", default=10.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
def body_additive_box(body_index: int, length: float, width: float,
- height: float) -> None:
+ height: float, position: Optional[str],
+ rotation: Optional[str]) -> None:
"""Add an additive box primitive."""
sess = get_session()
sess.snapshot(f"Additive box body #{body_index}")
proj = sess.get_project()
- result = body_mod.additive_box(proj, body_index, length=length, width=width,
- height=height)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.additive_box(
+ proj,
+ body_index,
+ length=length,
+ width=width,
+ height=height,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added additive box")
@@ -1374,26 +1519,49 @@ def body_additive_box(body_index: int, length: float, width: float,
@click.argument("body_index", type=int)
@click.option("--radius", "-r", default=5.0, type=float)
@click.option("--height", "-h", default=10.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
-def body_additive_cylinder(body_index: int, radius: float, height: float) -> None:
+def body_additive_cylinder(body_index: int, radius: float, height: float,
+ position: Optional[str], rotation: Optional[str]) -> None:
"""Add an additive cylinder primitive."""
sess = get_session()
sess.snapshot(f"Additive cylinder body #{body_index}")
proj = sess.get_project()
- result = body_mod.additive_cylinder(proj, body_index, radius=radius, height=height)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.additive_cylinder(
+ proj,
+ body_index,
+ radius=radius,
+ height=height,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added additive cylinder")
@body_group.command("additive-sphere")
@click.argument("body_index", type=int)
@click.option("--radius", "-r", default=5.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
-def body_additive_sphere(body_index: int, radius: float) -> None:
+def body_additive_sphere(body_index: int, radius: float,
+ position: Optional[str], rotation: Optional[str]) -> None:
"""Add an additive sphere primitive."""
sess = get_session()
sess.snapshot(f"Additive sphere body #{body_index}")
proj = sess.get_project()
- result = body_mod.additive_sphere(proj, body_index, radius=radius)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.additive_sphere(
+ proj,
+ body_index,
+ radius=radius,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added additive sphere")
@@ -1402,15 +1570,27 @@ def body_additive_sphere(body_index: int, radius: float) -> None:
@click.option("--radius1", default=5.0, type=float)
@click.option("--radius2", default=0.0, type=float)
@click.option("--height", "-h", default=10.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
def body_additive_cone(body_index: int, radius1: float, radius2: float,
- height: float) -> None:
+ height: float, position: Optional[str],
+ rotation: Optional[str]) -> None:
"""Add an additive cone primitive."""
sess = get_session()
sess.snapshot(f"Additive cone body #{body_index}")
proj = sess.get_project()
- result = body_mod.additive_cone(proj, body_index, radius1=radius1,
- radius2=radius2, height=height)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.additive_cone(
+ proj,
+ body_index,
+ radius1=radius1,
+ radius2=radius2,
+ height=height,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added additive cone")
@@ -1418,28 +1598,50 @@ def body_additive_cone(body_index: int, radius1: float, radius2: float,
@click.argument("body_index", type=int)
@click.option("--radius1", default=10.0, type=float)
@click.option("--radius2", default=2.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
-def body_additive_torus(body_index: int, radius1: float, radius2: float) -> None:
+def body_additive_torus(body_index: int, radius1: float, radius2: float,
+ position: Optional[str], rotation: Optional[str]) -> None:
"""Add an additive torus primitive."""
sess = get_session()
sess.snapshot(f"Additive torus body #{body_index}")
proj = sess.get_project()
- result = body_mod.additive_torus(proj, body_index, radius1=radius1,
- radius2=radius2)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.additive_torus(
+ proj,
+ body_index,
+ radius1=radius1,
+ radius2=radius2,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added additive torus")
@body_group.command("additive-wedge")
@click.argument("body_index", type=int)
@click.option("--param", "-P", multiple=True, help="Wedge param as key=value.")
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
-def body_additive_wedge(body_index: int, param: tuple) -> None:
+def body_additive_wedge(body_index: int, param: tuple,
+ position: Optional[str], rotation: Optional[str]) -> None:
"""Add an additive wedge primitive."""
sess = get_session()
sess.snapshot(f"Additive wedge body #{body_index}")
proj = sess.get_project()
params = _parse_params(param) or {}
- result = body_mod.additive_wedge(proj, body_index, **params)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.additive_wedge(
+ proj,
+ body_index,
+ position=pos,
+ rotation=rot,
+ **params,
+ )
output_fn(result, "Added additive wedge")
@@ -1450,15 +1652,27 @@ def body_additive_wedge(body_index: int, param: tuple) -> None:
@click.option("--length", "-l", default=10.0, type=float)
@click.option("--width", "-w", default=10.0, type=float)
@click.option("--height", "-h", default=10.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
def body_subtractive_box(body_index: int, length: float, width: float,
- height: float) -> None:
+ height: float, position: Optional[str],
+ rotation: Optional[str]) -> None:
"""Add a subtractive box primitive."""
sess = get_session()
sess.snapshot(f"Subtractive box body #{body_index}")
proj = sess.get_project()
- result = body_mod.subtractive_box(proj, body_index, length=length, width=width,
- height=height)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.subtractive_box(
+ proj,
+ body_index,
+ length=length,
+ width=width,
+ height=height,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added subtractive box")
@@ -1466,28 +1680,50 @@ def body_subtractive_box(body_index: int, length: float, width: float,
@click.argument("body_index", type=int)
@click.option("--radius", "-r", default=5.0, type=float)
@click.option("--height", "-h", default=10.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
def body_subtractive_cylinder(body_index: int, radius: float,
- height: float) -> None:
+ height: float, position: Optional[str],
+ rotation: Optional[str]) -> None:
"""Add a subtractive cylinder primitive."""
sess = get_session()
sess.snapshot(f"Subtractive cylinder body #{body_index}")
proj = sess.get_project()
- result = body_mod.subtractive_cylinder(proj, body_index, radius=radius,
- height=height)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.subtractive_cylinder(
+ proj,
+ body_index,
+ radius=radius,
+ height=height,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added subtractive cylinder")
@body_group.command("subtractive-sphere")
@click.argument("body_index", type=int)
@click.option("--radius", "-r", default=5.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
-def body_subtractive_sphere(body_index: int, radius: float) -> None:
+def body_subtractive_sphere(body_index: int, radius: float,
+ position: Optional[str], rotation: Optional[str]) -> None:
"""Add a subtractive sphere primitive."""
sess = get_session()
sess.snapshot(f"Subtractive sphere body #{body_index}")
proj = sess.get_project()
- result = body_mod.subtractive_sphere(proj, body_index, radius=radius)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.subtractive_sphere(
+ proj,
+ body_index,
+ radius=radius,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added subtractive sphere")
@@ -1496,15 +1732,27 @@ def body_subtractive_sphere(body_index: int, radius: float) -> None:
@click.option("--radius1", default=5.0, type=float)
@click.option("--radius2", default=0.0, type=float)
@click.option("--height", "-h", default=10.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
def body_subtractive_cone(body_index: int, radius1: float, radius2: float,
- height: float) -> None:
+ height: float, position: Optional[str],
+ rotation: Optional[str]) -> None:
"""Add a subtractive cone primitive."""
sess = get_session()
sess.snapshot(f"Subtractive cone body #{body_index}")
proj = sess.get_project()
- result = body_mod.subtractive_cone(proj, body_index, radius1=radius1,
- radius2=radius2, height=height)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.subtractive_cone(
+ proj,
+ body_index,
+ radius1=radius1,
+ radius2=radius2,
+ height=height,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added subtractive cone")
@@ -1512,29 +1760,51 @@ def body_subtractive_cone(body_index: int, radius1: float, radius2: float,
@click.argument("body_index", type=int)
@click.option("--radius1", default=10.0, type=float)
@click.option("--radius2", default=2.0, type=float)
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
def body_subtractive_torus(body_index: int, radius1: float,
- radius2: float) -> None:
+ radius2: float, position: Optional[str],
+ rotation: Optional[str]) -> None:
"""Add a subtractive torus primitive."""
sess = get_session()
sess.snapshot(f"Subtractive torus body #{body_index}")
proj = sess.get_project()
- result = body_mod.subtractive_torus(proj, body_index, radius1=radius1,
- radius2=radius2)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.subtractive_torus(
+ proj,
+ body_index,
+ radius1=radius1,
+ radius2=radius2,
+ position=pos,
+ rotation=rot,
+ )
output_fn(result, "Added subtractive torus")
@body_group.command("subtractive-wedge")
@click.argument("body_index", type=int)
@click.option("--param", "-P", multiple=True, help="Wedge param as key=value.")
[email protected]("--position", default=None, help="Placement position as x,y,z.")
[email protected]("--rotation", default=None, help="Placement rotation as rx,ry,rz degrees.")
@handle_error
-def body_subtractive_wedge(body_index: int, param: tuple) -> None:
+def body_subtractive_wedge(body_index: int, param: tuple,
+ position: Optional[str], rotation: Optional[str]) -> None:
"""Add a subtractive wedge primitive."""
sess = get_session()
sess.snapshot(f"Subtractive wedge body #{body_index}")
proj = sess.get_project()
params = _parse_params(param) or {}
- result = body_mod.subtractive_wedge(proj, body_index, **params)
+ pos = _parse_vec3(position) if position else None
+ rot = _parse_vec3(rotation) if rotation else None
+ result = body_mod.subtractive_wedge(
+ proj,
+ body_index,
+ position=pos,
+ rotation=rot,
+ **params,
+ )
output_fn(result, "Added subtractive wedge")
@@ -1949,6 +2219,365 @@ def export_presets() -> None:
output_fn(result, "Export presets:")
+def preview_group():
+ """Preview bundle capture and inspection."""
+ pass
+
+
+@preview_group.group("live")
+def preview_live_group():
+ """Live preview session commands."""
+ pass
+
+
+@preview_group.command("recipes")
+@handle_error
+def preview_recipes() -> None:
+ """List available preview recipes."""
+ result = preview_mod.list_recipes()
+ output_fn(result, "Preview recipes:")
+
+
+@preview_group.command("capture")
[email protected]("--recipe", default="quick", help="Preview recipe name.")
[email protected]("--force", is_flag=True, help="Bypass preview cache.")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory.")
+@handle_error
+def preview_capture(recipe: str, force: bool, root_dir: Optional[str]) -> None:
+ """Capture a preview bundle for the active project."""
+ sess = get_session()
+ result = preview_mod.capture(
+ sess,
+ recipe=recipe,
+ force=force,
+ root_dir=root_dir,
+ command=f"cli-anything-freecad --project {sess.project_path or ''} preview capture --recipe {recipe}".strip(),
+ )
+ bundle_dir = result.get("_bundle_dir", result.get("bundle_dir", ""))
+ status = "Reused preview bundle" if result.get("cached") else "Created preview bundle"
+ output_fn(result, f"{status}: {bundle_dir}")
+
+
+@preview_group.command("latest")
[email protected]("--recipe", default=None, help="Filter by recipe name.")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory.")
+@handle_error
+def preview_latest(recipe: Optional[str], root_dir: Optional[str]) -> None:
+ """Show the latest preview bundle manifest."""
+ sess = get_session()
+ result = preview_mod.latest(project_path=sess.project_path, recipe=recipe, root_dir=root_dir)
+ output_fn(result, f"Latest preview bundle: {result.get('_bundle_dir', '')}")
+
+
+@preview_live_group.command("start")
[email protected]("--recipe", default="quick", help="Preview recipe name.")
[email protected]("--force", is_flag=True, help="Bypass preview cache.")
[email protected]("--root-dir", default=None, help="Override preview root directory.")
[email protected]("--poll-ms", default=1500, show_default=True, help="Suggested viewer polling interval.")
[email protected]("--mode", type=click.Choice(["poll", "manual"]), default="poll", show_default=True,
+ help="Live preview mode. Poll mode auto-captures when the project file changes.")
[email protected]("--source-poll-ms", default=500, show_default=True,
+ help="Polling interval for source project changes in poll mode.")
[email protected]("--open", "open_window", is_flag=True, help="Launch cli-hub live viewer in a separate window.")
+@handle_error
+def preview_live_start(
+ recipe: str,
+ force: bool,
+ root_dir: Optional[str],
+ poll_ms: int,
+ mode: str,
+ source_poll_ms: int,
+ open_window: bool,
+) -> None:
+ """Start a live preview session and publish the latest bundle."""
+ sess = get_session()
+ result = preview_mod.live_start(
+ sess,
+ recipe=recipe,
+ force=force,
+ root_dir=root_dir,
+ refresh_hint_ms=poll_ms,
+ live_mode=mode,
+ source_poll_ms=source_poll_ms,
+ command=(
+ f"cli-anything-freecad -p {sess.project_path or ''} "
+ f"preview live start --recipe {recipe}"
+ ).strip(),
+ )
+ if result.get("live_mode") == "poll" and not result.get("poller", {}).get("running"):
+ result["poller"] = _spawn_live_poller(result["_session_dir"])
+ if open_window:
+ result["viewer"] = _spawn_live_viewer(result["_session_dir"], poll_ms)
+ output_fn(result, f"Started live preview session: {result.get('_session_dir', '')}")
+
+
+@preview_live_group.command("push")
[email protected]("--recipe", default="quick", help="Preview recipe name.")
[email protected]("--force", is_flag=True, help="Bypass preview cache.")
[email protected]("--root-dir", default=None, help="Override preview root directory.")
[email protected]("--poll-ms", default=1500, show_default=True, help="Suggested viewer polling interval.")
+@handle_error
+def preview_live_push(recipe: str, force: bool, root_dir: Optional[str], poll_ms: int) -> None:
+ """Publish a fresh bundle into the live preview session."""
+ sess = get_session()
+ result = preview_mod.live_push(
+ sess,
+ recipe=recipe,
+ force=force,
+ root_dir=root_dir,
+ refresh_hint_ms=poll_ms,
+ source_poll_ms=preview_mod.DEFAULT_SOURCE_POLL_MS,
+ command=(
+ f"cli-anything-freecad -p {sess.project_path or ''} "
+ f"preview live push --recipe {recipe}"
+ ).strip(),
+ )
+ output_fn(result, f"Updated live preview session: {result.get('_session_dir', '')}")
+
+
+@preview_live_group.command("status")
[email protected]("--recipe", default="quick", help="Preview recipe name.")
[email protected]("--root-dir", default=None, help="Override preview root directory.")
+@handle_error
+def preview_live_status(recipe: str, root_dir: Optional[str]) -> None:
+ """Show live preview session metadata."""
+ sess = get_session()
+ result = preview_mod.live_status(sess, recipe=recipe, root_dir=root_dir)
+ output_fn(result, f"Live preview session: {result.get('_session_dir', '')}")
+
+
+@preview_live_group.command("stop")
[email protected]("--recipe", default="quick", help="Preview recipe name.")
[email protected]("--root-dir", default=None, help="Override preview root directory.")
+@handle_error
+def preview_live_stop(recipe: str, root_dir: Optional[str]) -> None:
+ """Stop the live preview session without deleting artifacts."""
+ sess = get_session()
+ result = preview_mod.live_stop(sess, recipe=recipe, root_dir=root_dir)
+ output_fn(result, f"Stopped live preview session: {result.get('_session_dir', '')}")
+
+
+@preview_live_group.command("monitor", hidden=True)
[email protected]("--session-dir", required=True, help="Live session directory to monitor.")
+@handle_error
+def preview_live_monitor(session_dir: str) -> None:
+ """Internal background poller for live preview sessions."""
+ result = preview_mod.run_live_poller(session_dir)
+ output_fn(result, "")
+
+
+# ── Motion commands ──────────────────────────────────────────────────
+
+def motion_group():
+ """Motion sequencing and final showcase rendering commands."""
+ pass
+
+
+@motion_group.command("new")
[email protected]("--name", default=None, help="Motion sequence name.")
[email protected]("--duration", type=float, default=2.0, help="Motion duration in seconds.")
[email protected]("--fps", type=int, default=24, help="Frames per second.")
[email protected]("--camera", type=click.Choice(sorted(motion_mod.CAMERA_PRESETS)), default="hero",
+ help="Camera preset for rendering.")
[email protected]("--width", type=int, default=1280, help="Output frame width.")
[email protected]("--height", type=int, default=960, help="Output frame height.")
[email protected]("--background", default="White", help="Viewport background color.")
[email protected]("--fit-mode", type=click.Choice(sorted(motion_mod.FIT_MODES)), default="initial",
+ help="Whether to fit camera only once or on every frame.")
+@handle_error
+def motion_new(
+ name: Optional[str],
+ duration: float,
+ fps: int,
+ camera: str,
+ width: int,
+ height: int,
+ background: str,
+ fit_mode: str,
+) -> None:
+ """Create a new motion sequence."""
+ sess = get_session()
+ sess.snapshot("New motion sequence")
+ proj = sess.get_project()
+ result = motion_mod.create_motion(
+ proj,
+ name=name,
+ duration=duration,
+ fps=fps,
+ camera=camera,
+ width=width,
+ height=height,
+ background=background,
+ fit_mode=fit_mode,
+ )
+ output_fn(result, f"Created motion: {result.get('name', '')}")
+
+
+@motion_group.command("list")
+@handle_error
+def motion_list() -> None:
+ """List motion sequences in the project."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = motion_mod.list_motions(proj)
+ output_fn(result, f"{len(result)} motion sequence(s):")
+
+
+@motion_group.command("get")
[email protected]("motion_index", type=int)
+@handle_error
+def motion_get(motion_index: int) -> None:
+ """Show motion sequence details."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = motion_mod.get_motion(proj, motion_index)
+ output_fn(result, f"Motion #{motion_index}")
+
+
+@motion_group.command("delete")
[email protected]("motion_index", type=int)
+@handle_error
+def motion_delete(motion_index: int) -> None:
+ """Delete a motion sequence."""
+ sess = get_session()
+ sess.snapshot(f"Delete motion #{motion_index}")
+ proj = sess.get_project()
+ result = motion_mod.delete_motion(proj, motion_index)
+ output_fn(result, f"Deleted motion: {result.get('name', '')}")
+
+
+@motion_group.command("keyframe")
[email protected]("motion_index", type=int)
[email protected]("target_kind", type=click.Choice(sorted(motion_mod.TARGET_KINDS)))
[email protected]("target_index", type=int)
[email protected]("time_value", type=float)
[email protected]("--position", default=None, help="Position as x,y,z. Defaults to the current placement.")
[email protected]("--rotation", default=None, help="Rotation as rx,ry,rz. Defaults to the current placement.")
+@handle_error
+def motion_keyframe(
+ motion_index: int,
+ target_kind: str,
+ target_index: int,
+ time_value: float,
+ position: Optional[str],
+ rotation: Optional[str],
+) -> None:
+ """Add or replace a motion keyframe for a target object."""
+ sess = get_session()
+ sess.snapshot(f"Motion keyframe on {target_kind} #{target_index}")
+ proj = sess.get_project()
+ result = motion_mod.add_keyframe(
+ proj,
+ motion_index,
+ target_kind=target_kind,
+ target_index=target_index,
+ time_value=time_value,
+ position=_parse_vec3(position) if position else None,
+ rotation=_parse_vec3(rotation) if rotation else None,
+ )
+ output_fn(result, f"Updated motion #{motion_index}")
+
+
+@motion_group.command("sample")
[email protected]("motion_index", type=int)
[email protected]("time_value", type=float)
+@handle_error
+def motion_sample(motion_index: int, time_value: float) -> None:
+ """Sample interpolated motion placements at a given time."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = motion_mod.sample_motion(proj, motion_index, time_value)
+ output_fn(result, f"Motion sample at t={result.get('time')}")
+
+
+@motion_group.command("render-frames")
[email protected]("motion_index", type=int)
[email protected]("output_dir", type=click.Path())
[email protected]("--overwrite", is_flag=True, help="Replace an existing output directory.")
[email protected]("--camera", type=click.Choice(sorted(motion_mod.CAMERA_PRESETS)), default=None,
+ help="Override the motion camera preset.")
[email protected]("--width", type=int, default=None, help="Override the frame width.")
[email protected]("--height", type=int, default=None, help="Override the frame height.")
[email protected]("--background", default=None, help="Override the viewport background.")
[email protected]("--fit-mode", type=click.Choice(sorted(motion_mod.FIT_MODES)), default=None,
+ help="Override the camera fit mode.")
+@handle_error
+def motion_render_frames(
+ motion_index: int,
+ output_dir: str,
+ overwrite: bool,
+ camera: Optional[str],
+ width: Optional[int],
+ height: Optional[int],
+ background: Optional[str],
+ fit_mode: Optional[str],
+) -> None:
+ """Render a motion sequence to real FreeCAD frame images."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = motion_mod.render_frames(
+ proj,
+ motion_index,
+ output_dir,
+ overwrite=overwrite,
+ camera=camera,
+ width=width,
+ height=height,
+ background=background,
+ fit_mode=fit_mode,
+ )
+ output_fn(result, f"Rendered {result.get('frame_count', 0)} motion frame(s)")
+
+
+@motion_group.command("render-video")
[email protected]("motion_index", type=int)
[email protected]("output_path", type=click.Path())
[email protected]("--overwrite", is_flag=True, help="Replace an existing output file.")
[email protected]("--frames-dir", default=None, type=click.Path(),
+ help="Persist rendered frame images to this directory.")
[email protected]("--keep-frames", is_flag=True,
+ help="Keep rendered frames even when --frames-dir is not specified.")
[email protected]("--camera", type=click.Choice(sorted(motion_mod.CAMERA_PRESETS)), default=None,
+ help="Override the motion camera preset.")
[email protected]("--width", type=int, default=None, help="Override the frame width.")
[email protected]("--height", type=int, default=None, help="Override the frame height.")
[email protected]("--background", default=None, help="Override the viewport background.")
[email protected]("--fit-mode", type=click.Choice(sorted(motion_mod.FIT_MODES)), default=None,
+ help="Override the camera fit mode.")
+@handle_error
+def motion_render_video(
+ motion_index: int,
+ output_path: str,
+ overwrite: bool,
+ frames_dir: Optional[str],
+ keep_frames: bool,
+ camera: Optional[str],
+ width: Optional[int],
+ height: Optional[int],
+ background: Optional[str],
+ fit_mode: Optional[str],
+) -> None:
+ """Render a motion sequence to a final showcase video."""
+ sess = get_session()
+ proj = sess.get_project()
+ result = motion_mod.render_video(
+ proj,
+ motion_index,
+ output_path,
+ overwrite=overwrite,
+ frames_dir=frames_dir,
+ keep_frames=keep_frames,
+ camera=camera,
+ width=width,
+ height=height,
+ background=background,
+ fit_mode=fit_mode,
+ )
+ output_fn(result, f"Rendered motion video: {result.get('output', '')}")
+
+
# ── Session commands ─────────────────────────────────────────────────
@cli.group("session")
@@ -4211,11 +4840,13 @@ def repl(project_path: Optional[str]) -> None:
_repl_commands = {
"document": "new|open|save|info|profiles",
- "part": "add|remove|list|get|transform|boolean|copy|mirror|scale|offset|thickness|compound|explode|fillet-3d|chamfer-3d|loft|sweep|revolve|extrude|section|slice|line-3d|wire|polygon-3d|info",
+ "part": "add|remove|list|get|transform|boolean|copy|mirror|scale|offset|thickness|compound|explode|fillet-3d|chamfer-3d|loft|sweep|revolve|extrude|section|slice|line-3d|wire|polygon-3d|info|bounds|align",
"sketch": "new|add-line|add-circle|add-rect|add-arc|constrain|close|list|get|add-point|add-ellipse|add-polygon|add-bspline|add-slot|edit-element|remove-element|remove-constraint|edit-constraint|mirror|offset|trim|extend|validate|solve-status|set-construction|project-external|intersection|add-external-face",
"body": "new|pad|pocket|fillet|chamfer|revolution|list|get|groove|additive-loft|additive-pipe|additive-helix|subtractive-loft|subtractive-pipe|subtractive-helix|additive-box|additive-cylinder|additive-sphere|additive-cone|additive-torus|additive-wedge|subtractive-box|subtractive-cylinder|subtractive-sphere|subtractive-cone|subtractive-torus|subtractive-wedge|draft-feature|thickness-feature|hole|linear-pattern|polar-pattern|mirrored|multi-transform|datum-plane|datum-line|datum-point|shape-binder|local-coordinate-system|toggle-freeze",
"material": "create|assign|list|get|set|presets|import-material|export-material",
"export": "render|info|presets",
+ "preview": "recipes|capture|latest|live",
+ "motion": "new|list|get|delete|keyframe|sample|render-frames|render-video",
"session": "undo|redo|status|history",
"measure": "distance|length|angle|area|volume|radius|diameter|position|center-of-mass|bounding-box|inertia|check-geometry",
"spreadsheet": "new|set-cell|get-cell|set-alias|import-csv|export-csv|list",
diff --git a/freecad/agent-harness/cli_anything/freecad/tests/test_core.py b/freecad/agent-harness/cli_anything/freecad/tests/test_core.py
index 8260a7959..73859d6bd 100644
--- a/freecad/agent-harness/cli_anything/freecad/tests/test_core.py
+++ b/freecad/agent-harness/cli_anything/freecad/tests/test_core.py
@@ -8,6 +8,7 @@ beyond pytest.
import json
import math
import os
+from pathlib import Path
import pytest
@@ -22,9 +23,11 @@ from cli_anything.freecad.core.document import (
from cli_anything.freecad.core.parts import (
PRIMITIVES,
add_part,
+ align_part,
boolean_op,
get_part,
list_parts,
+ part_bounds,
remove_part,
transform_part,
)
@@ -40,6 +43,9 @@ from cli_anything.freecad.core.sketch import (
list_sketches,
)
from cli_anything.freecad.core.body import (
+ additive_box,
+ additive_cone,
+ additive_cylinder,
chamfer,
create_body,
datum_plane,
@@ -48,11 +54,14 @@ from cli_anything.freecad.core.body import (
fillet,
get_body,
hole_feature,
+ linear_pattern,
list_bodies,
local_coordinate_system,
pad,
pocket,
+ polar_pattern,
revolution,
+ subtractive_box,
toggle_freeze,
)
from cli_anything.freecad.core.materials import (
@@ -64,7 +73,10 @@ from cli_anything.freecad.core.materials import (
list_presets,
set_material_property,
)
+from cli_anything.freecad.core import preview as preview_mod
+from cli_anything.freecad.core import motion as motion_mod
from cli_anything.freecad.core.session import Session
+from cli_anything.freecad.utils import freecad_backend
# ---------------------------------------------------------------------------
@@ -79,6 +91,16 @@ def _make_project(**overrides):
return proj
+def _make_wrapper_script(path: Path) -> Path:
+ path.write_text(
+ "#!/bin/bash\n"
+ "SCRIPT_MODE=1\n"
+ "xvfb-run freecadcmd \"$@\"\n",
+ encoding="utf-8",
+ )
+ return path
+
+
# ===========================================================================
# TestDocument
# ===========================================================================
@@ -140,6 +162,7 @@ class TestDocument:
assert info["sketches_count"] == 0
assert info["bodies_count"] == 0
assert info["materials_count"] == 0
+ assert info["motions_count"] == 0
def test_get_info_with_data(self):
proj = create_document(name="DataTest")
@@ -214,6 +237,71 @@ class TestParts:
with pytest.raises(ValueError, match="Unknown part_type"):
add_part(proj, "hexagon")
+ def test_part_bounds_reports_world_space_box(self):
+ proj = _make_project()
+ add_part(
+ proj,
+ "box",
+ name="BoundsBox",
+ params={"length": 20.0, "width": 8.0, "height": 6.0},
+ position=[5.0, 10.0, 15.0],
+ )
+ bounds = part_bounds(proj, 0)
+ assert bounds["local_bounding_box"]["min"] == {"x": 0.0, "y": 0.0, "z": 0.0}
+ assert bounds["local_bounding_box"]["max"] == {"x": 20.0, "y": 8.0, "z": 6.0}
+ assert bounds["world_bounding_box"]["min"] == {"x": 5.0, "y": 10.0, "z": 15.0}
+ assert bounds["world_bounding_box"]["max"] == {"x": 25.0, "y": 18.0, "z": 21.0}
+
+ def test_align_part_matches_bbox_faces(self):
+ proj = _make_project()
+ add_part(
+ proj,
+ "box",
+ name="Base",
+ params={"length": 20.0, "width": 10.0, "height": 6.0},
+ position=[0.0, 0.0, 0.0],
+ )
+ add_part(
+ proj,
+ "box",
+ name="Cap",
+ params={"length": 8.0, "width": 6.0, "height": 4.0},
+ position=[100.0, 50.0, 20.0],
+ )
+
+ result = align_part(
+ proj,
+ 1,
+ 0,
+ x="min",
+ to_x="max",
+ y="center",
+ to_y="center",
+ z="min",
+ to_z="max",
+ )
+
+ assert result["placement"]["position"] == [20.0, 2.0, 6.0]
+ aligned = part_bounds(proj, 1)["world_bounding_box"]
+ target = part_bounds(proj, 0)["world_bounding_box"]
+ assert aligned["min"]["x"] == pytest.approx(target["max"]["x"])
+ assert aligned["center"]["y"] == pytest.approx(target["center"]["y"])
+ assert aligned["min"]["z"] == pytest.approx(target["max"]["z"])
+
+ def test_align_part_requires_supported_bounds(self):
+ proj = _make_project()
+ add_part(proj, "box", name="Base")
+ add_part(
+ proj,
+ "cylinder",
+ name="Tool",
+ params={"radius": 2.0, "height": 12.0},
+ position=[4.0, 4.0, -1.0],
+ )
+ boolean_op(proj, "cut", 0, 1, name="CutResult")
+ with pytest.raises(ValueError, match="does not support bounding-box alignment"):
+ align_part(proj, 2, 0, x="min", to_x="max")
+
def test_remove_part(self):
proj = _make_project()
add_part(proj, "box", name="A")
@@ -522,6 +610,81 @@ class TestBody:
with pytest.raises(ValueError, match="Invalid revolution axis"):
revolution(proj, body_index=0, sketch_index=0, axis="W")
+ def test_additive_primitive_placement_and_patterns(self):
+ proj = _make_project()
+ create_body(proj, name="TowerBody")
+
+ base = additive_box(
+ proj,
+ body_index=0,
+ length=12.0,
+ width=10.0,
+ height=18.0,
+ position=[1.0, 2.0, 3.0],
+ rotation=[0.0, 0.0, 15.0],
+ )
+ assert base["type"] == "additive_box"
+ assert base["placement"]["position"] == [1.0, 2.0, 3.0]
+ assert base["placement"]["rotation"] == [0.0, 0.0, 15.0]
+
+ rib = additive_cylinder(
+ proj,
+ body_index=0,
+ radius=2.5,
+ height=6.0,
+ position=[8.0, 0.0, 9.0],
+ )
+ assert rib["type"] == "additive_cylinder"
+ assert rib["placement"]["position"] == [8.0, 0.0, 9.0]
+
+ cone = additive_cone(
+ proj,
+ body_index=0,
+ radius1=3.0,
+ radius2=1.0,
+ height=8.0,
+ position=[0.0, 0.0, 18.0],
+ )
+ assert cone["type"] == "additive_cone"
+
+ linear = linear_pattern(
+ proj,
+ body_index=0,
+ direction=[0.0, 0.0, 1.0],
+ length=24.0,
+ occurrences=4,
+ )
+ assert linear["type"] == "linear_pattern"
+ assert linear["direction"] == [0.0, 0.0, 1.0]
+ assert linear["occurrences"] == 4
+
+ polar = polar_pattern(
+ proj,
+ body_index=0,
+ axis="Z",
+ angle=360.0,
+ occurrences=4,
+ )
+ assert polar["type"] == "polar_pattern"
+ assert polar["axis"] == "Z"
+ assert polar["occurrences"] == 4
+
+ def test_subtractive_primitive_placement(self):
+ proj = _make_project()
+ create_body(proj, name="CutBody")
+ additive_box(proj, body_index=0, length=20.0, width=20.0, height=20.0)
+
+ cut = subtractive_box(
+ proj,
+ body_index=0,
+ length=6.0,
+ width=6.0,
+ height=10.0,
+ position=[0.0, 0.0, 5.0],
+ )
+ assert cut["type"] == "subtractive_box"
+ assert cut["placement"]["position"] == [0.0, 0.0, 5.0]
+
def test_list_and_get_body(self):
proj = self._project_with_sketch()
create_body(proj, name="B1")
@@ -869,3 +1032,348 @@ class TestFreeCAD11Features:
create_body(proj, name="FreezeBody2")
with pytest.raises(IndexError):
toggle_freeze(proj, 0, 99)
+
+
+class TestPreview:
+ @staticmethod
+ def _fake_bundle(tmp_path, bundle_id):
+ bundle_dir = tmp_path / bundle_id
+ artifacts_dir = bundle_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=True)
+ for artifact_id in ("hero", "front", "top", "right"):
+ (artifacts_dir / f"{artifact_id}.png").write_bytes(b"\x89PNG\r\n\x1a\npreview")
+ summary_path = bundle_dir / "summary.json"
+ summary_path.write_text(
+ json.dumps(
+ {
+ "headline": "FreeCAD quick preview",
+ "facts": {"views": 4, "units": "mm"},
+ }
+ )
+ )
+ manifest_path = bundle_dir / "manifest.json"
+ manifest_path.write_text(json.dumps({"bundle_id": bundle_id, "status": "ok"}))
+ return {
+ "bundle_id": bundle_id,
+ "status": "ok",
+ "_bundle_dir": str(bundle_dir),
+ "_manifest_path": str(manifest_path),
+ "_summary_path": str(summary_path),
+ "cached": False,
+ }
+
+ def test_list_recipes(self):
+ recipes = preview_mod.list_recipes()
+ assert recipes
+ assert recipes[0]["name"] == "quick"
+
+ def test_capture_bundle(self, tmp_path, monkeypatch):
+ sess = Session()
+ proj = create_document(name="PreviewDoc")
+ add_part(proj, "box", name="HeroBox")
+ sess.set_project(proj, str(tmp_path / "project.json"))
+
+ def fake_capture(script_content, timeout=120, gui_required=False, env=None):
+ marker = "artifacts/"
+ for line in script_content.splitlines():
+ if marker in line and ".png" in line:
+ path = line.split("'")[3]
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
+ Path(path).write_bytes(b"\x89PNG\r\n\x1a\npreview")
+ return {"returncode": 0, "stdout": "", "stderr": ""}
+
+ monkeypatch.setattr(freecad_backend, "run_macro_content", fake_capture)
+
+ manifest = preview_mod.capture(sess, root_dir=str(tmp_path))
+ assert manifest["software"] == "freecad"
+ assert manifest["recipe"] == "quick"
+ assert any(item["role"] == "hero" for item in manifest["artifacts"])
+ assert len(manifest["artifacts"]) >= 4
+
+ def test_latest_bundle(self, tmp_path, monkeypatch):
+ sess = Session()
+ proj = create_document(name="PreviewDoc")
+ add_part(proj, "box", name="HeroBox")
+ sess.set_project(proj)
+
+ def fake_capture(script_content, timeout=120, gui_required=False, env=None):
+ for line in script_content.splitlines():
+ if "artifacts/" in line and ".png" in line:
+ path = line.split("'")[3]
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
+ Path(path).write_bytes(b"\x89PNG\r\n\x1a\npreview")
+ return {"returncode": 0, "stdout": "", "stderr": ""}
+
+ monkeypatch.setattr(freecad_backend, "run_macro_content", fake_capture)
+
+ created = preview_mod.capture(sess, root_dir=str(tmp_path))
+ latest = preview_mod.latest(root_dir=str(tmp_path))
+ assert latest["bundle_id"] == created["bundle_id"]
+
+ def test_live_start_publishes_session(self, tmp_path, monkeypatch):
+ sess = Session()
+ proj = create_document(name="LivePreviewDoc")
+ add_part(proj, "box", name="HeroBox")
+ project_path = tmp_path / "live-demo.json"
+ save_document(proj, str(project_path))
+ sess.set_project(proj, str(project_path))
+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+
+ def fake_capture(*args, **kwargs):
+ return dict(bundle_manifest)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ live = preview_mod.live_start(
+ sess,
+ root_dir=str(tmp_path),
+ refresh_hint_ms=900,
+ live_mode="poll",
+ source_poll_ms=420,
+ )
+ assert live["protocol_version"] == preview_mod.LIVE_PROTOCOL_VERSION
+ assert live["current_bundle_id"] == "bundle-a"
+ assert live["refresh_hint_ms"] == 900
+ assert live["live_mode"] == "poll"
+ assert live["source_poll_ms"] == 420
+ assert live["source_state"]["project_path"] == str(project_path)
+ assert live["source_state"]["last_rendered_fingerprint"].startswith("sha256:")
+ assert Path(live["_session_path"]).is_file()
+ assert (Path(live["_session_dir"]) / "current" / "manifest.json").is_file()
+
+ def test_live_push_updates_history(self, tmp_path, monkeypatch):
+ sess = Session()
+ proj = create_document(name="LivePreviewDoc")
+ add_part(proj, "box", name="HeroBox")
+ project_path = tmp_path / "live-demo.json"
+ save_document(proj, str(project_path))
+ sess.set_project(proj, str(project_path))
+ bundle_a = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+ bundle_b = self._fake_bundle(tmp_path / "bundles", "bundle-b")
+ manifests = [dict(bundle_a), dict(bundle_b)]
+
+ def fake_capture(*args, **kwargs):
+ return manifests.pop(0)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ started = preview_mod.live_start(sess, root_dir=str(tmp_path))
+ pushed = preview_mod.live_push(sess, root_dir=str(tmp_path))
+ assert started["current_bundle_id"] == "bundle-a"
+ assert pushed["current_bundle_id"] == "bundle-b"
+ assert pushed["history"][0]["bundle_id"] == "bundle-b"
+ assert pushed["history"][1]["bundle_id"] == "bundle-a"
+
+ def test_live_stop_marks_session_stopped(self, tmp_path, monkeypatch):
+ sess = Session()
+ proj = create_document(name="LivePreviewDoc")
+ add_part(proj, "box", name="HeroBox")
+ project_path = tmp_path / "live-demo.json"
+ save_document(proj, str(project_path))
+ sess.set_project(proj, str(project_path))
+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+
+ def fake_capture(*args, **kwargs):
+ return dict(bundle_manifest)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ preview_mod.live_start(sess, root_dir=str(tmp_path))
+ stopped = preview_mod.live_stop(sess, root_dir=str(tmp_path))
+ assert stopped["status"] == "stopped"
+ assert "stopped_at" in stopped
+
+ def test_live_session_name_is_stable_for_same_project_path(self, tmp_path):
+ project_path = tmp_path / "stable-demo.json"
+ proj = create_document(name="StablePreviewDoc")
+ save_document(proj, str(project_path))
+
+ session_a = Session()
+ session_a.set_project(proj, str(project_path))
+
+ session_b = Session()
+ session_b.set_project(open_document(str(project_path)), str(project_path))
+
+ name_a = preview_mod._live_session_name(session_a, "quick")
+ name_b = preview_mod._live_session_name(session_b, "quick")
+ assert name_a == name_b
+
+ def test_project_fingerprint_is_stable_across_sessions_for_saved_project(self, tmp_path):
+ project_path = tmp_path / "stable-project.json"
+ proj = create_document(name="StablePreviewDoc")
+ save_document(proj, str(project_path))
+
+ session_a = Session()
+ session_a.set_project(proj, str(project_path))
+
+ session_b = Session()
+ session_b.set_project(open_document(str(project_path)), str(project_path))
+
+ assert preview_mod._project_fingerprint(session_a) == preview_mod._project_fingerprint(session_b)
+
+ def test_poll_live_session_once_captures_after_source_change(self, tmp_path, monkeypatch):
+ sess = Session()
+ proj = create_document(name="PollingPreviewDoc")
+ add_part(proj, "box", name="HeroBox")
+ project_path = tmp_path / "polling-demo.json"
+ save_document(proj, str(project_path))
+ sess.set_project(proj, str(project_path))
+ bundle_a = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+ bundle_b = self._fake_bundle(tmp_path / "bundles", "bundle-b")
+ manifests = [dict(bundle_a), dict(bundle_b)]
+
+ def fake_capture(*args, **kwargs):
+ return manifests.pop(0)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ started = preview_mod.live_start(
+ sess,
+ root_dir=str(tmp_path),
+ live_mode="poll",
+ source_poll_ms=500,
+ )
+ started_session_dir = Path(started["_session_dir"])
+
+ updated = open_document(str(project_path))
+ add_part(updated, "cylinder", name="ChangedPart")
+ save_document(updated, str(project_path))
+
+ result = preview_mod.poll_live_session_once(str(started_session_dir))
+ payload = json.loads((started_session_dir / "session.json").read_text(encoding="utf-8"))
+ assert result["action"] == "captured"
+ assert result["bundle_id"] == "bundle-b"
+ assert payload["bundle_count"] >= 2
+ assert payload["source_state"]["last_publish_reason"] == "auto-poll"
+
+ def test_poll_live_session_once_exits_for_manual_mode(self, tmp_path, monkeypatch):
+ sess = Session()
+ proj = create_document(name="ManualPreviewDoc")
+ add_part(proj, "box", name="HeroBox")
+ project_path = tmp_path / "manual-demo.json"
+ save_document(proj, str(project_path))
+ sess.set_project(proj, str(project_path))
+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+
+ def fake_capture(*args, **kwargs):
+ return dict(bundle_manifest)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ started = preview_mod.live_start(sess, root_dir=str(tmp_path), live_mode="manual")
+ result = preview_mod.poll_live_session_once(started["_session_dir"])
+ assert result["action"] == "exit"
+ assert result["reason"] == "mode:manual"
+
+
+class TestMotion:
+ """Tests for motion sequencing and interpolation."""
+
+ def test_create_motion_defaults(self):
+ proj = _make_project()
+ motion = motion_mod.create_motion(proj, name="Drive")
+ assert motion["name"] == "Drive"
+ assert motion["duration"] == 2.0
+ assert motion["fps"] == 24
+ assert motion["camera"] == "hero"
+ assert motion["fit_mode"] == "initial"
+ assert motion["tracks"] == []
+ assert len(proj["motions"]) == 1
+
+ def test_add_keyframes_and_sample_interpolates(self):
+ proj = _make_project()
+ add_part(proj, "box", name="RoverBody", position=[0.0, 0.0, 0.0])
+ motion_mod.create_motion(proj, name="Drive", duration=2.0, fps=10)
+ motion_mod.add_keyframe(
+ proj,
+ 0,
+ target_kind="part",
+ target_index=0,
+ time_value=0.0,
+ position=[0.0, 0.0, 0.0],
+ rotation=[0.0, 0.0, 0.0],
+ )
+ motion_mod.add_keyframe(
+ proj,
+ 0,
+ target_kind="part",
+ target_index=0,
+ time_value=2.0,
+ position=[20.0, 10.0, 0.0],
+ rotation=[0.0, 0.0, 90.0],
+ )
+
+ sample = motion_mod.sample_motion(proj, 0, 1.0)
+ assert sample["time"] == 1.0
+ assert len(sample["placements"]) == 1
+ placement = sample["placements"][0]
+ assert placement["position"] == [10.0, 5.0, 0.0]
+ assert placement["rotation"] == [0.0, 0.0, 45.0]
+
+ def test_apply_motion_returns_project_copy(self):
+ proj = _make_project()
+ add_part(proj, "box", name="Wheel", position=[1.0, 2.0, 3.0], rotation=[0.0, 0.0, 0.0])
+ motion_mod.create_motion(proj, duration=1.0, fps=5)
+ motion_mod.add_keyframe(proj, 0, target_kind="part", target_index=0, time_value=0.0)
+ motion_mod.add_keyframe(
+ proj,
+ 0,
+ target_kind="part",
+ target_index=0,
+ time_value=1.0,
+ position=[11.0, 2.0, 3.0],
+ rotation=[0.0, 30.0, 0.0],
+ )
+
+ animated = motion_mod.apply_motion(proj, 0, 0.5)
+ assert animated is not proj
+ assert animated["parts"][0]["placement"]["position"] == [6.0, 2.0, 3.0]
+ assert animated["parts"][0]["placement"]["rotation"] == [0.0, 15.0, 0.0]
+ assert proj["parts"][0]["placement"]["position"] == [1.0, 2.0, 3.0]
+
+ def test_render_video_requires_supported_extension(self, tmp_path):
+ proj = _make_project()
+ add_part(proj, "box", name="Box")
+ motion_mod.create_motion(proj, duration=1.0, fps=5)
+ motion_mod.add_keyframe(proj, 0, target_kind="part", target_index=0, time_value=0.0)
+ with pytest.raises(ValueError, match="supports .mp4, .webm, and .gif"):
+ motion_mod.render_video(proj, 0, str(tmp_path / "bad.avi"))
+
+
+class TestFreeCADBackend:
+ """Tests for backend command selection and wrapper handling."""
+
+ def test_detects_gui_wrapper_script(self, tmp_path):
+ wrapper = _make_wrapper_script(tmp_path / "freecad-wrapper")
+ assert freecad_backend._is_gui_wrapper_script(str(wrapper)) is True
+
+ def test_macro_command_forces_gui_branch_for_wrapper(self, tmp_path):
+ wrapper = _make_wrapper_script(tmp_path / "freecad-wrapper")
+ script_path = tmp_path / "macro.py"
+ script_path.write_text("print('ok')\n", encoding="utf-8")
+
+ argv = freecad_backend._macro_command(str(wrapper), str(script_path), gui_required=True)
+ assert argv == [str(wrapper), "freecad", str(script_path)]
+
+ def test_run_macro_uses_wrapper_gui_override(self, tmp_path, monkeypatch):
+ wrapper = _make_wrapper_script(tmp_path / "freecad-wrapper")
+ script_path = tmp_path / "macro.py"
+ script_path.write_text("print('ok')\n", encoding="utf-8")
+ captured = {}
+
+ monkeypatch.setattr(freecad_backend, "find_freecad", lambda gui_required=False: str(wrapper))
+
+ def fake_run(args, *, timeout=120, check=False, env=None):
+ captured["args"] = args
+ captured["timeout"] = timeout
+ captured["env"] = env
+ return {"command": " ".join(args), "returncode": 0, "stdout": "", "stderr": "", "ok": True}
+
+ monkeypatch.setattr(freecad_backend, "_run", fake_run)
+
+ result = freecad_backend.run_macro(str(script_path), timeout=55, gui_required=True, env={"QT_QPA_PLATFORM": "offscreen"})
+
+ assert result["returncode"] == 0
+ assert captured["args"] == [str(wrapper), "freecad", str(script_path.resolve())]
+ assert captured["timeout"] == 55
+ assert captured["env"] == {"QT_QPA_PLATFORM": "offscreen"}
diff --git a/freecad/agent-harness/cli_anything/freecad/tests/test_full_e2e.py b/freecad/agent-harness/cli_anything/freecad/tests/test_full_e2e.py
index e99111aac..afecf3ac6 100644
--- a/freecad/agent-harness/cli_anything/freecad/tests/test_full_e2e.py
+++ b/freecad/agent-harness/cli_anything/freecad/tests/test_full_e2e.py
@@ -15,10 +15,12 @@ import os
import struct
import subprocess
import sys
+import time
from copy import deepcopy
from typing import List
import pytest
+from PIL import Image, ImageChops
# ---------------------------------------------------------------------------
# Imports from the harness under test
@@ -34,6 +36,7 @@ from cli_anything.freecad.core.parts import (
list_parts,
get_part,
boolean_op,
+ mirror_part,
transform_part,
)
from cli_anything.freecad.core.sketch import (
@@ -47,13 +50,18 @@ from cli_anything.freecad.core.sketch import (
list_sketches,
)
from cli_anything.freecad.core.body import (
+ additive_box,
+ additive_cone,
+ additive_cylinder,
create_body,
pad,
pocket,
fillet,
chamfer,
+ linear_pattern,
revolution,
list_bodies,
+ polar_pattern,
)
from cli_anything.freecad.core.materials import (
create_material,
@@ -61,6 +69,8 @@ from cli_anything.freecad.core.materials import (
list_materials,
)
from cli_anything.freecad.core.export import export_project, get_export_info
+from cli_anything.freecad.core import preview as preview_mod
+from cli_anything.freecad.core.session import Session
from cli_anything.freecad.utils.freecad_macro_gen import generate_macro
@@ -78,6 +88,65 @@ def _has_freecad() -> bool:
return False
+def _has_freecad_preview() -> bool:
+ """Return True if a GUI-capable FreeCAD executable appears to be available."""
+ try:
+ from cli_anything.freecad.utils.freecad_backend import find_freecad
+ path = find_freecad(gui_required=True)
+ return "cmd" not in os.path.basename(path).lower()
+ except (RuntimeError, Exception):
+ return False
+
+
+def _has_ffmpeg() -> bool:
+ import shutil
+
+ return shutil.which("ffmpeg") is not None
+
+
+PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
+
+
+def _artifact_path(manifest, artifact_id):
+ for artifact in manifest["artifacts"]:
+ if artifact["artifact_id"] == artifact_id:
+ return os.path.join(manifest["_bundle_dir"], artifact["path"])
+ raise KeyError(f"Artifact not found: {artifact_id}")
+
+
+def _assert_png(path):
+ assert os.path.isfile(path), f"Missing PNG artifact: {path}"
+ with open(path, "rb") as fh:
+ assert fh.read(8) == PNG_MAGIC, f"Invalid PNG header: {path}"
+ assert os.path.getsize(path) > 0, f"Empty PNG artifact: {path}"
+
+
+def _assert_png_not_blank(path):
+ _assert_png(path)
+ image = Image.open(path).convert("L")
+ extrema = image.getextrema()
+ assert extrema != (255, 255), f"PNG artifact is fully white: {path}"
+
+
+def _assert_images_differ(path_a, path_b):
+ image_a = Image.open(path_a).convert("RGB")
+ image_b = Image.open(path_b).convert("RGB")
+ diff = ImageChops.difference(image_a, image_b)
+ assert diff.getbbox() is not None, f"Images are identical: {path_a} vs {path_b}"
+
+
+def _wait_for_live_bundle_count(session_path, expected_count, timeout_s=30.0):
+ deadline = time.time() + timeout_s
+ latest = None
+ while time.time() < deadline:
+ with open(session_path, "r", encoding="utf-8") as fh:
+ latest = json.load(fh)
+ if latest.get("bundle_count", 0) >= expected_count:
+ return latest
+ time.sleep(0.5)
+ raise AssertionError(f"Timed out waiting for bundle_count >= {expected_count}: {latest}")
+
+
def _resolve_cli(name: str) -> List[str]:
"""Resolve the CLI entry-point for subprocess tests.
@@ -256,6 +325,60 @@ class TestIntermediateFiles:
print(f"\n Macro: {macro_path} ({len(macro):,} chars, {macro.count(chr(10))} lines)")
+ def test_macro_generation_body_primitives_and_patterns(self, tmp_path):
+ """Generate a macro containing body primitive placements and pattern features."""
+ proj = create_document(name="MacroBodyTower")
+ create_body(proj, name="TowerBody")
+ additive_box(
+ proj,
+ 0,
+ length=36,
+ width=36,
+ height=18,
+ position=[0, 0, 0],
+ )
+ additive_box(
+ proj,
+ 0,
+ length=8,
+ width=6,
+ height=4,
+ position=[22, 0, 8],
+ )
+ polar_pattern(proj, 0, axis="Z", angle=360, occurrences=4)
+ additive_cylinder(proj, 0, radius=2.0, height=16, position=[0, 0, 18])
+ linear_pattern(proj, 0, direction=[0, 0, 1], length=48, occurrences=3)
+ additive_cone(proj, 0, radius1=3, radius2=0.6, height=10, position=[0, 0, 70])
+
+ macro = generate_macro(proj, str(tmp_path / "tower.step"))
+ ast.parse(macro)
+
+ assert "PartDesign::AdditiveBox" in macro
+ assert "PartDesign::PolarPattern" in macro
+ assert "PartDesign::LinearPattern" in macro
+ assert "Placement = FreeCAD.Placement" in macro
+ assert "_body_origin_ref" in macro
+
+ def test_macro_generation_mirror_part_rendering(self, tmp_path):
+ """Generate a macro that reconstructs mirrored primitive parts for preview/export."""
+ proj = create_document(name="MirrorPreview")
+ add_part(
+ proj,
+ "cylinder",
+ name="LeftWheel",
+ params={"radius": 12, "height": 6},
+ position=[24, -20, 12],
+ rotation=[90, 0, 0],
+ )
+ mirror_part(proj, 0, plane="XZ", name="RightWheel")
+
+ macro = generate_macro(proj, str(tmp_path / "mirror.step"))
+ ast.parse(macro)
+
+ assert "obj_RightWheel = doc.addObject('Part::Cylinder', 'RightWheel')" in macro
+ assert "Unknown part type 'mirror'" not in macro
+ assert "obj_RightWheel.Placement = FreeCAD.Placement(FreeCAD.Vector(24.0, 20.0, 12.0)" in macro
+
def test_save_load_roundtrip(self, tmp_path):
"""Save a project, reload it, verify contents are identical."""
proj = create_document(name="RoundTrip", units="in", profile="imperial")
@@ -510,6 +633,80 @@ class TestFreeCADBackend:
print(f"\n FCStd: {output} ({size:,} bytes)")
+ @pytest.mark.skipif(not _has_freecad_preview(), reason="GUI-capable FreeCAD not installed")
+ def test_preview_capture_bundle(self, tmp_path):
+ proj = create_document(name="PreviewPart")
+ add_part(proj, "box", name="MainBlock", params={"length": 30, "width": 20, "height": 12})
+ add_part(
+ proj,
+ "cylinder",
+ name="SideBoss",
+ params={"radius": 4, "height": 14},
+ position=[18, 0, 0],
+ )
+
+ project_path = str(tmp_path / "preview.json")
+ save_document(proj, project_path)
+
+ sess = Session()
+ sess.set_project(proj, path=project_path)
+
+ manifest = preview_mod.capture(sess, root_dir=str(tmp_path), force=True)
+ assert manifest["software"] == "freecad"
+ assert manifest["bundle_kind"] == "capture"
+ assert manifest["status"] in ("ok", "partial")
+
+ hero_path = _artifact_path(manifest, "hero")
+ front_path = _artifact_path(manifest, "front")
+ top_path = _artifact_path(manifest, "top")
+ right_path = _artifact_path(manifest, "right")
+ _assert_png(hero_path)
+ _assert_png(front_path)
+ _assert_png(top_path)
+ _assert_png(right_path)
+
+ latest = preview_mod.latest(project_path=project_path, recipe="quick", root_dir=str(tmp_path))
+ assert latest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n FreeCAD preview bundle: {manifest['_bundle_dir']}")
+ print(f" FreeCAD preview hero: {hero_path}")
+ print(f" FreeCAD preview front: {front_path}")
+ print(f" FreeCAD preview top: {top_path}")
+ print(f" FreeCAD preview right: {right_path}")
+
+ @pytest.mark.skipif(not _has_freecad_preview(), reason="GUI-capable FreeCAD not installed")
+ def test_preview_capture_bundle_body_patterns(self, tmp_path):
+ proj = create_document(name="PreviewBodyTower")
+ create_body(proj, name="TowerBody")
+ additive_box(proj, 0, length=34, width=34, height=18, position=[0, 0, 0])
+ additive_box(proj, 0, length=8, width=6, height=4, position=[21, 0, 7])
+ polar_pattern(proj, 0, axis="Z", angle=360, occurrences=4)
+ additive_box(proj, 0, length=30, width=30, height=16, position=[0, 0, 18])
+ additive_box(proj, 0, length=7, width=5, height=3, position=[18.5, 0, 24])
+ polar_pattern(proj, 0, axis="Z", angle=360, occurrences=4)
+ additive_cylinder(proj, 0, radius=2.2, height=18, position=[0, 0, 34])
+ additive_cone(proj, 0, radius1=2.5, radius2=0.4, height=10, position=[0, 0, 52])
+
+ project_path = str(tmp_path / "preview_body.json")
+ save_document(proj, project_path)
+
+ sess = Session()
+ sess.set_project(proj, path=project_path)
+
+ manifest = preview_mod.capture(sess, root_dir=str(tmp_path), force=True)
+ assert manifest["software"] == "freecad"
+ assert manifest["bundle_kind"] == "capture"
+ assert manifest["status"] in ("ok", "partial")
+
+ hero_path = _artifact_path(manifest, "hero")
+ front_path = _artifact_path(manifest, "front")
+ _assert_png_not_blank(hero_path)
+ _assert_png_not_blank(front_path)
+
+ print(f"\n FreeCAD body preview bundle: {manifest['_bundle_dir']}")
+ print(f" FreeCAD body preview hero: {hero_path}")
+ print(f" FreeCAD body preview front: {front_path}")
+
# =========================================================================
# 3. CLI subprocess tests
@@ -523,14 +720,14 @@ class TestCLISubprocess:
"""Resolve the CLI command once for all tests."""
self.cli = _resolve_cli("cli-anything-freecad")
- def _run(self, *args: str, **kwargs) -> subprocess.CompletedProcess:
+ def _run(self, *args: str, timeout: int = 30, **kwargs) -> subprocess.CompletedProcess:
"""Run a CLI command and return the result."""
cmd = self.cli + list(args)
return subprocess.run(
cmd,
capture_output=True,
text=True,
- timeout=30,
+ timeout=timeout,
**kwargs,
)
@@ -609,6 +806,79 @@ class TestCLISubprocess:
print(f"\n part list: {len(parts)} parts ({names})")
+ def test_part_align_and_bounds_json(self, tmp_path):
+ """Create parts, align one to another, and verify bbox output."""
+ proj_file = str(tmp_path / "part_align.json")
+
+ self._run("--json", "document", "new", "--name", "AlignTest", "-o", proj_file)
+ self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "part",
+ "add",
+ "box",
+ "--name",
+ "Base",
+ "-P",
+ "length=20",
+ "-P",
+ "width=10",
+ "-P",
+ "height=6",
+ )
+ self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "part",
+ "add",
+ "box",
+ "--name",
+ "Cap",
+ "-P",
+ "length=8",
+ "-P",
+ "width=6",
+ "-P",
+ "height=4",
+ "-pos",
+ "100,50,20",
+ )
+
+ aligned = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "part",
+ "align",
+ "1",
+ "0",
+ "--x",
+ "min",
+ "--to-x",
+ "max",
+ "--y",
+ "center",
+ "--to-y",
+ "center",
+ "--z",
+ "min",
+ "--to-z",
+ "max",
+ )
+ assert aligned.returncode == 0, aligned.stderr
+ align_payload = json.loads(aligned.stdout)
+ assert align_payload["placement"]["position"] == [20.0, 2.0, 6.0]
+
+ bounds = self._run("--json", "-p", proj_file, "part", "bounds", "1")
+ assert bounds.returncode == 0, bounds.stderr
+ bounds_payload = json.loads(bounds.stdout)
+ world = bounds_payload["world_bounding_box"]
+ assert world["min"]["x"] == pytest.approx(20.0)
+ assert world["center"]["y"] == pytest.approx(5.0)
+ assert world["min"]["z"] == pytest.approx(6.0)
+
def test_full_workflow_subprocess(self, tmp_path):
"""Full subprocess workflow: create -> box -> cylinder -> boolean cut -> list."""
proj_file = str(tmp_path / "workflow.json")
@@ -657,3 +927,304 @@ class TestCLISubprocess:
print(f"\n Workflow complete: {len(parts)} parts")
for p in parts:
print(f" {p['name']}: type={p['type']}, visible={p.get('visible', '?')}")
+
+ @pytest.mark.skipif(not _has_freecad_preview(), reason="GUI-capable FreeCAD not installed")
+ def test_preview_capture_subprocess(self, tmp_path):
+ proj_file = str(tmp_path / "preview_cli.json")
+
+ proj = create_document(name="PreviewCLI")
+ add_part(proj, "box", name="Body", params={"length": 24, "width": 18, "height": 10})
+ save_document(proj, proj_file)
+
+ result = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "preview",
+ "capture",
+ "--root-dir",
+ str(tmp_path),
+ timeout=240,
+ )
+ assert result.returncode == 0, result.stderr
+
+ manifest = json.loads(result.stdout)
+ assert manifest["software"] == "freecad"
+ hero_path = _artifact_path(manifest, "hero")
+ _assert_png(hero_path)
+
+ latest = self._run(
+ "--json",
+ "preview",
+ "latest",
+ "--recipe",
+ "quick",
+ "--root-dir",
+ str(tmp_path),
+ timeout=60,
+ )
+ assert latest.returncode == 0, latest.stderr
+ latest_manifest = json.loads(latest.stdout)
+ assert latest_manifest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n FreeCAD preview bundle: {manifest['_bundle_dir']}")
+ print(f" FreeCAD preview hero: {hero_path}")
+
+ @pytest.mark.skipif(not _has_freecad_preview(), reason="GUI-capable FreeCAD not installed")
+ def test_motion_render_frames_subprocess(self, tmp_path):
+ proj_file = str(tmp_path / "motion_frames.json")
+ frames_dir = str(tmp_path / "motion-frames")
+
+ created = self._run(
+ "--json",
+ "document",
+ "new",
+ "--name",
+ "MotionFrames",
+ "-o",
+ proj_file,
+ )
+ assert created.returncode == 0, created.stderr
+
+ added = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "part",
+ "add",
+ "box",
+ "--name",
+ "Mover",
+ "-P",
+ "length=20",
+ "-P",
+ "width=12",
+ "-P",
+ "height=8",
+ )
+ assert added.returncode == 0, added.stderr
+
+ motion_new = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "motion",
+ "new",
+ "--name",
+ "Drive",
+ "--duration",
+ "1.0",
+ "--fps",
+ "4",
+ "--camera",
+ "hero",
+ "--width",
+ "640",
+ "--height",
+ "480",
+ )
+ assert motion_new.returncode == 0, motion_new.stderr
+
+ k0 = self._run("--json", "-p", proj_file, "motion", "keyframe", "0", "part", "0", "0.0")
+ assert k0.returncode == 0, k0.stderr
+
+ k1 = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "motion",
+ "keyframe",
+ "0",
+ "part",
+ "0",
+ "1.0",
+ "--position",
+ "35,0,0",
+ "--rotation",
+ "0,0,45",
+ )
+ assert k1.returncode == 0, k1.stderr
+
+ rendered = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "motion",
+ "render-frames",
+ "0",
+ frames_dir,
+ "--overwrite",
+ timeout=240,
+ )
+ assert rendered.returncode == 0, rendered.stderr
+ payload = json.loads(rendered.stdout)
+ assert payload["frame_count"] == 5
+ assert payload["method"] == "freecad-gui-sequence"
+
+ sequence_path = payload["sequence_path"]
+ assert os.path.isfile(sequence_path)
+ with open(sequence_path, "r", encoding="utf-8") as fh:
+ sequence = json.load(fh)
+ assert sequence["frame_count"] == 5
+
+ first_frame = os.path.join(payload["output_dir"], sequence["frames"][0]["path"])
+ last_frame = os.path.join(payload["output_dir"], sequence["frames"][-1]["path"])
+ _assert_png_not_blank(first_frame)
+ _assert_png_not_blank(last_frame)
+ _assert_images_differ(first_frame, last_frame)
+
+ @pytest.mark.skipif(not (_has_freecad_preview() and _has_ffmpeg()), reason="GUI-capable FreeCAD and ffmpeg required")
+ def test_motion_render_video_subprocess(self, tmp_path):
+ proj_file = str(tmp_path / "motion_video.json")
+ frames_dir = str(tmp_path / "motion-video-frames")
+ video_path = str(tmp_path / "motion.mp4")
+
+ proj = create_document(name="MotionVideo")
+ add_part(proj, "box", name="Mover", params={"length": 20, "width": 12, "height": 8})
+ save_document(proj, proj_file)
+
+ assert self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "motion",
+ "new",
+ "--name",
+ "Drive",
+ "--duration",
+ "1.0",
+ "--fps",
+ "4",
+ "--camera",
+ "hero",
+ "--width",
+ "640",
+ "--height",
+ "480",
+ ).returncode == 0
+
+ assert self._run(
+ "--json", "-p", proj_file, "motion", "keyframe", "0", "part", "0", "0.0"
+ ).returncode == 0
+ assert self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "motion",
+ "keyframe",
+ "0",
+ "part",
+ "0",
+ "1.0",
+ "--position",
+ "35,0,0",
+ "--rotation",
+ "0,0,90",
+ ).returncode == 0
+
+ rendered = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "motion",
+ "render-video",
+ "0",
+ video_path,
+ "--overwrite",
+ "--frames-dir",
+ frames_dir,
+ timeout=300,
+ )
+ assert rendered.returncode == 0, rendered.stderr
+ payload = json.loads(rendered.stdout)
+ assert payload["format"] == "mp4"
+ assert os.path.isfile(video_path)
+ assert os.path.getsize(video_path) > 0
+ assert payload["frame_count"] == 5
+ assert payload["frames_dir"] == os.path.abspath(frames_dir)
+ assert os.path.isfile(payload["sequence_path"])
+
+ @pytest.mark.skipif(not _has_freecad_preview(), reason="GUI-capable FreeCAD not installed")
+ def test_preview_live_poll_auto_refresh(self, tmp_path):
+ proj_file = str(tmp_path / "preview_live_poll.json")
+ live_root = str(tmp_path / "live-root")
+
+ proj = create_document(name="PreviewLiveCLI")
+ add_part(proj, "box", name="BaseBody", params={"length": 24, "width": 18, "height": 10})
+ save_document(proj, proj_file)
+
+ started = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "preview",
+ "live",
+ "start",
+ "--recipe",
+ "quick",
+ "--mode",
+ "poll",
+ "--source-poll-ms",
+ "500",
+ "--poll-ms",
+ "700",
+ "--root-dir",
+ live_root,
+ timeout=240,
+ )
+ assert started.returncode == 0, started.stderr
+ started_payload = json.loads(started.stdout)
+ session_path = started_payload["_session_path"]
+ assert started_payload["bundle_count"] == 1
+ assert started_payload["live_mode"] == "poll"
+
+ try:
+ changed = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "part",
+ "add",
+ "cylinder",
+ "--name",
+ "SideBoss",
+ "-P",
+ "radius=4",
+ "-P",
+ "height=14",
+ "-pos",
+ "18,0,0",
+ timeout=60,
+ )
+ assert changed.returncode == 0, changed.stderr
+
+ session_payload = _wait_for_live_bundle_count(session_path, 2, timeout_s=30.0)
+ assert session_payload["bundle_count"] >= 2
+ assert session_payload["source_state"]["last_publish_reason"] == "auto-poll"
+ assert session_payload["poller"]["running"] is True
+
+ current_manifest_path = session_payload["current_manifest_path"]
+ assert os.path.isfile(current_manifest_path)
+ with open(current_manifest_path, "r", encoding="utf-8") as fh:
+ current_manifest = json.load(fh)
+ current_manifest["_bundle_dir"] = os.path.dirname(current_manifest_path)
+ hero_path = _artifact_path(current_manifest, "hero")
+ _assert_png(hero_path)
+
+ print(f"\n FreeCAD poll session: {os.path.dirname(session_path)}")
+ print(f" FreeCAD live hero: {hero_path}")
+ finally:
+ stopped = self._run(
+ "--json",
+ "-p",
+ proj_file,
+ "preview",
+ "live",
+ "stop",
+ "--recipe",
+ "quick",
+ "--root-dir",
+ live_root,
+ timeout=60,
+ )
+ assert stopped.returncode == 0, stopped.stderr
diff --git a/freecad/agent-harness/cli_anything/freecad/utils/freecad_backend.py b/freecad/agent-harness/cli_anything/freecad/utils/freecad_backend.py
index e3c1deab7..6b07cb91a 100644
--- a/freecad/agent-harness/cli_anything/freecad/utils/freecad_backend.py
+++ b/freecad/agent-harness/cli_anything/freecad/utils/freecad_backend.py
@@ -47,10 +47,11 @@ _INSTALL_INSTRUCTIONS = textwrap.dedent("""\
""")
# Executable names to search for, in priority order
-_FREECAD_NAMES = ["freecadcmd", "FreeCADCmd", "freecad", "FreeCAD"]
+_FREECAD_CMD_NAMES = ["freecadcmd", "FreeCADCmd", "freecad", "FreeCAD"]
+_FREECAD_GUI_NAMES = ["freecad", "FreeCAD", "freecadcmd", "FreeCADCmd"]
-def find_freecad() -> str:
+def find_freecad(gui_required: bool = False) -> str:
"""Locate the FreeCAD console executable on the system.
Search order:
@@ -76,8 +77,10 @@ def find_freecad() -> str:
if env_path and os.path.isfile(env_path):
return os.path.abspath(env_path)
+ names = _FREECAD_GUI_NAMES if gui_required else _FREECAD_CMD_NAMES
+
# 2. On PATH
- for name in _FREECAD_NAMES:
+ for name in names:
which = shutil.which(name)
if which:
return os.path.abspath(which)
@@ -131,14 +134,19 @@ def _run(
*,
timeout: int = 120,
check: bool = False,
+ env: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""Run a subprocess and return a normalised result dict."""
try:
+ proc_env = os.environ.copy()
+ if env:
+ proc_env.update(env)
proc = subprocess.run(
args,
capture_output=True,
text=True,
timeout=timeout,
+ env=proc_env,
)
result: Dict[str, Any] = {
"ok": proc.returncode == 0,
@@ -180,6 +188,31 @@ def _write_temp_script(content: str) -> str:
return path
+def _is_gui_wrapper_script(path: str) -> bool:
+ """Return True when *path* looks like the local GUI-launch wrapper.
+
+ On this machine the `freecad` command is a shell wrapper that dispatches to
+ either the GUI binary or `freecadcmd`. When a Python script path is passed,
+ the wrapper defaults to console mode unless we explicitly ask for the GUI
+ binary.
+ """
+ try:
+ resolved = Path(path).resolve()
+ if not resolved.is_file():
+ return False
+ head = resolved.read_bytes()[:4096]
+ except OSError:
+ return False
+ return b"SCRIPT_MODE" in head and b"xvfb-run" in head and b"freecadcmd" in head
+
+
+def _macro_command(freecad: str, script_path: str, *, gui_required: bool) -> list[str]:
+ """Build the argv used to execute a FreeCAD macro script."""
+ if gui_required and _is_gui_wrapper_script(freecad):
+ return [freecad, "freecad", script_path]
+ return [freecad, script_path]
+
+
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
@@ -224,6 +257,8 @@ def get_version() -> str:
def run_macro(
script_path: str,
timeout: int = 120,
+ gui_required: bool = False,
+ env: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""Execute a FreeCAD Python macro script headlessly.
@@ -239,10 +274,10 @@ def run_macro(
dict
``{"command": str, "returncode": int, "stdout": str, "stderr": str}``
"""
- freecad = find_freecad()
+ freecad = find_freecad(gui_required=gui_required)
script_path = str(Path(script_path).resolve())
- result = _run([freecad, script_path], timeout=timeout)
+ result = _run(_macro_command(freecad, script_path, gui_required=gui_required), timeout=timeout, env=env)
return {
"command": result["command"],
@@ -252,6 +287,28 @@ def run_macro(
}
+def run_macro_content(
+ script_content: str,
+ timeout: int = 120,
+ gui_required: bool = False,
+ env: Optional[Dict[str, str]] = None,
+) -> Dict[str, Any]:
+ """Execute macro content by writing it to a temp file first."""
+ script_path = _write_temp_script(script_content)
+ try:
+ return run_macro(
+ script_path,
+ timeout=timeout,
+ gui_required=gui_required,
+ env=env,
+ )
+ finally:
+ try:
+ os.unlink(script_path)
+ except OSError:
+ pass
+
+
def export_headless(
macro_content: str,
output_path: str,
@@ -287,15 +344,7 @@ def export_headless(
output_path = os.path.abspath(output_path)
os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
- script_path = _write_temp_script(macro_content)
- try:
- result = run_macro(script_path, timeout=timeout)
- finally:
- # Best-effort cleanup of the temp script
- try:
- os.unlink(script_path)
- except OSError:
- pass
+ result = run_macro_content(macro_content, timeout=timeout)
if result["returncode"] != 0:
raise RuntimeError(
diff --git a/freecad/agent-harness/cli_anything/freecad/utils/freecad_macro_gen.py b/freecad/agent-harness/cli_anything/freecad/utils/freecad_macro_gen.py
index a606d6a68..55bfdb542 100644
--- a/freecad/agent-harness/cli_anything/freecad/utils/freecad_macro_gen.py
+++ b/freecad/agent-harness/cli_anything/freecad/utils/freecad_macro_gen.py
@@ -48,53 +48,129 @@ def _gen_header() -> List[str]:
]
+_RENDERABLE_PRIMITIVES = {"box", "cylinder", "sphere", "cone", "torus"}
+
+
+def _emit_primitive(lines: List[str], part_type: str, name: str, props: Dict[str, Any]) -> bool:
+ """Append FreeCAD object creation lines for a supported primitive."""
+ if part_type == "box":
+ length = props.get("length", props.get("Length", 10.0))
+ width = props.get("width", props.get("Width", 10.0))
+ height = props.get("height", props.get("Height", 10.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Box', '{name}')")
+ lines.append(f"obj_{name}.Length = {length}")
+ lines.append(f"obj_{name}.Width = {width}")
+ lines.append(f"obj_{name}.Height = {height}")
+ return True
+
+ if part_type == "cylinder":
+ radius = props.get("radius", props.get("Radius", 5.0))
+ height = props.get("height", props.get("Height", 10.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Cylinder', '{name}')")
+ lines.append(f"obj_{name}.Radius = {radius}")
+ lines.append(f"obj_{name}.Height = {height}")
+ return True
+
+ if part_type == "sphere":
+ radius = props.get("radius", props.get("Radius", 5.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Sphere', '{name}')")
+ lines.append(f"obj_{name}.Radius = {radius}")
+ return True
+
+ if part_type == "cone":
+ radius1 = props.get("radius1", props.get("Radius1", 5.0))
+ radius2 = props.get("radius2", props.get("Radius2", 0.0))
+ height = props.get("height", props.get("Height", 10.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Cone', '{name}')")
+ lines.append(f"obj_{name}.Radius1 = {radius1}")
+ lines.append(f"obj_{name}.Radius2 = {radius2}")
+ lines.append(f"obj_{name}.Height = {height}")
+ return True
+
+ if part_type == "torus":
+ radius1 = props.get("radius1", props.get("Radius1", 10.0))
+ radius2 = props.get("radius2", props.get("Radius2", 2.0))
+ lines.append(f"obj_{name} = doc.addObject('Part::Torus', '{name}')")
+ lines.append(f"obj_{name}.Radius1 = {radius1}")
+ lines.append(f"obj_{name}.Radius2 = {radius2}")
+ return True
+
+ return False
+
+
+def _part_by_id(project: dict, part_id: Any) -> Optional[Dict[str, Any]]:
+ """Return the part payload matching *part_id*, if present."""
+ for part in project.get("parts", []):
+ if part.get("id") == part_id:
+ return part
+ return None
+
+
+def _mirrored_position(position: Any, plane: str) -> List[float]:
+ """Return a mirrored position vector for a simple plane reflection."""
+ if isinstance(position, (list, tuple)):
+ coords = [float(position[idx]) if len(position) > idx else 0.0 for idx in range(3)]
+ else:
+ coords = [
+ float(position.get("x", 0.0)),
+ float(position.get("y", 0.0)),
+ float(position.get("z", 0.0)),
+ ]
+ axis_index = {"YZ": 0, "XZ": 1, "XY": 2}.get(plane.upper())
+ if axis_index is not None:
+ coords[axis_index] *= -1.0
+ return coords
+
+
+def _mirror_render_spec(project: dict, part: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """Resolve a mirrored part into a renderable primitive approximation."""
+ params = part.get("params", {})
+ original = _part_by_id(project, params.get("original_id"))
+ if not original:
+ return None
+ original_type = str(original.get("type", "")).lower()
+ if original_type not in _RENDERABLE_PRIMITIVES:
+ return None
+
+ placement = dict(original.get("placement") or {})
+ placement["position"] = _mirrored_position(
+ placement.get("position") or [0.0, 0.0, 0.0],
+ str(params.get("mirror_plane", "XZ")),
+ )
+ return {
+ "type": original_type,
+ "params": dict(original.get("params") or {}),
+ "placement": placement,
+ }
+
+
+def _render_spec_for_part(project: dict, part: Dict[str, Any]) -> Optional[Dict[str, Any]]:
+ """Return the renderable primitive spec for *part*, if supported."""
+ part_type = str(part.get("type", "")).lower()
+ if part_type in _RENDERABLE_PRIMITIVES:
+ return {
+ "type": part_type,
+ "params": dict(part.get("params") or {}),
+ "placement": dict(part.get("placement") or {}),
+ }
+ if part_type == "mirror":
+ return _mirror_render_spec(project, part)
+ return None
+
+
def _gen_parts(project: dict) -> List[str]:
"""Generate Part primitives (Box, Cylinder, Sphere, Cone, Torus)."""
lines: List[str] = []
parts = project.get("parts", [])
for part in parts:
- part_type = part.get("type", "box").lower()
+ part_type = str(part.get("type", "box")).lower()
name = _safe_name(part.get("name", f"Part_{part_type}"))
- props = part.get("params", part.get("properties", {}))
-
- if part_type == "box":
- length = props.get("length", props.get("Length", 10.0))
- width = props.get("width", props.get("Width", 10.0))
- height = props.get("height", props.get("Height", 10.0))
- lines.append(f"obj_{name} = doc.addObject('Part::Box', '{name}')")
- lines.append(f"obj_{name}.Length = {length}")
- lines.append(f"obj_{name}.Width = {width}")
- lines.append(f"obj_{name}.Height = {height}")
-
- elif part_type == "cylinder":
- radius = props.get("radius", props.get("Radius", 5.0))
- height = props.get("height", props.get("Height", 10.0))
- lines.append(f"obj_{name} = doc.addObject('Part::Cylinder', '{name}')")
- lines.append(f"obj_{name}.Radius = {radius}")
- lines.append(f"obj_{name}.Height = {height}")
-
- elif part_type == "sphere":
- radius = props.get("radius", props.get("Radius", 5.0))
- lines.append(f"obj_{name} = doc.addObject('Part::Sphere', '{name}')")
- lines.append(f"obj_{name}.Radius = {radius}")
-
- elif part_type == "cone":
- radius1 = props.get("radius1", props.get("Radius1", 5.0))
- radius2 = props.get("radius2", props.get("Radius2", 0.0))
- height = props.get("height", props.get("Height", 10.0))
- lines.append(f"obj_{name} = doc.addObject('Part::Cone', '{name}')")
- lines.append(f"obj_{name}.Radius1 = {radius1}")
- lines.append(f"obj_{name}.Radius2 = {radius2}")
- lines.append(f"obj_{name}.Height = {height}")
-
- elif part_type == "torus":
- radius1 = props.get("radius1", props.get("Radius1", 10.0))
- radius2 = props.get("radius2", props.get("Radius2", 2.0))
- lines.append(f"obj_{name} = doc.addObject('Part::Torus', '{name}')")
- lines.append(f"obj_{name}.Radius1 = {radius1}")
- lines.append(f"obj_{name}.Radius2 = {radius2}")
+ render_spec = _render_spec_for_part(project, part)
+ props = render_spec["params"] if render_spec else part.get("params", part.get("properties", {}))
+ if render_spec and _emit_primitive(lines, render_spec["type"], name, props):
+ pass
else:
lines.append(f"# WARNING: Unknown part type '{part_type}' for '{name}'")
@@ -134,8 +210,39 @@ def _gen_boolean_ops(project: dict) -> List[str]:
return lines
+def _placement_expr(placement: Optional[Dict[str, Any]]) -> Optional[str]:
+ """Return a FreeCAD placement expression for a stored placement payload."""
+ if not placement:
+ return None
+ position = placement.get("position") or [0.0, 0.0, 0.0]
+ rotation = placement.get("rotation") or [0.0, 0.0, 0.0]
+ x = float(position[0] if len(position) > 0 else 0.0)
+ y = float(position[1] if len(position) > 1 else 0.0)
+ z = float(position[2] if len(position) > 2 else 0.0)
+ rx = float(rotation[0] if len(rotation) > 0 else 0.0)
+ ry = float(rotation[1] if len(rotation) > 1 else 0.0)
+ rz = float(rotation[2] if len(rotation) > 2 else 0.0)
+ return (
+ "FreeCAD.Placement("
+ f"FreeCAD.Vector({x}, {y}, {z}), "
+ f"FreeCAD.Rotation({rz}, {ry}, {rx}))"
+ )
+
+
+def _dominant_axis(direction: Any) -> tuple[str, bool, bool]:
+ """Resolve a direction vector to the closest body-origin axis."""
+ if not isinstance(direction, (list, tuple)) or len(direction) != 3:
+ return ("X", False, False)
+ values = [float(component) for component in direction]
+ axis_index = max(range(3), key=lambda idx: abs(values[idx]))
+ axis_name = "XYZ"[axis_index]
+ reversed_axis = values[axis_index] < 0
+ off_axis = any(abs(value) > 1e-9 for idx, value in enumerate(values) if idx != axis_index)
+ return (axis_name, reversed_axis, off_axis)
+
+
def _gen_bodies(project: dict) -> List[str]:
- """Generate PartDesign bodies with features (Pad, Pocket, etc.)."""
+ """Generate PartDesign bodies with primitive and pattern features."""
lines: List[str] = []
bodies = project.get("bodies", [])
@@ -144,58 +251,181 @@ def _gen_bodies(project: dict) -> List[str]:
lines.append("import PartDesign")
lines.append("")
+ lines.extend(
+ [
+ "def _body_origin_ref(body_obj, role):",
+ " for origin_obj in body_obj.Origin.OriginFeatures:",
+ " if getattr(origin_obj, 'Role', None) == role:",
+ " return origin_obj",
+ " raise RuntimeError(f'Could not resolve body origin role: {role}')",
+ "",
+ ]
+ )
for body in bodies:
body_name = _safe_name(body.get("name", "Body"))
- lines.append(
- f"body_{body_name} = doc.addObject('PartDesign::Body', '{body_name}')"
- )
+ body_var = f"body_{body_name}"
+ lines.append(f"{body_var} = doc.addObject('PartDesign::Body', '{body_name}')")
features = body.get("features", [])
+ previous_var: Optional[str] = None
+ feature_counter = 0
+
+ def emit_pattern(
+ pattern_type: str,
+ pattern_payload: Dict[str, Any],
+ source_var: Optional[str],
+ suffix: Optional[str] = None,
+ ) -> Optional[str]:
+ nonlocal feature_counter
+ if source_var is None:
+ lines.append(f"# WARNING: Cannot add {pattern_type} without a previous body feature")
+ return None
+ feature_counter += 1
+ pattern_var = f"feat_{body_name}_{feature_counter}_{pattern_type}"
+ label = _safe_name(f"{pattern_type}_{feature_counter}")
+ if pattern_type == "linear_pattern":
+ axis, reversed_axis, off_axis = _dominant_axis(pattern_payload.get("direction"))
+ lines.append(
+ f"{pattern_var} = {body_var}.newObject('PartDesign::LinearPattern', '{label}')"
+ )
+ lines.append(f"{pattern_var}.Originals = [{source_var}]")
+ lines.append(
+ f"{pattern_var}.Direction = (_body_origin_ref({body_var}, '{axis}_Axis'), [''])"
+ )
+ lines.append(f"{pattern_var}.Length = {float(pattern_payload.get('length', 50.0))}")
+ lines.append(
+ f"{pattern_var}.Occurrences = {int(pattern_payload.get('occurrences', 3))}"
+ )
+ if reversed_axis:
+ lines.append(f"{pattern_var}.Reversed = True")
+ if off_axis:
+ lines.append(
+ f"# WARNING: Non-axis-aligned direction {pattern_payload.get('direction')} "
+ f"collapsed to dominant {axis}-axis"
+ )
+ elif pattern_type == "polar_pattern":
+ axis = str(pattern_payload.get("axis", "Z")).upper()
+ lines.append(
+ f"{pattern_var} = {body_var}.newObject('PartDesign::PolarPattern', '{label}')"
+ )
+ lines.append(f"{pattern_var}.Originals = [{source_var}]")
+ lines.append(
+ f"{pattern_var}.Axis = (_body_origin_ref({body_var}, '{axis}_Axis'), [''])"
+ )
+ lines.append(f"{pattern_var}.Angle = {float(pattern_payload.get('angle', 360.0))}")
+ lines.append(
+ f"{pattern_var}.Occurrences = {int(pattern_payload.get('occurrences', 4))}"
+ )
+ elif pattern_type == "mirrored":
+ plane = str(pattern_payload.get("plane", "XY")).upper()
+ lines.append(
+ f"{pattern_var} = {body_var}.newObject('PartDesign::Mirrored', '{label}')"
+ )
+ lines.append(f"{pattern_var}.Originals = [{source_var}]")
+ lines.append(
+ f"{pattern_var}.MirrorPlane = (_body_origin_ref({body_var}, '{plane}_Plane'), [''])"
+ )
+ else:
+ lines.append(f"# WARNING: Unknown pattern type '{pattern_type}' in {suffix or 'feature'}")
+ return source_var
+ lines.append("")
+ return pattern_var
+
+ primitive_map = {
+ "additive_box": ("PartDesign::AdditiveBox", ("Length", "length"), ("Width", "width"), ("Height", "height")),
+ "additive_cylinder": ("PartDesign::AdditiveCylinder", ("Radius", "radius"), ("Height", "height")),
+ "additive_sphere": ("PartDesign::AdditiveSphere", ("Radius", "radius")),
+ "additive_cone": ("PartDesign::AdditiveCone", ("Radius1", "radius1"), ("Radius2", "radius2"), ("Height", "height")),
+ "additive_torus": ("PartDesign::AdditiveTorus", ("Radius1", "radius1"), ("Radius2", "radius2")),
+ "additive_wedge": ("PartDesign::AdditiveWedge", ("Xmin", "xmin"), ("Xmax", "xmax"), ("Ymin", "ymin"), ("Ymax", "ymax"), ("Zmin", "zmin"), ("Zmax", "zmax"), ("X2min", "x2min"), ("X2max", "x2max"), ("Z2min", "z2min"), ("Z2max", "z2max")),
+ "subtractive_box": ("PartDesign::SubtractiveBox", ("Length", "length"), ("Width", "width"), ("Height", "height")),
+ "subtractive_cylinder": ("PartDesign::SubtractiveCylinder", ("Radius", "radius"), ("Height", "height")),
+ "subtractive_sphere": ("PartDesign::SubtractiveSphere", ("Radius", "radius")),
+ "subtractive_cone": ("PartDesign::SubtractiveCone", ("Radius1", "radius1"), ("Radius2", "radius2"), ("Height", "height")),
+ "subtractive_torus": ("PartDesign::SubtractiveTorus", ("Radius1", "radius1"), ("Radius2", "radius2")),
+ "subtractive_wedge": ("PartDesign::SubtractiveWedge", ("Xmin", "xmin"), ("Xmax", "xmax"), ("Ymin", "ymin"), ("Ymax", "ymax"), ("Zmin", "zmin"), ("Zmax", "zmax"), ("X2min", "x2min"), ("X2max", "x2max"), ("Z2min", "z2min"), ("Z2max", "z2max")),
+ }
+
for feat in features:
feat_type = feat.get("type", "pad").lower()
feat_name = _safe_name(feat.get("name", f"Feature_{feat_type}"))
feat_props = feat.get("properties", {})
-
- if feat_type == "pad":
+ feature_counter += 1
+ feat_var = f"feat_{body_name}_{feature_counter}_{_safe_name(feat_type)}"
+
+ if feat_type in primitive_map:
+ class_name, *prop_pairs = primitive_map[feat_type]
+ lines.append(f"{feat_var} = {body_var}.newObject('{class_name}', '{feat_name}')")
+ for prop_name, key in prop_pairs:
+ value = feat.get(key, feat_props.get(key))
+ if value is not None:
+ lines.append(f"{feat_var}.{prop_name} = {float(value)}")
+ placement_expr = _placement_expr(feat.get("placement") or feat_props.get("placement"))
+ if placement_expr:
+ lines.append(f"{feat_var}.Placement = {placement_expr}")
+ previous_var = feat_var
+
+ elif feat_type == "linear_pattern":
+ previous_var = emit_pattern("linear_pattern", feat, previous_var)
+
+ elif feat_type == "polar_pattern":
+ previous_var = emit_pattern("polar_pattern", feat, previous_var)
+
+ elif feat_type == "mirrored":
+ previous_var = emit_pattern("mirrored", feat, previous_var)
+
+ elif feat_type == "multi_transform":
+ transforms = feat.get("transformations", [])
+ if not transforms:
+ lines.append(f"# WARNING: multi_transform '{feat_name}' has no transformations")
+ for transform_index, transform in enumerate(transforms):
+ previous_var = emit_pattern(
+ str(transform.get("type", "")).lower(),
+ transform,
+ previous_var,
+ suffix=f"multi_transform[{transform_index}]",
+ )
+
+ elif feat_type == "pad":
length = feat_props.get("length", feat_props.get("Length", 10.0))
lines.append(
- f"feat_{feat_name} = body_{body_name}.newObject("
- f"'PartDesign::Pad', '{feat_name}')"
+ f"{feat_var} = {body_var}.newObject('PartDesign::Pad', '{feat_name}')"
)
- lines.append(f"feat_{feat_name}.Length = {length}")
+ lines.append(f"{feat_var}.Length = {length}")
+ previous_var = feat_var
elif feat_type == "pocket":
length = feat_props.get("length", feat_props.get("Length", 5.0))
lines.append(
- f"feat_{feat_name} = body_{body_name}.newObject("
- f"'PartDesign::Pocket', '{feat_name}')"
+ f"{feat_var} = {body_var}.newObject('PartDesign::Pocket', '{feat_name}')"
)
- lines.append(f"feat_{feat_name}.Length = {length}")
+ lines.append(f"{feat_var}.Length = {length}")
+ previous_var = feat_var
elif feat_type == "revolution":
angle = feat_props.get("angle", feat_props.get("Angle", 360.0))
lines.append(
- f"feat_{feat_name} = body_{body_name}.newObject("
- f"'PartDesign::Revolution', '{feat_name}')"
+ f"{feat_var} = {body_var}.newObject('PartDesign::Revolution', '{feat_name}')"
)
- lines.append(f"feat_{feat_name}.Angle = {angle}")
+ lines.append(f"{feat_var}.Angle = {angle}")
+ previous_var = feat_var
elif feat_type == "chamfer":
size = feat_props.get("size", feat_props.get("Size", 1.0))
lines.append(
- f"feat_{feat_name} = body_{body_name}.newObject("
- f"'PartDesign::Chamfer', '{feat_name}')"
+ f"{feat_var} = {body_var}.newObject('PartDesign::Chamfer', '{feat_name}')"
)
- lines.append(f"feat_{feat_name}.Size = {size}")
+ lines.append(f"{feat_var}.Size = {size}")
+ previous_var = feat_var
elif feat_type == "fillet":
radius = feat_props.get("radius", feat_props.get("Radius", 1.0))
lines.append(
- f"feat_{feat_name} = body_{body_name}.newObject("
- f"'PartDesign::Fillet', '{feat_name}')"
+ f"{feat_var} = {body_var}.newObject('PartDesign::Fillet', '{feat_name}')"
)
- lines.append(f"feat_{feat_name}.Radius = {radius}")
+ lines.append(f"{feat_var}.Radius = {radius}")
+ previous_var = feat_var
else:
lines.append(
@@ -215,7 +445,12 @@ def _gen_placements(project: dict) -> List[str]:
for part in parts:
name = _safe_name(part.get("name", ""))
- placement = part.get("placement", {})
+ render_spec = _render_spec_for_part(project, part)
+ if render_spec is None:
+ lines.append(f"# WARNING: Skipping placement for unsupported part '{name}'")
+ lines.append("")
+ continue
+ placement = render_spec.get("placement", {})
if not placement:
continue
diff --git a/freecad/agent-harness/cli_anything/freecad/utils/preview_bundle.py b/freecad/agent-harness/cli_anything/freecad/utils/preview_bundle.py
new file mode 100644
index 000000000..3cba5dbf0
--- /dev/null
+++ b/freecad/agent-harness/cli_anything/freecad/utils/preview_bundle.py
@@ -0,0 +1,304 @@
+"""Shared helpers for CLI-Anything preview bundles."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import mimetypes
+import os
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, Iterable, Optional
+
+PROTOCOL_VERSION = "preview-bundle/v1"
+
+
+def _slug(value: str) -> str:
+ text = (value or "preview").strip().lower()
+ text = re.sub(r"[^a-z0-9]+", "-", text)
+ text = re.sub(r"-{2,}", "-", text).strip("-")
+ return text or "preview"
+
+
+def _json_dumps(data: Any) -> str:
+ return json.dumps(
+ data,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ )
+
+
+def hash_data(data: Any) -> str:
+ return hashlib.sha256(_json_dumps(data).encode("utf-8")).hexdigest()
+
+
+def fingerprint_data(data: Any) -> str:
+ return f"sha256:{hash_data(data)}"
+
+
+def fingerprint_file(path: str) -> str:
+ resolved = os.path.abspath(path)
+ stat = os.stat(resolved)
+ return fingerprint_data(
+ {
+ "path": resolved,
+ "size": stat.st_size,
+ "mtime_ns": stat.st_mtime_ns,
+ }
+ )
+
+
+def bundle_root(
+ software: str,
+ recipe: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Path:
+ if root_dir:
+ base = Path(root_dir).expanduser().resolve()
+ elif project_path:
+ base = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews"
+ else:
+ base = Path.home() / ".cli-anything" / "previews"
+ return base / _slug(software) / _slug(recipe)
+
+
+def build_cache_key(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ protocol_version: str = PROTOCOL_VERSION,
+) -> str:
+ return fingerprint_data(
+ {
+ "protocol_version": protocol_version,
+ "software": software,
+ "recipe": recipe,
+ "bundle_kind": bundle_kind,
+ "source_fingerprint": source_fingerprint,
+ "options": options or {},
+ "harness_version": harness_version or "",
+ }
+ )
+
+
+def _iter_manifests(search_root: Path) -> Iterable[Path]:
+ if not search_root.exists():
+ return []
+ return sorted(search_root.rglob("manifest.json"), reverse=True)
+
+
+def _load_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def find_cached_manifest(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ cache_key: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ root = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir)
+ for manifest_path in _iter_manifests(root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if (
+ manifest.get("protocol_version") == PROTOCOL_VERSION
+ and manifest.get("software") == software
+ and manifest.get("recipe") == recipe
+ and manifest.get("bundle_kind") == bundle_kind
+ and manifest.get("status") in {"ok", "partial"}
+ and manifest.get("cache_key") == cache_key
+ ):
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def find_latest_manifest(
+ software: str,
+ recipe: Optional[str] = None,
+ bundle_kind: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ if root_dir:
+ search_root = Path(root_dir).expanduser().resolve() / _slug(software)
+ elif project_path:
+ search_root = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews" / _slug(software)
+ else:
+ search_root = Path.home() / ".cli-anything" / "previews" / _slug(software)
+ if recipe:
+ search_root = search_root / _slug(recipe)
+ for manifest_path in _iter_manifests(search_root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if manifest.get("software") != software:
+ continue
+ if recipe and manifest.get("recipe") != recipe:
+ continue
+ if bundle_kind and manifest.get("bundle_kind") != bundle_kind:
+ continue
+ if manifest.get("status") not in {"ok", "partial"}:
+ continue
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def prepare_bundle(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+) -> Dict[str, Any]:
+ cache_key = build_cache_key(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ source_fingerprint=source_fingerprint,
+ options=options or {},
+ harness_version=harness_version,
+ )
+ if not force:
+ cached = find_cached_manifest(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ cache_key=cache_key,
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if cached:
+ return {
+ "cached": True,
+ "cache_key": cache_key,
+ "bundle_id": cached.get("bundle_id"),
+ "bundle_dir": cached["_bundle_dir"],
+ "manifest_path": cached["_manifest_path"],
+ "summary_path": os.path.join(cached["_bundle_dir"], cached.get("summary_path", "summary.json")),
+ "manifest": cached,
+ }
+
+ now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ bundle_id = f"{now}_{cache_key.split(':', 1)[-1][:8]}_{_slug(recipe)}"
+ out_dir = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir) / bundle_id
+ artifacts_dir = out_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=False)
+ return {
+ "cached": False,
+ "cache_key": cache_key,
+ "bundle_id": bundle_id,
+ "bundle_dir": str(out_dir.resolve()),
+ "artifacts_dir": str(artifacts_dir.resolve()),
+ "manifest_path": str((out_dir / "manifest.json").resolve()),
+ "summary_path": str((out_dir / "summary.json").resolve()),
+ }
+
+
+def artifact_record(
+ bundle_dir: str,
+ path: str,
+ artifact_id: str,
+ role: str,
+ kind: str,
+ label: str,
+ media_type: Optional[str] = None,
+ **extra: Any,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ file_path = Path(path).resolve()
+ rel_path = file_path.relative_to(bundle_path).as_posix()
+ record: Dict[str, Any] = {
+ "artifact_id": artifact_id,
+ "role": role,
+ "kind": kind,
+ "label": label,
+ "media_type": media_type or mimetypes.guess_type(str(file_path))[0] or "application/octet-stream",
+ "path": rel_path,
+ }
+ if file_path.exists():
+ record["bytes"] = file_path.stat().st_size
+ record.update({k: v for k, v in extra.items() if v is not None})
+ return record
+
+
+def write_json(path: str, data: Any) -> str:
+ output_path = Path(path).resolve()
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(output_path, "w", encoding="utf-8") as fh:
+ json.dump(data, fh, indent=2, ensure_ascii=False, default=str)
+ fh.write("\n")
+ return str(output_path)
+
+
+def finalize_bundle(
+ bundle_dir: str,
+ bundle_id: str,
+ bundle_kind: str,
+ software: str,
+ recipe: str,
+ source: Dict[str, Any],
+ artifacts: list[Dict[str, Any]],
+ summary: Dict[str, Any],
+ cache_key: str,
+ generator: Dict[str, Any],
+ status: str = "ok",
+ warnings: Optional[list[str]] = None,
+ context: Optional[Dict[str, Any]] = None,
+ metrics: Optional[Dict[str, Any]] = None,
+ labels: Optional[list[str]] = None,
+ source_bundles: Optional[list[Dict[str, Any]]] = None,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ summary_rel = "summary.json"
+ summary_path = write_json(str(bundle_path / summary_rel), summary)
+ manifest = {
+ "protocol_version": PROTOCOL_VERSION,
+ "bundle_id": bundle_id,
+ "bundle_kind": bundle_kind,
+ "software": software,
+ "recipe": recipe,
+ "status": status,
+ "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
+ "cache_key": cache_key,
+ "generator": generator,
+ "source": source,
+ "summary_path": summary_rel,
+ "artifacts": artifacts,
+ }
+ if warnings:
+ manifest["warnings"] = warnings
+ if context:
+ manifest["context"] = context
+ if metrics:
+ manifest["metrics"] = metrics
+ if labels:
+ manifest["labels"] = labels
+ if source_bundles:
+ manifest["source_bundles"] = source_bundles
+ manifest_path = write_json(str(bundle_path / "manifest.json"), manifest)
+ manifest["_manifest_path"] = manifest_path
+ manifest["_bundle_dir"] = str(bundle_path)
+ manifest["_summary_path"] = summary_path
+ return manifest
diff --git a/openscreen/agent-harness/cli_anything/openscreen/core/preview.py b/openscreen/agent-harness/cli_anything/openscreen/core/preview.py
new file mode 100644
index 000000000..eeb012651
--- /dev/null
+++ b/openscreen/agent-harness/cli_anything/openscreen/core/preview.py
@@ -0,0 +1,223 @@
+"""Preview bundle generation for the Openscreen harness."""
+
+from __future__ import annotations
+
+import os
+from typing import Any, Dict, List, Optional
+
+from ..utils.preview_bundle import (
+ artifact_record,
+ finalize_bundle,
+ find_latest_manifest,
+ fingerprint_data,
+ fingerprint_file,
+ prepare_bundle,
+)
+from . import export as export_mod
+from . import media as media_mod
+from .session import Session
+
+HARNESS_VERSION = "1.0.0"
+
+RECIPES: Dict[str, Dict[str, Any]] = {
+ "quick": {
+ "description": "Render a review clip and extract sampled frames",
+ "thumbnail_times": [0.0, 0.25, 0.5, 0.75, 0.95],
+ },
+}
+
+
+def list_recipes() -> List[Dict[str, Any]]:
+ """Return available preview recipes."""
+ return [
+ {
+ "name": name,
+ "description": config["description"],
+ "bundle_kind": "capture",
+ "artifacts": ["preview-clip", "hero", "gallery"],
+ }
+ for name, config in RECIPES.items()
+ ]
+
+
+def _project_fingerprint(session: Session) -> str:
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+ media = session.data.get("media", {})
+ source_video = media.get("screenVideoPath") or session.data.get("videoPath")
+ payload: Dict[str, Any] = {
+ "project_path": session.project_path,
+ "session_id": session.session_id,
+ "project_data": session.data,
+ }
+ if source_video and os.path.isfile(source_video):
+ payload["source_video"] = {
+ "path": os.path.abspath(source_video),
+ "fingerprint": fingerprint_file(source_video),
+ }
+ return fingerprint_data(payload)
+
+
+def _metrics(session: Session) -> Dict[str, Any]:
+ editor = session.editor
+ return {
+ "zoom_region_count": len(editor.get("zoomRegions", [])),
+ "speed_region_count": len(editor.get("speedRegions", [])),
+ "trim_region_count": len(editor.get("trimRegions", [])),
+ "annotation_count": len(editor.get("annotationRegions", [])),
+ "aspect_ratio": editor.get("aspectRatio", "16:9"),
+ "padding": editor.get("padding", 50),
+ "background": editor.get("wallpaper", "gradient_dark"),
+ }
+
+
+def capture(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ command: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Render a preview bundle for the active Openscreen project."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+ if recipe not in RECIPES:
+ raise ValueError(
+ f"Unknown preview recipe: {recipe!r}. Available: {', '.join(sorted(RECIPES))}"
+ )
+
+ config = RECIPES[recipe]
+ source_fingerprint = _project_fingerprint(session)
+ prepared = prepare_bundle(
+ software="openscreen",
+ recipe=recipe,
+ bundle_kind="capture",
+ source_fingerprint=source_fingerprint,
+ options=config,
+ harness_version=HARNESS_VERSION,
+ project_path=session.project_path,
+ root_dir=root_dir,
+ force=force,
+ )
+ if prepared["cached"]:
+ manifest = dict(prepared["manifest"])
+ manifest["cached"] = True
+ return manifest
+
+ bundle_dir = prepared["bundle_dir"]
+ artifacts_dir = prepared["artifacts_dir"]
+ preview_clip = os.path.join(artifacts_dir, "preview.mp4")
+
+ render_result = export_mod.render(session, preview_clip)
+ clip_meta = media_mod.probe(preview_clip)
+ duration_s = float(clip_meta.get("duration", render_result.get("duration", 0.0)) or 0.0)
+ width = int(clip_meta.get("width", render_result.get("width", 0)) or 0)
+ height = int(clip_meta.get("height", render_result.get("height", 0)) or 0)
+
+ warnings: List[str] = []
+ artifacts = [
+ artifact_record(
+ bundle_dir,
+ preview_clip,
+ artifact_id="clip",
+ role="preview-clip",
+ kind="clip",
+ label="Rendered preview clip",
+ width=width or None,
+ height=height or None,
+ duration_s=round(duration_s, 3),
+ segments_rendered=render_result.get("segments_rendered"),
+ )
+ ]
+
+ for index, ratio in enumerate(config["thumbnail_times"]):
+ capture_time = duration_s * ratio if duration_s > 0 else 0.0
+ image_path = os.path.join(artifacts_dir, f"frame_{index + 1:02d}.jpg")
+ try:
+ media_mod.extract_thumbnail(preview_clip, image_path, capture_time)
+ except Exception as exc:
+ warnings.append(f"frame sample {index + 1} failed: {exc}")
+ continue
+ role = "hero" if abs(ratio - 0.5) < 1e-9 else "gallery"
+ label = "Midpoint frame" if role == "hero" else f"Sample frame {index + 1}"
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ image_path,
+ artifact_id=f"frame_{index + 1:02d}",
+ role=role,
+ kind="image",
+ label=label,
+ time_s=round(capture_time, 3),
+ )
+ )
+
+ metrics = _metrics(session)
+ summary = {
+ "headline": (
+ f"Openscreen {recipe} preview rendered"
+ + (f" at {width}x{height}" if width and height else "")
+ ),
+ "facts": {
+ "recipe": recipe,
+ "duration_s": round(duration_s, 3),
+ "resolution": f"{width}x{height}" if width and height else "unknown",
+ **metrics,
+ },
+ "warnings": warnings,
+ "next_actions": [
+ "Inspect the review clip for zoom timing, speed ramps, and padding.",
+ "Open the bundle in cli-hub preview html for a gallery layout.",
+ ],
+ }
+
+ source_video = session.data.get("media", {}).get("screenVideoPath") or session.data.get("videoPath")
+ manifest = finalize_bundle(
+ bundle_dir=bundle_dir,
+ bundle_id=prepared["bundle_id"],
+ bundle_kind="capture",
+ software="openscreen",
+ recipe=recipe,
+ source={
+ "project_path": session.project_path,
+ "project_name": os.path.basename(session.project_path) if session.project_path else None,
+ "project_fingerprint": source_fingerprint,
+ "source_video": source_video,
+ "session_id": session.session_id,
+ },
+ artifacts=artifacts,
+ summary=summary,
+ cache_key=prepared["cache_key"],
+ generator={
+ "entry_point": "cli-anything-openscreen",
+ "harness_version": HARNESS_VERSION,
+ "command": command or f"cli-anything-openscreen preview capture --recipe {recipe}",
+ },
+ status="partial" if warnings else "ok",
+ warnings=warnings or None,
+ context={"editor": {"aspectRatio": metrics["aspect_ratio"], "background": metrics["background"]}},
+ metrics=metrics,
+ labels=["video", "screen-recording", "preview"],
+ )
+ manifest["cached"] = False
+ return manifest
+
+
+def latest(
+ *,
+ project_path: Optional[str] = None,
+ recipe: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Return the latest preview bundle manifest for Openscreen."""
+ manifest = find_latest_manifest(
+ software="openscreen",
+ recipe=recipe,
+ bundle_kind="capture",
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if manifest is None:
+ raise FileNotFoundError("No Openscreen preview bundle found")
+ return manifest
diff --git a/openscreen/agent-harness/cli_anything/openscreen/openscreen_cli.py b/openscreen/agent-harness/cli_anything/openscreen/openscreen_cli.py
index 4729275fb..a2c6727f6 100644
--- a/openscreen/agent-harness/cli_anything/openscreen/openscreen_cli.py
+++ b/openscreen/agent-harness/cli_anything/openscreen/openscreen_cli.py
@@ -19,6 +19,7 @@ from .core import project as proj_mod
from .core import timeline as tl_mod
from .core import export as export_mod
from .core import media as media_mod
+from .core import preview as preview_mod
# ── Global state ──────────────────────────────────────────────────────────
@@ -462,6 +463,12 @@ def export():
pass
+def preview():
+ """Preview bundle capture and inspection."""
+ pass
+
+
@export.command("presets")
@handle_error
def export_presets():
@@ -483,6 +490,42 @@ def export_render(output_path):
output(result, f"Exported to: {output_path}")
+@handle_error
+def preview_recipes():
+ """List available preview recipes."""
+ output(preview_mod.list_recipes(), "Preview recipes")
+
+
[email protected]("--recipe", default="quick", help="Preview recipe name")
[email protected]("--force", is_flag=True, help="Bypass preview cache")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory")
+@handle_error
+def preview_capture(recipe, force, root_dir):
+ """Capture a preview bundle for the active project."""
+ result = preview_mod.capture(
+ _session,
+ recipe=recipe,
+ force=force,
+ root_dir=root_dir,
+ command=f"cli-anything-openscreen --project {_session.project_path or ''} preview capture --recipe {recipe}".strip(),
+ )
+ bundle_dir = result.get("_bundle_dir", result.get("bundle_dir", ""))
+ status = "Reused preview bundle" if result.get("cached") else "Created preview bundle"
+ output(result, f"{status}: {bundle_dir}")
+
+
[email protected]("--recipe", default=None, help="Filter by recipe name")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory")
+@handle_error
+def preview_latest(recipe, root_dir):
+ """Show the latest preview bundle manifest."""
+ result = preview_mod.latest(project_path=_session.project_path, recipe=recipe, root_dir=root_dir)
+ output(result, f"Latest preview bundle: {result.get('_bundle_dir', '')}")
+
+
# ── Session commands ──────────────────────────────────────────────────────
@cli.group("session")
@@ -574,6 +617,8 @@ def repl():
"crop set": "Set crop (prompts)",
"probe <path>": "Probe a video file",
"export <path>": "Render and export video",
+ "preview [recipe]": "Capture a preview bundle",
+ "preview-latest [recipe]": "Show the latest preview bundle",
}
while True:
@@ -701,6 +746,16 @@ def repl():
result = export_mod.render(_session, parts[1], on_prog)
skin.success(f"Exported: {result['output']} ({result['file_size']} bytes)")
+ elif cmd == "preview":
+ recipe = parts[1] if len(parts) > 1 else "quick"
+ result = preview_mod.capture(_session, recipe=recipe)
+ output(result, f"Preview bundle: {result.get('_bundle_dir', '')}")
+
+ elif cmd == "preview-latest":
+ recipe = parts[1] if len(parts) > 1 else None
+ result = preview_mod.latest(project_path=_session.project_path, recipe=recipe)
+ output(result, f"Latest preview bundle: {result.get('_bundle_dir', '')}")
+
else:
skin.warning(f"Unknown command: {cmd}. Type 'help' for commands.")
diff --git a/openscreen/agent-harness/cli_anything/openscreen/tests/test_core.py b/openscreen/agent-harness/cli_anything/openscreen/tests/test_core.py
index 97e436870..d4a69674b 100644
--- a/openscreen/agent-harness/cli_anything/openscreen/tests/test_core.py
+++ b/openscreen/agent-harness/cli_anything/openscreen/tests/test_core.py
@@ -7,6 +7,7 @@ All operations are in-memory JSON manipulation.
import json
import os
import tempfile
+from pathlib import Path
import pytest
@@ -14,6 +15,8 @@ from cli_anything.openscreen.core.session import Session
from cli_anything.openscreen.core import project as proj_mod
from cli_anything.openscreen.core import timeline as tl_mod
from cli_anything.openscreen.core import export as export_mod
+from cli_anything.openscreen.core import media as media_mod
+from cli_anything.openscreen.core import preview as preview_mod
# ── Session Tests ─────────────────────────────────────────────────────────
@@ -255,6 +258,76 @@ class TestProject:
proj_mod.set_setting(s, "cropRegion", {"x": 0.5, "y": 0.0, "width": 0.8, "height": 1.0})
+class TestPreview:
+ def test_list_recipes(self):
+ recipes = preview_mod.list_recipes()
+ assert recipes
+ assert recipes[0]["name"] == "quick"
+
+ def test_capture_bundle(self, tmp_path, monkeypatch):
+ session = Session("preview_test")
+ session.new_project("/tmp/source.mp4")
+
+ def fake_render(session_obj, output_path, on_progress=None):
+ Path(output_path).write_bytes(b"\x00\x00\x00\x18ftypmp42")
+ return {
+ "output": output_path,
+ "duration": 8.0,
+ "width": 1920,
+ "height": 1080,
+ "segments_rendered": 3,
+ }
+
+ def fake_probe(path):
+ return {"duration": 8.0, "width": 1920, "height": 1080}
+
+ def fake_thumb(input_path, output_path, time_s=0.0):
+ Path(output_path).write_bytes(b"\xff\xd8\xff\xe0preview")
+ return {"output": output_path, "time_s": time_s}
+
+ monkeypatch.setattr(export_mod, "render", fake_render)
+ monkeypatch.setattr(media_mod, "probe", fake_probe)
+ monkeypatch.setattr(media_mod, "extract_thumbnail", fake_thumb)
+
+ manifest = preview_mod.capture(session, root_dir=str(tmp_path))
+ assert manifest["software"] == "openscreen"
+ assert manifest["recipe"] == "quick"
+ assert manifest["status"] == "ok"
+ assert manifest["cached"] is False
+ assert any(item["role"] == "preview-clip" for item in manifest["artifacts"])
+ assert any(item["role"] == "hero" for item in manifest["artifacts"])
+ assert os.path.isfile(manifest["_manifest_path"])
+
+ def test_latest_bundle(self, tmp_path, monkeypatch):
+ session = Session("preview_test")
+ session.new_project("/tmp/source.mp4")
+
+ def fake_render(session_obj, output_path, on_progress=None):
+ Path(output_path).write_bytes(b"\x00\x00\x00\x18ftypmp42")
+ return {
+ "output": output_path,
+ "duration": 5.0,
+ "width": 1280,
+ "height": 720,
+ "segments_rendered": 2,
+ }
+
+ def fake_probe(path):
+ return {"duration": 5.0, "width": 1280, "height": 720}
+
+ def fake_thumb(input_path, output_path, time_s=0.0):
+ Path(output_path).write_bytes(b"\xff\xd8\xff\xe0preview")
+ return {"output": output_path, "time_s": time_s}
+
+ monkeypatch.setattr(export_mod, "render", fake_render)
+ monkeypatch.setattr(media_mod, "probe", fake_probe)
+ monkeypatch.setattr(media_mod, "extract_thumbnail", fake_thumb)
+
+ created = preview_mod.capture(session, root_dir=str(tmp_path))
+ latest = preview_mod.latest(root_dir=str(tmp_path))
+ assert latest["bundle_id"] == created["bundle_id"]
+
+
# ── Zoom Tests ────────────────────────────────────────────────────────────
class TestZoom:
diff --git a/openscreen/agent-harness/cli_anything/openscreen/tests/test_full_e2e.py b/openscreen/agent-harness/cli_anything/openscreen/tests/test_full_e2e.py
index cdb029f24..db4fde05f 100644
--- a/openscreen/agent-harness/cli_anything/openscreen/tests/test_full_e2e.py
+++ b/openscreen/agent-harness/cli_anything/openscreen/tests/test_full_e2e.py
@@ -35,6 +35,7 @@ from cli_anything.openscreen.core import project as proj_mod
from cli_anything.openscreen.core import timeline as tl_mod
from cli_anything.openscreen.core import export as export_mod
from cli_anything.openscreen.core import media as media_mod
+from cli_anything.openscreen.core import preview as preview_mod
from cli_anything.openscreen.utils import ffmpeg_backend
@@ -62,6 +63,8 @@ def _resolve_cli(name: str):
# ── Fixtures ──────────────────────────────────────────────────────────────
+JPEG_MAGIC_PREFIX = b"\xff\xd8\xff"
+
@pytest.fixture(scope="module")
def test_video():
"""Create a 5-second test video with ffmpeg."""
@@ -98,6 +101,20 @@ def session(test_video):
return s
+def _artifact_path(manifest, artifact_id):
+ for artifact in manifest["artifacts"]:
+ if artifact["artifact_id"] == artifact_id:
+ return os.path.join(manifest["_bundle_dir"], artifact["path"])
+ raise KeyError(f"Artifact not found: {artifact_id}")
+
+
+def _assert_jpeg(path):
+ assert os.path.isfile(path), f"Missing JPEG artifact: {path}"
+ with open(path, "rb") as fh:
+ assert fh.read(3) == JPEG_MAGIC_PREFIX, f"Invalid JPEG header: {path}"
+ assert os.path.getsize(path) > 0, f"Empty JPEG artifact: {path}"
+
+
# ── Media Tests ───────────────────────────────────────────────────────────
class TestMediaE2E:
@@ -255,15 +272,49 @@ class TestExportE2E:
export_mod.render(s, os.path.join(tmp_dir, "out.mp4"))
+class TestPreviewE2E:
+ def test_capture_preview_bundle(self, session):
+ tl_mod.add_zoom_region(session, 800, 2400, depth=2, focus_x=0.65, focus_y=0.35)
+ tl_mod.add_speed_region(session, 2500, 3800, speed=1.5)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ project_path = os.path.join(tmp_dir, "preview.openscreen")
+ proj_mod.save_project(session, project_path)
+
+ manifest = preview_mod.capture(session, root_dir=tmp_dir, force=True)
+ assert manifest["software"] == "openscreen"
+ assert manifest["bundle_kind"] == "capture"
+ assert manifest["status"] in ("ok", "partial")
+
+ clip_path = _artifact_path(manifest, "clip")
+ hero_path = _artifact_path(manifest, "frame_03")
+ probe = media_mod.probe(clip_path)
+
+ assert os.path.isfile(clip_path)
+ assert os.path.getsize(clip_path) > 0
+ assert probe["width"] > 0
+ assert probe["height"] > 0
+ assert probe["duration"] > 0
+ _assert_jpeg(hero_path)
+
+ latest = preview_mod.latest(project_path=project_path, recipe="quick", root_dir=tmp_dir)
+ assert latest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n Openscreen preview bundle: {manifest['_bundle_dir']}")
+ print(f" Openscreen preview clip: {clip_path}")
+ print(f" Openscreen preview hero: {hero_path}")
+
+
# ── CLI Subprocess Tests ──────────────────────────────────────────────────
class TestCLISubprocess:
CLI_BASE = _resolve_cli("cli-anything-openscreen")
- def _run(self, args, check=True):
+ def _run(self, args, check=True, timeout=30):
return subprocess.run(
self.CLI_BASE + args,
capture_output=True, text=True,
+ timeout=timeout,
check=check,
)
@@ -400,3 +451,74 @@ class TestCLISubprocess:
data = json.loads(result.stdout)
assert "project_open" in data
assert "undo_available" in data
+
+ def test_cli_preview_capture(self, test_video):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ proj_path = os.path.join(tmp_dir, "preview.openscreen")
+
+ result = self._run(
+ ["project", "new", "-v", test_video, "-o", proj_path],
+ check=False,
+ timeout=60,
+ )
+ assert result.returncode == 0
+
+ self._run(
+ [
+ "--project",
+ proj_path,
+ "zoom",
+ "add",
+ "--start",
+ "700",
+ "--end",
+ "2200",
+ "--depth",
+ "2",
+ ],
+ check=False,
+ timeout=60,
+ )
+
+ result = self._run(
+ [
+ "--json",
+ "--project",
+ proj_path,
+ "preview",
+ "capture",
+ "--root-dir",
+ tmp_dir,
+ ],
+ check=False,
+ timeout=180,
+ )
+ assert result.returncode == 0, result.stderr
+
+ manifest = json.loads(result.stdout)
+ assert manifest["software"] == "openscreen"
+ clip_path = _artifact_path(manifest, "clip")
+ hero_path = _artifact_path(manifest, "frame_03")
+ assert os.path.isfile(clip_path)
+ _assert_jpeg(hero_path)
+
+ latest = self._run(
+ [
+ "--json",
+ "preview",
+ "latest",
+ "--recipe",
+ "quick",
+ "--root-dir",
+ tmp_dir,
+ ],
+ check=False,
+ timeout=60,
+ )
+ assert latest.returncode == 0, latest.stderr
+ latest_manifest = json.loads(latest.stdout)
+ assert latest_manifest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n Openscreen preview bundle: {manifest['_bundle_dir']}")
+ print(f" Openscreen preview clip: {clip_path}")
+ print(f" Openscreen preview hero: {hero_path}")
diff --git a/openscreen/agent-harness/cli_anything/openscreen/utils/preview_bundle.py b/openscreen/agent-harness/cli_anything/openscreen/utils/preview_bundle.py
new file mode 100644
index 000000000..3cba5dbf0
--- /dev/null
+++ b/openscreen/agent-harness/cli_anything/openscreen/utils/preview_bundle.py
@@ -0,0 +1,304 @@
+"""Shared helpers for CLI-Anything preview bundles."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import mimetypes
+import os
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, Iterable, Optional
+
+PROTOCOL_VERSION = "preview-bundle/v1"
+
+
+def _slug(value: str) -> str:
+ text = (value or "preview").strip().lower()
+ text = re.sub(r"[^a-z0-9]+", "-", text)
+ text = re.sub(r"-{2,}", "-", text).strip("-")
+ return text or "preview"
+
+
+def _json_dumps(data: Any) -> str:
+ return json.dumps(
+ data,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ )
+
+
+def hash_data(data: Any) -> str:
+ return hashlib.sha256(_json_dumps(data).encode("utf-8")).hexdigest()
+
+
+def fingerprint_data(data: Any) -> str:
+ return f"sha256:{hash_data(data)}"
+
+
+def fingerprint_file(path: str) -> str:
+ resolved = os.path.abspath(path)
+ stat = os.stat(resolved)
+ return fingerprint_data(
+ {
+ "path": resolved,
+ "size": stat.st_size,
+ "mtime_ns": stat.st_mtime_ns,
+ }
+ )
+
+
+def bundle_root(
+ software: str,
+ recipe: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Path:
+ if root_dir:
+ base = Path(root_dir).expanduser().resolve()
+ elif project_path:
+ base = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews"
+ else:
+ base = Path.home() / ".cli-anything" / "previews"
+ return base / _slug(software) / _slug(recipe)
+
+
+def build_cache_key(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ protocol_version: str = PROTOCOL_VERSION,
+) -> str:
+ return fingerprint_data(
+ {
+ "protocol_version": protocol_version,
+ "software": software,
+ "recipe": recipe,
+ "bundle_kind": bundle_kind,
+ "source_fingerprint": source_fingerprint,
+ "options": options or {},
+ "harness_version": harness_version or "",
+ }
+ )
+
+
+def _iter_manifests(search_root: Path) -> Iterable[Path]:
+ if not search_root.exists():
+ return []
+ return sorted(search_root.rglob("manifest.json"), reverse=True)
+
+
+def _load_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def find_cached_manifest(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ cache_key: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ root = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir)
+ for manifest_path in _iter_manifests(root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if (
+ manifest.get("protocol_version") == PROTOCOL_VERSION
+ and manifest.get("software") == software
+ and manifest.get("recipe") == recipe
+ and manifest.get("bundle_kind") == bundle_kind
+ and manifest.get("status") in {"ok", "partial"}
+ and manifest.get("cache_key") == cache_key
+ ):
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def find_latest_manifest(
+ software: str,
+ recipe: Optional[str] = None,
+ bundle_kind: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ if root_dir:
+ search_root = Path(root_dir).expanduser().resolve() / _slug(software)
+ elif project_path:
+ search_root = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews" / _slug(software)
+ else:
+ search_root = Path.home() / ".cli-anything" / "previews" / _slug(software)
+ if recipe:
+ search_root = search_root / _slug(recipe)
+ for manifest_path in _iter_manifests(search_root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if manifest.get("software") != software:
+ continue
+ if recipe and manifest.get("recipe") != recipe:
+ continue
+ if bundle_kind and manifest.get("bundle_kind") != bundle_kind:
+ continue
+ if manifest.get("status") not in {"ok", "partial"}:
+ continue
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def prepare_bundle(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+) -> Dict[str, Any]:
+ cache_key = build_cache_key(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ source_fingerprint=source_fingerprint,
+ options=options or {},
+ harness_version=harness_version,
+ )
+ if not force:
+ cached = find_cached_manifest(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ cache_key=cache_key,
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if cached:
+ return {
+ "cached": True,
+ "cache_key": cache_key,
+ "bundle_id": cached.get("bundle_id"),
+ "bundle_dir": cached["_bundle_dir"],
+ "manifest_path": cached["_manifest_path"],
+ "summary_path": os.path.join(cached["_bundle_dir"], cached.get("summary_path", "summary.json")),
+ "manifest": cached,
+ }
+
+ now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ bundle_id = f"{now}_{cache_key.split(':', 1)[-1][:8]}_{_slug(recipe)}"
+ out_dir = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir) / bundle_id
+ artifacts_dir = out_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=False)
+ return {
+ "cached": False,
+ "cache_key": cache_key,
+ "bundle_id": bundle_id,
+ "bundle_dir": str(out_dir.resolve()),
+ "artifacts_dir": str(artifacts_dir.resolve()),
+ "manifest_path": str((out_dir / "manifest.json").resolve()),
+ "summary_path": str((out_dir / "summary.json").resolve()),
+ }
+
+
+def artifact_record(
+ bundle_dir: str,
+ path: str,
+ artifact_id: str,
+ role: str,
+ kind: str,
+ label: str,
+ media_type: Optional[str] = None,
+ **extra: Any,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ file_path = Path(path).resolve()
+ rel_path = file_path.relative_to(bundle_path).as_posix()
+ record: Dict[str, Any] = {
+ "artifact_id": artifact_id,
+ "role": role,
+ "kind": kind,
+ "label": label,
+ "media_type": media_type or mimetypes.guess_type(str(file_path))[0] or "application/octet-stream",
+ "path": rel_path,
+ }
+ if file_path.exists():
+ record["bytes"] = file_path.stat().st_size
+ record.update({k: v for k, v in extra.items() if v is not None})
+ return record
+
+
+def write_json(path: str, data: Any) -> str:
+ output_path = Path(path).resolve()
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(output_path, "w", encoding="utf-8") as fh:
+ json.dump(data, fh, indent=2, ensure_ascii=False, default=str)
+ fh.write("\n")
+ return str(output_path)
+
+
+def finalize_bundle(
+ bundle_dir: str,
+ bundle_id: str,
+ bundle_kind: str,
+ software: str,
+ recipe: str,
+ source: Dict[str, Any],
+ artifacts: list[Dict[str, Any]],
+ summary: Dict[str, Any],
+ cache_key: str,
+ generator: Dict[str, Any],
+ status: str = "ok",
+ warnings: Optional[list[str]] = None,
+ context: Optional[Dict[str, Any]] = None,
+ metrics: Optional[Dict[str, Any]] = None,
+ labels: Optional[list[str]] = None,
+ source_bundles: Optional[list[Dict[str, Any]]] = None,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ summary_rel = "summary.json"
+ summary_path = write_json(str(bundle_path / summary_rel), summary)
+ manifest = {
+ "protocol_version": PROTOCOL_VERSION,
+ "bundle_id": bundle_id,
+ "bundle_kind": bundle_kind,
+ "software": software,
+ "recipe": recipe,
+ "status": status,
+ "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
+ "cache_key": cache_key,
+ "generator": generator,
+ "source": source,
+ "summary_path": summary_rel,
+ "artifacts": artifacts,
+ }
+ if warnings:
+ manifest["warnings"] = warnings
+ if context:
+ manifest["context"] = context
+ if metrics:
+ manifest["metrics"] = metrics
+ if labels:
+ manifest["labels"] = labels
+ if source_bundles:
+ manifest["source_bundles"] = source_bundles
+ manifest_path = write_json(str(bundle_path / "manifest.json"), manifest)
+ manifest["_manifest_path"] = manifest_path
+ manifest["_bundle_dir"] = str(bundle_path)
+ manifest["_summary_path"] = summary_path
+ return manifest
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/core/preview.py b/renderdoc/agent-harness/cli_anything/renderdoc/core/preview.py
new file mode 100644
index 000000000..81263a825
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/core/preview.py
@@ -0,0 +1,459 @@
+"""Preview bundle generation for the RenderDoc harness."""
+
+from __future__ import annotations
+
+import os
+from typing import Any, Dict, List, Optional
+
+from ..utils.preview_bundle import (
+ artifact_record,
+ finalize_bundle,
+ find_latest_manifest,
+ fingerprint_data,
+ fingerprint_file,
+ prepare_bundle,
+ write_json,
+)
+from . import actions as actions_mod
+from . import diff as diff_mod
+from . import pipeline as pipeline_mod
+from . import textures as textures_mod
+
+HARNESS_VERSION = "0.1.0"
+
+RECIPES: Dict[str, Dict[str, Any]] = {
+ "quick": {
+ "description": "Capture thumbnail, output targets, and pipeline snapshot",
+ "max_thumb_dim": 768,
+ },
+}
+
+
+def list_recipes() -> List[Dict[str, Any]]:
+ """Return available preview recipes."""
+ recipes = [
+ {
+ "name": name,
+ "description": config["description"],
+ "bundle_kind": "capture",
+ "artifacts": ["hero", "gallery", "metadata"],
+ }
+ for name, config in RECIPES.items()
+ ]
+ recipes.append(
+ {
+ "name": "diff",
+ "description": "Compare two pipeline states and their output targets",
+ "bundle_kind": "diff",
+ "artifacts": ["gallery", "diff", "metadata"],
+ }
+ )
+ return recipes
+
+
+def _default_event_id(handle) -> Optional[int]:
+ drawcalls = actions_mod.get_drawcalls_only(handle.controller)
+ if not drawcalls:
+ return None
+ return int(drawcalls[-1]["eventId"])
+
+
+def _compact_diff(obj: Any) -> Any:
+ if isinstance(obj, dict):
+ pruned = {}
+ for key, value in obj.items():
+ if value == "SAME":
+ continue
+ compacted = _compact_diff(value)
+ if compacted is not None:
+ pruned[key] = compacted
+ return pruned or None
+ if isinstance(obj, list):
+ values = [_compact_diff(item) for item in obj if item != "SAME"]
+ values = [item for item in values if item is not None]
+ return values or None
+ return obj
+
+
+def _count_differences(obj: Any) -> int:
+ if isinstance(obj, dict):
+ return sum(_count_differences(value) for value in obj.values()) or len(obj)
+ if isinstance(obj, list):
+ return sum(_count_differences(item) for item in obj) or len(obj)
+ return 1
+
+
+def capture(
+ handle,
+ capture_path: str,
+ recipe: str = "quick",
+ *,
+ event_id: Optional[int] = None,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ command: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a capture preview bundle for a RenderDoc capture."""
+ if recipe not in RECIPES:
+ raise ValueError(
+ f"Unknown preview recipe: {recipe!r}. Available: {', '.join(sorted(RECIPES))}"
+ )
+
+ config = RECIPES[recipe]
+ source_fingerprint = fingerprint_file(capture_path)
+ prepared = prepare_bundle(
+ software="renderdoc",
+ recipe=recipe,
+ bundle_kind="capture",
+ source_fingerprint=source_fingerprint,
+ options={"event_id": event_id or "auto", **config},
+ harness_version=HARNESS_VERSION,
+ project_path=capture_path,
+ root_dir=root_dir,
+ force=force,
+ )
+ if prepared["cached"]:
+ manifest = dict(prepared["manifest"])
+ manifest["cached"] = True
+ return manifest
+
+ bundle_dir = prepared["bundle_dir"]
+ artifacts_dir = prepared["artifacts_dir"]
+ warnings: List[str] = []
+ artifacts: List[Dict[str, Any]] = []
+ metadata = handle.metadata()
+ action_summary = actions_mod.action_summary(handle.controller)
+
+ hero_path = os.path.join(artifacts_dir, "hero.png")
+ thumb_result = handle.thumbnail(hero_path, config["max_thumb_dim"])
+ if thumb_result.get("error"):
+ warnings.append(str(thumb_result["error"]))
+ elif os.path.isfile(hero_path):
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ hero_path,
+ artifact_id="hero",
+ role="hero",
+ kind="image",
+ label="Capture thumbnail",
+ renderdoc_format=thumb_result.get("format"),
+ )
+ )
+
+ chosen_event = event_id or _default_event_id(handle)
+ output_count = 0
+ if chosen_event is not None:
+ outputs_dir = os.path.join(artifacts_dir, "outputs")
+ output_results = textures_mod.save_action_outputs(handle.controller, chosen_event, outputs_dir, file_format="png")
+ for index, item in enumerate(output_results):
+ if item.get("error") or not item.get("path") or not os.path.isfile(item["path"]):
+ warnings.append(item.get("error", f"missing output target {index}"))
+ continue
+ output_count += 1
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ item["path"],
+ artifact_id=f"output_{index:02d}",
+ role="gallery",
+ kind="image",
+ label=item.get("label", f"Output {index}"),
+ )
+ )
+
+ pipeline_state = pipeline_mod.get_pipeline_state(handle.controller, chosen_event)
+ pipeline_path = os.path.join(artifacts_dir, "pipeline_state.json")
+ write_json(pipeline_path, pipeline_state)
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ pipeline_path,
+ artifact_id="pipeline_state",
+ role="metadata",
+ kind="json",
+ label=f"Pipeline state at event {chosen_event}",
+ media_type="application/json",
+ )
+ )
+ else:
+ warnings.append("No drawcall event found; skipped output-target and pipeline capture.")
+
+ summary_path = os.path.join(artifacts_dir, "action_summary.json")
+ write_json(summary_path, action_summary)
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ summary_path,
+ artifact_id="action_summary",
+ role="metadata",
+ kind="json",
+ label="Action summary",
+ media_type="application/json",
+ )
+ )
+
+ summary = {
+ "headline": f"RenderDoc preview captured from {os.path.basename(capture_path)}",
+ "facts": {
+ "recipe": recipe,
+ "api": metadata.get("api"),
+ "event_id": chosen_event,
+ "drawcalls": action_summary.get("drawcalls", 0),
+ "output_targets": output_count,
+ },
+ "warnings": warnings,
+ "next_actions": [
+ "Inspect the hero thumbnail for a quick capture-level sanity check.",
+ "Inspect output targets and pipeline_state.json for the selected event.",
+ ],
+ }
+
+ manifest = finalize_bundle(
+ bundle_dir=bundle_dir,
+ bundle_id=prepared["bundle_id"],
+ bundle_kind="capture",
+ software="renderdoc",
+ recipe=recipe,
+ source={
+ "capture_path": os.path.abspath(capture_path),
+ "capture_name": os.path.basename(capture_path),
+ "capture_fingerprint": source_fingerprint,
+ },
+ artifacts=artifacts,
+ summary=summary,
+ cache_key=prepared["cache_key"],
+ generator={
+ "entry_point": "cli-anything-renderdoc",
+ "harness_version": HARNESS_VERSION,
+ "command": command or f"cli-anything-renderdoc -c {capture_path} preview capture --recipe {recipe}",
+ },
+ status="partial" if warnings else "ok",
+ warnings=warnings or None,
+ context={"event_id": chosen_event},
+ metrics={
+ "drawcalls": action_summary.get("drawcalls", 0),
+ "output_targets": output_count,
+ },
+ labels=["gpu", "capture", "preview"],
+ )
+ manifest["cached"] = False
+ return manifest
+
+
+def diff(
+ handle_a,
+ capture_path_a: str,
+ event_a: int,
+ handle_b,
+ capture_path_b: str,
+ event_b: int,
+ *,
+ compact: bool = True,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ command: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Create a diff preview bundle for two RenderDoc events."""
+ source_fingerprint = fingerprint_data(
+ {
+ "capture_a": fingerprint_file(capture_path_a),
+ "event_a": event_a,
+ "capture_b": fingerprint_file(capture_path_b),
+ "event_b": event_b,
+ }
+ )
+ prepared = prepare_bundle(
+ software="renderdoc",
+ recipe="diff",
+ bundle_kind="diff",
+ source_fingerprint=source_fingerprint,
+ options={"compact": compact, "event_a": event_a, "event_b": event_b},
+ harness_version=HARNESS_VERSION,
+ project_path=capture_path_a,
+ root_dir=root_dir,
+ force=force,
+ )
+ if prepared["cached"]:
+ manifest = dict(prepared["manifest"])
+ manifest["cached"] = True
+ return manifest
+
+ bundle_dir = prepared["bundle_dir"]
+ artifacts_dir = prepared["artifacts_dir"]
+ warnings: List[str] = []
+ artifacts: List[Dict[str, Any]] = []
+
+ thumb_a = os.path.join(artifacts_dir, "capture_a_thumb.png")
+ thumb_a_result = handle_a.thumbnail(thumb_a, 512)
+ if not thumb_a_result.get("error") and os.path.isfile(thumb_a):
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ thumb_a,
+ artifact_id="capture_a_thumb",
+ role="gallery",
+ kind="image",
+ label=f"{os.path.basename(capture_path_a)} thumbnail",
+ )
+ )
+
+ thumb_b = os.path.join(artifacts_dir, "capture_b_thumb.png")
+ thumb_b_result = handle_b.thumbnail(thumb_b, 512)
+ if not thumb_b_result.get("error") and os.path.isfile(thumb_b):
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ thumb_b,
+ artifact_id="capture_b_thumb",
+ role="gallery",
+ kind="image",
+ label=f"{os.path.basename(capture_path_b)} thumbnail",
+ )
+ )
+
+ outputs_a = textures_mod.save_action_outputs(
+ handle_a.controller,
+ event_a,
+ os.path.join(artifacts_dir, "outputs_a"),
+ file_format="png",
+ )
+ outputs_b = textures_mod.save_action_outputs(
+ handle_b.controller,
+ event_b,
+ os.path.join(artifacts_dir, "outputs_b"),
+ file_format="png",
+ )
+ for side, output_results in (("A", outputs_a), ("B", outputs_b)):
+ for index, item in enumerate(output_results):
+ if item.get("error") or not item.get("path") or not os.path.isfile(item["path"]):
+ warnings.append(item.get("error", f"missing output target {side}{index}"))
+ continue
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ item["path"],
+ artifact_id=f"{side.lower()}_output_{index:02d}",
+ role="gallery",
+ kind="image",
+ label=f"{side} {item.get('label', f'Output {index}')}",
+ )
+ )
+
+ diff_data = diff_mod.diff_pipeline(handle_a.controller, event_a, handle_b.controller, event_b)
+ if compact:
+ diff_data = _compact_diff(diff_data) or {}
+
+ diff_path = os.path.join(artifacts_dir, "pipeline_diff.json")
+ write_json(diff_path, diff_data)
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ diff_path,
+ artifact_id="pipeline_diff",
+ role="diff",
+ kind="json",
+ label="Pipeline diff",
+ media_type="application/json",
+ )
+ )
+
+ pipeline_a = pipeline_mod.get_pipeline_state(handle_a.controller, event_a)
+ pipeline_a_path = os.path.join(artifacts_dir, "pipeline_a.json")
+ write_json(pipeline_a_path, pipeline_a)
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ pipeline_a_path,
+ artifact_id="pipeline_a",
+ role="metadata",
+ kind="json",
+ label=f"Pipeline state A at event {event_a}",
+ media_type="application/json",
+ )
+ )
+
+ pipeline_b = pipeline_mod.get_pipeline_state(handle_b.controller, event_b)
+ pipeline_b_path = os.path.join(artifacts_dir, "pipeline_b.json")
+ write_json(pipeline_b_path, pipeline_b)
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ pipeline_b_path,
+ artifact_id="pipeline_b",
+ role="metadata",
+ kind="json",
+ label=f"Pipeline state B at event {event_b}",
+ media_type="application/json",
+ )
+ )
+
+ diff_count = _count_differences(diff_data)
+ summary = {
+ "headline": f"RenderDoc diff bundle created for events {event_a} vs {event_b}",
+ "facts": {
+ "event_a": event_a,
+ "event_b": event_b,
+ "capture_a": os.path.basename(capture_path_a),
+ "capture_b": os.path.basename(capture_path_b),
+ "difference_count": diff_count,
+ },
+ "warnings": warnings,
+ "next_actions": [
+ "Inspect pipeline_diff.json for resource, shader, and state changes.",
+ "Compare A/B output-target images for visible regressions.",
+ ],
+ }
+
+ manifest = finalize_bundle(
+ bundle_dir=bundle_dir,
+ bundle_id=prepared["bundle_id"],
+ bundle_kind="diff",
+ software="renderdoc",
+ recipe="diff",
+ source={
+ "capture_path": os.path.abspath(capture_path_a),
+ "capture_name": os.path.basename(capture_path_a),
+ "capture_fingerprint": fingerprint_file(capture_path_a),
+ },
+ artifacts=artifacts,
+ summary=summary,
+ cache_key=prepared["cache_key"],
+ generator={
+ "entry_point": "cli-anything-renderdoc",
+ "harness_version": HARNESS_VERSION,
+ "command": command
+ or f"cli-anything-renderdoc -c {capture_path_a} preview diff {event_a} {event_b} --capture-b {capture_path_b}",
+ },
+ status="partial" if warnings else "ok",
+ warnings=warnings or None,
+ context={"event_a": event_a, "event_b": event_b},
+ metrics={"difference_count": diff_count},
+ labels=["gpu", "capture", "diff", "preview"],
+ source_bundles=[
+ {"capture_path": os.path.abspath(capture_path_a), "event_id": event_a},
+ {"capture_path": os.path.abspath(capture_path_b), "event_id": event_b},
+ ],
+ )
+ manifest["cached"] = False
+ return manifest
+
+
+def latest(
+ *,
+ project_path: Optional[str] = None,
+ recipe: Optional[str] = None,
+ bundle_kind: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Return the latest preview bundle manifest for RenderDoc."""
+ manifest = find_latest_manifest(
+ software="renderdoc",
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if manifest is None:
+ raise FileNotFoundError("No RenderDoc preview bundle found")
+ return manifest
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py b/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py
index 78d787f65..d7ccfcafb 100644
--- a/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/renderdoc_cli.py
@@ -833,6 +833,112 @@ def pipeline_diff_cmd(ctx, event_a, event_b, capture_b, compact, output):
_output(ctx, {"path": output})
else:
click.echo(output)
+
+
+# ===========================================================================
+# preview bundles
+# ===========================================================================
+
+
+def preview_group():
+ """Preview bundle capture and inspection."""
+ pass
+
+
+@preview_group.command("recipes")
+def preview_recipes(ctx):
+ """List available preview recipes."""
+ from cli_anything.renderdoc.core.preview import list_recipes
+
+ _output(ctx, list_recipes())
+
+
+@preview_group.command("capture")
[email protected]("--recipe", default="quick", help="Preview recipe name.")
[email protected]("--event-id", type=int, default=None, help="Specific event to inspect.")
[email protected]("--force", is_flag=True, help="Bypass preview cache.")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory.")
+def preview_capture_cmd(ctx, recipe, event_id, force, root_dir):
+ """Capture a preview bundle for the active RenderDoc capture."""
+ from cli_anything.renderdoc.core.preview import capture
+
+ handle = _get_handle(ctx)
+ capture_path = ctx.obj.get("capture_path")
+ result = capture(
+ handle,
+ capture_path,
+ recipe=recipe,
+ event_id=event_id,
+ force=force,
+ root_dir=root_dir,
+ command=f"cli-anything-renderdoc -c {capture_path} preview capture --recipe {recipe}",
+ )
+ _output(ctx, result)
+
+
+@preview_group.command("diff")
[email protected]("event_a", type=int)
[email protected]("event_b", type=int)
+ "--capture-b", "-b",
+ type=click.Path(exists=False),
+ default=None,
+ help="Path to second .rdc capture (default: same as --capture).",
+)
[email protected]("--compact/--no-compact", default=True, help="Prune identical sections.")
[email protected]("--force", is_flag=True, help="Bypass preview cache.")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory.")
+def preview_diff_cmd(ctx, event_a, event_b, capture_b, compact, force, root_dir):
+ """Capture a diff preview bundle for two RenderDoc events."""
+ from cli_anything.renderdoc.core.preview import diff
+
+ handle_a = _get_handle(ctx)
+ capture_path_a = ctx.obj.get("capture_path")
+ if capture_b:
+ handle_b = _get_handle_b(ctx, capture_b)
+ capture_path_b = capture_b
+ else:
+ handle_b = handle_a
+ capture_path_b = capture_path_a
+
+ result = diff(
+ handle_a,
+ capture_path_a,
+ event_a,
+ handle_b,
+ capture_path_b,
+ event_b,
+ compact=compact,
+ force=force,
+ root_dir=root_dir,
+ command=(
+ f"cli-anything-renderdoc -c {capture_path_a} preview diff {event_a} {event_b}"
+ + (f" --capture-b {capture_path_b}" if capture_b else "")
+ ),
+ )
+ _output(ctx, result)
+
+
+@preview_group.command("latest")
[email protected]("--recipe", default=None, help="Filter by recipe name.")
[email protected]("--kind", "bundle_kind", type=click.Choice(["capture", "diff"]), default=None)
[email protected]("--root-dir", default=None, help="Override preview bundle root directory.")
+def preview_latest_cmd(ctx, recipe, bundle_kind, root_dir):
+ """Show the latest preview bundle manifest."""
+ from cli_anything.renderdoc.core.preview import latest
+
+ result = latest(
+ project_path=ctx.obj.get("capture_path"),
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ root_dir=root_dir,
+ )
+ _output(ctx, result)
# Cleanup hook
# ===========================================================================
@@ -870,6 +976,7 @@ def repl(ctx):
"actions": "list|summary|find|get",
"textures": "list|get|save|save-outputs|pick",
"pipeline": "state|shader-export|cbuffer|diff",
+ "preview": "recipes|capture|diff|latest",
"resources": "list|buffers|read-buffer",
"mesh": "inputs|outputs",
"counters": "list|fetch",
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py
index a034f7c88..40e9306b6 100644
--- a/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_core.py
@@ -8,6 +8,7 @@ Run with: pytest test_core.py -v
from __future__ import annotations
import json
+import os
import struct
import sys
from pathlib import Path
@@ -686,3 +687,102 @@ class TestDiffModule:
text = buf.getvalue()
assert "Alice" in text
assert "extra_col" not in text
+
+
+class TestPreviewModule:
+ def _make_handle(self, tmp_path: Path, name: str = "frame") -> tuple[MagicMock, Path]:
+ capture_path = tmp_path / f"{name}.rdc"
+ capture_path.write_bytes(b"RDC")
+ handle = MagicMock()
+ handle.controller = MagicMock()
+ handle.metadata.return_value = {"api": "Vulkan", "replay_supported": True}
+
+ def _thumb(output_path, max_dim=0):
+ Path(output_path).write_bytes(b"\x89PNG\r\n\x1a\nthumb")
+ return {"path": output_path, "format": "PNG"}
+
+ handle.thumbnail.side_effect = _thumb
+ return handle, capture_path
+
+ def test_capture_bundle(self, tmp_path, monkeypatch):
+ from cli_anything.renderdoc.core import preview as preview_mod
+ from cli_anything.renderdoc.core import actions as actions_mod
+ from cli_anything.renderdoc.core import textures as textures_mod
+ from cli_anything.renderdoc.core import pipeline as pipeline_mod
+
+ handle, capture_path = self._make_handle(tmp_path, "capture_a")
+
+ monkeypatch.setattr(actions_mod, "get_drawcalls_only", lambda controller: [{"eventId": 42}])
+ monkeypatch.setattr(actions_mod, "action_summary", lambda controller: {"drawcalls": 5})
+
+ def fake_save_outputs(controller, event_id, output_dir, file_format="png"):
+ os.makedirs(output_dir, exist_ok=True)
+ output_path = Path(output_dir) / f"event{event_id}_rt0.png"
+ output_path.write_bytes(b"\x89PNG\r\n\x1a\nout")
+ return [{"path": str(output_path), "label": "RT0"}]
+
+ monkeypatch.setattr(textures_mod, "save_action_outputs", fake_save_outputs)
+ monkeypatch.setattr(pipeline_mod, "get_pipeline_state", lambda controller, event_id: {"eventId": event_id})
+
+ manifest = preview_mod.capture(handle, str(capture_path), root_dir=str(tmp_path))
+ assert manifest["software"] == "renderdoc"
+ assert manifest["recipe"] == "quick"
+ assert manifest["status"] == "ok"
+ assert any(item["role"] == "hero" for item in manifest["artifacts"])
+ assert any(item["artifact_id"] == "pipeline_state" for item in manifest["artifacts"])
+
+ def test_diff_bundle(self, tmp_path, monkeypatch):
+ from cli_anything.renderdoc.core import preview as preview_mod
+ from cli_anything.renderdoc.core import textures as textures_mod
+ from cli_anything.renderdoc.core import pipeline as pipeline_mod
+ from cli_anything.renderdoc.core import diff as diff_mod
+
+ handle_a, capture_a = self._make_handle(tmp_path, "capture_a")
+ handle_b, capture_b = self._make_handle(tmp_path, "capture_b")
+
+ def fake_save_outputs(controller, event_id, output_dir, file_format="png"):
+ os.makedirs(output_dir, exist_ok=True)
+ output_path = Path(output_dir) / f"event{event_id}_rt0.png"
+ output_path.write_bytes(b"\x89PNG\r\n\x1a\nout")
+ return [{"path": str(output_path), "label": "RT0"}]
+
+ monkeypatch.setattr(textures_mod, "save_action_outputs", fake_save_outputs)
+ monkeypatch.setattr(pipeline_mod, "get_pipeline_state", lambda controller, event_id: {"eventId": event_id})
+ monkeypatch.setattr(diff_mod, "diff_pipeline", lambda *args, **kwargs: {"identical": False, "blend": {"enabled": {"A": True, "B": False}}})
+
+ manifest = preview_mod.diff(
+ handle_a,
+ str(capture_a),
+ 100,
+ handle_b,
+ str(capture_b),
+ 200,
+ root_dir=str(tmp_path),
+ )
+ assert manifest["software"] == "renderdoc"
+ assert manifest["bundle_kind"] == "diff"
+ assert any(item["artifact_id"] == "pipeline_diff" for item in manifest["artifacts"])
+
+ def test_latest_bundle(self, tmp_path, monkeypatch):
+ from cli_anything.renderdoc.core import preview as preview_mod
+ from cli_anything.renderdoc.core import actions as actions_mod
+ from cli_anything.renderdoc.core import textures as textures_mod
+ from cli_anything.renderdoc.core import pipeline as pipeline_mod
+
+ handle, capture_path = self._make_handle(tmp_path, "capture_latest")
+
+ monkeypatch.setattr(actions_mod, "get_drawcalls_only", lambda controller: [{"eventId": 7}])
+ monkeypatch.setattr(actions_mod, "action_summary", lambda controller: {"drawcalls": 1})
+
+ def fake_save_outputs(controller, event_id, output_dir, file_format="png"):
+ os.makedirs(output_dir, exist_ok=True)
+ output_path = Path(output_dir) / f"event{event_id}_rt0.png"
+ output_path.write_bytes(b"\x89PNG\r\n\x1a\nout")
+ return [{"path": str(output_path), "label": "RT0"}]
+
+ monkeypatch.setattr(textures_mod, "save_action_outputs", fake_save_outputs)
+ monkeypatch.setattr(pipeline_mod, "get_pipeline_state", lambda controller, event_id: {"eventId": event_id})
+
+ created = preview_mod.capture(handle, str(capture_path), root_dir=str(tmp_path))
+ latest = preview_mod.latest(root_dir=str(tmp_path))
+ assert latest["bundle_id"] == created["bundle_id"]
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_full_e2e.py b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_full_e2e.py
index 133c65979..82a5463dd 100644
--- a/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_full_e2e.py
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/tests/test_full_e2e.py
@@ -21,6 +21,9 @@ from pathlib import Path
import pytest
+from cli_anything.renderdoc.core.capture import open_capture
+from cli_anything.renderdoc.core import preview as preview_mod
+
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
@@ -58,6 +61,13 @@ def _run_cli(*args, json_mode=True) -> dict | list | str:
return result.stdout
+def _artifact_path(manifest, artifact_id: str) -> str:
+ for artifact in manifest["artifacts"]:
+ if artifact["artifact_id"] == artifact_id:
+ return os.path.join(manifest["_bundle_dir"], artifact["path"])
+ raise KeyError(f"Artifact not found: {artifact_id}")
+
+
# ===========================================================================
# E2E: Capture info
# ===========================================================================
@@ -225,3 +235,140 @@ class TestWorkflowE2E:
# Step 5: List textures
textures = _run_cli("textures", "list")
assert isinstance(textures, list)
+
+
+@skip_no_rd
+@skip_no_cap
+class TestPreviewAPIE2E:
+ def test_preview_capture_bundle(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ with open_capture(TEST_CAPTURE) as handle:
+ manifest = preview_mod.capture(
+ handle,
+ TEST_CAPTURE,
+ root_dir=tmpdir,
+ force=True,
+ )
+
+ assert manifest["software"] == "renderdoc"
+ assert manifest["bundle_kind"] == "capture"
+ assert manifest["status"] in ("ok", "partial")
+
+ artifact_ids = {artifact["artifact_id"] for artifact in manifest["artifacts"]}
+ assert "action_summary" in artifact_ids
+ summary_path = _artifact_path(manifest, "action_summary")
+ assert os.path.isfile(summary_path)
+
+ latest = preview_mod.latest(
+ project_path=TEST_CAPTURE,
+ recipe="quick",
+ bundle_kind="capture",
+ root_dir=tmpdir,
+ )
+ assert latest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n RenderDoc preview bundle: {manifest['_bundle_dir']}")
+ print(f" RenderDoc action summary: {summary_path}")
+
+ def test_preview_diff_bundle(self):
+ draws = _run_cli("actions", "list", "--draws-only")
+ if not draws:
+ pytest.skip("No draw calls in capture")
+
+ event_a = int(draws[0]["eventId"])
+ event_b = int(draws[-1]["eventId"])
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ with open_capture(TEST_CAPTURE) as handle_a, open_capture(TEST_CAPTURE) as handle_b:
+ manifest = preview_mod.diff(
+ handle_a,
+ TEST_CAPTURE,
+ event_a,
+ handle_b,
+ TEST_CAPTURE,
+ event_b,
+ root_dir=tmpdir,
+ force=True,
+ )
+
+ assert manifest["software"] == "renderdoc"
+ assert manifest["bundle_kind"] == "diff"
+ diff_path = _artifact_path(manifest, "pipeline_diff")
+ assert os.path.isfile(diff_path)
+ with open(diff_path, "r", encoding="utf-8") as fh:
+ diff_data = json.load(fh)
+ assert isinstance(diff_data, dict)
+
+ latest = preview_mod.latest(
+ project_path=TEST_CAPTURE,
+ recipe="diff",
+ bundle_kind="diff",
+ root_dir=tmpdir,
+ )
+ assert latest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n RenderDoc diff bundle: {manifest['_bundle_dir']}")
+ print(f" RenderDoc pipeline diff: {diff_path}")
+
+
+@skip_no_rd
+@skip_no_cap
+class TestPreviewCLIE2E:
+ def test_cli_preview_capture(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ manifest = _run_cli("preview", "capture", "--root-dir", tmpdir)
+ assert manifest["software"] == "renderdoc"
+ summary_path = _artifact_path(manifest, "action_summary")
+ assert os.path.isfile(summary_path)
+
+ latest = _run_cli(
+ "preview",
+ "latest",
+ "--recipe",
+ "quick",
+ "--bundle-kind",
+ "capture",
+ "--root-dir",
+ tmpdir,
+ )
+ assert latest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n RenderDoc preview bundle: {manifest['_bundle_dir']}")
+ print(f" RenderDoc action summary: {summary_path}")
+
+ def test_cli_preview_diff(self):
+ draws = _run_cli("actions", "list", "--draws-only")
+ if not draws:
+ pytest.skip("No draw calls in capture")
+
+ event_a = int(draws[0]["eventId"])
+ event_b = int(draws[-1]["eventId"])
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ manifest = _run_cli(
+ "preview",
+ "diff",
+ str(event_a),
+ str(event_b),
+ "--root-dir",
+ tmpdir,
+ )
+ assert manifest["software"] == "renderdoc"
+ assert manifest["bundle_kind"] == "diff"
+ diff_path = _artifact_path(manifest, "pipeline_diff")
+ assert os.path.isfile(diff_path)
+
+ latest = _run_cli(
+ "preview",
+ "latest",
+ "--recipe",
+ "diff",
+ "--bundle-kind",
+ "diff",
+ "--root-dir",
+ tmpdir,
+ )
+ assert latest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n RenderDoc diff bundle: {manifest['_bundle_dir']}")
+ print(f" RenderDoc pipeline diff: {diff_path}")
diff --git a/renderdoc/agent-harness/cli_anything/renderdoc/utils/preview_bundle.py b/renderdoc/agent-harness/cli_anything/renderdoc/utils/preview_bundle.py
new file mode 100644
index 000000000..3cba5dbf0
--- /dev/null
+++ b/renderdoc/agent-harness/cli_anything/renderdoc/utils/preview_bundle.py
@@ -0,0 +1,304 @@
+"""Shared helpers for CLI-Anything preview bundles."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import mimetypes
+import os
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, Iterable, Optional
+
+PROTOCOL_VERSION = "preview-bundle/v1"
+
+
+def _slug(value: str) -> str:
+ text = (value or "preview").strip().lower()
+ text = re.sub(r"[^a-z0-9]+", "-", text)
+ text = re.sub(r"-{2,}", "-", text).strip("-")
+ return text or "preview"
+
+
+def _json_dumps(data: Any) -> str:
+ return json.dumps(
+ data,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ )
+
+
+def hash_data(data: Any) -> str:
+ return hashlib.sha256(_json_dumps(data).encode("utf-8")).hexdigest()
+
+
+def fingerprint_data(data: Any) -> str:
+ return f"sha256:{hash_data(data)}"
+
+
+def fingerprint_file(path: str) -> str:
+ resolved = os.path.abspath(path)
+ stat = os.stat(resolved)
+ return fingerprint_data(
+ {
+ "path": resolved,
+ "size": stat.st_size,
+ "mtime_ns": stat.st_mtime_ns,
+ }
+ )
+
+
+def bundle_root(
+ software: str,
+ recipe: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Path:
+ if root_dir:
+ base = Path(root_dir).expanduser().resolve()
+ elif project_path:
+ base = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews"
+ else:
+ base = Path.home() / ".cli-anything" / "previews"
+ return base / _slug(software) / _slug(recipe)
+
+
+def build_cache_key(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ protocol_version: str = PROTOCOL_VERSION,
+) -> str:
+ return fingerprint_data(
+ {
+ "protocol_version": protocol_version,
+ "software": software,
+ "recipe": recipe,
+ "bundle_kind": bundle_kind,
+ "source_fingerprint": source_fingerprint,
+ "options": options or {},
+ "harness_version": harness_version or "",
+ }
+ )
+
+
+def _iter_manifests(search_root: Path) -> Iterable[Path]:
+ if not search_root.exists():
+ return []
+ return sorted(search_root.rglob("manifest.json"), reverse=True)
+
+
+def _load_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def find_cached_manifest(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ cache_key: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ root = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir)
+ for manifest_path in _iter_manifests(root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if (
+ manifest.get("protocol_version") == PROTOCOL_VERSION
+ and manifest.get("software") == software
+ and manifest.get("recipe") == recipe
+ and manifest.get("bundle_kind") == bundle_kind
+ and manifest.get("status") in {"ok", "partial"}
+ and manifest.get("cache_key") == cache_key
+ ):
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def find_latest_manifest(
+ software: str,
+ recipe: Optional[str] = None,
+ bundle_kind: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ if root_dir:
+ search_root = Path(root_dir).expanduser().resolve() / _slug(software)
+ elif project_path:
+ search_root = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews" / _slug(software)
+ else:
+ search_root = Path.home() / ".cli-anything" / "previews" / _slug(software)
+ if recipe:
+ search_root = search_root / _slug(recipe)
+ for manifest_path in _iter_manifests(search_root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if manifest.get("software") != software:
+ continue
+ if recipe and manifest.get("recipe") != recipe:
+ continue
+ if bundle_kind and manifest.get("bundle_kind") != bundle_kind:
+ continue
+ if manifest.get("status") not in {"ok", "partial"}:
+ continue
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def prepare_bundle(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+) -> Dict[str, Any]:
+ cache_key = build_cache_key(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ source_fingerprint=source_fingerprint,
+ options=options or {},
+ harness_version=harness_version,
+ )
+ if not force:
+ cached = find_cached_manifest(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ cache_key=cache_key,
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if cached:
+ return {
+ "cached": True,
+ "cache_key": cache_key,
+ "bundle_id": cached.get("bundle_id"),
+ "bundle_dir": cached["_bundle_dir"],
+ "manifest_path": cached["_manifest_path"],
+ "summary_path": os.path.join(cached["_bundle_dir"], cached.get("summary_path", "summary.json")),
+ "manifest": cached,
+ }
+
+ now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ bundle_id = f"{now}_{cache_key.split(':', 1)[-1][:8]}_{_slug(recipe)}"
+ out_dir = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir) / bundle_id
+ artifacts_dir = out_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=False)
+ return {
+ "cached": False,
+ "cache_key": cache_key,
+ "bundle_id": bundle_id,
+ "bundle_dir": str(out_dir.resolve()),
+ "artifacts_dir": str(artifacts_dir.resolve()),
+ "manifest_path": str((out_dir / "manifest.json").resolve()),
+ "summary_path": str((out_dir / "summary.json").resolve()),
+ }
+
+
+def artifact_record(
+ bundle_dir: str,
+ path: str,
+ artifact_id: str,
+ role: str,
+ kind: str,
+ label: str,
+ media_type: Optional[str] = None,
+ **extra: Any,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ file_path = Path(path).resolve()
+ rel_path = file_path.relative_to(bundle_path).as_posix()
+ record: Dict[str, Any] = {
+ "artifact_id": artifact_id,
+ "role": role,
+ "kind": kind,
+ "label": label,
+ "media_type": media_type or mimetypes.guess_type(str(file_path))[0] or "application/octet-stream",
+ "path": rel_path,
+ }
+ if file_path.exists():
+ record["bytes"] = file_path.stat().st_size
+ record.update({k: v for k, v in extra.items() if v is not None})
+ return record
+
+
+def write_json(path: str, data: Any) -> str:
+ output_path = Path(path).resolve()
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(output_path, "w", encoding="utf-8") as fh:
+ json.dump(data, fh, indent=2, ensure_ascii=False, default=str)
+ fh.write("\n")
+ return str(output_path)
+
+
+def finalize_bundle(
+ bundle_dir: str,
+ bundle_id: str,
+ bundle_kind: str,
+ software: str,
+ recipe: str,
+ source: Dict[str, Any],
+ artifacts: list[Dict[str, Any]],
+ summary: Dict[str, Any],
+ cache_key: str,
+ generator: Dict[str, Any],
+ status: str = "ok",
+ warnings: Optional[list[str]] = None,
+ context: Optional[Dict[str, Any]] = None,
+ metrics: Optional[Dict[str, Any]] = None,
+ labels: Optional[list[str]] = None,
+ source_bundles: Optional[list[Dict[str, Any]]] = None,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ summary_rel = "summary.json"
+ summary_path = write_json(str(bundle_path / summary_rel), summary)
+ manifest = {
+ "protocol_version": PROTOCOL_VERSION,
+ "bundle_id": bundle_id,
+ "bundle_kind": bundle_kind,
+ "software": software,
+ "recipe": recipe,
+ "status": status,
+ "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
+ "cache_key": cache_key,
+ "generator": generator,
+ "source": source,
+ "summary_path": summary_rel,
+ "artifacts": artifacts,
+ }
+ if warnings:
+ manifest["warnings"] = warnings
+ if context:
+ manifest["context"] = context
+ if metrics:
+ manifest["metrics"] = metrics
+ if labels:
+ manifest["labels"] = labels
+ if source_bundles:
+ manifest["source_bundles"] = source_bundles
+ manifest_path = write_json(str(bundle_path / "manifest.json"), manifest)
+ manifest["_manifest_path"] = manifest_path
+ manifest["_bundle_dir"] = str(bundle_path)
+ manifest["_summary_path"] = summary_path
+ return manifest
diff --git a/shotcut/agent-harness/cli_anything/shotcut/core/export.py b/shotcut/agent-harness/cli_anything/shotcut/core/export.py
index c3b38b71a..3d350dc2e 100644
--- a/shotcut/agent-harness/cli_anything/shotcut/core/export.py
+++ b/shotcut/agent-harness/cli_anything/shotcut/core/export.py
@@ -140,7 +140,25 @@ def render(session: Session, output_path: str,
width: Optional[int] = None,
height: Optional[int] = None,
overwrite: bool = False,
- extra_args: Optional[list[str]] = None) -> dict:
+ extra_args: Optional[list[str]] = None,
+ prefer_ffmpeg: bool = False) -> dict:
+ """Render the project to an output file.
+
+ This works by:
+ 1. Saving the current project to a temporary .mlt file
+ 2. Using melt to render it
+
+ Args:
+ session: Active session with an open project
+ output_path: Path for the output file
+ preset: Export preset name
+ width: Override output width
+ height: Override output height
+ overwrite: Overwrite existing output file
+ extra_args: Additional command-line arguments for the encoder
+ prefer_ffmpeg: Backward-compatible preview hint; melt remains the
+ render backend because it natively interprets MLT projects.
+ """
if not session.is_open:
raise RuntimeError("No project is open")
diff --git a/shotcut/agent-harness/cli_anything/shotcut/core/preview.py b/shotcut/agent-harness/cli_anything/shotcut/core/preview.py
new file mode 100644
index 000000000..1eefc1413
--- /dev/null
+++ b/shotcut/agent-harness/cli_anything/shotcut/core/preview.py
@@ -0,0 +1,783 @@
+"""Preview bundle generation for the Shotcut harness."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import signal
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from ..utils import mlt_xml
+from ..utils.preview_bundle import (
+ artifact_record,
+ finalize_bundle,
+ find_latest_manifest,
+ fingerprint_data,
+ fingerprint_file,
+ prepare_bundle,
+)
+from . import export as export_mod
+from . import media as media_mod
+from .session import Session
+
+HARNESS_VERSION = "1.0.0"
+LIVE_PROTOCOL_VERSION = "preview-live/v1"
+DEFAULT_REFRESH_HINT_MS = 1500
+DEFAULT_SOURCE_POLL_MS = 500
+MIN_SOURCE_POLL_MS = 250
+
+RECIPES: Dict[str, Dict[str, Any]] = {
+ "quick": {
+ "description": "Fast low-res preview clip plus sampled frames",
+ "preset": "h264-fast",
+ "width": 640,
+ "height": 360,
+ "thumbnail_width": 640,
+ "thumbnail_height": 360,
+ "sample_ratios": [0.0, 0.25, 0.5, 0.75, 0.95],
+ },
+}
+
+
+def list_recipes() -> List[Dict[str, Any]]:
+ """Return available preview recipes."""
+ recipes = []
+ for name, config in RECIPES.items():
+ recipes.append(
+ {
+ "name": name,
+ "description": config["description"],
+ "bundle_kind": "capture",
+ "artifacts": ["preview-clip", "hero", "gallery"],
+ "resolution": f"{config['width']}x{config['height']}",
+ }
+ )
+ return recipes
+
+
+def _seconds_to_timecode(seconds: float) -> str:
+ total_ms = max(0, int(round(seconds * 1000)))
+ hours, rem = divmod(total_ms, 3600 * 1000)
+ minutes, rem = divmod(rem, 60 * 1000)
+ whole_seconds, ms = divmod(rem, 1000)
+ return f"{hours:02d}:{minutes:02d}:{whole_seconds:02d}.{ms:03d}"
+
+
+def _project_fingerprint(session: Session) -> str:
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+ payload: Dict[str, Any] = {
+ "project_path": os.path.abspath(session.project_path) if session.project_path else "",
+ "xml": mlt_xml.mlt_to_string(session.root),
+ }
+ if not session.project_path:
+ payload["session_id"] = session.session_id
+ return fingerprint_data(payload)
+
+
+def _metrics(session: Session) -> Dict[str, Any]:
+ tractor = session.get_main_tractor()
+ producers = mlt_xml.get_all_producers(session.root)
+ filters = mlt_xml.get_all_filters(session.root)
+ renderable_producers = [
+ producer
+ for producer in producers
+ if mlt_xml.get_property(producer, "resource", "") not in ("", "0")
+ and mlt_xml.get_property(producer, "mlt_service", "") not in ("color", "colour")
+ ]
+ return {
+ "track_count": len(mlt_xml.get_tractor_tracks(tractor)),
+ "producer_count": len(renderable_producers),
+ "filter_count": len(filters),
+ "profile": session.get_profile(),
+ }
+
+
+def capture(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ command: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Render a preview bundle for the active Shotcut project."""
+ if not session.is_open:
+ raise RuntimeError("No project is open")
+ if recipe not in RECIPES:
+ raise ValueError(
+ f"Unknown preview recipe: {recipe!r}. Available: {', '.join(sorted(RECIPES))}"
+ )
+
+ config = RECIPES[recipe]
+ source_fingerprint = _project_fingerprint(session)
+ prepared = prepare_bundle(
+ software="shotcut",
+ recipe=recipe,
+ bundle_kind="capture",
+ source_fingerprint=source_fingerprint,
+ options={k: config[k] for k in ("preset", "width", "height", "sample_ratios")},
+ harness_version=HARNESS_VERSION,
+ project_path=session.project_path,
+ root_dir=root_dir,
+ force=force,
+ )
+ if prepared["cached"]:
+ manifest = dict(prepared["manifest"])
+ manifest["cached"] = True
+ return manifest
+
+ bundle_dir = prepared["bundle_dir"]
+ artifacts_dir = prepared["artifacts_dir"]
+ preview_clip = os.path.join(artifacts_dir, "preview.mp4")
+
+ render_result = export_mod.render(
+ session,
+ preview_clip,
+ preset=config["preset"],
+ width=config["width"],
+ height=config["height"],
+ overwrite=True,
+ prefer_ffmpeg=True,
+ )
+ clip_meta = media_mod.probe_media(preview_clip)
+ duration_s = float(clip_meta.get("duration_seconds", 0.0) or 0.0)
+ video_stream = (clip_meta.get("video_streams") or [{}])[0]
+ width = int(video_stream.get("width") or config["width"])
+ height = int(video_stream.get("height") or config["height"])
+
+ warnings: List[str] = []
+ artifacts = [
+ artifact_record(
+ bundle_dir,
+ preview_clip,
+ artifact_id="clip",
+ role="preview-clip",
+ kind="clip",
+ label="Quick preview render",
+ width=width,
+ height=height,
+ duration_s=round(duration_s, 3),
+ render_method=render_result.get("method"),
+ )
+ ]
+
+ for index, ratio in enumerate(config["sample_ratios"]):
+ capture_time = duration_s * ratio if duration_s > 0 else 0.0
+ image_path = os.path.join(artifacts_dir, f"frame_{index + 1:02d}.png")
+ try:
+ media_mod.generate_thumbnail(
+ preview_clip,
+ image_path,
+ _seconds_to_timecode(capture_time),
+ config["thumbnail_width"],
+ config["thumbnail_height"],
+ )
+ except Exception as exc:
+ warnings.append(f"frame sample {index + 1} failed: {exc}")
+ continue
+
+ role = "hero" if abs(ratio - 0.5) < 1e-9 else "gallery"
+ label = "Midpoint frame" if role == "hero" else f"Sample frame {index + 1}"
+ artifacts.append(
+ artifact_record(
+ bundle_dir,
+ image_path,
+ artifact_id=f"frame_{index + 1:02d}",
+ role=role,
+ kind="image",
+ label=label,
+ width=config["thumbnail_width"],
+ height=config["thumbnail_height"],
+ time_s=round(capture_time, 3),
+ )
+ )
+
+ metrics = _metrics(session)
+ summary = {
+ "headline": (
+ f"Shotcut {recipe} preview rendered at {width}x{height}"
+ + (f" for {duration_s:.2f}s" if duration_s > 0 else "")
+ ),
+ "facts": {
+ "recipe": recipe,
+ "resolution": f"{width}x{height}",
+ "duration_s": round(duration_s, 3),
+ "track_count": metrics["track_count"],
+ "producer_count": metrics["producer_count"],
+ "filter_count": metrics["filter_count"],
+ },
+ "warnings": warnings,
+ "next_actions": [
+ "Inspect the preview clip for pacing, timing, and cut order.",
+ "Use cli-hub preview html on the bundle for a richer inspection page.",
+ ],
+ }
+
+ manifest = finalize_bundle(
+ bundle_dir=bundle_dir,
+ bundle_id=prepared["bundle_id"],
+ bundle_kind="capture",
+ software="shotcut",
+ recipe=recipe,
+ source={
+ "project_path": session.project_path,
+ "project_name": os.path.basename(session.project_path) if session.project_path else None,
+ "project_fingerprint": source_fingerprint,
+ "session_id": session.session_id,
+ },
+ artifacts=artifacts,
+ summary=summary,
+ cache_key=prepared["cache_key"],
+ generator={
+ "entry_point": "cli-anything-shotcut",
+ "harness_version": HARNESS_VERSION,
+ "command": command or f"cli-anything-shotcut preview capture --recipe {recipe}",
+ },
+ status="partial" if warnings else "ok",
+ warnings=warnings or None,
+ context={"profile": metrics["profile"]},
+ metrics={k: v for k, v in metrics.items() if k != "profile"},
+ labels=["video", "timeline", "preview"],
+ )
+ manifest["cached"] = False
+ return manifest
+
+
+def latest(
+ *,
+ project_path: Optional[str] = None,
+ recipe: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Return the latest preview bundle manifest for Shotcut."""
+ manifest = find_latest_manifest(
+ software="shotcut",
+ recipe=recipe,
+ bundle_kind="capture",
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if manifest is None:
+ raise FileNotFoundError("No Shotcut preview bundle found")
+ return manifest
+
+
+def _slug(value: str) -> str:
+ text = (value or "preview").strip().lower()
+ text = re.sub(r"[^a-z0-9]+", "-", text)
+ text = re.sub(r"-{2,}", "-", text).strip("-")
+ return text or "preview"
+
+
+def _preview_base_dir(project_path: Optional[str] = None, root_dir: Optional[str] = None) -> Path:
+ if root_dir:
+ return Path(root_dir).expanduser().resolve() / "shotcut"
+ if project_path:
+ return Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews" / "shotcut"
+ return Path.home() / ".cli-anything" / "previews" / "shotcut"
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def _normalize_poll_ms(value: Optional[int]) -> int:
+ try:
+ numeric = int(value or DEFAULT_SOURCE_POLL_MS)
+ except (TypeError, ValueError):
+ numeric = DEFAULT_SOURCE_POLL_MS
+ return max(MIN_SOURCE_POLL_MS, numeric)
+
+
+def _project_file_fingerprint(project_path: Optional[str]) -> Optional[str]:
+ if not project_path:
+ return None
+ resolved = os.path.abspath(project_path)
+ if not os.path.isfile(resolved):
+ return None
+ return fingerprint_file(resolved)
+
+
+def _live_session_name(session: Session, recipe: str) -> str:
+ project_name = Path(session.project_path).stem if session.project_path else session.session_id or "untitled"
+ fingerprint_source = {
+ "project_path": os.path.abspath(session.project_path) if session.project_path else "",
+ "recipe": recipe,
+ }
+ if not session.project_path:
+ fingerprint_source["session_id"] = session.session_id
+ suffix = fingerprint_data(
+ fingerprint_source
+ ).split(":", 1)[-1][:8]
+ return f"{_slug(project_name)}-{suffix}-{_slug(recipe)}"
+
+
+def _live_session_dir(session: Session, recipe: str, root_dir: Optional[str] = None) -> Path:
+ return _preview_base_dir(session.project_path, root_dir=root_dir) / "live" / _live_session_name(session, recipe)
+
+
+def _read_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def _write_json(path: Path, payload: Dict[str, Any]) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "w", encoding="utf-8") as fh:
+ json.dump(payload, fh, indent=2, ensure_ascii=False, default=str)
+ fh.write("\n")
+ return path
+
+
+def _merge_nested_dict(base: Dict[str, Any], updates: Dict[str, Any]) -> Dict[str, Any]:
+ for key, value in updates.items():
+ if isinstance(value, dict) and isinstance(base.get(key), dict):
+ _merge_nested_dict(base[key], value)
+ else:
+ base[key] = value
+ return base
+
+
+def _pid_is_running(pid: Any) -> bool:
+ try:
+ numeric = int(pid)
+ except (TypeError, ValueError):
+ return False
+ if numeric <= 0:
+ return False
+ try:
+ os.kill(numeric, 0)
+ return True
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+
+
+def _terminate_pid(pid: Any) -> bool:
+ try:
+ numeric = int(pid)
+ except (TypeError, ValueError):
+ return False
+ if numeric <= 0:
+ return False
+ try:
+ os.kill(numeric, signal.SIGTERM)
+ return True
+ except ProcessLookupError:
+ return False
+
+
+def _with_live_refs(session_dir: Path, payload: Dict[str, Any]) -> Dict[str, Any]:
+ payload["_session_dir"] = str(session_dir.resolve())
+ payload["_session_path"] = str((session_dir / "session.json").resolve())
+ return payload
+
+
+def _write_live_session_updates(session_dir: Path, updates: Dict[str, Any]) -> Dict[str, Any]:
+ payload = _load_existing_live_session(session_dir)
+ if not payload:
+ raise FileNotFoundError(f"Live preview session not found: {session_dir}")
+ _merge_nested_dict(payload, updates)
+ payload["updated_at"] = updates.get("updated_at", _now_iso())
+ _write_json(session_dir / "session.json", payload)
+ return _with_live_refs(session_dir, payload)
+
+
+def _load_existing_live_session(session_dir: Path) -> Dict[str, Any]:
+ session_path = session_dir / "session.json"
+ if session_path.is_file():
+ return _read_json(session_path)
+ return {}
+
+
+def _update_current_symlink(session_dir: Path, bundle_dir: str) -> Path:
+ current_link = session_dir / "current"
+ if current_link.is_symlink() or current_link.exists():
+ if current_link.is_dir() and not current_link.is_symlink():
+ raise RuntimeError(f"Live preview current path is unexpectedly a directory: {current_link}")
+ current_link.unlink()
+ target = os.path.relpath(Path(bundle_dir).resolve(), session_dir)
+ os.symlink(target, current_link, target_is_directory=True)
+ return current_link
+
+
+def _history_item(bundle_manifest: Dict[str, Any]) -> Dict[str, Any]:
+ return {
+ "bundle_id": bundle_manifest.get("bundle_id"),
+ "bundle_dir": bundle_manifest.get("_bundle_dir"),
+ "manifest_path": bundle_manifest.get("_manifest_path"),
+ "summary_path": bundle_manifest.get("_summary_path"),
+ "created_at": bundle_manifest.get("created_at"),
+ "status": bundle_manifest.get("status"),
+ "cached": bool(bundle_manifest.get("cached")),
+ }
+
+
+def _publish_live_session(
+ session: Session,
+ bundle_manifest: Dict[str, Any],
+ *,
+ recipe: str,
+ root_dir: Optional[str] = None,
+ refresh_hint_ms: int = DEFAULT_REFRESH_HINT_MS,
+ live_mode: Optional[str] = None,
+ source_poll_ms: int = DEFAULT_SOURCE_POLL_MS,
+ publish_reason: str = "manual",
+) -> Dict[str, Any]:
+ session_dir = _live_session_dir(session, recipe, root_dir=root_dir)
+ session_dir.mkdir(parents=True, exist_ok=True)
+ _update_current_symlink(session_dir, bundle_manifest["_bundle_dir"])
+
+ existing = _load_existing_live_session(session_dir)
+ now = _now_iso()
+ current_item = _history_item(bundle_manifest)
+ history = [current_item]
+ for item in existing.get("history", []):
+ if item.get("bundle_id") == current_item["bundle_id"]:
+ continue
+ history.append(item)
+ history = history[:12]
+
+ current_live_mode = live_mode or existing.get("live_mode") or "manual"
+ current_source_poll_ms = _normalize_poll_ms(
+ source_poll_ms if live_mode is not None or "source_poll_ms" not in existing else existing.get("source_poll_ms")
+ )
+ root_flag = f" --root-dir {root_dir}" if root_dir else ""
+ project_flag = f" --project {session.project_path}" if session.project_path else ""
+ poller = dict(existing.get("poller") or {})
+ poller["running"] = _pid_is_running(poller.get("pid"))
+ source_state = dict(existing.get("source_state") or {})
+ project_file_fingerprint = _project_file_fingerprint(session.project_path)
+ if session.project_path:
+ source_state["source_type"] = "project-file"
+ source_state["project_path"] = session.project_path
+ if project_file_fingerprint:
+ source_state["last_seen_fingerprint"] = project_file_fingerprint
+ source_state["last_rendered_fingerprint"] = project_file_fingerprint
+ source_state["last_rendered_at"] = now
+ source_state["last_publish_reason"] = publish_reason
+
+ payload = {
+ "protocol_version": LIVE_PROTOCOL_VERSION,
+ "software": "shotcut",
+ "recipe": recipe,
+ "status": "active",
+ "live_mode": current_live_mode,
+ "session_name": session_dir.name,
+ "session_id": session.session_id,
+ "project_path": session.project_path,
+ "project_name": Path(session.project_path).name if session.project_path else "untitled",
+ "created_at": existing.get("created_at", now),
+ "updated_at": now,
+ "refresh_hint_ms": int(refresh_hint_ms),
+ "source_poll_ms": current_source_poll_ms,
+ "preview_root_dir": root_dir,
+ "current_link": "current",
+ "current_bundle_id": bundle_manifest.get("bundle_id"),
+ "current_bundle_dir": bundle_manifest.get("_bundle_dir"),
+ "current_manifest_path": bundle_manifest.get("_manifest_path"),
+ "current_summary_path": bundle_manifest.get("_summary_path"),
+ "current_cached": bool(bundle_manifest.get("cached")),
+ "bundle_count": len(history),
+ "history": history,
+ "source_state": source_state,
+ "poller": poller,
+ "publish_command": (
+ f"cli-anything-shotcut{project_flag} preview live push --recipe {recipe}{root_flag}"
+ ).strip(),
+ "watch_command": (
+ f"cli-hub preview watch {session_dir} --open --poll-ms {int(refresh_hint_ms)}"
+ ),
+ "inspect_command": f"cli-hub preview inspect {session_dir}",
+ "html_command": f"cli-hub preview html {session_dir}",
+ "start_command": (
+ f"cli-anything-shotcut{project_flag} preview live start --recipe {recipe} "
+ f"--mode {current_live_mode} --source-poll-ms {current_source_poll_ms}{root_flag}"
+ ).strip(),
+ "monitor_command": (
+ f"cli-anything-shotcut preview live monitor --session-dir {session_dir}"
+ ),
+ }
+ session_path = _write_json(session_dir / "session.json", payload)
+ payload["_session_dir"] = str(session_dir.resolve())
+ payload["_session_path"] = str(session_path.resolve())
+ return payload
+
+
+def live_start(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ refresh_hint_ms: int = DEFAULT_REFRESH_HINT_MS,
+ live_mode: str = "poll",
+ source_poll_ms: int = DEFAULT_SOURCE_POLL_MS,
+ command: Optional[str] = None,
+ publish_reason: str = "live-start",
+) -> Dict[str, Any]:
+ """Capture a preview and publish it into a live session."""
+ if live_mode not in {"poll", "manual"}:
+ raise ValueError("live_mode must be 'poll' or 'manual'")
+ if live_mode == "poll" and not session.project_path:
+ raise RuntimeError("Poll mode requires a saved project path")
+ bundle_manifest = capture(
+ session,
+ recipe=recipe,
+ root_dir=root_dir,
+ force=force,
+ command=command,
+ )
+ live_payload = _publish_live_session(
+ session,
+ bundle_manifest,
+ recipe=recipe,
+ root_dir=root_dir,
+ refresh_hint_ms=refresh_hint_ms,
+ live_mode=live_mode,
+ source_poll_ms=source_poll_ms,
+ publish_reason=publish_reason,
+ )
+ live_payload["bundle"] = {
+ "bundle_id": bundle_manifest.get("bundle_id"),
+ "bundle_dir": bundle_manifest.get("_bundle_dir"),
+ "manifest_path": bundle_manifest.get("_manifest_path"),
+ "cached": bool(bundle_manifest.get("cached")),
+ }
+ return live_payload
+
+
+def live_push(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+ refresh_hint_ms: int = DEFAULT_REFRESH_HINT_MS,
+ source_poll_ms: int = DEFAULT_SOURCE_POLL_MS,
+ command: Optional[str] = None,
+ publish_reason: str = "manual-push",
+) -> Dict[str, Any]:
+ """Publish a fresh preview bundle into the current live session."""
+ existing_mode: Optional[str] = None
+ try:
+ existing_mode = live_status(session, recipe=recipe, root_dir=root_dir).get("live_mode")
+ except FileNotFoundError:
+ existing_mode = "manual"
+ return live_start(
+ session,
+ recipe=recipe,
+ root_dir=root_dir,
+ force=force,
+ refresh_hint_ms=refresh_hint_ms,
+ live_mode=existing_mode or "manual",
+ source_poll_ms=source_poll_ms,
+ command=command,
+ publish_reason=publish_reason,
+ )
+
+
+def live_status(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Return the live session metadata for the active project."""
+ session_dir = _live_session_dir(session, recipe, root_dir=root_dir)
+ session_path = session_dir / "session.json"
+ if not session_path.is_file():
+ raise FileNotFoundError("No Shotcut live preview session found")
+ payload = _read_json(session_path)
+ poller = dict(payload.get("poller") or {})
+ if poller:
+ poller["running"] = _pid_is_running(poller.get("pid"))
+ payload["poller"] = poller
+ return _with_live_refs(session_dir, payload)
+
+
+def live_stop(
+ session: Session,
+ recipe: str = "quick",
+ *,
+ root_dir: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Mark a live preview session as stopped while preserving its latest bundle."""
+ payload = live_status(session, recipe=recipe, root_dir=root_dir)
+ now = _now_iso()
+ poller = dict(payload.get("poller") or {})
+ terminated = _terminate_pid(poller.get("pid"))
+ poller["running"] = False
+ poller["stopped_at"] = now
+ poller["last_exit_reason"] = "manual-stop"
+ poller["terminated"] = terminated
+ payload["status"] = "stopped"
+ payload["stopped_at"] = now
+ payload["poller"] = poller
+ session_path = Path(payload["_session_path"])
+ _write_json(session_path, {k: v for k, v in payload.items() if not k.startswith("_")})
+ return _with_live_refs(session_path.parent, payload)
+
+
+def record_live_poller_spawn(
+ session_dir: str,
+ *,
+ pid: int,
+ command: List[str],
+ log_path: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Persist initial poller spawn metadata before the worker heartbeat lands."""
+ session_path = Path(session_dir).expanduser().resolve()
+ return _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": int(pid),
+ "running": True,
+ "spawned_at": _now_iso(),
+ "command": command,
+ "log_path": log_path,
+ }
+ },
+ )
+
+
+def poll_live_session_once(session_dir: str) -> Dict[str, Any]:
+ """Run one poll cycle for a live session and capture if the source changed."""
+ session_path = Path(session_dir).expanduser().resolve()
+ payload = _load_existing_live_session(session_path)
+ now = _now_iso()
+ if not payload:
+ return {"action": "exit", "reason": "missing-session"}
+
+ if payload.get("status") != "active":
+ _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": os.getpid(),
+ "running": False,
+ "last_heartbeat": now,
+ "last_exit_reason": f"session-status:{payload.get('status')}",
+ }
+ },
+ )
+ return {"action": "exit", "reason": f"status:{payload.get('status')}"}
+
+ if payload.get("live_mode") != "poll":
+ _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": os.getpid(),
+ "running": False,
+ "last_heartbeat": now,
+ "last_exit_reason": f"live-mode:{payload.get('live_mode')}",
+ }
+ },
+ )
+ return {"action": "exit", "reason": f"mode:{payload.get('live_mode')}"}
+
+ project_path = payload.get("project_path")
+ current_fingerprint = _project_file_fingerprint(project_path)
+ base_updates: Dict[str, Any] = {
+ "poller": {
+ "pid": os.getpid(),
+ "running": True,
+ "last_heartbeat": now,
+ },
+ "source_state": {
+ "source_type": "project-file",
+ "project_path": project_path,
+ },
+ }
+ if current_fingerprint:
+ base_updates["source_state"]["last_seen_fingerprint"] = current_fingerprint
+
+ last_rendered = (payload.get("source_state") or {}).get("last_rendered_fingerprint")
+ if not project_path or not os.path.isfile(project_path):
+ base_updates["source_state"]["last_error"] = f"Project path unavailable: {project_path or '(none)'}"
+ base_updates["source_state"]["last_error_at"] = now
+ _write_live_session_updates(session_path, base_updates)
+ return {"action": "idle", "reason": "missing-project", "project_path": project_path}
+
+ if current_fingerprint and current_fingerprint == last_rendered:
+ _write_live_session_updates(session_path, base_updates)
+ return {"action": "idle", "fingerprint": current_fingerprint}
+
+ try:
+ session = Session(f"live_poller_{int(time.time())}")
+ session.open_project(project_path)
+ live_payload = live_start(
+ session,
+ recipe=str(payload.get("recipe") or "quick"),
+ root_dir=payload.get("preview_root_dir"),
+ force=False,
+ refresh_hint_ms=int(payload.get("refresh_hint_ms") or DEFAULT_REFRESH_HINT_MS),
+ live_mode="poll",
+ source_poll_ms=int(payload.get("source_poll_ms") or DEFAULT_SOURCE_POLL_MS),
+ command=str(payload.get("monitor_command") or f"cli-anything-shotcut preview live monitor --session-dir {session_path}"),
+ publish_reason="auto-poll",
+ )
+ _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": os.getpid(),
+ "running": True,
+ "last_heartbeat": now,
+ "last_capture_status": "ok",
+ "last_capture_finished_at": _now_iso(),
+ },
+ "source_state": {
+ "last_seen_fingerprint": current_fingerprint,
+ "last_rendered_fingerprint": current_fingerprint,
+ "last_rendered_at": _now_iso(),
+ "last_error": None,
+ "last_error_at": None,
+ },
+ },
+ )
+ return {
+ "action": "captured",
+ "bundle_id": live_payload.get("current_bundle_id"),
+ "fingerprint": current_fingerprint,
+ }
+ except Exception as exc:
+ _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": os.getpid(),
+ "running": True,
+ "last_heartbeat": now,
+ "last_capture_status": "error",
+ "last_capture_error": str(exc),
+ "last_capture_error_at": _now_iso(),
+ },
+ "source_state": {
+ "last_seen_fingerprint": current_fingerprint,
+ "last_error": str(exc),
+ "last_error_at": _now_iso(),
+ },
+ },
+ )
+ return {"action": "error", "error": str(exc), "fingerprint": current_fingerprint}
+
+
+def run_live_poller(session_dir: str) -> Dict[str, Any]:
+ """Run the long-lived poll loop for a live session."""
+ session_path = Path(session_dir).expanduser().resolve()
+ while True:
+ result = poll_live_session_once(str(session_path))
+ if result.get("action") == "exit":
+ return result
+ payload = _load_existing_live_session(session_path)
+ poll_ms = _normalize_poll_ms((payload or {}).get("source_poll_ms"))
+ time.sleep(poll_ms / 1000.0)
diff --git a/shotcut/agent-harness/cli_anything/shotcut/shotcut_cli.py b/shotcut/agent-harness/cli_anything/shotcut/shotcut_cli.py
index aeb7ad05a..fed298ffe 100755
--- a/shotcut/agent-harness/cli_anything/shotcut/shotcut_cli.py
+++ b/shotcut/agent-harness/cli_anything/shotcut/shotcut_cli.py
@@ -18,6 +18,8 @@ import sys
import os
import json
import shlex
+import shutil
+import subprocess
import click
from typing import Optional
@@ -32,6 +34,7 @@ from cli_anything.shotcut.core import media as media_mod
from cli_anything.shotcut.core import export as export_mod
from cli_anything.shotcut.core import transitions as trans_mod
from cli_anything.shotcut.core import compositing as comp_mod
+from cli_anything.shotcut.core import preview as preview_mod
# Global session state (persists across commands in REPL mode)
_session: Optional[Session] = None
@@ -61,6 +64,77 @@ def output(data, message: str = ""):
click.echo(str(data))
+def _spawn_live_viewer(session_dir: str, poll_ms: int) -> dict:
+ """Launch cli-hub live preview watcher when available."""
+ hub = shutil.which("cli-hub")
+ command = [
+ hub or "cli-hub",
+ "preview",
+ "watch",
+ session_dir,
+ "--open",
+ "--poll-ms",
+ str(int(poll_ms)),
+ ]
+ if hub is None:
+ return {
+ "launched": False,
+ "command": command,
+ "reason": "cli-hub not found on PATH",
+ }
+ process = subprocess.Popen(
+ command,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ return {
+ "launched": True,
+ "pid": process.pid,
+ "command": command,
+ }
+
+
+def _spawn_live_poller(session_dir: str) -> dict:
+ """Launch the Shotcut live preview poller in the background."""
+ cli_path = shutil.which("cli-anything-shotcut")
+ if cli_path:
+ command = [cli_path, "preview", "live", "monitor", "--session-dir", session_dir]
+ else:
+ command = [
+ sys.executable,
+ "-m",
+ "cli_anything.shotcut.shotcut_cli",
+ "preview",
+ "live",
+ "monitor",
+ "--session-dir",
+ session_dir,
+ ]
+ log_path = os.path.join(session_dir, "poller.log")
+ log_fh = open(log_path, "ab")
+ process = subprocess.Popen(
+ command,
+ stdout=log_fh,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ close_fds=True,
+ )
+ log_fh.close()
+ preview_mod.record_live_poller_spawn(
+ session_dir,
+ pid=process.pid,
+ command=command,
+ log_path=log_path,
+ )
+ return {
+ "launched": True,
+ "pid": process.pid,
+ "command": command,
+ "log_path": log_path,
+ }
+
+
def _print_dict(d: dict, indent: int = 0):
"""Pretty-print a dict."""
prefix = " " * indent
@@ -889,6 +963,18 @@ def session():
pass
+def preview():
+ """Preview bundle capture and inspection."""
+ pass
+
+
+def preview_live():
+ """Live preview session commands."""
+ pass
+
+
@session.command("status")
@handle_error
def session_status():
@@ -939,6 +1025,137 @@ def session_list():
output(result, "Saved sessions:")
+@handle_error
+def preview_recipes():
+ """List available preview recipes."""
+ output(preview_mod.list_recipes(), "Preview recipes:")
+
+
[email protected]("--recipe", default="quick", help="Preview recipe name")
[email protected]("--force", is_flag=True, help="Bypass preview cache")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory")
+@handle_error
+def preview_capture(recipe, force, root_dir):
+ """Capture a preview bundle for the active project."""
+ session_obj = get_session()
+ result = preview_mod.capture(
+ session_obj,
+ recipe=recipe,
+ force=force,
+ root_dir=root_dir,
+ command=f"cli-anything-shotcut --project {session_obj.project_path or ''} preview capture --recipe {recipe}".strip(),
+ )
+ bundle_dir = result.get("_bundle_dir", result.get("bundle_dir", ""))
+ status = "Reused preview bundle" if result.get("cached") else "Created preview bundle"
+ output(result, f"{status}: {bundle_dir}")
+
+
[email protected]("--recipe", default=None, help="Filter by recipe name")
[email protected]("--root-dir", default=None, help="Override preview bundle root directory")
+@handle_error
+def preview_latest(recipe, root_dir):
+ """Show the latest preview bundle manifest."""
+ session_obj = get_session()
+ result = preview_mod.latest(
+ project_path=session_obj.project_path,
+ recipe=recipe,
+ root_dir=root_dir,
+ )
+ output(result, f"Latest preview bundle: {result.get('_bundle_dir', '')}")
+
+
+@preview_live.command("start")
[email protected]("--recipe", default="quick", help="Preview recipe name")
[email protected]("--force", is_flag=True, help="Bypass preview cache")
[email protected]("--root-dir", default=None, help="Override preview root directory")
[email protected]("--poll-ms", default=1500, show_default=True, help="Suggested viewer polling interval")
[email protected]("--mode", type=click.Choice(["poll", "manual"]), default="poll", show_default=True,
+ help="Live preview mode. Poll mode auto-captures when the project file changes.")
[email protected]("--source-poll-ms", default=500, show_default=True,
+ help="Polling interval for source project changes in poll mode.")
[email protected]("--open", "open_window", is_flag=True, help="Launch cli-hub live viewer in a separate window")
+@handle_error
+def preview_live_start(recipe, force, root_dir, poll_ms, mode, source_poll_ms, open_window):
+ """Start a live preview session and publish the latest bundle."""
+ session_obj = get_session()
+ result = preview_mod.live_start(
+ session_obj,
+ recipe=recipe,
+ force=force,
+ root_dir=root_dir,
+ refresh_hint_ms=poll_ms,
+ live_mode=mode,
+ source_poll_ms=source_poll_ms,
+ command=(
+ f"cli-anything-shotcut --project {session_obj.project_path or ''} "
+ f"preview live start --recipe {recipe}"
+ ).strip(),
+ )
+ if result.get("live_mode") == "poll" and not result.get("poller", {}).get("running"):
+ result["poller"] = _spawn_live_poller(result["_session_dir"])
+ if open_window:
+ result["viewer"] = _spawn_live_viewer(result["_session_dir"], poll_ms)
+ output(result, f"Started live preview session: {result.get('_session_dir', '')}")
+
+
+@preview_live.command("push")
[email protected]("--recipe", default="quick", help="Preview recipe name")
[email protected]("--force", is_flag=True, help="Bypass preview cache")
[email protected]("--root-dir", default=None, help="Override preview root directory")
[email protected]("--poll-ms", default=1500, show_default=True, help="Suggested viewer polling interval")
+@handle_error
+def preview_live_push(recipe, force, root_dir, poll_ms):
+ """Publish a fresh bundle into the live preview session."""
+ session_obj = get_session()
+ result = preview_mod.live_push(
+ session_obj,
+ recipe=recipe,
+ force=force,
+ root_dir=root_dir,
+ refresh_hint_ms=poll_ms,
+ source_poll_ms=preview_mod.DEFAULT_SOURCE_POLL_MS,
+ command=(
+ f"cli-anything-shotcut --project {session_obj.project_path or ''} "
+ f"preview live push --recipe {recipe}"
+ ).strip(),
+ )
+ output(result, f"Updated live preview session: {result.get('_session_dir', '')}")
+
+
+@preview_live.command("status")
[email protected]("--recipe", default="quick", help="Preview recipe name")
[email protected]("--root-dir", default=None, help="Override preview root directory")
+@handle_error
+def preview_live_status(recipe, root_dir):
+ """Show live preview session metadata."""
+ session_obj = get_session()
+ result = preview_mod.live_status(session_obj, recipe=recipe, root_dir=root_dir)
+ output(result, f"Live preview session: {result.get('_session_dir', '')}")
+
+
+@preview_live.command("stop")
[email protected]("--recipe", default="quick", help="Preview recipe name")
[email protected]("--root-dir", default=None, help="Override preview root directory")
+@handle_error
+def preview_live_stop(recipe, root_dir):
+ """Stop the live preview session without deleting artifacts."""
+ session_obj = get_session()
+ result = preview_mod.live_stop(session_obj, recipe=recipe, root_dir=root_dir)
+ output(result, f"Stopped live preview session: {result.get('_session_dir', '')}")
+
+
+@preview_live.command("monitor", hidden=True)
[email protected]("--session-dir", required=True, help="Live session directory to monitor")
+@handle_error
+def preview_live_monitor(session_dir):
+ """Internal background poller for live preview sessions."""
+ result = preview_mod.run_live_poller(session_dir)
+ output(result, "")
+
+
# ============================================================================
# REPL (Interactive mode)
# ============================================================================
@@ -1008,6 +1225,8 @@ def _run_repl(s: Session, skin):
"check": "Check media files exist",
"presets": "List export presets",
"render <output> [--preset name]": "Render project",
+ "preview [recipe]": "Capture a preview bundle",
+ "preview-latest [recipe]": "Show the latest preview bundle",
"undo": "Undo last operation",
"redo": "Redo last undone operation",
}
@@ -1374,6 +1593,16 @@ def _run_repl(s: Session, skin):
result = export_mod.render(s, out_path, preset)
output(result)
+ elif cmd == "preview":
+ recipe = args[0] if args else "quick"
+ result = preview_mod.capture(s, recipe=recipe)
+ output(result, f"Preview bundle: {result.get('_bundle_dir', '')}")
+
+ elif cmd == "preview-latest":
+ recipe = args[0] if args else None
+ result = preview_mod.latest(project_path=s.project_path, recipe=recipe)
+ output(result, f"Latest preview bundle: {result.get('_bundle_dir', '')}")
+
elif cmd == "undo":
if s.undo():
click.echo("Undone")
diff --git a/shotcut/agent-harness/cli_anything/shotcut/tests/test_core.py b/shotcut/agent-harness/cli_anything/shotcut/tests/test_core.py
index fd34bd574..892e77167 100644
--- a/shotcut/agent-harness/cli_anything/shotcut/tests/test_core.py
+++ b/shotcut/agent-harness/cli_anything/shotcut/tests/test_core.py
@@ -4,6 +4,7 @@ import os
import sys
import json
import xml.etree.ElementTree as ET
+import tempfile
from pathlib import Path
import pytest
@@ -18,6 +19,7 @@ from cli_anything.shotcut.core import media as media_mod
from cli_anything.shotcut.core import export as export_mod
from cli_anything.shotcut.core import transitions as trans_mod
from cli_anything.shotcut.core import compositing as comp_mod
+from cli_anything.shotcut.core import preview as preview_mod
from cli_anything.shotcut.utils.time import (
timecode_to_frames, frames_to_timecode, parse_time_input,
frames_to_seconds, seconds_to_frames,
@@ -359,6 +361,243 @@ class TestSession:
assert len(session_with_track._bin_chains) == 0
+class TestPreview:
+ @staticmethod
+ def _fake_bundle(tmp_path, bundle_id):
+ bundle_dir = tmp_path / bundle_id
+ artifacts_dir = bundle_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=True)
+ hero_path = artifacts_dir / "hero.png"
+ clip_path = artifacts_dir / "preview.mp4"
+ hero_path.write_bytes(b"\x89PNG\r\n\x1a\npreview")
+ clip_path.write_bytes(b"\x00\x00\x00\x18ftypmp42")
+ summary_path = bundle_dir / "summary.json"
+ summary_path.write_text(json.dumps({"headline": "Shotcut quick preview", "facts": {"duration_s": 5.0}}))
+ manifest_path = bundle_dir / "manifest.json"
+ manifest_path.write_text(json.dumps({"bundle_id": bundle_id, "status": "ok"}))
+ return {
+ "bundle_id": bundle_id,
+ "status": "ok",
+ "_bundle_dir": str(bundle_dir),
+ "_manifest_path": str(manifest_path),
+ "_summary_path": str(summary_path),
+ "cached": False,
+ }
+
+ def test_list_recipes(self):
+ recipes = preview_mod.list_recipes()
+ assert recipes
+ assert recipes[0]["name"] == "quick"
+
+ def test_capture_bundle(self, tmp_path, monkeypatch):
+ session = Session("preview_test")
+ session.new_project()
+
+ def fake_render(session_obj, output_path, preset, width, height, overwrite, prefer_ffmpeg=False):
+ Path(output_path).write_bytes(b"\x00\x00\x00\x18ftypmp42")
+ return {
+ "output": output_path,
+ "method": "ffmpeg-filtergraph" if prefer_ffmpeg else "melt",
+ "size_bytes": 12,
+ }
+
+ def fake_probe(path):
+ return {
+ "duration_seconds": 6.0,
+ "video_streams": [{"width": 640, "height": 360}],
+ }
+
+ def fake_thumb(filepath, output_path, timecode, width, height):
+ Path(output_path).write_bytes(b"\x89PNG\r\n\x1a\npreview")
+ return {"output": output_path, "time": timecode}
+
+ monkeypatch.setattr(export_mod, "render", fake_render)
+ monkeypatch.setattr(media_mod, "probe_media", fake_probe)
+ monkeypatch.setattr(media_mod, "generate_thumbnail", fake_thumb)
+
+ manifest = preview_mod.capture(session, root_dir=str(tmp_path))
+ assert manifest["software"] == "shotcut"
+ assert manifest["recipe"] == "quick"
+ assert manifest["status"] == "ok"
+ assert manifest["cached"] is False
+ assert any(item["role"] == "preview-clip" for item in manifest["artifacts"])
+ assert any(item["role"] == "hero" for item in manifest["artifacts"])
+ assert os.path.isfile(manifest["_manifest_path"])
+
+ def test_latest_bundle(self, tmp_path, monkeypatch):
+ session = Session("preview_test")
+ session.new_project()
+
+ def fake_render(session_obj, output_path, preset, width, height, overwrite, prefer_ffmpeg=False):
+ Path(output_path).write_bytes(b"\x00\x00\x00\x18ftypmp42")
+ return {"output": output_path, "method": "ffmpeg-filtergraph" if prefer_ffmpeg else "melt"}
+
+ def fake_probe(path):
+ return {
+ "duration_seconds": 3.0,
+ "video_streams": [{"width": 640, "height": 360}],
+ }
+
+ def fake_thumb(filepath, output_path, timecode, width, height):
+ Path(output_path).write_bytes(b"\x89PNG\r\n\x1a\nthumb")
+ return {"output": output_path, "time": timecode}
+
+ monkeypatch.setattr(export_mod, "render", fake_render)
+ monkeypatch.setattr(media_mod, "probe_media", fake_probe)
+ monkeypatch.setattr(media_mod, "generate_thumbnail", fake_thumb)
+
+ created = preview_mod.capture(session, root_dir=str(tmp_path))
+ latest = preview_mod.latest(root_dir=str(tmp_path))
+ assert latest["bundle_id"] == created["bundle_id"]
+
+ def test_live_start_publishes_session(self, tmp_path, monkeypatch):
+ session = Session("preview_live")
+ session.new_project()
+ project_path = tmp_path / "live-demo.mlt"
+ session.save_project(str(project_path))
+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+
+ def fake_capture(*args, **kwargs):
+ return dict(bundle_manifest)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ live = preview_mod.live_start(
+ session,
+ root_dir=str(tmp_path),
+ refresh_hint_ms=900,
+ live_mode="poll",
+ source_poll_ms=420,
+ )
+ assert live["protocol_version"] == preview_mod.LIVE_PROTOCOL_VERSION
+ assert live["current_bundle_id"] == "bundle-a"
+ assert live["refresh_hint_ms"] == 900
+ assert live["live_mode"] == "poll"
+ assert live["source_poll_ms"] == 420
+ assert live["source_state"]["project_path"] == str(project_path)
+ assert live["source_state"]["last_rendered_fingerprint"].startswith("sha256:")
+ assert Path(live["_session_path"]).is_file()
+ assert (Path(live["_session_dir"]) / "current" / "manifest.json").is_file()
+
+ def test_live_push_updates_history(self, tmp_path, monkeypatch):
+ session = Session("preview_live")
+ session.new_project()
+ project_path = tmp_path / "live-demo.mlt"
+ session.save_project(str(project_path))
+ bundle_a = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+ bundle_b = self._fake_bundle(tmp_path / "bundles", "bundle-b")
+ manifests = [dict(bundle_a), dict(bundle_b)]
+
+ def fake_capture(*args, **kwargs):
+ return manifests.pop(0)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ started = preview_mod.live_start(session, root_dir=str(tmp_path))
+ pushed = preview_mod.live_push(session, root_dir=str(tmp_path))
+ assert started["current_bundle_id"] == "bundle-a"
+ assert pushed["current_bundle_id"] == "bundle-b"
+ assert pushed["history"][0]["bundle_id"] == "bundle-b"
+ assert pushed["history"][1]["bundle_id"] == "bundle-a"
+
+ def test_live_stop_marks_session_stopped(self, tmp_path, monkeypatch):
+ session = Session("preview_live")
+ session.new_project()
+ project_path = tmp_path / "live-demo.mlt"
+ session.save_project(str(project_path))
+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+
+ def fake_capture(*args, **kwargs):
+ return dict(bundle_manifest)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ preview_mod.live_start(session, root_dir=str(tmp_path))
+ stopped = preview_mod.live_stop(session, root_dir=str(tmp_path))
+ assert stopped["status"] == "stopped"
+ assert "stopped_at" in stopped
+
+ def test_live_session_name_is_stable_for_same_project_path(self, tmp_path):
+ project_path = tmp_path / "stable-demo.mlt"
+
+ session_a = Session("session-a")
+ session_a.new_project()
+ session_a.save_project(str(project_path))
+
+ session_b = Session("session-b")
+ session_b.open_project(str(project_path))
+
+ name_a = preview_mod._live_session_name(session_a, "quick")
+ name_b = preview_mod._live_session_name(session_b, "quick")
+ assert name_a == name_b
+
+ def test_project_fingerprint_is_stable_across_sessions_for_saved_project(self, tmp_path):
+ project_path = tmp_path / "stable-project.mlt"
+
+ session_a = Session("session-a")
+ session_a.new_project()
+ session_a.save_project(str(project_path))
+
+ session_b = Session("session-b")
+ session_b.open_project(str(project_path))
+
+ assert preview_mod._project_fingerprint(session_a) == preview_mod._project_fingerprint(session_b)
+
+ def test_poll_live_session_once_captures_after_source_change(self, tmp_path, monkeypatch):
+ session = Session("preview_live")
+ session.new_project()
+ project_path = tmp_path / "poll-demo.mlt"
+ session.save_project(str(project_path))
+ bundle_a = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+ bundle_b = self._fake_bundle(tmp_path / "bundles", "bundle-b")
+ manifests = [dict(bundle_a), dict(bundle_b)]
+ calls = []
+
+ def fake_capture(*args, **kwargs):
+ calls.append(kwargs.get("command"))
+ return manifests.pop(0)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ started = preview_mod.live_start(
+ session,
+ root_dir=str(tmp_path),
+ live_mode="poll",
+ source_poll_ms=preview_mod.MIN_SOURCE_POLL_MS,
+ )
+ started_session_dir = Path(started["_session_dir"])
+ session_payload = json.loads(Path(started["_session_path"]).read_text())
+ session_payload["source_state"]["last_rendered_fingerprint"] = "sha256:stale"
+ Path(started["_session_path"]).write_text(json.dumps(session_payload, indent=2))
+
+ result = preview_mod.poll_live_session_once(str(started_session_dir))
+ refreshed = json.loads(Path(started["_session_path"]).read_text())
+ assert result["action"] == "captured"
+ assert refreshed["current_bundle_id"] == "bundle-b"
+ assert refreshed["source_state"]["last_rendered_fingerprint"].startswith("sha256:")
+ assert refreshed["poller"]["last_capture_status"] == "ok"
+ assert calls
+
+ def test_poll_live_session_once_exits_for_manual_mode(self, tmp_path, monkeypatch):
+ session = Session("preview_live")
+ session.new_project()
+ project_path = tmp_path / "manual-demo.mlt"
+ session.save_project(str(project_path))
+ bundle_manifest = self._fake_bundle(tmp_path / "bundles", "bundle-a")
+
+ def fake_capture(*args, **kwargs):
+ return dict(bundle_manifest)
+
+ monkeypatch.setattr(preview_mod, "capture", fake_capture)
+
+ started = preview_mod.live_start(session, root_dir=str(tmp_path), live_mode="manual")
+ result = preview_mod.poll_live_session_once(started["_session_dir"])
+ refreshed = json.loads(Path(started["_session_path"]).read_text())
+ assert result["action"] == "exit"
+ assert refreshed["poller"]["running"] is False
+ assert refreshed["poller"]["last_exit_reason"] == "live-mode:manual"
+
+
# ============================================================================
# Project module
# ============================================================================
diff --git a/shotcut/agent-harness/cli_anything/shotcut/tests/test_full_e2e.py b/shotcut/agent-harness/cli_anything/shotcut/tests/test_full_e2e.py
index 53e4a56b8..ee26b0279 100644
--- a/shotcut/agent-harness/cli_anything/shotcut/tests/test_full_e2e.py
+++ b/shotcut/agent-harness/cli_anything/shotcut/tests/test_full_e2e.py
@@ -11,7 +11,8 @@ import json
import shutil
import tempfile
import subprocess
-
+import re
+import time
import pytest
from PIL import Image, ImageStat
@@ -24,10 +25,24 @@ from cli_anything.shotcut.core import filters as filt_mod
from cli_anything.shotcut.core import media as media_mod
from cli_anything.shotcut.core import export as export_mod
from cli_anything.shotcut.core import transitions as trans_mod
+from cli_anything.shotcut.core import preview as preview_mod
+from cli_anything.shotcut.utils.time import (
+ timecode_to_frames, frames_to_timecode, parse_time_input,
+ frames_to_seconds, seconds_to_frames, format_duration,
+)
from cli_anything.shotcut.utils.mlt_xml import (
get_property, get_all_producers, create_producer,
)
+VIDEO = "/root/shotcut/1.mp4"
+PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
+
+
+def video():
+ """Ensure the test video exists."""
+ assert os.path.isfile(VIDEO), f"Test video not found: {VIDEO}"
+ return VIDEO
@pytest.fixture
def session():
@@ -44,6 +59,95 @@ def session_with_tracks(session):
return session
[email protected](scope="module")
+def preview_video():
+ """Create a colorful deterministic source video for preview verification."""
+ tmpdir = tempfile.mkdtemp()
+ video_path = os.path.join(tmpdir, "preview_source.mp4")
+ try:
+ subprocess.run(
+ [
+ "ffmpeg",
+ "-y",
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc=duration=5:size=1280x720:rate=30",
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=frequency=440:duration=5",
+ "-c:v",
+ "libx264",
+ "-c:a",
+ "aac",
+ "-shortest",
+ video_path,
+ ],
+ capture_output=True,
+ check=True,
+ timeout=60,
+ )
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ pytest.skip("ffmpeg not available")
+
+ yield video_path
+
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def _artifact_path(manifest, artifact_id):
+ for artifact in manifest["artifacts"]:
+ if artifact["artifact_id"] == artifact_id:
+ return os.path.join(manifest["_bundle_dir"], artifact["path"])
+ raise KeyError(f"Artifact not found: {artifact_id}")
+
+
+def _assert_png(path):
+ assert os.path.isfile(path), f"Missing PNG artifact: {path}"
+ with open(path, "rb") as fh:
+ assert fh.read(8) == PNG_MAGIC, f"Invalid PNG header: {path}"
+ assert os.path.getsize(path) > 0, f"Empty PNG artifact: {path}"
+
+
+def _luma_yavg(path):
+ result = subprocess.run(
+ [
+ "ffmpeg",
+ "-hide_banner",
+ "-i",
+ path,
+ "-vf",
+ "signalstats,metadata=print:file=-",
+ "-frames:v",
+ "1",
+ "-f",
+ "null",
+ "-",
+ ],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=True,
+ )
+ match = re.search(r"lavfi\.signalstats\.YAVG=([0-9.]+)", result.stdout + result.stderr)
+ if not match:
+ raise AssertionError(f"Could not determine YAVG for {path}")
+ return float(match.group(1))
+
+
+def _wait_for_live_bundle_count(session_path, expected_count, timeout_s=20.0):
+ deadline = time.time() + timeout_s
+ latest = None
+ while time.time() < deadline:
+ with open(session_path, "r", encoding="utf-8") as fh:
+ latest = json.load(fh)
+ if latest.get("bundle_count", 0) >= expected_count:
+ return latest
+ time.sleep(0.5)
+ raise AssertionError(f"Timed out waiting for bundle_count >= {expected_count}: {latest}")
+
+
# ============================================================================
# 1. SAVE / LOAD ROUNDTRIP
# ============================================================================
@@ -640,12 +744,14 @@ def _resolve_cli(name, force=False):
class TestCLISubprocess:
CLI_BASE = _resolve_cli("cli-anything-shotcut")
- def _run(self, *args, json_mode=False):
+ def _run(self, *args, json_mode=False, timeout=30):
+ import subprocess
cmd = list(self.CLI_BASE)
if json_mode:
cmd.append("--json")
cmd.extend(args)
- return subprocess.run(cmd, capture_output=True, text=True, timeout=30)
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
+ return result
def test_help(self):
r = self._run("--help")
@@ -689,6 +795,214 @@ class TestCLISubprocess:
assert r.returncode == 0
assert os.path.basename(video) in r.stdout
+ def test_preview_capture_json(self, preview_video):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ project_path = os.path.join(tmp_dir, "preview_source.mlt")
+
+ session = Session()
+ proj_mod.new_project(session, "hd1080p30")
+ tl_mod.add_track(session, "video", "Preview")
+ tl_mod.add_clip(
+ session,
+ preview_video,
+ 1,
+ in_point="00:00:00.000",
+ out_point="00:00:03.000",
+ caption="Preview Shot",
+ )
+ filt_mod.add_filter(
+ session,
+ "brightness",
+ track_index=1,
+ clip_index=0,
+ params={"level": "1.15"},
+ )
+ proj_mod.save_project(session, project_path)
+
+ result = self._run(
+ "--project",
+ project_path,
+ "preview",
+ "capture",
+ "--root-dir",
+ tmp_dir,
+ json_mode=True,
+ timeout=180,
+ )
+ assert result.returncode == 0, result.stderr
+
+ manifest = json.loads(result.stdout)
+ assert manifest["software"] == "shotcut"
+ assert manifest["bundle_kind"] == "capture"
+ assert manifest["status"] in ("ok", "partial")
+ clip_path = _artifact_path(manifest, "clip")
+ hero_path = _artifact_path(manifest, "frame_03")
+ assert manifest["artifacts"][0]["render_method"] == "ffmpeg-filtergraph"
+ assert os.path.isfile(clip_path)
+ _assert_png(hero_path)
+ assert _luma_yavg(hero_path) > 10.0
+
+ latest = self._run(
+ "preview",
+ "latest",
+ "--recipe",
+ "quick",
+ "--root-dir",
+ tmp_dir,
+ json_mode=True,
+ timeout=60,
+ )
+ assert latest.returncode == 0, latest.stderr
+ latest_manifest = json.loads(latest.stdout)
+ assert latest_manifest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n Shotcut preview bundle: {manifest['_bundle_dir']}")
+ print(f" Shotcut preview clip: {clip_path}")
+ print(f" Shotcut preview hero: {hero_path}")
+
+ def test_preview_live_poll_auto_refresh(self, preview_video):
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ project_path = os.path.join(tmp_dir, "preview_live_poll.mlt")
+ live_root = os.path.join(tmp_dir, "live-root")
+
+ r = self._run("project", "new", "--profile", "hd1080p30", "-o", project_path, timeout=60)
+ assert r.returncode == 0, r.stderr
+
+ r = self._run("-s", "--project", project_path, "timeline", "add-track", "--type", "video", "--name", "Preview", timeout=60)
+ assert r.returncode == 0, r.stderr
+
+ r = self._run(
+ "-s",
+ "--project",
+ project_path,
+ "timeline",
+ "add-clip",
+ preview_video,
+ "--track",
+ "1",
+ "--in",
+ "00:00:00.000",
+ "--out",
+ "00:00:04.000",
+ "--caption",
+ "Preview Clip",
+ timeout=60,
+ )
+ assert r.returncode == 0, r.stderr
+
+ started = self._run(
+ "--json",
+ "--project",
+ project_path,
+ "preview",
+ "live",
+ "start",
+ "--recipe",
+ "quick",
+ "--mode",
+ "poll",
+ "--source-poll-ms",
+ "500",
+ "--poll-ms",
+ "700",
+ "--root-dir",
+ live_root,
+ timeout=180,
+ )
+ assert started.returncode == 0, started.stderr
+ started_payload = json.loads(started.stdout)
+ session_path = started_payload["_session_path"]
+ assert started_payload["bundle_count"] == 1
+ assert started_payload["live_mode"] == "poll"
+
+ try:
+ changed = self._run(
+ "-s",
+ "--project",
+ project_path,
+ "filter",
+ "add",
+ "brightness",
+ "--track",
+ "1",
+ "--clip",
+ "0",
+ "--param",
+ "level=1.35",
+ timeout=60,
+ )
+ assert changed.returncode == 0, changed.stderr
+
+ session_payload = _wait_for_live_bundle_count(session_path, 2, timeout_s=20.0)
+ assert session_payload["bundle_count"] >= 2
+ assert session_payload["source_state"]["last_publish_reason"] == "auto-poll"
+ assert session_payload["poller"]["running"] is True
+
+ print(f"\n Shotcut poll session: {session_payload['_session_dir'] if '_session_dir' in session_payload else os.path.dirname(session_path)}")
+ print(f" Shotcut poll bundle count: {session_payload['bundle_count']}")
+ print(f" Shotcut poll current bundle: {session_payload['current_bundle_id']}")
+ finally:
+ stopped = self._run(
+ "--project",
+ project_path,
+ "preview",
+ "live",
+ "stop",
+ "--root-dir",
+ live_root,
+ timeout=60,
+ )
+ assert stopped.returncode == 0, stopped.stderr
+
+
+class TestPreviewE2E:
+ def test_capture_preview_bundle(self, session, preview_video):
+ tl_mod.add_track(session, "video", "Preview")
+ tl_mod.add_clip(
+ session,
+ preview_video,
+ 1,
+ in_point="00:00:00.000",
+ out_point="00:00:04.000",
+ caption="Preview Clip",
+ )
+ filt_mod.add_filter(
+ session,
+ "brightness",
+ track_index=1,
+ clip_index=0,
+ params={"level": "1.25"},
+ )
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ project_path = os.path.join(tmp_dir, "preview_capture.mlt")
+ proj_mod.save_project(session, project_path)
+
+ manifest = preview_mod.capture(session, root_dir=tmp_dir, force=True)
+ assert manifest["software"] == "shotcut"
+ assert manifest["bundle_kind"] == "capture"
+ assert manifest["status"] in ("ok", "partial")
+
+ clip_path = _artifact_path(manifest, "clip")
+ hero_path = _artifact_path(manifest, "frame_03")
+ probe = media_mod.probe_media(clip_path)
+ video_stream = (probe.get("video_streams") or [{}])[0]
+
+ assert os.path.isfile(clip_path)
+ assert os.path.getsize(clip_path) > 0
+ assert manifest["artifacts"][0]["render_method"] == "ffmpeg-filtergraph"
+ assert int(video_stream.get("width") or 0) == 640
+ assert int(video_stream.get("height") or 0) == 360
+ _assert_png(hero_path)
+ assert _luma_yavg(hero_path) > 10.0
+
+ latest = preview_mod.latest(project_path=project_path, recipe="quick", root_dir=tmp_dir)
+ assert latest["bundle_id"] == manifest["bundle_id"]
+
+ print(f"\n Shotcut preview bundle: {manifest['_bundle_dir']}")
+ print(f" Shotcut preview clip: {clip_path}")
+ print(f" Shotcut preview hero: {hero_path}")
+
# ============================================================================
# 9. MELT BACKEND + RENDER
diff --git a/shotcut/agent-harness/cli_anything/shotcut/utils/preview_bundle.py b/shotcut/agent-harness/cli_anything/shotcut/utils/preview_bundle.py
new file mode 100644
index 000000000..3cba5dbf0
--- /dev/null
+++ b/shotcut/agent-harness/cli_anything/shotcut/utils/preview_bundle.py
@@ -0,0 +1,304 @@
+"""Shared helpers for CLI-Anything preview bundles."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import mimetypes
+import os
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, Iterable, Optional
+
+PROTOCOL_VERSION = "preview-bundle/v1"
+
+
+def _slug(value: str) -> str:
+ text = (value or "preview").strip().lower()
+ text = re.sub(r"[^a-z0-9]+", "-", text)
+ text = re.sub(r"-{2,}", "-", text).strip("-")
+ return text or "preview"
+
+
+def _json_dumps(data: Any) -> str:
+ return json.dumps(
+ data,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ default=str,
+ )
+
+
+def hash_data(data: Any) -> str:
+ return hashlib.sha256(_json_dumps(data).encode("utf-8")).hexdigest()
+
+
+def fingerprint_data(data: Any) -> str:
+ return f"sha256:{hash_data(data)}"
+
+
+def fingerprint_file(path: str) -> str:
+ resolved = os.path.abspath(path)
+ stat = os.stat(resolved)
+ return fingerprint_data(
+ {
+ "path": resolved,
+ "size": stat.st_size,
+ "mtime_ns": stat.st_mtime_ns,
+ }
+ )
+
+
+def bundle_root(
+ software: str,
+ recipe: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Path:
+ if root_dir:
+ base = Path(root_dir).expanduser().resolve()
+ elif project_path:
+ base = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews"
+ else:
+ base = Path.home() / ".cli-anything" / "previews"
+ return base / _slug(software) / _slug(recipe)
+
+
+def build_cache_key(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ protocol_version: str = PROTOCOL_VERSION,
+) -> str:
+ return fingerprint_data(
+ {
+ "protocol_version": protocol_version,
+ "software": software,
+ "recipe": recipe,
+ "bundle_kind": bundle_kind,
+ "source_fingerprint": source_fingerprint,
+ "options": options or {},
+ "harness_version": harness_version or "",
+ }
+ )
+
+
+def _iter_manifests(search_root: Path) -> Iterable[Path]:
+ if not search_root.exists():
+ return []
+ return sorted(search_root.rglob("manifest.json"), reverse=True)
+
+
+def _load_json(path: Path) -> Dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def find_cached_manifest(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ cache_key: str,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ root = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir)
+ for manifest_path in _iter_manifests(root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if (
+ manifest.get("protocol_version") == PROTOCOL_VERSION
+ and manifest.get("software") == software
+ and manifest.get("recipe") == recipe
+ and manifest.get("bundle_kind") == bundle_kind
+ and manifest.get("status") in {"ok", "partial"}
+ and manifest.get("cache_key") == cache_key
+ ):
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def find_latest_manifest(
+ software: str,
+ recipe: Optional[str] = None,
+ bundle_kind: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+) -> Optional[Dict[str, Any]]:
+ if root_dir:
+ search_root = Path(root_dir).expanduser().resolve() / _slug(software)
+ elif project_path:
+ search_root = Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews" / _slug(software)
+ else:
+ search_root = Path.home() / ".cli-anything" / "previews" / _slug(software)
+ if recipe:
+ search_root = search_root / _slug(recipe)
+ for manifest_path in _iter_manifests(search_root):
+ try:
+ manifest = _load_json(manifest_path)
+ except (OSError, json.JSONDecodeError):
+ continue
+ if manifest.get("software") != software:
+ continue
+ if recipe and manifest.get("recipe") != recipe:
+ continue
+ if bundle_kind and manifest.get("bundle_kind") != bundle_kind:
+ continue
+ if manifest.get("status") not in {"ok", "partial"}:
+ continue
+ manifest["_manifest_path"] = str(manifest_path.resolve())
+ manifest["_bundle_dir"] = str(manifest_path.parent.resolve())
+ return manifest
+ return None
+
+
+def prepare_bundle(
+ software: str,
+ recipe: str,
+ bundle_kind: str,
+ source_fingerprint: str,
+ options: Optional[Dict[str, Any]] = None,
+ harness_version: Optional[str] = None,
+ project_path: Optional[str] = None,
+ root_dir: Optional[str] = None,
+ force: bool = False,
+) -> Dict[str, Any]:
+ cache_key = build_cache_key(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ source_fingerprint=source_fingerprint,
+ options=options or {},
+ harness_version=harness_version,
+ )
+ if not force:
+ cached = find_cached_manifest(
+ software=software,
+ recipe=recipe,
+ bundle_kind=bundle_kind,
+ cache_key=cache_key,
+ project_path=project_path,
+ root_dir=root_dir,
+ )
+ if cached:
+ return {
+ "cached": True,
+ "cache_key": cache_key,
+ "bundle_id": cached.get("bundle_id"),
+ "bundle_dir": cached["_bundle_dir"],
+ "manifest_path": cached["_manifest_path"],
+ "summary_path": os.path.join(cached["_bundle_dir"], cached.get("summary_path", "summary.json")),
+ "manifest": cached,
+ }
+
+ now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+ bundle_id = f"{now}_{cache_key.split(':', 1)[-1][:8]}_{_slug(recipe)}"
+ out_dir = bundle_root(software, recipe, project_path=project_path, root_dir=root_dir) / bundle_id
+ artifacts_dir = out_dir / "artifacts"
+ artifacts_dir.mkdir(parents=True, exist_ok=False)
+ return {
+ "cached": False,
+ "cache_key": cache_key,
+ "bundle_id": bundle_id,
+ "bundle_dir": str(out_dir.resolve()),
+ "artifacts_dir": str(artifacts_dir.resolve()),
+ "manifest_path": str((out_dir / "manifest.json").resolve()),
+ "summary_path": str((out_dir / "summary.json").resolve()),
+ }
+
+
+def artifact_record(
+ bundle_dir: str,
+ path: str,
+ artifact_id: str,
+ role: str,
+ kind: str,
+ label: str,
+ media_type: Optional[str] = None,
+ **extra: Any,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ file_path = Path(path).resolve()
+ rel_path = file_path.relative_to(bundle_path).as_posix()
+ record: Dict[str, Any] = {
+ "artifact_id": artifact_id,
+ "role": role,
+ "kind": kind,
+ "label": label,
+ "media_type": media_type or mimetypes.guess_type(str(file_path))[0] or "application/octet-stream",
+ "path": rel_path,
+ }
+ if file_path.exists():
+ record["bytes"] = file_path.stat().st_size
+ record.update({k: v for k, v in extra.items() if v is not None})
+ return record
+
+
+def write_json(path: str, data: Any) -> str:
+ output_path = Path(path).resolve()
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(output_path, "w", encoding="utf-8") as fh:
+ json.dump(data, fh, indent=2, ensure_ascii=False, default=str)
+ fh.write("\n")
+ return str(output_path)
+
+
+def finalize_bundle(
+ bundle_dir: str,
+ bundle_id: str,
+ bundle_kind: str,
+ software: str,
+ recipe: str,
+ source: Dict[str, Any],
+ artifacts: list[Dict[str, Any]],
+ summary: Dict[str, Any],
+ cache_key: str,
+ generator: Dict[str, Any],
+ status: str = "ok",
+ warnings: Optional[list[str]] = None,
+ context: Optional[Dict[str, Any]] = None,
+ metrics: Optional[Dict[str, Any]] = None,
+ labels: Optional[list[str]] = None,
+ source_bundles: Optional[list[Dict[str, Any]]] = None,
+) -> Dict[str, Any]:
+ bundle_path = Path(bundle_dir).resolve()
+ summary_rel = "summary.json"
+ summary_path = write_json(str(bundle_path / summary_rel), summary)
+ manifest = {
+ "protocol_version": PROTOCOL_VERSION,
+ "bundle_id": bundle_id,
+ "bundle_kind": bundle_kind,
+ "software": software,
+ "recipe": recipe,
+ "status": status,
+ "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
+ "cache_key": cache_key,
+ "generator": generator,
+ "source": source,
+ "summary_path": summary_rel,
+ "artifacts": artifacts,
+ }
+ if warnings:
+ manifest["warnings"] = warnings
+ if context:
+ manifest["context"] = context
+ if metrics:
+ manifest["metrics"] = metrics
+ if labels:
+ manifest["labels"] = labels
+ if source_bundles:
+ manifest["source_bundles"] = source_bundles
+ manifest_path = write_json(str(bundle_path / "manifest.json"), manifest)
+ manifest["_manifest_path"] = manifest_path
+ manifest["_bundle_dir"] = str(bundle_path)
+ manifest["_summary_path"] = summary_path
+ return manifest