Skip to content

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

Python

feat(blender): add live preview sessions and gyro observatory demo

yuhao6079b1878439
diff --git a/blender/agent-harness/cli_anything/blender/blender_cli.py b/blender/agent-harness/cli_anything/blender/blender_cli.py
index 4816d4f60..f468b6b03 100644
--- a/blender/agent-harness/cli_anything/blender/blender_cli.py
+++ b/blender/agent-harness/cli_anything/blender/blender_cli.py
@@ -18,6 +18,8 @@ import sys
import os
import json
import shlex
+import shutil
+import subprocess
import click
from typing import Optional
@@ -61,6 +63,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 Blender live preview poller in the background."""
+ cli_path = shutil.which("cli-anything-blender")
+ if cli_path:
+ command = [cli_path, "preview", "live", "monitor", "--session-dir", session_dir]
+ else:
+ command = [
+ sys.executable,
+ "-m",
+ "cli_anything.blender.blender_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):
prefix = " " * indent
for k, v in d.items():
@@ -820,6 +893,12 @@ def preview_group():
pass
+@preview_group.group("live")
+def preview_live_group():
+ """Live preview session management."""
+ pass
+
+
@preview_group.command("recipes")
@handle_error
def preview_recipes():
@@ -858,6 +937,94 @@ def preview_latest(recipe, root_dir):
output(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, force, root_dir, poll_ms, mode, source_poll_ms, open_window):
+ """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-blender --project {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(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, force, root_dir, poll_ms):
+ """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,
+ command=(
+ f"cli-anything-blender --project {sess.project_path or ''} "
+ f"preview live push --recipe {recipe}"
+ ).strip(),
+ )
+ output(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, root_dir):
+ """Show live preview session metadata."""
+ sess = get_session()
+ result = preview_mod.live_status(sess, recipe=recipe, root_dir=root_dir)
+ output(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, root_dir):
+ """Stop the live preview session without deleting artifacts."""
+ sess = get_session()
+ result = preview_mod.live_stop(sess, recipe=recipe, root_dir=root_dir)
+ output(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):
+ """Internal background poller for live preview sessions."""
+ result = preview_mod.run_live_poller(session_dir)
+ output(result, "")
+
+
# ── Session Commands ────────────────────────────────────────────
@cli.group()
def session():
@@ -931,7 +1098,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",
+ "preview": "recipes|capture|latest|live start|push|status|stop",
"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
index 0048f1259..a9ae855e0 100644
--- a/blender/agent-harness/cli_anything/blender/core/preview.py
+++ b/blender/agent-harness/cli_anything/blender/core/preview.py
@@ -1,9 +1,15 @@
-"""Preview bundle generation for the Blender harness."""
+"""Preview bundle generation and live polling for the Blender harness."""
from __future__ import annotations
import copy
+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, Tuple
from ..utils import blender_backend
@@ -12,13 +18,19 @@ from ..utils.preview_bundle import (
finalize_bundle,
find_latest_manifest,
fingerprint_data,
+ fingerprint_file,
prepare_bundle,
)
from . import render as render_mod
+from . import scene as scene_mod
from .lighting import add_camera, add_light
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": {
@@ -47,12 +59,171 @@ def list_recipes() -> List[Dict[str, Any]]:
def _project_fingerprint(session: Session) -> str:
project = session.get_project()
- return fingerprint_data(
- {
- "project_path": session.project_path,
- "project": 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 _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() / "blender"
+ if project_path:
+ return Path(project_path).expanduser().resolve().parent / ".cli-anything" / "previews" / "blender"
+ return Path.home() / ".cli-anything" / "previews" / "blender"
+
+
+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 _ensure_preview_rig(project: Dict[str, Any]) -> List[str]:
@@ -282,3 +453,374 @@ def latest(
if manifest is None:
raise FileNotFoundError("No Blender 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")
+ )
+ current_refresh_hint_ms = int(refresh_hint_ms or existing.get("refresh_hint_ms") or DEFAULT_REFRESH_HINT_MS)
+ project_flag = f" --project {session.project_path}" if session.project_path else ""
+ root_flag = f" --root-dir {root_dir}" if root_dir 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": "blender",
+ "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": current_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-blender{project_flag} preview live push --recipe {recipe}{root_flag}"
+ ).strip(),
+ "watch_command": (
+ f"cli-hub preview watch {session_dir} --open --poll-ms {current_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-blender{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-blender 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: Optional[int] = None,
+ command: Optional[str] = None,
+ publish_reason: str = "manual-push",
+) -> Dict[str, Any]:
+ """Publish a fresh preview bundle into the current live session."""
+ existing_mode = "manual"
+ existing_source_poll_ms = DEFAULT_SOURCE_POLL_MS
+ try:
+ existing = live_status(session, recipe=recipe, root_dir=root_dir)
+ existing_mode = existing.get("live_mode") or "manual"
+ existing_source_poll_ms = int(existing.get("source_poll_ms") or DEFAULT_SOURCE_POLL_MS)
+ except FileNotFoundError:
+ pass
+ return live_start(
+ session,
+ recipe=recipe,
+ root_dir=root_dir,
+ force=force,
+ refresh_hint_ms=refresh_hint_ms,
+ live_mode=existing_mode,
+ source_poll_ms=int(source_poll_ms or existing_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 Blender 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 = scene_mod.open_scene(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-blender preview live monitor --session-dir {session_path}"),
+ publish_reason="auto-poll",
+ )
+ render_time = _now_iso()
+ _write_live_session_updates(
+ session_path,
+ {
+ "poller": {
+ "pid": os.getpid(),
+ "running": True,
+ "last_heartbeat": now,
+ "last_capture_status": "ok",
+ "last_capture_finished_at": render_time,
+ },
+ "source_state": {
+ "last_seen_fingerprint": current_fingerprint,
+ "last_rendered_fingerprint": current_fingerprint,
+ "last_rendered_at": render_time,
+ "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:
+ error_time = _now_iso()
+ _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": error_time,
+ },
+ "source_state": {
+ "last_seen_fingerprint": current_fingerprint,
+ "last_error": str(exc),
+ "last_error_at": error_time,
+ },
+ },
+ )
+ 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/blender/agent-harness/cli_anything/blender/tests/test_core.py b/blender/agent-harness/cli_anything/blender/tests/test_core.py
index e689c12f5..fb9e6f0a7 100644
--- a/blender/agent-harness/cli_anything/blender/tests/test_core.py
+++ b/blender/agent-harness/cli_anything/blender/tests/test_core.py
@@ -1039,6 +1039,34 @@ class TestSession:
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", "workbench"):
+ (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": "Blender quick preview",
+ "facts": {"views": 2, "engine": "EEVEE"},
+ }
+ ),
+ encoding="utf-8",
+ )
+ manifest_path = bundle_dir / "manifest.json"
+ manifest_path.write_text(json.dumps({"bundle_id": bundle_id, "status": "ok"}), encoding="utf-8")
+ 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
@@ -1084,3 +1112,153 @@ class TestPreview:
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_scene(name="LivePreviewScene")
+ project_path = tmp_path / "live-demo.json"
+ save_scene(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_scene(name="LivePreviewScene")
+ project_path = tmp_path / "live-demo.json"
+ save_scene(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="manual")
+ 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_scene(name="LivePreviewScene")
+ project_path = tmp_path / "live-demo.json"
+ save_scene(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), live_mode="manual")
+ 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_scene(name="StablePreviewScene")
+ save_scene(proj, str(project_path))
+
+ session_a = Session()
+ session_a.set_project(proj, str(project_path))
+
+ session_b = Session()
+ session_b.set_project(open_scene(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_scene(name="StablePreviewScene")
+ save_scene(proj, str(project_path))
+
+ session_a = Session()
+ session_a.set_project(proj, str(project_path))
+
+ session_b = Session()
+ session_b.set_project(open_scene(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_scene(name="PollingPreviewScene")
+ project_path = tmp_path / "polling-demo.json"
+ save_scene(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_scene(str(project_path))
+ add_object(updated, mesh_type="cube", name="ChangedCube")
+ save_scene(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_scene(name="ManualPreviewScene")
+ project_path = tmp_path / "manual-demo.json"
+ save_scene(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"
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 dec61089c..c87a38509 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
@@ -10,6 +10,7 @@ import os
import sys
import tempfile
import subprocess
+import time
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
@@ -49,6 +50,18 @@ def _assert_png(path):
assert os.path.getsize(path) > 0, f"Empty PNG artifact: {path}"
+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}")
+
+
# ── Scene Lifecycle ─────────────────────────────────────────────
class TestSceneLifecycle:
@@ -704,8 +717,122 @@ class TestCLISubprocess:
print(f" Blender preview hero: {hero_path}")
print(f" Blender preview workbench: {workbench_path}")
+ def test_cli_preview_live_manual_session(self, tmp_dir):
+ proj_path = os.path.join(tmp_dir, "preview_live_manual.json")
+ live_root = os.path.join(tmp_dir, "live-root")
+
+ proj = create_scene(name="cli-live-manual", profile="preview")
+ add_object(proj, mesh_type="plane", name="Ground", scale=[5, 5, 1])
+ add_object(proj, mesh_type="torus", name="RingA", location=[0, 0, 1.3], rotation=[90, 0, 0])
+ add_object(proj, mesh_type="sphere", name="Core", location=[0, 0, 1.3], scale=[0.55, 0.55, 0.55])
+ create_material(proj, name="Brass", color=[0.83, 0.7, 0.28, 1.0], metallic=0.85, roughness=0.25)
+ create_material(proj, name="CoreGlow", color=[0.2, 0.85, 1.0, 1.0], metallic=0.0, roughness=0.1)
+ set_material_property(proj, 1, "emission_color", [0.2, 0.85, 1.0, 1.0])
+ set_material_property(proj, 1, "emission_strength", 3.5)
+ assign_material(proj, 0, 1)
+ assign_material(proj, 1, 2)
+ add_camera(proj, name="MainCam", location=[7, -7, 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)
+
+ started = self._run(
+ [
+ "--json",
+ "--project",
+ proj_path,
+ "preview",
+ "live",
+ "start",
+ "--recipe",
+ "quick",
+ "--mode",
+ "manual",
+ "--root-dir",
+ live_root,
+ ],
+ check=False,
+ timeout=240,
+ )
+ assert started.returncode == 0, started.stderr
+ started_payload = json.loads(started.stdout)
+ assert started_payload["live_mode"] == "manual"
+ assert started_payload["bundle_count"] == 1
+ session_path = started_payload["_session_path"]
+ assert os.path.isfile(session_path)
+
+ status = self._run(
+ [
+ "--json",
+ "--project",
+ proj_path,
+ "preview",
+ "live",
+ "status",
+ "--recipe",
+ "quick",
+ "--root-dir",
+ live_root,
+ ],
+ check=False,
+ timeout=60,
+ )
+ assert status.returncode == 0, status.stderr
+ status_payload = json.loads(status.stdout)
+ assert status_payload["current_bundle_id"] == started_payload["current_bundle_id"]
+
+ pushed = self._run(
+ [
+ "--json",
+ "--project",
+ proj_path,
+ "preview",
+ "live",
+ "push",
+ "--recipe",
+ "quick",
+ "--force",
+ "--root-dir",
+ live_root,
+ ],
+ check=False,
+ timeout=240,
+ )
+ assert pushed.returncode == 0, pushed.stderr
+ pushed_payload = json.loads(pushed.stdout)
+ assert pushed_payload["bundle_count"] >= 2
+
+ stopped = self._run(
+ [
+ "--json",
+ "--project",
+ proj_path,
+ "preview",
+ "live",
+ "stop",
+ "--recipe",
+ "quick",
+ "--root-dir",
+ live_root,
+ ],
+ check=False,
+ timeout=60,
+ )
+ assert stopped.returncode == 0, stopped.stderr
+ stopped_payload = json.loads(stopped.stdout)
+ assert stopped_payload["status"] == "stopped"
+
class TestPreviewE2E:
+ @staticmethod
+ def _run_cli(args, check=False, timeout=240):
+ return subprocess.run(
+ TestCLISubprocess.CLI_BASE + args,
+ capture_output=True,
+ text=True,
+ check=check,
+ timeout=timeout,
+ )
+
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])
@@ -748,6 +875,109 @@ class TestPreviewE2E:
print(f" Blender preview hero: {hero_path}")
print(f" Blender preview workbench: {workbench_path}")
+ def test_preview_live_poll_auto_refresh(self, tmp_dir):
+ proj_path = os.path.join(tmp_dir, "preview_live_poll.json")
+ live_root = os.path.join(tmp_dir, "live-root")
+
+ proj = create_scene(name="poll-live", profile="preview")
+ add_object(proj, mesh_type="plane", name="Ground", scale=[6, 6, 1])
+ add_object(proj, mesh_type="torus", name="RingA", location=[0, 0, 1.35], rotation=[90, 0, 0])
+ add_object(proj, mesh_type="sphere", name="Core", location=[0, 0, 1.35], scale=[0.45, 0.45, 0.45])
+ create_material(proj, name="Bronze", color=[0.79, 0.58, 0.24, 1.0], metallic=0.9, roughness=0.22)
+ create_material(proj, name="AzureCore", color=[0.22, 0.7, 0.95, 1.0], metallic=0.0, roughness=0.12)
+ set_material_property(proj, 1, "emission_color", [0.22, 0.7, 0.95, 1.0])
+ set_material_property(proj, 1, "emission_strength", 4.2)
+ assign_material(proj, 0, 1)
+ assign_material(proj, 1, 2)
+ add_camera(proj, name="MainCam", location=[7.5, -7.0, 5.5], rotation=[63, 0, 46], set_active=True)
+ add_light(proj, light_type="SUN", name="Sun", rotation=[-42, 0, 30], power=2.5)
+ save_scene(proj, proj_path)
+
+ started = self._run_cli(
+ [
+ "--json",
+ "--project",
+ proj_path,
+ "preview",
+ "live",
+ "start",
+ "--recipe",
+ "quick",
+ "--mode",
+ "poll",
+ "--source-poll-ms",
+ "500",
+ "--poll-ms",
+ "700",
+ "--root-dir",
+ live_root,
+ ],
+ check=False,
+ timeout=240,
+ )
+ assert started.returncode == 0, started.stderr
+ started_payload = json.loads(started.stdout)
+ assert started_payload["bundle_count"] == 1
+ assert started_payload["live_mode"] == "poll"
+ session_path = started_payload["_session_path"]
+
+ try:
+ changed = self._run_cli(
+ [
+ "--json",
+ "--project",
+ proj_path,
+ "object",
+ "add",
+ "torus",
+ "--name",
+ "RingB",
+ "--location",
+ "0,0,1.35",
+ "--rotation",
+ "0,90,0",
+ "--scale",
+ "0.7,0.7,0.7",
+ ],
+ check=False,
+ timeout=90,
+ )
+ assert changed.returncode == 0, changed.stderr
+
+ session_payload = _wait_for_live_bundle_count(session_path, 2, timeout_s=45.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 Blender poll session: {os.path.dirname(session_path)}")
+ print(f" Blender live hero: {hero_path}")
+ finally:
+ stopped = self._run_cli(
+ [
+ "--json",
+ "--project",
+ proj_path,
+ "preview",
+ "live",
+ "stop",
+ "--recipe",
+ "quick",
+ "--root-dir",
+ live_root,
+ ],
+ check=False,
+ timeout=60,
+ )
+ assert stopped.returncode == 0, stopped.stderr
+
# ── Script Validity Tests ───────────────────────────────────────
diff --git a/docs/PREVIEW_MECHANISM_PROGRESS.md b/docs/PREVIEW_MECHANISM_PROGRESS.md
index 655b15fa3..93b409d03 100644
--- a/docs/PREVIEW_MECHANISM_PROGRESS.md
+++ b/docs/PREVIEW_MECHANISM_PROGRESS.md
@@ -81,9 +81,10 @@ The current mechanism is built as five layers:
- bundle emission
- `blender`
- - preview capture support exists
- - current branch contains first-pass implementation only
- - next active work should continue here
+ - preview capture
+ - live session
+ - poll-mode auto refresh
+ - real Gyro Observatory demo script with stage-by-stage preview checkpoints
- `freecad`
- quick preview capture
@@ -155,12 +156,12 @@ Current limits:
- FreeCAD motion is currently part-placement driven, not Assembly-joint driven
- RenderDoc preview is limited by machine graphics/runtime constraints when
generating fresh captures locally
-- Blender preview has the least polish among the currently implemented preview
- pilots and is the most obvious next target
+- Blender now has live preview parity at the protocol/session level, but its
+ showcase/demo tooling is still shallower than FreeCAD's motion/video stack
## Recommended Next Work
-1. Continue Blender previewing on top of this checkpoint.
+1. Expand Blender demo tooling beyond the first Gyro Observatory proof point.
2. Restack this preview branch onto a clean `origin/main` base before the PR
stack grows larger.
3. Split this large checkpoint into a reviewable commit stack later:
diff --git a/docs/PREVIEW_PROGRESS.md b/docs/PREVIEW_PROGRESS.md
index 2632c1286..16f96c477 100644
--- a/docs/PREVIEW_PROGRESS.md
+++ b/docs/PREVIEW_PROGRESS.md
@@ -40,8 +40,11 @@ The current shape is:
## New In This Iteration
-The preview branch now has working first-pass live popup preview loops for
-`shotcut` and `freecad`.
+The preview branch now has working live popup preview loops for:
+
+- `shotcut`
+- `freecad`
+- `blender`
The current FreeCAD demo selection notes now live in:
@@ -104,6 +107,19 @@ What was added:
- `orbital-relay`
- `empire-state-building`
- `taipei-101`
+- `blender` live session lifecycle:
+ - `preview live start`
+ - `preview live push`
+ - `preview live status`
+ - `preview live stop`
+- `blender` producer-side auto polling:
+ - `preview live start --mode poll --source-poll-ms ...`
+ - hidden background `preview live monitor --session-dir ...`
+ - saved scene JSON fingerprint polling with automatic preview recapture
+ - demo tooling for `blender`:
+ - `docs/scripts/blender_gyro_observatory_demo.py`
+ - scenario:
+ - `gyro-observatory`
- `cli-hub` live viewer surface:
- `preview inspect` now understands live sessions
- `preview html` now renders live-session HTML
@@ -134,6 +150,12 @@ This is the intended cross-software direction.
- `blender`
- preview implementation works
- preview E2E passes
+ - live preview session lifecycle now works end-to-end
+ - automatic poll mode now works end-to-end without manual `preview live push`
+ - a real stage-by-stage `gyro-observatory` build now exists with:
+ - 4 preview bundle checkpoints
+ - a persisted live session
+ - a final 1600x1600 Blender still render
- `freecad`
- preview implementation works on the current Ubuntu machine after local
environment setup
@@ -225,6 +247,12 @@ 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`
+- Blender Gyro Observatory artifacts:
+ - `/root/preview-artifacts/20260422/blender-gyro-observatory/gyro_observatory.blend-cli.json`
+ - `/root/preview-artifacts/20260422/blender-gyro-observatory/live-root/blender/live/gyro-observatory-blend-cli-0043d42f-quick/session.json`
+ - `/root/preview-artifacts/20260422/blender-gyro-observatory/live-root/blender/quick/20260422T123252Z_a0409b02_quick/artifacts/hero.png`
+ - `/root/preview-artifacts/20260422/blender-gyro-observatory/live.html`
+ - `/root/preview-artifacts/20260422/blender-gyro-observatory/renders/gyro_observatory_final.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`
diff --git a/docs/scripts/blender_gyro_observatory_demo.py b/docs/scripts/blender_gyro_observatory_demo.py
new file mode 100644
index 000000000..c9cf73df9
--- /dev/null
+++ b/docs/scripts/blender_gyro_observatory_demo.py
@@ -0,0 +1,422 @@
+#!/usr/bin/env python3
+"""Build a complex Blender demo scene with real preview checkpoints."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Dict, List
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+BLENDER_HARNESS_ROOT = REPO_ROOT / "blender" / "agent-harness"
+sys.path.insert(0, str(BLENDER_HARNESS_ROOT))
+
+from cli_anything.blender.core import preview as preview_mod
+from cli_anything.blender.core.animation import add_keyframe, set_current_frame, set_frame_range, set_fps
+from cli_anything.blender.core.lighting import add_camera, add_light
+from cli_anything.blender.core.materials import assign_material, create_material, set_material_property
+from cli_anything.blender.core.modifiers import add_modifier
+from cli_anything.blender.core.objects import add_object
+from cli_anything.blender.core.render import set_render_settings, generate_bpy_script
+from cli_anything.blender.core.scene import create_scene, save_scene
+from cli_anything.blender.core.session import Session
+from cli_anything.blender.utils import blender_backend
+
+
+def _object_index(project: Dict, name: str) -> int:
+ for index, obj in enumerate(project.get("objects", [])):
+ if obj.get("name") == name:
+ return index
+ raise KeyError(f"Object not found: {name}")
+
+
+def _material_index(project: Dict, name: str) -> int:
+ for index, material in enumerate(project.get("materials", [])):
+ if material.get("name") == name:
+ return index
+ raise KeyError(f"Material not found: {name}")
+
+
+def _assign(project: Dict, material_name: str, object_name: str) -> None:
+ try:
+ object_index = _object_index(project, object_name)
+ except KeyError:
+ return
+ assign_material(project, _material_index(project, material_name), object_index)
+
+
+def _add_orbit_nodes(project: Dict, material_name: str) -> None:
+ radius = 3.25
+ for index in range(8):
+ angle = math.tau * index / 8.0
+ x = round(math.cos(angle) * radius, 4)
+ y = round(math.sin(angle) * radius, 4)
+ node_name = f"OrbitNode{index + 1:02d}"
+ add_object(
+ project,
+ mesh_type="sphere",
+ name=node_name,
+ location=[x, y, 3.15],
+ scale=[0.12, 0.12, 0.12],
+ mesh_params={"radius": 1.0, "segments": 20, "rings": 12},
+ )
+ _assign(project, material_name, node_name)
+
+
+def _build_blockout(project: Dict) -> None:
+ add_object(project, mesh_type="plane", name="Ground", mesh_params={"size": 20.0}, location=[0, 0, 0])
+ add_object(
+ project,
+ mesh_type="cylinder",
+ name="BasePlinth",
+ location=[0, 0, 0.42],
+ mesh_params={"radius": 2.9, "depth": 0.84, "vertices": 48},
+ )
+ add_modifier(project, "bevel", _object_index(project, "BasePlinth"), params={"width": 0.08, "segments": 3})
+ add_object(
+ project,
+ mesh_type="cylinder",
+ name="InnerDais",
+ location=[0, 0, 1.02],
+ mesh_params={"radius": 1.95, "depth": 0.38, "vertices": 48},
+ )
+ add_modifier(project, "bevel", _object_index(project, "InnerDais"), params={"width": 0.04, "segments": 2})
+ add_object(
+ project,
+ mesh_type="sphere",
+ name="CoreSphere",
+ location=[0, 0, 3.2],
+ scale=[0.72, 0.72, 0.72],
+ mesh_params={"radius": 1.0, "segments": 36, "rings": 18},
+ )
+ add_modifier(
+ project,
+ "subdivision_surface",
+ _object_index(project, "CoreSphere"),
+ params={"levels": 2, "render_levels": 3},
+ )
+ add_object(
+ project,
+ mesh_type="torus",
+ name="RingA",
+ location=[0, 0, 3.2],
+ rotation=[90, 0, 0],
+ mesh_params={"major_radius": 2.4, "minor_radius": 0.14, "major_segments": 64, "minor_segments": 18},
+ )
+ add_object(
+ project,
+ mesh_type="torus",
+ name="RingB",
+ location=[0, 0, 3.2],
+ rotation=[0, 90, 0],
+ mesh_params={"major_radius": 1.7, "minor_radius": 0.1, "major_segments": 64, "minor_segments": 18},
+ )
+ add_object(
+ project,
+ mesh_type="torus",
+ name="RingC",
+ location=[0, 0, 3.2],
+ rotation=[45, 0, 45],
+ mesh_params={"major_radius": 1.08, "minor_radius": 0.08, "major_segments": 56, "minor_segments": 16},
+ )
+ add_object(
+ project,
+ mesh_type="cylinder",
+ name="Spindle",
+ location=[0, 0, 3.2],
+ mesh_params={"radius": 0.14, "depth": 4.6, "vertices": 28},
+ )
+
+
+def _build_supports(project: Dict) -> None:
+ pylons = [
+ ("PylonNorth", [0.0, 2.7, 2.0]),
+ ("PylonSouth", [0.0, -2.7, 2.0]),
+ ("PylonEast", [2.7, 0.0, 2.0]),
+ ("PylonWest", [-2.7, 0.0, 2.0]),
+ ]
+ for name, location in pylons:
+ add_object(
+ project,
+ mesh_type="cube",
+ name=name,
+ location=location,
+ scale=[0.2, 0.2, 1.4],
+ )
+ add_modifier(project, "bevel", _object_index(project, name), params={"width": 0.035, "segments": 2})
+
+ struts = [
+ ("StrutNE", [1.75, 1.75, 2.55], [24, 0, 45]),
+ ("StrutNW", [-1.75, 1.75, 2.55], [24, 0, -45]),
+ ("StrutSE", [1.75, -1.75, 2.55], [-24, 0, 45]),
+ ("StrutSW", [-1.75, -1.75, 2.55], [-24, 0, -45]),
+ ]
+ for name, location, rotation in struts:
+ add_object(
+ project,
+ mesh_type="cylinder",
+ name=name,
+ location=location,
+ rotation=rotation,
+ mesh_params={"radius": 0.1, "depth": 2.25, "vertices": 18},
+ )
+
+
+def _build_details(project: Dict) -> None:
+ add_object(
+ project,
+ mesh_type="cone",
+ name="UpperCrown",
+ location=[0, 0, 5.04],
+ mesh_params={"radius1": 0.62, "radius2": 0.16, "depth": 0.75, "vertices": 36},
+ )
+ add_modifier(project, "bevel", _object_index(project, "UpperCrown"), params={"width": 0.02, "segments": 2})
+ add_object(
+ project,
+ mesh_type="cone",
+ name="LowerAnchor",
+ location=[0, 0, 1.38],
+ rotation=[180, 0, 0],
+ mesh_params={"radius1": 0.56, "radius2": 0.16, "depth": 0.62, "vertices": 36},
+ )
+ add_modifier(project, "bevel", _object_index(project, "LowerAnchor"), params={"width": 0.02, "segments": 2})
+
+ for index, rotation in enumerate([0, 45, 90, 135], start=1):
+ name = f"FieldFin{index}"
+ add_object(
+ project,
+ mesh_type="cube",
+ name=name,
+ location=[0, 0, 3.2],
+ rotation=[0, 0, rotation],
+ scale=[0.055, 1.4, 0.55],
+ )
+ add_modifier(project, "bevel", _object_index(project, name), params={"width": 0.015, "segments": 2})
+
+ add_object(
+ project,
+ mesh_type="sphere",
+ name="UpperEmitter",
+ location=[0, 0, 4.35],
+ scale=[0.18, 0.18, 0.18],
+ mesh_params={"radius": 1.0, "segments": 24, "rings": 12},
+ )
+ add_object(
+ project,
+ mesh_type="sphere",
+ name="LowerEmitter",
+ location=[0, 0, 2.05],
+ scale=[0.14, 0.14, 0.14],
+ mesh_params={"radius": 1.0, "segments": 24, "rings": 12},
+ )
+ _add_orbit_nodes(project, "SignalWhite")
+
+
+def _add_animation(project: Dict) -> None:
+ set_frame_range(project, 1, 120)
+ set_fps(project, 24)
+
+ add_keyframe(project, _object_index(project, "RingA"), 1, "rotation", [90, 0, 0], interpolation="LINEAR")
+ add_keyframe(project, _object_index(project, "RingA"), 120, "rotation", [90, 0, 360], interpolation="LINEAR")
+
+ add_keyframe(project, _object_index(project, "RingB"), 1, "rotation", [0, 90, 0], interpolation="LINEAR")
+ add_keyframe(project, _object_index(project, "RingB"), 120, "rotation", [360, 90, 0], interpolation="LINEAR")
+
+ add_keyframe(project, _object_index(project, "RingC"), 1, "rotation", [45, 0, 45], interpolation="LINEAR")
+ add_keyframe(project, _object_index(project, "RingC"), 120, "rotation", [45, 360, 405], interpolation="LINEAR")
+
+ add_keyframe(project, _object_index(project, "CoreSphere"), 1, "scale", [0.72, 0.72, 0.72], interpolation="BEZIER")
+ add_keyframe(project, _object_index(project, "CoreSphere"), 60, "scale", [0.84, 0.84, 0.84], interpolation="BEZIER")
+ add_keyframe(project, _object_index(project, "CoreSphere"), 120, "scale", [0.72, 0.72, 0.72], interpolation="BEZIER")
+
+ set_current_frame(project, 60)
+
+
+def _add_materials(project: Dict) -> None:
+ create_material(project, name="FoundationStone", color=[0.16, 0.18, 0.22, 1.0], metallic=0.0, roughness=0.92)
+ create_material(project, name="ObsidianMetal", color=[0.06, 0.07, 0.1, 1.0], metallic=0.35, roughness=0.18)
+ create_material(project, name="BrushedBrass", color=[0.78, 0.63, 0.28, 1.0], metallic=0.92, roughness=0.24)
+ create_material(project, name="AzureCore", color=[0.2, 0.78, 1.0, 1.0], metallic=0.0, roughness=0.08)
+ set_material_property(project, _material_index(project, "AzureCore"), "emission_color", [0.2, 0.78, 1.0, 1.0])
+ set_material_property(project, _material_index(project, "AzureCore"), "emission_strength", 4.8)
+ create_material(project, name="SignalWhite", color=[0.94, 0.96, 1.0, 1.0], metallic=0.0, roughness=0.15)
+ set_material_property(project, _material_index(project, "SignalWhite"), "emission_color", [0.94, 0.96, 1.0, 1.0])
+ set_material_property(project, _material_index(project, "SignalWhite"), "emission_strength", 1.35)
+
+
+def _assign_materials(project: Dict) -> None:
+ for object_name in ("Ground",):
+ _assign(project, "FoundationStone", object_name)
+ for object_name in ("BasePlinth", "InnerDais", "UpperCrown", "LowerAnchor"):
+ _assign(project, "ObsidianMetal", object_name)
+ for object_name in (
+ "RingA",
+ "RingB",
+ "RingC",
+ "Spindle",
+ "PylonNorth",
+ "PylonSouth",
+ "PylonEast",
+ "PylonWest",
+ "StrutNE",
+ "StrutNW",
+ "StrutSE",
+ "StrutSW",
+ "FieldFin1",
+ "FieldFin2",
+ "FieldFin3",
+ "FieldFin4",
+ ):
+ _assign(project, "BrushedBrass", object_name)
+ for object_name in ("CoreSphere", "UpperEmitter", "LowerEmitter"):
+ _assign(project, "AzureCore", object_name)
+
+
+def _configure_scene(project: Dict) -> None:
+ project["world"]["background_color"] = [0.025, 0.03, 0.045]
+ set_render_settings(project, preset="eevee_preview")
+ add_camera(
+ project,
+ name="HeroCam",
+ location=[8.6, -8.4, 6.2],
+ rotation=[62, 0, 46],
+ focal_length=62,
+ set_active=True,
+ )
+ hero_camera = project["cameras"][-1]
+ hero_camera["dof_enabled"] = True
+ hero_camera["dof_focus_distance"] = 8.7
+ hero_camera["dof_aperture"] = 2.2
+
+ add_light(project, light_type="SUN", name="SunKey", rotation=[-38, 0, 26], power=2.6)
+ add_light(project, light_type="AREA", name="SideFill", location=[-5.5, 4.0, 4.2], rotation=[62, 0, -32], power=1250)
+ add_light(project, light_type="POINT", name="CoreBounce", location=[0, 0, 3.2], power=180)
+
+
+def _write_build_manifest(path: Path, payload: Dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+
+
+def _capture_stage(
+ session: Session,
+ stage_name: str,
+ stage_log: List[Dict],
+ preview_root: Path,
+ started: bool,
+) -> bool:
+ if not started:
+ live_payload = preview_mod.live_start(
+ session,
+ recipe="quick",
+ root_dir=str(preview_root),
+ force=True,
+ refresh_hint_ms=1000,
+ live_mode="manual",
+ publish_reason=f"stage:{stage_name}",
+ command=f"blender_gyro_observatory_demo.py --stage {stage_name}",
+ )
+ else:
+ live_payload = preview_mod.live_push(
+ session,
+ recipe="quick",
+ root_dir=str(preview_root),
+ force=True,
+ refresh_hint_ms=1000,
+ publish_reason=f"stage:{stage_name}",
+ command=f"blender_gyro_observatory_demo.py --stage {stage_name}",
+ )
+ stage_log.append(
+ {
+ "stage": stage_name,
+ "bundle_id": live_payload.get("current_bundle_id"),
+ "bundle_count": live_payload.get("bundle_count"),
+ "session_path": live_payload.get("_session_path"),
+ "current_manifest_path": live_payload.get("current_manifest_path"),
+ "current_bundle_dir": live_payload.get("current_bundle_dir"),
+ }
+ )
+ return True
+
+
+def build_demo(output_dir: Path, use_live_preview: bool = True) -> Dict:
+ output_dir.mkdir(parents=True, exist_ok=True)
+ preview_root = output_dir / "live-root"
+ project_path = output_dir / "gyro_observatory.blend-cli.json"
+ manifest_path = output_dir / "build_manifest.json"
+ final_render_path = output_dir / "renders" / "gyro_observatory_final.png"
+
+ project = create_scene(name="gyro-observatory", profile="preview")
+ _configure_scene(project)
+ _add_materials(project)
+
+ session = Session()
+ stage_log: List[Dict] = []
+ live_started = False
+
+ _build_blockout(project)
+ save_scene(project, str(project_path))
+ session.set_project(project, str(project_path))
+ if use_live_preview:
+ live_started = _capture_stage(session, "01_blockout", stage_log, preview_root, live_started)
+
+ _build_supports(project)
+ _assign_materials(project)
+ save_scene(project, str(project_path))
+ if use_live_preview:
+ live_started = _capture_stage(session, "02_supports", stage_log, preview_root, live_started)
+
+ _build_details(project)
+ _assign_materials(project)
+ save_scene(project, str(project_path))
+ if use_live_preview:
+ live_started = _capture_stage(session, "03_details", stage_log, preview_root, live_started)
+
+ _add_animation(project)
+ save_scene(project, str(project_path))
+ if use_live_preview:
+ live_started = _capture_stage(session, "04_animation", stage_log, preview_root, live_started)
+ live_payload = preview_mod.live_stop(session, recipe="quick", root_dir=str(preview_root))
+ else:
+ live_payload = None
+
+ set_render_settings(project, preset="eevee_high", resolution_x=1600, resolution_y=1600, samples=128)
+ set_current_frame(project, 60)
+ save_scene(project, str(project_path))
+ render_script = generate_bpy_script(project, str(final_render_path), frame=60, animation=False)
+ final_render = blender_backend.render_scene_headless(render_script, str(final_render_path), timeout=480)
+
+ payload = {
+ "project_path": str(project_path),
+ "preview_root": str(preview_root),
+ "stage_log": stage_log,
+ "live_session": live_payload,
+ "final_render": final_render,
+ }
+ _write_build_manifest(manifest_path, payload)
+ return payload
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--output-dir",
+ default=f"/root/preview-artifacts/20260422/blender-gyro-observatory",
+ help="Directory for the generated scene, preview bundles, and final render.",
+ )
+ parser.add_argument(
+ "--no-live-preview",
+ action="store_true",
+ help="Skip stage-by-stage preview bundle capture.",
+ )
+ args = parser.parse_args()
+
+ result = build_demo(Path(args.output_dir).expanduser().resolve(), use_live_preview=not args.no_live_preview)
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+
+
+if __name__ == "__main__":
+ main()