diff --git a/Cargo.lock b/Cargo.lock index f01e20a..cedd285 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -57,6 +57,7 @@ dependencies = [ "serde_json", "tempfile", "uuid", + "windows-sys 0.61.2", ] [[package]] diff --git a/README.md b/README.md index c42f6ea..e0be8d0 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ broker. - `surfaces/unity/Packages/com.gamecult.brokkr`: Unity editor package scaffold. - `surfaces/blender/brokkr_bridge`: Blender add-on target backed by - CultLib's Python CultMesh node/server, with optional debug export/import + CultLib's Python CultMesh node/server, with an optional debug export probes. - `brokkr-command`: .NET CLI that writes one Unity command intent through the project's directory store and reports the editor's receipt (`docs/provider-contract.md`). diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml index 4470cd6..b74147e 100644 --- a/brokkr-ctl/Cargo.toml +++ b/brokkr-ctl/Cargo.toml @@ -11,5 +11,8 @@ rmp-serde = "1.3" serde_json = "1" uuid = { version = "1", features = ["v7"] } +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] } + [dev-dependencies] tempfile = "3" diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index c342e91..e2a7a40 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -18,8 +18,6 @@ const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "no const DEFAULT_TIMEOUT_SECS: u64 = 60; const POLL: Duration = Duration::from_millis(200); const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600); -/// Even when the file looks unchanged, read it again this often. -const RECHECK: Duration = Duration::from_secs(5); /// What a receipt (or its absence) says; the exit code derives from it and from nothing else. pub enum Outcome { @@ -162,9 +160,35 @@ fn open_store(options: &Options) -> Result { if meta.file_type().is_symlink() || !meta.is_file() { bail!("store {} must be the add-on's regular file, not a link", path.display()); } + // The same swap would leave a second name on the old bytes. + if link_count(&path)? > 1 { + bail!("store {} has more than one hard link; it must be the add-on's only name for the file", path.display()); + } Ok(SingleFileMessagePackBackingStore::new(path)) } +#[cfg(unix)] +fn link_count(path: &std::path::Path) -> Result { + use std::os::unix::fs::MetadataExt; + Ok(std::fs::metadata(path)?.nlink()) +} + +/// std's `number_of_links` is unstable, so ask the handle. +#[cfg(windows)] +fn link_count(path: &std::path::Path) -> Result { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle}; + let file = std::fs::File::open(path)?; + let mut info = std::mem::MaybeUninit::::zeroed(); + // SAFETY: the handle is live for the call and `info` is a writable BY_HANDLE_FILE_INFORMATION. + let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle() as _, info.as_mut_ptr()) }; + if ok == 0 { + return Err(std::io::Error::last_os_error().into()); + } + // SAFETY: the call succeeded, so it filled the struct. + Ok(u64::from(unsafe { info.assume_init() }.nNumberOfLinks)) +} + fn requested_by(options: &Options) -> Result { let instance = std::env::var("EUREKA_INSTANCE").unwrap_or_default(); let agent = options @@ -244,16 +268,7 @@ fn wait_for_receipt( limit: Duration, ) -> Result { let started = Instant::now(); - let mut gate = ChangeGate::new(store.path()); loop { - if !gate.should_read() { - if started.elapsed() >= limit { - println!("status: timeout"); - return Ok(Outcome::Timeout.code()); - } - thread::sleep(POLL); - continue; - } if let Some(receipt) = read_receipt(store, id)? { print_fields(&receipt); let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); @@ -267,32 +282,6 @@ fn wait_for_receipt( } } -/// Polling must not hold the store: a read takes the shared lock and an open handle, and on -/// Windows that can make the add-on's replace fail. So the file's stat is polled and the store -/// is read only after it changed (and every RECHECK as a backstop). -pub struct ChangeGate { - path: PathBuf, - seen: Option<(u64, Option)>, - last_read: Option, -} - -impl ChangeGate { - pub fn new(path: &std::path::Path) -> Self { - Self { path: path.to_path_buf(), seen: None, last_read: None } - } - - pub fn should_read(&mut self) -> bool { - let stamp = std::fs::metadata(&self.path).ok().map(|m| (m.len(), m.modified().ok())); - let stale = self.last_read.is_none_or(|at| at.elapsed() >= RECHECK); - if self.seen.is_none() || stamp != self.seen || stale { - self.seen = stamp; - self.last_read = Some(Instant::now()); - return true; - } - false - } -} - fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> Result { let mut found = Vec::new(); for envelope in store.pull_all()? { @@ -628,22 +617,6 @@ mod tests { assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); } - #[test] - fn the_gate_reads_first_then_only_after_the_file_changes() { - let dir = std::env::temp_dir().join(format!("brokkr-gate-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("s.ccmp"); - std::fs::write(&file, b"one").unwrap(); - let mut gate = ChangeGate::new(&file); - assert!(gate.should_read()); - assert!(!gate.should_read()); - assert!(!gate.should_read()); - std::fs::write(&file, b"three").unwrap(); - assert!(gate.should_read()); - assert!(!gate.should_read()); - std::fs::remove_dir_all(&dir).unwrap(); - } - #[test] fn statuses_map_to_exit_codes() { for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 072ae2a..c3df5a6 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -240,6 +240,43 @@ fn a_symlinked_store_is_refused() { assert_eq!(ctl(&link, &["receipts"], None).status.code(), Some(1)); } +#[test] +fn a_hard_linked_store_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let link = dir.path().join("second-name.ccmp"); + std::fs::hard_link(&path, &link).unwrap(); + let before = std::fs::read(&path).unwrap(); + for name in [&path, &link] { + let output = ctl(name, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{}", name.display()); + assert!(String::from_utf8_lossy(&output.stderr).contains("hard link")); + } + assert_eq!(std::fs::read(&path).unwrap(), before); +} + +#[test] +fn the_timeout_cap_is_one_day_inclusive() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + // --help returns after parsing, so a legal timeout does not wait + let at_cap = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400"], None); + assert_eq!(at_cap.status.code(), Some(0)); + let over = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400.5"], None); + assert_eq!(over.status.code(), Some(1)); +} + +#[test] +fn short_help_is_a_flag() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let output = ctl(&path, &["send", "createObject", "-h"], Some("nibu")); + assert_eq!(output.status.code(), Some(0)); + assert!(stdout(&output).contains("actions:")); + let group = ctl(&path, &["receipts", "-h"], None); + assert!(stdout(&group).contains("brokkr-ctl blender:")); +} + #[test] fn receipts_only_come_from_the_receipt_keys_and_type() { let dir = tempfile::tempdir().unwrap(); @@ -250,6 +287,7 @@ fn receipts_only_come_from_the_receipt_keys_and_type() { &[ envelope_at(RECEIPT, "elsewhere/fake", &fake), envelope_at(INTENT, "blender/receipts/wrongtype", &fake), + envelope_at(RECEIPT, "nested/blender/receipts/fake2", &fake), ], ); let listed = stdout(&ctl(&path, &["receipts"], None)); @@ -306,7 +344,7 @@ fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() { .filter_map(|rest| rest.split('"').next()) .map(String::from) .collect(); - let actions_line = source.lines().find(|l| l.contains("ACTIONS = (\"")).unwrap(); + let actions_line = source.lines().find(|l| l.trim_start().starts_with("ACTIONS = (\"")).unwrap(); dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from)); assert!(dispatched.len() >= 20, "{dispatched:?}"); let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect(); diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 13592ad..fcfedaa 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -100,7 +100,9 @@ resident service on that number); reading a record's stored version through Aeth in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and valid), run the action with every operator called `undo=False`, push exactly one undo step labelled `Brokkr : `, write the receipt. A -refusal or a failure pushes nothing and leaves the scene unchanged. There is no second +refusal caught before any write pushes nothing and leaves the scene unchanged; an action +that fails after writing pushes one step labelled `(failed)`, so the partial write is one +undoable step. There is no second writer and no script action (`no-free-form-python`): what the typed actions do not cover waits for a new typed action. @@ -234,8 +236,8 @@ are the primitive for the push. collections (an edit buffer over the `.cc`); the stdin dump (a pipe, not state). - **Forbidden writers.** `execute_command` called around the primitive; operators run with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from - add-on code; any agent-sent Python; the debug-mirror JSON import as a door for intents - (`blender_target.py` `_import_debug_command_files`); `brokkr-ctl` deciding anything; + add-on code; any agent-sent Python; any reader that turns a file under + the debug-mirror root into an intent (removed in cut-live-1); `brokkr-ctl` deciding anything; `ship_cc.py`'s envelope writes and any other direct `.cc` writer; `layout_revision` as a revision. - **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index e2bcbe8..8a81707 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -58,7 +58,7 @@ class BrokkrPreferences(bpy.types.AddonPreferences): name="Debug Export Root", subtype="DIR_PATH", default=DEFAULT_DEBUG_MIRROR_ROOT, - description="Optional JSON debug export/import root; CultMesh remains the mirror owner", + description="Optional JSON debug export root (export only); CultMesh remains the mirror owner", ) import_dir: bpy.props.StringProperty( @@ -476,7 +476,6 @@ class BROKKR_OT_start_server(bpy.types.Operator): prefs.serve_port, prefs.max_snapshot_documents, prefs.max_snapshot_bytes, - prefs.debug_mirror_root, prefs.allow_non_loopback, prefs.require_session_token, ) diff --git a/surfaces/blender/brokkr_bridge/blender_manifest.toml b/surfaces/blender/brokkr_bridge/blender_manifest.toml new file mode 100644 index 0000000..ec5feed --- /dev/null +++ b/surfaces/blender/brokkr_bridge/blender_manifest.toml @@ -0,0 +1,15 @@ +schema_version = "1.0.0" +id = "brokkr_bridge" +version = "0.2.0" +name = "Brokkr Bridge" +tagline = "Brokkr command intents, receipts and snapshots over CultMesh" +maintainer = "GameCult " +type = "add-on" +blender_version_min = "5.3.0" +platforms = ["windows-x64"] +license = ["SPDX:GPL-3.0-or-later"] +# CultLib's cultnet-py and cultcache-py import msgpack; Blender's Python does not ship it. The wheel is +# the installed msgpack 1.2.2 CPython 3.13 Windows build (Blender 5.3 runs Python 3.13). The C extension +# matters: CultLib at baf4ecf7 fails on msgpack's pure-Python fallback (object_pairs_hook gets a generator). +# Linux and macOS wheels are not bundled yet. +wheels = ["./wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl"] diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 677f03d..8684e8e 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -5,6 +5,7 @@ import functools import json import math import os +import re import sys import uuid from array import array @@ -43,6 +44,26 @@ CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") GL_RUNTIME_LIBRARY = "libEGL.so.1" +# Actions that only read the scene and so push no undo step (live-5 adds look). +READ_ACTIONS: tuple[str, ...] = () +MUTATING_ACTIONS = ( + "createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent", + "setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf", + "setCamera", "setLight", "setWorld", "renderStill", +) +# Actions that change no scene state: they push no undo step (exportGltf restores its selection; +# renderStill restores its settings). +NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill") +# While an object is in Edit Mode, undo steps are edit-mesh steps, so a scene write is not reverted by +# one undo, and some operators leave Edit Mode (brokkr-live:ruling:object-intents-refused-in-edit-mode). +# Anything that writes scene state or changes her mode is refused; renderStill does neither. +EDIT_MODE_SAFE_ACTIONS = ("renderStill",) +REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") +# A commandId becomes part of a receipt key, so it is a short string of key-safe characters ('.' is left +# out: it separates the '.denied' suffix). +COMMAND_ID_SHAPE = re.compile(r"^[A-Za-z0-9_-]{1,128}$") +NOTE_LIMIT = 200 + EVALUATED_POSITION_CAP = 256 EVALUATED_VERTEX_LIMIT = 1_000_000 EVALUATED_INSTANCE_SCAN_LIMIT = 100_000 # depsgraph items visited per capture; iterating one in Python costs ~5 us @@ -88,10 +109,12 @@ class BrokkrBlenderTarget: self._server: Any | None = None self._guard: SessionGuard | None = None self._cultmesh_module: str = "" - self._debug_mirror_root: str = "" self.import_dir: str = "" self.output_dir: str = "" self.nodes = na.NodeActions(bpy_module) + self.agent_turn = False # true only inside run_intent + self._wrote = True # run_intent: false when an accepted action changed nothing + self._receipted: set[str] = set() def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -127,16 +150,26 @@ class BrokkrBlenderTarget: debug_mirror_root: str = "", ) -> list[dict[str, Any]]: node, documents = self._open_node(cache_path, cultlib_py_src) - if debug_mirror_root: - self._import_debug_command_files(node, documents["command_intent"], debug_mirror_root) - snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] + self._receipted.update( + r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() + if isinstance(r.get("commandId"), str)) for command_key, command in sorted(commands.items()): - receipt = self.execute_command(context, command) - self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root) + command_id = command.get("commandId") + valid = _valid_command_id(command_id) + reused = valid and command_id in self._receipted + receipt = self.run_intent(context, command) + if not valid: + # No safe key exists for this id: the denial is receipted under a fresh key and names the + # queue key, so the intent leaves the queue and its sender can still find the refusal. + receipt["message"] += f" (queue key {command_key})" + # Receipts are write-once: a reused id's denial goes under '.denied', never over the + # original. The sender learns of it by reading that key (and the drain's returned list). + self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, + key_suffix=".denied" if reused else "") node.database.delete(documents["command_intent"], command_key) receipts.append(receipt) @@ -148,8 +181,9 @@ class BrokkrBlenderTarget: cultlib_py_src: str, receipt: dict[str, Any], debug_mirror_root: str = "", + key_suffix: str = "", ) -> None: - command_id = receipt.get("commandId") or uuid.uuid4().hex + command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node, documents = self._open_node(cache_path, cultlib_py_src) node.database.put(documents["command_receipt"], f"blender/receipts/{command_id}", receipt) if debug_mirror_root: @@ -328,7 +362,6 @@ class BrokkrBlenderTarget: port: int, max_snapshot_documents: int, max_snapshot_bytes: int, - debug_mirror_root: str = "", allow_non_loopback: bool = False, require_token: bool = False, ) -> dict[str, Any]: @@ -354,8 +387,7 @@ class BrokkrBlenderTarget: self.stop_server() self._cultmesh_module = "" - self._debug_mirror_root = self.resolve_debug_mirror_root(debug_mirror_root) if debug_mirror_root else "" - purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, self._debug_mirror_root) + purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA) cultmesh, _cultcache = _load_cultmesh(cultlib_py_src) self._cultmesh_module = str(getattr(cultmesh, "__file__", "") or "") verse_catalog = cultmesh.CultMesh.create_verse_catalog() @@ -426,7 +458,7 @@ class BrokkrBlenderTarget: finally: try: if was_running and self._node is not None: - purge_command_intents(self._node, self._documents["command_intent"], COMMAND_INTENT_SCHEMA, self._debug_mirror_root) + purge_command_intents(self._node, self._documents["command_intent"], COMMAND_INTENT_SCHEMA) finally: self._server = None self._server_key = None @@ -488,45 +520,106 @@ class BrokkrBlenderTarget: "collections": [self._collection_snapshot(collection) for collection in bpy.data.collections], } - def execute_command(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt.""" + command_id = command.get("commandId") + requested_by = command.get("requestedBy") action = command.get("action", "") + denial = "" + if not _valid_command_id(command_id): + denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'." + elif command_id in self._receipted: + denial = f"commandId {command_id!r} was already receipted; ids are single-use." + elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.fullmatch(requested_by): + denial = "Intent has no requestedBy of the form '/'." + elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS: + denial = f"Unsupported Blender command action: {action}" + elif action not in EDIT_MODE_SAFE_ACTIONS and self._edit_mode_object() is not None: + denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " + "until she leaves it; nothing was changed.") + if denial: + if _valid_command_id(command_id): + self._receipted.add(command_id) + return self._receipt(command, "denied", denial, "") + + label = f"Brokkr {requested_by}: {action} {command_id[:8]}" + push = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS + self.agent_turn = True + self._wrote = True try: - if action == "createObject": - return self._create_object(context, command) - if action == "deleteObject": - return self._delete_object(context, command) - if action == "setObjectTransform": - return self._set_object_transform(context, command) - if action == "setObjectVisibility": - return self._set_object_visibility(context, command) - if action == "setObjectParent": - return self._set_object_parent(context, command) - if action == "setObjectCustomProperty": - return self._set_object_custom_property(context, command) - if action == "selectObject": - return self._select_object(context, command) - if action == "assignMaterial": - return self._assign_material(context, command) - if action == "importGltf": - return self._import_gltf(context, command) - if action == "exportGltf": - return self._export_gltf(context, command) - if action == "setCamera": - return self._set_camera(context, command) - if action == "setLight": - return self._set_light(context, command) - if action == "setWorld": - return self._set_world(context, command) - if action == "renderStill": - return self._render_still(context, command) - if action in na.NodeActions.ACTIONS: - message, name = self.nodes.execute(action, command) - return self._receipt(command, "accepted", message, name) - return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") - except sa.ActionRefused as error: - return self._receipt(command, "failed", str(error), "") - except Exception as error: - return self._receipt(command, "failed", str(error), "") + try: + receipt = self._dispatch(context, command) + if receipt["status"] != "accepted" or not self._wrote: + push = False # a refusal, or an accepted no-op: it wrote nothing + except sa.ActionRefused as error: # raised before any write: nothing to push + receipt, push = self._receipt(command, "failed", str(error), ""), False + except Exception as error: # a partial write is one undoable step, not part of her next action + label += " (failed)" + receipt = self._receipt(command, "failed", str(error), "") + if push: + try: + self._push_undo(label) + receipt["undoLabel"] = label + except Exception as error: # the write stands; the intent is receipted, never re-run + receipt = self._receipt( + command, "failed", + f"{receipt['message']} The undo step could not be pushed ({error}); the change stands " + "but is not one undo step.", receipt["objectName"]) + finally: + self.agent_turn = False + self._receipted.add(command_id) + return receipt + + def _edit_mode_object(self) -> str | None: + for obj in self.bpy.data.objects.values(): + if getattr(obj, "mode", "OBJECT") == "EDIT": + return obj.name + return None + + def _push_undo(self, label: str) -> None: + windows = self.bpy.context.window_manager.windows + if windows: + with self.bpy.context.temp_override(window=windows[0]): + self.bpy.ops.ed.undo_push(message=label) + else: + self.bpy.ops.ed.undo_push(message=label) + + def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """The action table. Only run_intent calls it; it owns refusal, failure and the undo step.""" + action = command.get("action", "") + if action == "createObject": + return self._create_object(context, command) + if action == "deleteObject": + return self._delete_object(context, command) + if action == "setObjectTransform": + return self._set_object_transform(context, command) + if action == "setObjectVisibility": + return self._set_object_visibility(context, command) + if action == "setObjectParent": + return self._set_object_parent(context, command) + if action == "setObjectCustomProperty": + return self._set_object_custom_property(context, command) + if action == "selectObject": + return self._select_object(context, command) + if action == "assignMaterial": + return self._assign_material(context, command) + if action == "importGltf": + return self._import_gltf(context, command) + if action == "exportGltf": + return self._export_gltf(context, command) + if action == "setCamera": + return self._set_camera(context, command) + if action == "setLight": + return self._set_light(context, command) + if action == "setWorld": + return self._set_world(context, command) + if action == "renderStill": + return self._render_still(context, command) + if action in na.NodeActions.ACTIONS: + message, name = self.nodes.execute(action, command) + self._wrote = self.nodes.changed + return self._receipt(command, "accepted", message, name) + return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") def _create_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: object_type = command.get("objectType", "EMPTY") @@ -542,13 +635,13 @@ class BrokkrBlenderTarget: location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0)) if object_type == "MESH": - self.bpy.ops.mesh.primitive_cube_add(size=float(command.get("size", 1.0)), location=location) + self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command.get("size", 1.0)), location=location) elif object_type == "LIGHT": - self.bpy.ops.object.light_add(type=command.get("lightType", "POINT"), location=location) + self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command.get("lightType", "POINT"), location=location) elif object_type == "CAMERA": - self.bpy.ops.object.camera_add(location=location) + self.bpy.ops.object.camera_add("EXEC_DEFAULT", False, location=location) else: # EMPTY - self.bpy.ops.object.empty_add(type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) + self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) obj = context.object obj.name = name @@ -662,7 +755,7 @@ class BrokkrBlenderTarget: (sa.fingerprint([path]), sa.fingerprint(existing)) != checked: raise sa.ActionRefused("Import file changed while it was being checked.") before = set(self.bpy.data.objects.keys()) - self.bpy.ops.import_scene.gltf(filepath=str(path)) + self.bpy.ops.import_scene.gltf("EXEC_DEFAULT", False, filepath=str(path)) added = sorted(set(self.bpy.data.objects.keys()) - before) return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}.", added[0] if added else "") @@ -708,7 +801,7 @@ class BrokkrBlenderTarget: try: for obj in objects: obj.select_set(obj in chosen) - result = self.bpy.ops.export_scene.gltf( + result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False, filepath=str(path), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", use_selection=bool(chosen), **options) finally: @@ -848,7 +941,7 @@ class BrokkrBlenderTarget: path.parent.mkdir(parents=True, exist_ok=True) if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: raise sa.ActionRefused("Output path changed while it was being checked.") - self.bpy.ops.render.render(write_still=True) + self.bpy.ops.render.render("EXEC_DEFAULT", False, write_still=True) finally: (render.engine, render.resolution_x, render.resolution_y, render.filepath, render.image_settings.file_format, scene.camera) = saved @@ -1008,11 +1101,14 @@ class BrokkrBlenderTarget: def _receipt(self, command: dict[str, Any], status: str, message: str, object_name: str) -> dict[str, Any]: return { "schema": COMMAND_RECEIPT_SCHEMA, - "commandId": command.get("commandId") or uuid.uuid4().hex, + "commandId": command["commandId"] if _valid_command_id(command.get("commandId")) else uuid.uuid4().hex, "action": command.get("action", ""), "status": status, "message": message, "objectName": object_name, + "requestedBy": command["requestedBy"] if isinstance(command.get("requestedBy"), str) else "", + "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", + "undoLabel": "", "observedAt": _now(), } @@ -1037,17 +1133,6 @@ class BrokkrBlenderTarget: self._documents = documents return node, documents - def _import_debug_command_files(self, node: Any, command_document: Any, debug_mirror_root: str) -> None: - commands_root = Path(self.resolve_debug_mirror_root(debug_mirror_root)) / "blender" / "commands" - for command_path in sorted(commands_root.glob("*.json")): - with command_path.open("r", encoding="utf-8") as handle: - command = json.load(handle) - command_id = command.get("commandId") or command_path.stem - command["schema"] = command.get("schema") or COMMAND_INTENT_SCHEMA - command["commandId"] = command_id - node.database.put(command_document, f"blender/commands/{command_id}", command) - command_path.unlink(missing_ok=True) - def _write_debug_document(self, debug_mirror_root: str, relative_path: str, document: dict[str, Any]) -> None: path = Path(self.resolve_debug_mirror_root(debug_mirror_root)) / relative_path path.parent.mkdir(parents=True, exist_ok=True) @@ -1133,9 +1218,15 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: import cultmesh_py # type: ignore import cultcache_py # type: ignore except ModuleNotFoundError as exc: + own = {name.replace("-", "_") for name in CULTLIB_PY_PACKAGES} + if exc.name in own: + raise RuntimeError( + "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " + "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + ) from exc raise RuntimeError( - "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " - "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + f"A CultLib Python package needs the module {exc.name!r}, which Blender's Python does not have. " + "Install the add-on as an extension (it bundles msgpack) or install that module into Blender's Python." ) from exc if not hasattr(cultcache_py, "convert"): raise RuntimeError( @@ -1166,6 +1257,10 @@ def _to_list(value: Any) -> list[float]: return [float(item) for item in value] +def _valid_command_id(value: Any) -> bool: + return isinstance(value, str) and COMMAND_ID_SHAPE.fullmatch(value) is not None + + def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: if value is None: return tuple(float(item) for item in fallback) diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py index 5210b86..aba236d 100644 --- a/surfaces/blender/brokkr_bridge/node_actions.py +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -121,8 +121,10 @@ class NodeActions: def __init__(self, bpy_module: Any): self.bpy = bpy_module + self.changed = False # whether the last execute wrote anything: an absent-target removal does not def execute(self, action: str, command: dict[str, Any]) -> tuple[str, str]: + self.changed = True return getattr(self, "_" + action)(command) # tree and node lookup @@ -236,6 +238,7 @@ class NodeActions: raise ActionRefused(f"{node_id!r} is the group's own input/output node and stays.") node = next((n for n in tree.nodes if n.get("brokkr_id") == node_id), None) if node is None: + self.changed = False return f"Node {node_id!r} was already absent.", node_id tree.nodes.remove(node) # Blender drops the node's links with it return "Node removed.", node_id @@ -305,6 +308,7 @@ class NodeActions: raise ActionRefused("modifierName must be a string of at most 255 characters.") modifier = obj.modifiers.get(name) if modifier is None: + self.changed = False return f"Modifier {name!r} was already absent.", obj.name if modifier.type != "NODES": raise ActionRefused(f"{name!r} is not a Geometry Nodes modifier; only those are removed here.") diff --git a/surfaces/blender/brokkr_bridge/server_guard.py b/surfaces/blender/brokkr_bridge/server_guard.py index 0e9d111..0dbba80 100644 --- a/surfaces/blender/brokkr_bridge/server_guard.py +++ b/surfaces/blender/brokkr_bridge/server_guard.py @@ -12,7 +12,6 @@ from __future__ import annotations import hmac import ipaddress import secrets -from pathlib import Path from typing import Any PUT_SCHEMA_VERSIONS = ("cultnet.document_put_raw.v0", "cultnet.document_delete.v0") @@ -91,17 +90,12 @@ def guarded_server_class(base: type, guard: SessionGuard) -> type: return GuardedServer -def purge_command_intents(node: Any, command_document: Any, command_schema: str, debug_mirror_root: str) -> int: - """Delete every queued command intent from the node and every command JSON under - /blender/commands. Returns how many were removed.""" +def purge_command_intents(node: Any, command_document: Any, command_schema: str) -> int: + """Delete every queued command intent from the node. Returns how many were removed.""" removed = 0 if node is not None: node.database.pull() for key in list(node.database.snapshot().get(command_schema, {})): node.database.delete(command_document, key) removed += 1 - if debug_mirror_root: - for path in (Path(debug_mirror_root) / "blender" / "commands").glob("*.json"): - path.unlink(missing_ok=True) - removed += 1 return removed diff --git a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl new file mode 100644 index 0000000..83a8682 Binary files /dev/null and b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl differ diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 3b3a93d..f29c195 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -28,6 +28,27 @@ py -3 -c "import sys; sys.path.insert(0, r'/surfaces/blender/brokkr_brid The command prints the record count and leaves the source unwritten. Records a new daemon already appended (MessagePack) are carried into the new file. +### msgpack for a stock Blender + +CultLib's `cultnet-py` and `cultcache-py` import `msgpack`, and Blender's Python does +not ship it. Install Brokkr as an extension so Blender installs it for you: +`surfaces/blender/brokkr_bridge/blender_manifest.toml` lists the bundled wheel +`wheels/msgpack-1.2.2-cp313-cp313-win_amd64.whl`, which Blender unpacks into the extension's own +site-packages when the extension is enabled. Build and install it: + +```text +blender --command extension build --source-dir surfaces/blender/brokkr_bridge --output-dir +blender --command extension install-file --repo user_default --enable /brokkr_bridge-0.2.0.zip +``` + +The bundled wheel is msgpack 1.2.2 for CPython 3.13 on Windows x64 (Blender 5.3's Python), +repacked from the installed package with its Apache-2.0 licence; the extension is therefore +declared `windows-x64`, Blender 5.3 or newer. The C extension matters: CultLib at `baf4ecf7` +fails on msgpack's pure-Python fallback. Linux and macOS wheels are not bundled yet: there, +or in a plain add-on directory install, put `msgpack` into Blender's Python yourself. A +CultLib package missing a module is reported by that module's name, not as a missing +CultLib package. + The default node cache is: ```text @@ -44,8 +65,7 @@ after `Start Server`. Always on: - `Start Server` and `Stop Server` purge queued command intents: every - `brokkr.blender.command_intent.v0` record in the node and every - `blender/commands/*.json` under `Debug Export Root`. Intents queued before a + `brokkr.blender.command_intent.v0` record in the node. Intents queued before a start never run under the new session. - After `Start Server` the panel shows the bind address, port and the file `cultmesh_py` was actually loaded from (its `__file__`, not the preference). @@ -75,9 +95,11 @@ Run the tests (no Blender needed; `CULTLIB_PACKAGES` adds the real-server tests) CULTLIB_PACKAGES=F:/Projects/CultLib/packages python -m unittest discover -s surfaces/blender/tests -v ``` -`Debug Export Root` may still emit readable JSON probe files under -`.brokkr/blender-editor-debug`, but those files are debug/import glue. CultMesh -owns the mirror state. +`Debug Export Root` may still emit readable JSON snapshot and receipt files under +`.brokkr/blender-editor-debug`. They are export only: nothing reads them back, and +a JSON file placed there is never an intent. CultMesh owns the mirror state, and +intents enter only through the node (`brokkr-ctl blender send`, a served peer, the +sync organ). ## Local Smoke @@ -85,11 +107,13 @@ owns the mirror state. 2. Open `View3D > Sidebar > Brokkr`. 3. Click `Capture Snapshot`. 4. Inspect `.brokkr/blender-editor.ccmp`. -5. Drop a command intent JSON file into - `.brokkr/blender-editor-debug/blender/commands/{commandId}.json`. +5. Send an intent into the node: + `brokkr-ctl blender send createObject --set objectType='"EMPTY"' --agent --no-wait` + (needs `EUREKA_INSTANCE` and `--store `). 6. Click `Drain Commands`, or enable `Auto Drain Commands` to poll command intents once per second while the add-on is loaded. -7. Inspect `.brokkr/blender-editor.ccmp` or the optional debug export +7. Read the receipt with `brokkr-ctl blender wait --store `, or + inspect `.brokkr/blender-editor.ccmp` or the optional debug export at `.brokkr/blender-editor-debug/blender/receipts/{commandId}.json`. 8. Click `Start Server`. 9. Use the reported `cultnet://host:port` endpoint from a CultMesh/CultNet diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py new file mode 100644 index 0000000..f2b2d3c --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -0,0 +1,274 @@ +"""Live proof, in GUI Blender with the add-on enabled, that intents arriving through the node queue +are drained by the add-on's own 1 s timer as one undo step each, with write-once receipts. + + BROKKR_USER_SCRIPTS= (also BLENDER_USER_SCRIPTS) + BROKKR_SCRATCH= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + BROKKR_PYLIBS= + blender --factory-startup --python agent_turn_queue.py -- + +Intents are put into the node database as brokkr-ctl does; a command JSON dropped under the debug +root is never an intent. Writes +.result.json, then quits Blender. Undo is read only here, by this driver. +""" +import importlib +import json +import os +import sys +import traceback +from pathlib import Path + +import bpy + +if os.environ.get("BROKKR_PYLIBS"): + sys.path.insert(0, os.environ["BROKKR_PYLIBS"]) +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +R = {"blender": bpy.app.version_string, "module": os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge"), + "pylibs": bool(os.environ.get("BROKKR_PYLIBS")), "checks": [], "receipts": {}} + +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge") +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") + +try: + import msgpack + R["msgpack"] = msgpack.__file__ +except ImportError: + R["msgpack"] = None +prefs = bpy.context.preferences.addons[MODULE].preferences +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = str(SCRATCH / "debug") # export only: q1 drops a command file there and it must stay inert +prefs.output_dir = str(SCRATCH / "out") +prefs.import_dir = "" +prefs.auto_drain_commands = True +if os.environ.get("BROKKR_CULTLIB"): + prefs.cultlib_py_src = os.environ["BROKKR_CULTLIB"] +(SCRATCH / "out").mkdir(exist_ok=True) +adapter = addon.target() + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def push(msg): + with win(): + bpy.ops.ed.undo_push(message=msg) + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +def queue(cid, **cmd): + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA) + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + + +def receipt(key): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{key}") + + +def all_receipts(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}) + + +def pending(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=24): + """A step that repeats each tick until pred() holds (the add-on's timer drains meanwhile).""" + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def drained(*ids): + return lambda: all(receipt(i) for i in ids) + + +def q1(): + push("driver baseline") + door = SCRATCH / "debug" / "blender" / "commands" + door.mkdir(parents=True, exist_ok=True) + (door / "door-0001.json").write_text(json.dumps( + {"commandId": "door-0001", "requestedBy": "nibu/hands", "action": "createObject", "objectType": "MESH", "name": "QDoor"})) + queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QCube", location=[4, 0, 0], + requestedBy="nibu/hands", note="queue test") + + +def q1_check(): + r = receipt("aaaaaaaa-0001") + R["receipts"]["q1"] = r + S["q1_label"] = r and r.get("undoLabel") + check("queue: createObject drained by the add-on timer, accepted, labelled, attributed", + r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaaaaaaa" + and r["requestedBy"] == "nibu/hands" and r["note"] == "queue test" and "QCube" in names(), r) + check("queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", + (SCRATCH / "debug" / "blender" / "commands" / "door-0001.json").exists() and "QDoor" not in names() + and receipt("door-0001") is None and (SCRATCH / "debug" / "blender" / "receipts" / "aaaaaaaa-0001.json").exists(), + names()) + check("queue: intent removed from the queue after the drain", "blender/commands/aaaaaaaa-0001" not in pending(), list(pending())) + + +def q2(): + queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QReuse", requestedBy="nibu/hands") + + +def q2_check(): + orig = receipt("aaaaaaaa-0001") + denial = receipt("aaaaaaaa-0001.denied") + R["receipts"]["q2_original"], R["receipts"]["q2_denial"] = orig, denial + check("queue: reused id leaves the original receipt untouched (write-once)", + orig["status"] == "accepted" and orig["undoLabel"] == S["q1_label"], orig) + check("queue: reused id reported under .denied, nothing created", + denial and denial["status"] == "denied" and "QReuse" not in names(), denial) + + +def q3(): + queue("aaaaaaaa-0003", action="createObject", objectType="MESH", name="QNoOwner") + + +def q3_check(): + r = receipt("aaaaaaaa-0003") + R["receipts"]["q3"] = r + check("queue: intent without requestedBy denied, scene unchanged", r["status"] == "denied" and "QNoOwner" not in names(), r) + + +def q4(): + queue("aaaaaaaa-0004", action="createObject", objectType="MESH", name="QOne", location=[0, 6, 0], requestedBy="nibu/hands") + queue("aaaaaaaa-0005", action="createObject", objectType="MESH", name="QTwo", location=[0, 8, 0], requestedBy="nibu/imagination") + + +def q4_undo_two(): + undo() + after_one = names() + undo() + after_two = names() + check("queue: two intents drained together are two undo steps, last first", + "QTwo" not in after_one and "QOne" in after_one and "QOne" not in after_two, [after_one, after_two]) + + +def q5_edit(): + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube + cube.select_set(True) + with win(): + bpy.ops.object.mode_set(mode="EDIT") + push("driver edit baseline") + queue("aaaaaaaa-0006", action="setWorld", color=[1, 0, 0], requestedBy="nibu/hands") + queue("aaaaaaaa-0007", action="exportGltf", filepath="edit.glb", requestedBy="nibu/hands") + queue("aaaaaaaa-0008", action="setObjectTransform", objectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands") + + +def q5_check(): + rs = [receipt(k) for k in ("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")] + R["receipts"]["q5"] = rs + check("queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", + all(r["status"] == "denied" and r["undoLabel"] == "" for r in rs) and bpy.context.mode == "EDIT_MESH" + and not (SCRATCH / "out" / "edit.glb").exists(), [r["message"] for r in rs]) + + +def q5_exit(): + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + check("queue: add-on drain reports no error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +def q6(): + queue("bad-list", action="createObject", objectType="MESH", name="QBadList", requestedBy="nibu/hands") + queue("bad-int", action="createObject", objectType="MESH", name="QBadInt", requestedBy="nibu/hands") + n, docs = node() + for key in ("bad-list", "bad-int"): # overwrite the id with a non-string, as a hand-written put could + doc = dict(n.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{key}"]) + doc["commandId"] = ["x"] if key == "bad-list" else 7 + n.database.put(docs["command_intent"], f"blender/commands/{key}", doc) + queue("zzzzzzzz-good", action="createObject", objectType="MESH", name="QAfterBad", requestedBy="nibu/hands") + + +def q6_check(): + denials = [r for k, r in all_receipts().items() if "queue key blender/commands/bad-" in r.get("message", "")] + R["receipts"]["q6"] = denials + check("queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + len(denials) == 2 and all(r["status"] == "denied" and isinstance(r["commandId"], str) for r in denials) + and not pending() and "QBadList" not in names() and "QBadInt" not in names() + and receipt("zzzzzzzz-good")["status"] == "accepted" and "QAfterBad" in names() + and adapter.last_auto_drain_error == "", [adapter.last_auto_drain_error, list(pending())]) + + +steps = [ + once(q1), until(drained("aaaaaaaa-0001")), once(q1_check), + once(q2), until(lambda: receipt("aaaaaaaa-0001.denied")), once(q2_check), + once(q3), until(drained("aaaaaaaa-0003")), once(q3_check), + once(q4), until(drained("aaaaaaaa-0004", "aaaaaaaa-0005")), once(q4_undo_two), + once(q6), until(drained("zzzzzzzz-good")), once(q6_check), + once(q5_edit), until(drained("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")), once(q5_check), once(q5_exit), +] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json new file mode 100644 index 0000000..e76bb3f --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -0,0 +1,243 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "pylibs": false, + "checks": [ + { + "name": "queue: createObject drained by the add-on timer, accepted, labelled, attributed", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:32:00.583673+00:00" + } + }, + { + "name": "queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "QCube" + ] + }, + { + "name": "queue: intent removed from the queue after the drain", + "ok": true, + "detail": [] + }, + { + "name": "queue: reused id leaves the original receipt untouched (write-once)", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:32:00.583673+00:00" + } + }, + { + "name": "queue: reused id reported under .denied, nothing created", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "denied", + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:32:02.587784+00:00" + } + }, + { + "name": "queue: intent without requestedBy denied, scene unchanged", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0003", + "action": "createObject", + "status": "denied", + "message": "Intent has no requestedBy of the form '/'.", + "objectName": "", + "requestedBy": "", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:32:04.590532+00:00" + } + }, + { + "name": "queue: two intents drained together are two undo steps, last first", + "ok": true, + "detail": [ + [ + "Camera", + "Cube", + "Light", + "QCube", + "QOne" + ], + [ + "Camera", + "Cube", + "Light", + "QCube" + ] + ] + }, + { + "name": "queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + "ok": true, + "detail": [ + "", + [] + ] + }, + { + "name": "queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", + "ok": true, + "detail": [ + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + ] + }, + { + "name": "queue: add-on drain reports no error", + "ok": true, + "detail": "" + } + ], + "receipts": { + "q1": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:32:00.583673+00:00" + }, + "q2_original": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaaaaaaa", + "observedAt": "2026-11-27T19:32:00.583673+00:00" + }, + "q2_denial": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "denied", + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:32:02.587784+00:00" + }, + "q3": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0003", + "action": "createObject", + "status": "denied", + "message": "Intent has no requestedBy of the form '/'.", + "objectName": "", + "requestedBy": "", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:32:04.590532+00:00" + }, + "q6": [ + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "8fe2e26fece047bcaca1b9938f1a030c", + "action": "createObject", + "status": "denied", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:32:08.599229+00:00" + }, + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "b1a5c7e22158468bb06f6b500c4fa2a7", + "action": "createObject", + "status": "denied", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:32:08.621069+00:00" + } + ], + "q5": [ + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0006", + "action": "setWorld", + "status": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:32:10.606424+00:00" + }, + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0007", + "action": "exportGltf", + "status": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:32:10.629698+00:00" + }, + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0008", + "action": "setObjectTransform", + "status": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "observedAt": "2026-11-27T19:32:10.665150+00:00" + } + ] + }, + "msgpack": "F:\\aeth-wt\\brokkr-live-1.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py new file mode 100644 index 0000000..9a9dc1b --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -0,0 +1,211 @@ +"""Live proof, in GUI Blender, that every agent intent is one undo step. + + BROKKR_ADDON= \ + blender --factory-startup --python agent_turn_undo.py -- + +Writes .result.json beside , then quits Blender. Each step is its own timer tick so the +event loop runs between steps, as it does for Brokkr's 1 s drain (probe_timer_undo.py pattern). +Undo is read only here, by this driver; the add-on never calls ed.undo or ed.redo. +Exit status is not meaningful in a GUI session: read the "ok" fields of the result. +""" +import json +import os +import sys +import tempfile +import traceback +import types +from pathlib import Path + +import bmesh +import bpy + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +OUT = sys.argv[sys.argv.index("--") + 1] +R = {"blender": bpy.app.version_string, "background": bpy.app.background, "checks": [], "steps": []} +target = bt.BrokkrBlenderTarget(bpy) +N = [0] +OUTDIR = tempfile.mkdtemp(prefix="brokkr-live2-") +target.configure_action_dirs("", OUTDIR) + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + w = bpy.context.window_manager.windows[0] + return bpy.context.temp_override(window=w) + + +def intent(**cmd): + N[0] += 1 + cmd.setdefault("commandId", "%08d-live-agent-turn" % N[0]) + cmd.setdefault("requestedBy", "nibu/hands") + r = target.run_intent(bpy.context, cmd) + R["steps"].append({"intent": cmd["action"], "status": r["status"], "undoLabel": r["undoLabel"], "message": r["message"]}) + return r + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def push(msg): + with win(): + bpy.ops.ed.undo_push(message=msg) + + +def loc(name): + o = bpy.data.objects.get(name) + return None if o is None else [round(v, 3) for v in o.location] + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} + + +def vz(): + bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data); bm.verts.ensure_lookup_table() + return round(bm.verts[0].co.z, 3) + + +def s_baseline(): + push("driver baseline") + S["objects0"] = names() + + +def s_create(): + r = intent(action="createObject", objectType="MESH", name="AgentCube", location=[3, 0, 0]) + check("createObject accepted with undoLabel", r["status"] == "accepted" and r["undoLabel"].startswith("Brokkr nibu/hands: createObject "), r["undoLabel"]) + + +def s_transform(): + intent(action="setObjectTransform", objectName="AgentCube", location=[3, 2, 0]) + check("transform applied", loc("AgentCube") == [3.0, 2.0, 0.0], loc("AgentCube")) + + +def s_undo_transform(): + undo() + check("one undo reverts only the transform step", "AgentCube" in names() and loc("AgentCube") == [3.0, 0.0, 0.0], + {"objects": names(), "loc": loc("AgentCube")}) + + +def s_undo_create(): + undo() + check("one undo reverts createObject (cube_add, rename, location) together", names() == S["objects0"], names()) + + +def s_denied_setup(): + intent(action="createObject", objectType="MESH", name="AgentCube2", location=[0, 5, 0]) + r = intent(action="createObject", objectType="MESH", requestedBy="", name="Intruder") + check("denied intent: status denied, scene unchanged", r["status"] == "denied" and "Intruder" not in names(), r["status"]) + check("denied intent: no undoLabel", r["undoLabel"] == "", r["undoLabel"]) + + +def s_denied_undo(): + undo() + check("denied intent pushed nothing: one undo removes the preceding accepted intent", names() == S["objects0"], names()) + + +def s_edit_enter(): + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube + cube.select_set(True) + with win(): + bpy.ops.object.mode_set(mode="EDIT") + S["loc0"] = loc("Cube") + push("driver edit-mode baseline") + S["z0"] = vz() + bm = bmesh.from_edit_mesh(cube.data); bm.verts.ensure_lookup_table(); bm.verts[0].co.z += 5.0 + bmesh.update_edit_mesh(cube.data) + push("her edit-mesh edit") + R["editMode"] = {"mode_before": bpy.context.mode, "loc_before": S["loc0"]} + + +def s_edit_agent(): + r = intent(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], + message=r["message"], undoLabel=r["undoLabel"]) + check("edit mode: object-level intent refused, scene and her mode unchanged", + r["status"] == "denied" and "Edit Mode" in r["message"] and r["undoLabel"] == "" + and loc("Cube") == S["loc0"] and bpy.context.mode == "EDIT_MESH", R["editMode"]) + + +def s_edit_others(): + """Anything that writes scene state or changes her mode is refused in Edit Mode; renderStill does neither.""" + world0 = bpy.context.scene.world + rw = intent(action="setWorld", color=[1, 0, 0], strength=2.0) + rx = intent(action="exportGltf", filepath="edit.glb") + rr = intent(action="renderStill", outputPath="edit.png", engine="CYCLES", resolutionX=8, resolutionY=8) + R["editMode"].update(setWorld=rw["status"], exportGltf=rx["status"], renderStill=rr["status"], + mode_after_others=bpy.context.mode) + check("edit mode: setWorld and exportGltf denied, world untouched, no file written", + rw["status"] == "denied" and rx["status"] == "denied" and bpy.context.scene.world == world0 + and "edit.glb" not in os.listdir(OUTDIR), R["editMode"]) + check("edit mode: renderStill accepted, pushes nothing, her mode kept", + rr["status"] == "accepted" and rr["undoLabel"] == "" and bpy.context.mode == "EDIT_MESH", R["editMode"]) + + +def s_edit_undo(): + """One undo must revert her edit-mesh step: a step pushed by the refused intent would have taken it.""" + undo() + R["editMode"].update(mode_after_undo=bpy.context.mode, loc_after_undo=loc("Cube"), z_before=S["z0"] + 5.0, z_after_undo=vz()) + check("edit mode: undo stack unchanged by the refused intent (one undo reverts her edit-mesh step)", + vz() == S["z0"] and loc("Cube") == S["loc0"], R["editMode"]) + + +def s_exit(): + if bpy.context.mode != "OBJECT": + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + + +def s_noop_setup(): + intent(action="createObject", objectType="MESH", name="AgentCube3", location=[0, -5, 0]) + rx = intent(action="exportGltf", filepath="object.glb") + rr = intent(action="renderStill", outputPath="object.png", engine="CYCLES", resolutionX=8, resolutionY=8) + check("exportGltf and renderStill accepted with no undoLabel", + rx["status"] == "accepted" and rr["status"] == "accepted" and rx["undoLabel"] == "" and rr["undoLabel"] == "", + [rx["message"], rr["message"]]) + + +def s_noop_undo(): + undo() + check("no-op actions pushed no step: one undo removes the preceding createObject", "AgentCube3" not in names(), names()) + + +steps = [s_baseline, s_create, s_transform, s_undo_transform, s_undo_create, s_denied_setup, s_denied_undo, + s_edit_enter, s_edit_agent, s_edit_others, s_edit_undo, s_exit, s_noop_setup, s_noop_undo] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not any("error" in s for s in R["steps"]) + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1) + + +def tick(): + global i + if i < len(steps): + try: + steps[i]() + except Exception: + R["steps"].append({"step": steps[i].__name__, "error": traceback.format_exc()}) + i += 1 + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=2.0) diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json new file mode 100644 index 0000000..0437128 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -0,0 +1,312 @@ +{ + "blender": "5.3.0", + "background": false, + "checks": [ + { + "name": "createObject accepted with undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createObject 00000001" + }, + { + "name": "transform applied", + "ok": true, + "detail": [ + 3.0, + 2.0, + 0.0 + ] + }, + { + "name": "one undo reverts only the transform step", + "ok": true, + "detail": { + "objects": [ + "AgentCube", + "Camera", + "Cube", + "Light" + ], + "loc": [ + 3.0, + 0.0, + 0.0 + ] + } + }, + { + "name": "one undo reverts createObject (cube_add, rename, location) together", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "denied intent: status denied, scene unchanged", + "ok": true, + "detail": "denied" + }, + { + "name": "denied intent: no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "denied intent pushed nothing: one undo removes the preceding accepted intent", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "edit mode: object-level intent refused, scene and her mode unchanged", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: setWorld and exportGltf denied, world untouched, no file written", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: renderStill accepted, pushes nothing, her mode kept", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: undo stack unchanged by the refused intent (one undo reverts her edit-mesh step)", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "exportGltf and renderStill accepted with no undoLabel", + "ok": true, + "detail": [ + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes).", + "Rendered still to object.png." + ] + }, + { + "name": "no-op actions pushed no step: one undo removes the preceding createObject", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + } + ], + "steps": [ + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject 00000001", + "message": "Blender object created." + }, + { + "intent": "setObjectTransform", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000002", + "message": "Blender object transform updated." + }, + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject 00000003", + "message": "Blender object created." + }, + { + "intent": "createObject", + "status": "denied", + "undoLabel": "", + "message": "Intent has no requestedBy of the form '/'." + }, + { + "intent": "setObjectTransform", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "setWorld", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "exportGltf", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "renderStill", + "status": "accepted", + "undoLabel": "", + "message": "Rendered still to edit.png." + }, + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject 00000009", + "message": "Blender object created." + }, + { + "intent": "exportGltf", + "status": "accepted", + "undoLabel": "", + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-_y_dg6ko\\object.glb (3484 bytes)." + }, + { + "intent": "renderStill", + "status": "accepted", + "undoLabel": "", + "message": "Rendered still to object.png." + } + ], + "ok": true, + "editMode": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index 1d9e329..62df949 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -4,7 +4,7 @@ blender -b --factory-startup --python gn_actions.py -- result.json Each native tree is built with bpy as the reference and evaluated with the depsgraph. The Brokkr side -uses BrokkrBlenderTarget.execute_command for every build step and capture_snapshot().objects[].evaluated +uses BrokkrBlenderTarget.run_intent for every build step and capture_snapshot().objects[].evaluated for every read: no bpy call touches the Brokkr-built scene except the harness's own reference trees. Exit status is non-zero if any check fails. """ @@ -29,7 +29,7 @@ def fresh(): N = [0] def act(t, **cmd): N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]) - r = t.execute_command(bpy.context, cmd) + r = t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) if r["status"] != "accepted": print("REFUSED", cmd["action"], r["message"], flush=True) return r diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py index 6ef8036..f8127d9 100644 --- a/surfaces/blender/tests/live/gn_recreation.py +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -4,7 +4,7 @@ blender -b --factory-startup --python gn_recreation.py -- result.json Each setup is built twice: natively (geometry-nodes tree via bpy, evaluated) and through -BrokkrBlenderTarget.execute_command using only the actions that exist. Prints GAP lines where an +BrokkrBlenderTarget.run_intent using only the actions that exist. Prints GAP lines where an action that would be needed is refused or has no effect. Not part of the unittest run (needs Blender). """ import bpy, sys, os, json, types, math, random @@ -25,7 +25,7 @@ def reset(): def act(t, **cmd): cmd.setdefault("commandId", "c%d" % act.n); act.n += 1 - return t.execute_command(bpy.context, cmd) + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) act.n = 0 def gap(key, **detail): diff --git a/surfaces/blender/tests/live/headless_smoke.py b/surfaces/blender/tests/live/headless_smoke.py index 085df0c..1d21601 100644 --- a/surfaces/blender/tests/live/headless_smoke.py +++ b/surfaces/blender/tests/live/headless_smoke.py @@ -43,7 +43,7 @@ results = [] def run(label, **cmd): cmd.setdefault("commandId", label) try: - r = target.execute_command(bpy.context, cmd) + r = target.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) except Exception: r = {"status": "EXCEPTION", "message": traceback.format_exc()} print("RESULT", label, r["status"], r.get("message", "").replace("\n", " | ")[:400], flush=True) diff --git a/surfaces/blender/tests/live/material_colour.py b/surfaces/blender/tests/live/material_colour.py index 4b43135..07c2f4d 100644 --- a/surfaces/blender/tests/live/material_colour.py +++ b/surfaces/blender/tests/live/material_colour.py @@ -26,7 +26,7 @@ cube = bpy.context.active_object N = [0] def act(**cmd): N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = "assignMaterial"; cmd["targetObjectName"] = cube.name - return t.execute_command(bpy.context, cmd) + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) def base(): return tuple(round(c, 6) for c in bpy.data.materials["oxide red"].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value) diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py new file mode 100644 index 0000000..02706de --- /dev/null +++ b/surfaces/blender/tests/test_agent_turn.py @@ -0,0 +1,284 @@ +"""run_intent: admission, one labelled undo step, receipts. A fake bpy records ops calls.""" +from __future__ import annotations + +import re +import sys +import tempfile +import unittest +import unittest.mock +from pathlib import Path + +import test_scene_actions as ts + +bt = ts.bt +SOURCE = Path(bt.__file__) + + +class AgentTurnTests(unittest.TestCase): + """Reuses the scene fixture (fake bpy, temp import/output dirs).""" + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def test_intent_without_requested_by_is_denied(self): + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.undo.pushes, []) + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="nibu") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_object_intent_is_refused_while_an_object_is_in_edit_mode(self): + self.bpy.mesh.mode = "EDIT" + receipt = self.run_action(action="setObjectTransform", objectName="Cube", location=[0, 0, 5]) + self.assertEqual(receipt["status"], "denied") + self.assertIn("Edit Mode", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.mesh.mode, "EDIT") # the agent never changes her mode + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + self.bpy.mesh.mode = "OBJECT" + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + + def test_unknown_action_is_denied(self): + self.assertEqual(self.run_action(action="runPython")["status"], "denied") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_reused_command_id_is_denied(self): + first = self.run_action(action="createObject", objectType="EMPTY", commandId="same-id-1") + self.assertEqual(first["status"], "accepted") + second = self.run_action(action="createObject", objectType="EMPTY", commandId="same-id-1") + self.assertEqual(second["status"], "denied") + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(len(self.bpy.undo.pushes), 1) + + def test_accepted_receipt_carries_undo_label(self): + receipt = self.run_action(action="createObject", objectType="EMPTY", + commandId="abcdef0123456789", requestedBy="nibu/hands", note="x" * 300) + label = "Brokkr nibu/hands: createObject abcdef01" + self.assertEqual(self.bpy.undo.pushes, [label]) + self.assertEqual(receipt["undoLabel"], label) + self.assertEqual(receipt["requestedBy"], "nibu/hands") + self.assertEqual(len(receipt["note"]), 200) + + def test_refusal_pushes_nothing(self): + receipt = self.run_action(action="createObject", objectType="BOGUS") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_read_action_pushes_nothing(self): + with unittest.mock.patch.object(bt, "READ_ACTIONS", ("createObject",)): + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_raise_after_admission_pushes_failed_step(self): + def boom(*a, **kw): + raise RuntimeError("half done") + self.bpy.ops.object.empty_add = boom + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="deadbeef99") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, ["Brokkr nibu/hands: createObject deadbeef (failed)"]) + + def test_agent_turn_flag_is_scoped(self): + seen = [] + original = self.bpy.ops.object.empty_add + self.bpy.ops.object.empty_add = lambda *a, **kw: (seen.append(self.target.agent_turn), original(*a, **kw))[1] + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(seen, [True]) + self.assertFalse(self.target.agent_turn) + + def test_operators_called_with_undo_false(self): + self.assertEqual(self.run_action(action="exportGltf", filepath="o.glb")["status"], "accepted") + self.assertEqual(self.run_action(action="importGltf", filepath="model.glb")["status"], "accepted") + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + for kind in ("MESH", "LIGHT", "CAMERA", "EMPTY"): + self.assertEqual(self.run_action(action="createObject", objectType=kind)["status"], "accepted") + # the fake ops assert ("EXEC_DEFAULT", False); the source pattern pins the spelling too + bad = re.findall(r'bpy\.ops\.(?:mesh|object|import_scene|export_scene|render)\.[a-z_]+\((?!"EXEC_DEFAULT", False)', + SOURCE.read_text(encoding="utf-8")) + self.assertEqual(bad, []) + + # fix batch s1 + def test_world_and_export_are_refused_in_edit_mode_render_is_not(self): + self.bpy.mesh.mode = "EDIT" + for action, fields in (("setWorld", {}), ("exportGltf", {"filepath": "o.glb"})): + receipt = self.run_action(action=action, **fields) + self.assertEqual(receipt["status"], "denied", action) + self.assertIn("Edit Mode", receipt["message"]) + self.assertEqual(self.bpy.exported, []) + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + + def test_export_and_render_push_no_undo_step(self): + self.assertEqual(self.run_action(action="exportGltf", filepath="o.glb")["status"], "accepted") + receipt = self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES") + self.assertEqual(receipt["status"], "accepted") + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_returned_failed_receipt_pushes_nothing(self): + receipt = self.run_action(action="setObjectTransform", objectName="NoSuchObject", location=[1, 2, 3]) + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_denied_id_is_recorded_as_receipted(self): + self.bpy.mesh.mode = "EDIT" + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY", commandId="denied-1")["status"], "denied") + self.bpy.mesh.mode = "OBJECT" + again = self.run_action(action="createObject", objectType="EMPTY", commandId="denied-1") + self.assertEqual(again["status"], "denied") + self.assertIn("single-use", again["message"]) + self.assertEqual(self.bpy.created, []) + + def test_undo_push_runs_under_the_first_window(self): + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(self.bpy.undo.overrides, [{"window": self.bpy.undo.window}]) + + def test_push_failure_is_a_failed_receipt_and_never_reruns(self): + def broken(message): + raise RuntimeError("no undo stack") + self.bpy.ops.ed.undo_push = broken + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="push-fail-1") + self.assertEqual(receipt["status"], "failed") + self.assertIn("no undo stack", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + again = self.run_action(action="createObject", objectType="EMPTY", commandId="push-fail-1") + self.assertEqual(again["status"], "denied") + self.assertEqual(len(self.bpy.created), 1) + + # fix batch s2 + def test_no_scene_change_set_is_exactly_export_and_render(self): + self.assertEqual(bt.NO_SCENE_CHANGE_ACTIONS, ("exportGltf", "renderStill")) + receipt = self.run_action(action="setWorld", color=[0.1, 0.2, 0.3]) + self.assertEqual(receipt["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 1) + + def test_malformed_command_ids_are_denied_without_raising(self): + for bad in (["x"], 7, 1.5, {"a": 1}, "", "a/b", "x.denied", "has space", "a" * 200, None, True): + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId=bad) + self.assertEqual(receipt["status"], "denied", repr(bad)) + self.assertIsInstance(receipt["commandId"], str) + self.assertRegex(receipt["commandId"], bt.COMMAND_ID_SHAPE.pattern, repr(bad)) + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_trailing_newline_does_not_pass_the_id_shapes(self): + self.assertFalse(bt._valid_command_id("okid\n")) + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="okid\n") + self.assertEqual(receipt["status"], "denied") + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="nibu/hands\n") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_load_cultmesh_pins_its_own_package_set(self): + # an unrelated module named like a CultLib package is a missing dependency, not "CultLib is absent" + self.assertEqual(bt.CULTLIB_PY_PACKAGES, ("cultcache-py", "cultnet-py", "cultmesh-py")) + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) + src = root / "cultmesh-py" / "src" / "cultmesh_py" + src.mkdir(parents=True) + (src / "__init__.py").write_text("import cultnet_py") # an own package that is absent here + saved = {k: sys.modules.pop(k) for k in ("cultmesh_py", "cultcache_py", "cultnet_py") if k in sys.modules} + saved_path = list(sys.path) + self.addCleanup(lambda: (sys.modules.update(saved), sys.path.__setitem__(slice(None), saved_path))) + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh(str(root)) + self.assertIn("requires CultLib's Python packages", str(caught.exception)) + + def test_debug_command_file_is_not_executed(self): + with tempfile.TemporaryDirectory() as tmp: + commands = Path(tmp) / "blender" / "commands" + commands.mkdir(parents=True) + door = commands / "door-1.json" + door.write_text('{"commandId": "door-1", "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY"}') + node = FakeNode({}) + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, docs)): + receipts = self.target.drain_commands(self.context, "cache", "src", tmp) + self.assertEqual(receipts, []) + self.assertEqual(node.puts, []) + self.assertEqual(self.bpy.created, []) + self.assertTrue(door.exists()) + + def test_load_cultmesh_names_the_missing_module(self): + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) + src = root / "cultmesh-py" / "src" / "cultmesh_py" + src.mkdir(parents=True) + (src / "__init__.py").write_text("import brokkr_no_such_dependency_xyz") + saved = {k: sys.modules.pop(k) for k in ("cultmesh_py", "cultcache_py") if k in sys.modules} + saved_path = list(sys.path) + self.addCleanup(lambda: (sys.modules.update(saved), sys.path[:] == saved_path or sys.path.__setitem__(slice(None), saved_path))) + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh(str(root)) + self.assertIn("brokkr_no_such_dependency_xyz", str(caught.exception)) + self.assertNotIn("requires CultLib's Python packages", str(caught.exception)) + + +class FakeNode: + """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" + def __init__(self, intents, receipts=()): + self.docs = {bt.COMMAND_INTENT_SCHEMA: dict(intents), bt.COMMAND_RECEIPT_SCHEMA: dict(receipts)} + self.puts = [] + self.deleted = [] + self.database = self + + def snapshot(self): + return {k: dict(v) for k, v in self.docs.items()} + + def put(self, document, key, value): + self.puts.append((key, value)) + + def delete(self, document, key): + self.deleted.append(key) + + +class DrainTests(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def drain(self, node): + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, docs)): + return self.target.drain_commands(self.context, "cache", "src") + + def intent(self, cid, **fields): + return {"commandId": cid, "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY", **fields} + + def test_malformed_ids_in_the_queue_never_wedge_the_drain(self): + node = FakeNode({ + "blender/commands/a-list": self.intent(["x"]), + "blender/commands/b-int": self.intent(7), + "blender/commands/c-good": self.intent("good-1"), + }) + receipts = self.drain(node) # must not raise + self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual([r["status"] for r in receipts], ["denied", "denied", "accepted"]) + keys = [k for k, _ in node.puts] + self.assertTrue(all(isinstance(k, str) and "[" not in k for k in keys), keys) + self.assertIn("blender/receipts/good-1", keys) + bad = [v for k, v in node.puts if k != "blender/receipts/good-1"] + self.assertTrue(all("blender/commands/" in v["message"] for v in bad), [v["message"] for v in bad]) + + def test_drain_seeds_receipted_from_persisted_receipts(self): + old = {"blender/receipts/old-1": {"commandId": "old-1", "status": "accepted"}} + node = FakeNode({"blender/commands/old-1": self.intent("old-1")}, old) + receipts = self.drain(node) + self.assertEqual(receipts[0]["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_reused_id_never_overwrites_the_original_receipt(self): + node = FakeNode({"blender/commands/a": self.intent("dup-1"), "blender/commands/b": self.intent("dup-1")}) + self.drain(node) + keys = [k for k, _ in node.puts] + self.assertEqual(keys.count("blender/receipts/dup-1"), 1) + self.assertEqual(dict(node.puts)["blender/receipts/dup-1"]["status"], "accepted") + denial = dict(node.puts)["blender/receipts/dup-1.denied"] + self.assertEqual(denial["status"], "denied") + self.assertEqual(sorted(node.deleted), ["blender/commands/a", "blender/commands/b"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py index 9ecc2ec..0caa663 100644 --- a/surfaces/blender/tests/test_material_actions.py +++ b/surfaces/blender/tests/test_material_actions.py @@ -5,6 +5,9 @@ The real API is exercised by tests/live/material_colour.py. """ from __future__ import annotations +import contextlib +import itertools + import sys import types import unittest @@ -50,11 +53,25 @@ class Materials(dict): return self[name] +IDS = itertools.count() + + +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.mesh = NS(name="Cube", type="MESH", data=NS(materials=[])) self.empty = NS(name="Empty", type="EMPTY", data=None) self.data = NS(objects={"Cube": self.mesh, "Empty": self.empty}, materials=Materials()) + self.undo = FakeUndo(self) class MaterialTests(unittest.TestCase): @@ -63,7 +80,7 @@ class MaterialTests(unittest.TestCase): self.target = bt.BrokkrBlenderTarget(self.bpy) def assign(self, **fields): - return self.target.execute_command(NS(), {"commandId": "c1", "action": "assignMaterial", + return self.target.run_intent(NS(), {"commandId": f"c{next(IDS)}", "requestedBy": "nibu/hands", "action": "assignMaterial", "targetObjectName": "Cube", **fields}) def base_color(self, name="oxide red"): @@ -137,7 +154,7 @@ class MaterialTests(unittest.TestCase): self.assertEqual(self.base_color("bare"), (0.2, 0.3, 0.4, 1.0)) def test_object_without_material_slots_is_refused(self): - receipt = self.target.execute_command(NS(), {"commandId": "c", "action": "assignMaterial", + receipt = self.target.run_intent(NS(), {"commandId": f"c{next(IDS)}", "requestedBy": "nibu/hands", "action": "assignMaterial", "targetObjectName": "Empty", "color": [1, 0, 0]}) self.assertEqual(receipt["status"], "failed") self.assertEqual(dict(self.bpy.data.materials), {}) diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 4c333f1..6aeee39 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -5,6 +5,8 @@ The real API is exercised by tests/live/gn_actions.py. """ from __future__ import annotations +import contextlib + import sys import types import unittest @@ -168,9 +170,20 @@ class Obj: self.custom = (key, value) +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.data = NS(node_groups=Groups(), objects={"Host": Obj("Host")}) + self.undo = FakeUndo(self) class NodeActionTests(unittest.TestCase): @@ -182,7 +195,8 @@ class NodeActionTests(unittest.TestCase): def run_action(self, **command): self.n += 1 command.setdefault("commandId", f"c{self.n}") - return self.target.execute_command(None, command) + command.setdefault("requestedBy", "nibu/hands") + return self.target.run_intent(None, command) def accepted(self, **command): receipt = self.run_action(**command) @@ -530,8 +544,11 @@ class NodeActionTests(unittest.TestCase): tree = self.chain() self.accepted(action="removeNode", treeKey="G", id="b") self.assertEqual([n.get("brokkr_id") for n in tree.nodes], ["gin", "gout", "a", "c"]) + pushes = len(self.bpy.undo.pushes) again = self.accepted(action="removeNode", treeKey="G", id="b") self.assertIn("already absent", again["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) # nothing changed: no undo step + self.assertEqual(again["undoLabel"], "") for keep in ("gin", "gout"): self.refused(action="removeNode", treeKey="G", id=keep) self.refused(action="removeNode", treeKey="Nope", id="a") @@ -561,7 +578,11 @@ class NodeActionTests(unittest.TestCase): self.accepted(action="removeModifier", objectName="Host", modifierName="GN") self.assertEqual([m.name for m in host.modifiers], ["Sub"]) self.assertEqual(host.tagged, tags + 1) - self.assertIn("already absent", self.accepted(action="removeModifier", objectName="Host", modifierName="GN")["message"]) + pushes = len(self.bpy.undo.pushes) + again = self.accepted(action="removeModifier", objectName="Host", modifierName="GN") + self.assertIn("already absent", again["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) + self.assertEqual(again["undoLabel"], "") self.refused(action="removeModifier", objectName="Nope", modifierName="GN") for bad in (["x"], "x" * 256, "a\0b", 5): self.refused(action="removeModifier", objectName="Host", modifierName=bad) diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index bb3a292..6c73c67 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -4,6 +4,7 @@ Run: python3 -m unittest discover -s surfaces/blender/tests -v """ from __future__ import annotations +import contextlib import json import os import struct @@ -69,6 +70,19 @@ class Objects(dict): """bpy.data.objects: a mapping with keys() and get().""" +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + self.overrides = [] + self.window = object() + bpy.context = NS(window_manager=NS(windows=[self.window]), + temp_override=lambda **kw: (self.overrides.append(kw), contextlib.nullcontext())[1]) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.imported = [] @@ -95,14 +109,16 @@ class FakeBpy: o.selected = o is self.mesh o.select_get = (lambda o=o: o.selected) o.select_set = (lambda state, o=o: setattr(o, "selected", state)) - add = lambda kind: (lambda **kw: self.add_object(kind, kw)) + add = lambda kind: (lambda mode, undo, **kw: self.add_object(kind, kw, (mode, undo))) self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still), export_scene=NS(gltf=self.export_gltf), mesh=NS(primitive_cube_add=add("MESH")), object=NS(light_add=add("LIGHT"), camera_add=add("CAMERA"), empty_add=add("EMPTY"))) self.on_add = lambda obj: None + self.undo = FakeUndo(self) - def add_object(self, kind, kwargs): + def add_object(self, kind, kwargs, call=("EXEC_DEFAULT", False)): + assert call == ("EXEC_DEFAULT", False), call # operators run with undo off self.created.append((kind, kwargs)) obj = NS(name=kind.title(), type=kind) self.data.objects[obj.name] = obj @@ -115,18 +131,21 @@ class FakeBpy: world.background = background return world - def import_gltf(self, filepath): + def import_gltf(self, mode, undo, filepath): + assert (mode, undo) == ("EXEC_DEFAULT", False) self.imported.append(filepath) self.data.objects["Imported"] = NS(name="Imported", type="MESH", data=None) - def export_gltf(self, **kwargs): + def export_gltf(self, mode, undo, **kwargs): + assert (mode, undo) == ("EXEC_DEFAULT", False) kwargs["selected_at_call"] = sorted(o.name for o in self.data.objects.values() if o.selected) self.exported.append(kwargs) if self.export_writes: Path(kwargs["filepath"]).write_bytes(b"x" * 10) return self.export_result - def render_still(self, write_still): + def render_still(self, mode, undo, write_still): + assert (mode, undo) == ("EXEC_DEFAULT", False) r = self.scene.render self.rendered.append((r.engine, r.resolution_x, r.resolution_y, r.filepath, r.image_settings.file_format, self.scene.camera)) @@ -149,8 +168,10 @@ class ActionTests(unittest.TestCase): self.bpy.on_add = lambda obj: setattr(self.context, "object", obj) def run_action(self, **command): - command.setdefault("commandId", "c1") - return self.target.execute_command(self.context, command) + self.n = getattr(self, "n", 0) + 1 + command.setdefault("commandId", f"c{self.n:07d}") + command.setdefault("requestedBy", "nibu/hands") + return self.target.run_intent(self.context, command) # importGltf def test_import_inside_the_import_dir_runs(self): @@ -289,7 +310,7 @@ class ActionTests(unittest.TestCase): self.assertFalse((self.root / "out" / "b.glb").exists()) def test_export_selection_restored_when_the_exporter_raises(self): - def boom(**kw): + def boom(*a, **kw): raise RuntimeError("exporter blew up") self.bpy.ops.export_scene.gltf = boom receipt = self.run_action(action="exportGltf", filepath="a.glb", selection=["Cam"]) @@ -362,7 +383,7 @@ class ActionTests(unittest.TestCase): self.assertIsNone(self.bpy.scene.camera) def test_render_still_restores_settings_when_the_render_fails(self): - def boom(write_still): + def boom(*a, **kw): raise RuntimeError("render failed") self.bpy.ops.render.render = boom self.assertEqual(self.run_action(action="renderStill", outputPath="a.png", engine="CYCLES")["status"], "failed") diff --git a/surfaces/blender/tests/test_server_guard.py b/surfaces/blender/tests/test_server_guard.py index 439cfe0..d726162 100644 --- a/surfaces/blender/tests/test_server_guard.py +++ b/surfaces/blender/tests/test_server_guard.py @@ -144,48 +144,29 @@ class FakeNode: class PurgeTests(unittest.TestCase): - def make_debug_root(self, tmp): - commands = Path(tmp) / "blender" / "commands" - commands.mkdir(parents=True) - (commands / "a.json").write_text("{}") - (commands / "b.json").write_text("{}") - (commands / "note.txt").write_text("keep") - receipts = Path(tmp) / "blender" / "receipts" - receipts.mkdir() - (receipts / "r.json").write_text("{}") - return commands, receipts + def test_purge_removes_queued_intents(self): + node = FakeNode(["c1", "c2"]) + removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA) + self.assertEqual(removed, 2) + self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) - def test_purge_removes_queued_intents_and_debug_command_files_only(self): - with tempfile.TemporaryDirectory() as tmp: - commands, receipts = self.make_debug_root(tmp) - node = FakeNode(["c1", "c2"]) - removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA, tmp) - self.assertEqual(removed, 4) - self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) - self.assertEqual(sorted(p.name for p in commands.iterdir()), ["note.txt"]) - self.assertTrue((receipts / "r.json").exists()) - - def test_purge_without_a_debug_root_or_node_is_quiet(self): - self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA, ""), 0) + def test_purge_without_a_node_is_quiet(self): + self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA), 0) def test_stop_server_purges_and_revokes(self): - with tempfile.TemporaryDirectory() as tmp: - commands, _ = self.make_debug_root(tmp) - target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) - stopped = [] - target._server = types.SimpleNamespace(stop=lambda: stopped.append(True)) - target._guard = sg.SessionGuard() - guard = target._guard - old = guard.token - target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} - target._debug_mirror_root = tmp - target.stop_server() - self.assertEqual(stopped, [True]) - self.assertEqual(target._node.database.keys, []) - self.assertEqual(sorted(p.name for p in commands.iterdir()), ["note.txt"]) - self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) - self.assertEqual(target.session_token, "") + target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) + stopped = [] + target._server = types.SimpleNamespace(stop=lambda: stopped.append(True)) + target._guard = sg.SessionGuard() + guard = target._guard + old = guard.token + target._node = FakeNode(["c1"]) + target._documents = {"command_intent": "DOC"} + target.stop_server() + self.assertEqual(stopped, [True]) + self.assertEqual(target._node.database.keys, []) + self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) + self.assertEqual(target.session_token, "") def test_stop_server_revokes_and_purges_even_when_the_socket_stop_raises(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) @@ -229,24 +210,19 @@ class RealServerTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) - self.debug = str(Path(self.tmp.name) / "debug") - commands = Path(self.debug) / "blender" / "commands" - commands.mkdir(parents=True) - (commands / "stale.json").write_text("{}") self.cache = str(Path(self.tmp.name) / "node.ccmp") self.target = bt.BrokkrBlenderTarget(types.SimpleNamespace( path=types.SimpleNamespace(abspath=lambda p: p))) self.addCleanup(self.target.stop_server) def start(self, **kwargs): - return self.target.start_server(self.cache, PACKAGES, "127.0.0.1", 0, 100, 1 << 20, self.debug, **kwargs) + return self.target.start_server(self.cache, PACKAGES, "127.0.0.1", 0, 100, 1 << 20, **kwargs) - def test_default_start_has_no_token_and_purges_stale_debug_commands(self): + def test_default_start_has_no_token(self): status = self.start() self.assertTrue(status["running"]) self.assertFalse(status["tokenRequired"]) self.assertEqual(self.target.session_token, "") - self.assertEqual(list((Path(self.debug) / "blender" / "commands").glob("*.json")), []) self.assertTrue(status["cultmeshModule"].endswith("__init__.py")) self.assertIn("cultmesh_py", status["cultmeshModule"]) self.assertTrue(status["loopback"]) @@ -311,17 +287,17 @@ class RealServerTests(unittest.TestCase): self.assertEqual(self.queued(self.cache), []) def test_allow_true_goes_through_start_server_and_unticking_stops_it(self): - status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=True) self.assertTrue(status["running"]) self.assertFalse(status["loopback"]) with self.assertRaises(sg.BindRefused): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=False) self.assertFalse(self.target.server_status()["running"]) def test_unticking_the_allow_stops_a_running_non_loopback_server(self): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=True) self.target.enforce_bind_policy(False) self.assertFalse(self.target.server_status()["running"]) @@ -378,7 +354,7 @@ class RealServerTests(unittest.TestCase): def test_non_loopback_bind_is_refused_before_anything_starts(self): with self.assertRaises(sg.BindRefused): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug) + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20) self.assertFalse(self.target.server_status()["running"])