diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md index 13592ad..aee7181 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. diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 677f03d..a3156c0 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,16 @@ 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", +) +REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") +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 @@ -92,6 +103,8 @@ class BrokkrBlenderTarget: self.import_dir: str = "" self.output_dir: str = "" self.nodes = na.NodeActions(bpy_module) + self.agent_turn = False # true only inside run_intent + 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.""" @@ -133,9 +146,11 @@ class BrokkrBlenderTarget: snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] + self._receipted.update( + r.get("commandId", "") for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values()) for command_key, command in sorted(commands.items()): - receipt = self.execute_command(context, command) + receipt = self.run_intent(context, command) self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root) node.database.delete(documents["command_intent"], command_key) receipts.append(receipt) @@ -488,45 +503,89 @@ 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 isinstance(command_id, str) or not command_id: + denial = "Intent has no commandId." + 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.match(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}" + if denial: + if isinstance(command_id, str) and 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 + self.agent_turn = 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": + push = False # returned a refusal: 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: + self._push_undo(label) + receipt["undoLabel"] = label + finally: + self.agent_turn = False + self._receipted.add(command_id) + return receipt + + 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) + 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 +601,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 +721,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 +767,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 +907,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 @@ -1013,6 +1072,9 @@ class BrokkrBlenderTarget: "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(), } 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..c41ca89 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -0,0 +1,170 @@ +"""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 traceback +import types +from pathlib import Path + +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] + + +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 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") + 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"], undoLabel=r["undoLabel"]) + check("edit mode: agent transform applied", loc("Cube") == [0.0, 0.0, 5.0], loc("Cube")) + + +def s_edit_undo(): + undo() + R["editMode"].update(mode_after_undo=bpy.context.mode, loc_after_undo=loc("Cube")) + check("edit mode: one undo reverts the agent transform", loc("Cube") == S["loc0"], R["editMode"]) + + +def s_edit_undo_again(): + """Diagnostic, not a check: where does the object-level write sit relative to Edit Mode steps?""" + undo() + R["editMode"].update(mode_after_second_undo=bpy.context.mode, loc_after_second_undo=loc("Cube")) + + +def s_exit(): + if bpy.context.mode != "OBJECT": + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + + +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_undo, s_edit_undo_again, s_exit] +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..5ae93a7 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -0,0 +1,167 @@ +{ + "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: agent transform applied", + "ok": true, + "detail": [ + 0.0, + 0.0, + 5.0 + ] + }, + { + "name": "edit mode: one undo reverts the agent transform", + "ok": false, + "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, + 5.0 + ], + "receipt": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 5.0 + ], + "mode_after_second_undo": "OBJECT", + "loc_after_second_undo": [ + 0.0, + 0.0, + 0.0 + ] + } + } + ], + "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": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "message": "Blender object transform updated." + } + ], + "ok": false, + "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, + 5.0 + ], + "receipt": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 00000005", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 5.0 + ], + "mode_after_second_undo": "OBJECT", + "loc_after_second_undo": [ + 0.0, + 0.0, + 0.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..353f709 --- /dev/null +++ b/surfaces/blender/tests/test_agent_turn.py @@ -0,0 +1,90 @@ +"""run_intent: admission, one labelled undo step, receipts. A fake bpy records ops calls.""" +from __future__ import annotations + +import re +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_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, []) + + +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..eac602f 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) diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index bb3a292..c60b657 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,16 @@ 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 = [] + 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.imported = [] @@ -95,14 +106,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 +128,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 +165,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 +307,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 +380,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")