From 692606ba75ee048aa55507362ae784426fa8357f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:10:08 +0100 Subject: [PATCH 1/6] Blender add-on: host add-ons add rows to the action table through brokkr_actions.json check_host, host_actions discovery with ownership and RNA checks, _run_host_operator in the agent turn, hostActions and hostActionErrors in the snapshot, hostResult in receipts, fixture host add-on and cases. Co-Authored-By: Claude Sonnet 5.5 --- .../blender/brokkr_bridge/action_table.py | 74 +++++- .../blender/brokkr_bridge/blender_target.py | 154 +++++++++++- .../fixtures/brokkr_host_fixture/__init__.py | 72 ++++++ .../brokkr_host_fixture/brokkr_actions.json | 37 +++ surfaces/blender/tests/host_action_cases.json | 21 ++ surfaces/blender/tests/test_action_table.py | 68 ++++++ surfaces/blender/tests/test_agent_turn.py | 222 ++++++++++++++++++ .../blender/tests/test_material_actions.py | 2 +- surfaces/blender/tests/test_node_actions.py | 2 +- surfaces/blender/tests/test_scene_actions.py | 2 +- surfaces/blender/tests/test_stop_presence.py | 2 +- 11 files changed, 638 insertions(+), 18 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py create mode 100644 surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json create mode 100644 surfaces/blender/tests/host_action_cases.json diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py index 3ecaa2f..48a888f 100644 --- a/surfaces/blender/brokkr_bridge/action_table.py +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -1,7 +1,9 @@ """The action table: which Blender intents exist, what fields each may carry, and each action's undo class. -actions.json (schema brokkr.blender.actions.v0) is the one owner. run_intent admits every intent through -validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and +actions.json (schema brokkr.blender.actions.v0) owns the built-in rows; a host add-on adds rows of its own +operators in brokkr_actions.json (schema brokkr.blender.host_actions.v0: scalar fields only, no free JSON, +an optional result naming a WindowManager string property), checked by check_host and passed to validate() +and entry() as `host`. run_intent admits every intent through validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and message text (surfaces/blender/tests/action_cases.json pins the two). Stdlib only, no bpy. Vocabulary: null means absent; a required field absent is refused; a field neither declared nor in the @@ -17,11 +19,15 @@ from __future__ import annotations import functools import json import math +import re from pathlib import Path from typing import Any TABLE_PATH = Path(__file__).with_name("actions.json") SCHEMA = "brokkr.blender.actions.v0" +HOST_SCHEMA = "brokkr.blender.host_actions.v0" +HOST_TYPES = ("string", "number", "integer", "boolean") +HOST_NAME = re.compile(r"^[a-z0-9_]+\.[a-z0-9_]+$") TYPES = ("string", "number", "integer", "boolean", "array", "object", "any") TYPE_WORDS = {"string": "a string", "number": "a finite number", "integer": "a whole number", "boolean": "true or false", "array": "an array", "object": "an object"} @@ -57,9 +63,14 @@ def table() -> dict[str, Any]: return document -def entry(action: Any) -> dict[str, Any] | None: - """The table row for an action name, or None.""" - return _by_name().get(action) if isinstance(action, str) else None +def entry(action: Any, host: Any = ()) -> dict[str, Any] | None: + """The row for an action name: the built-in row, else the first host row of that name, else None.""" + if not isinstance(action, str): + return None + row = _by_name().get(action) + if row is not None: + return row + return next((h for h in host if h.get("name") == action), None) @functools.lru_cache(maxsize=1) @@ -90,6 +101,55 @@ def check_table(document: dict[str, Any]) -> None: raise TableInvalid(f"{action['name']}.{field['name']} default: {error}") from None +def check_host(document: Any, charsets: dict[str, Any]) -> None: + """Refuse a host add-on's brokkr_actions.json unless its schema is the host schema, every name is a dotted + operator id and unique, every field is scalar and passes the built-in spec checks (and its default its own + rules), and result, if present, is an identifier. Raises TableInvalid naming the row and field.""" + if not isinstance(document, dict) or document.get("schema") != HOST_SCHEMA: + raise TableInvalid(f"host schema must be {HOST_SCHEMA}") + for key in document: + if key not in ("schema", "actions"): + raise TableInvalid(f"host file has no key '{key}'") + rows = document.get("actions") + if not isinstance(rows, list): + raise TableInvalid("host file actions must be an array") + names = set() + for row in rows: + name = row.get("name") if isinstance(row, dict) else None + if not isinstance(name, str) or not HOST_NAME.match(name): + raise TableInvalid(f"host action name {name!r} must look like addon.operator (a-z, 0-9, _)") + if name in names: + raise TableInvalid(f"host action {name} is listed twice") + names.add(name) + for key in ("doc", "changesScene", "editModeSafe", "fields"): + if key not in row: + raise TableInvalid(f"{name} lacks {key}") + if not isinstance(row["fields"], list): + raise TableInvalid(f"{name} fields must be an array") + for key in row: + if key not in ("name", "doc", "changesScene", "editModeSafe", "fields", "result"): + raise TableInvalid(f"{name} has no key '{key}'") + if "result" in row and not (isinstance(row["result"], str) and row["result"].isidentifier()): + raise TableInvalid(f"{name}.result must be an identifier") + fields = {} + for field in row["fields"]: + if not isinstance(field, dict) or not isinstance(field.get("name"), str) or field["name"] in fields: + raise TableInvalid(f"{name} has a missing or repeated field name") + fields[field["name"]] = field + for field in fields.values(): + where = f"{name}.{field['name']}" + if field.get("type") not in HOST_TYPES: + raise TableInvalid(f"{where}: a host field is one of {_list(list(HOST_TYPES))}") + if "only" in field: + raise TableInvalid(f"{where}: a host field has no 'only'") + _check_spec(field, where, charsets, fields, top=True) + if "default" in field: + try: + _value(field, field["default"], field["name"]) + except IntentInvalid as error: + raise TableInvalid(f"{where} default: {error}") from None + + def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict, top: bool) -> None: kind = spec.get("type") if kind not in TYPES: @@ -116,11 +176,11 @@ def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict _check_spec(prop, f"{where}.{prop['name']}", charsets, inner, top=False) -def validate(command: dict[str, Any]) -> dict[str, Any]: +def validate(command: dict[str, Any], host: Any = ()) -> dict[str, Any]: """The normalized copy of an intent (nulls dropped, whole numbers of integer fields as int, defaults filled), or IntentInvalid naming the rule. It raises nothing else, whatever the document holds.""" action = command.get("action", "") - row = entry(action) + row = entry(action, host) if row is None: raise IntentInvalid(f"Unsupported Blender command action: {action}") present = {k: v for k, v in command.items() if v is not None} diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index f87da9c..8bde4b0 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -42,6 +42,8 @@ CULTLIB_PY_PACKAGES = ("cultcache-py", "cultnet-py", "cultmesh-py") DEFAULT_DEBUG_MIRROR_ROOT = "//.brokkr/blender-editor-debug" HOST_SNAPSHOT_SCHEMA = "brokkr.blender.host_snapshot.v0" +HOST_ACTIONS_FILE = "brokkr_actions.json" +HOST_RESULT_LIMIT = 16000 # characters of a host operator's result copied into a receipt COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0" COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0" SYNC_SESSION_SCHEMA = "brokkr.sync.session.v0" @@ -100,6 +102,14 @@ CAPABILITIES = ( ) +class _NoHostFile(Exception): + """The add-on has no brokkr_actions.json: it is not a host.""" + + +def _first_line(text: str) -> str: + return text.strip().splitlines()[0] if text.strip() else "failed" + + class BrokkrBlenderTarget: """Blender-owned adapter target for Brokkr mirror documents.""" @@ -121,6 +131,7 @@ class BrokkrBlenderTarget: 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() + self._host_files: dict[str, tuple[tuple, Any]] = {} # module -> (file stamp, parsed document or error text): a cache of reads, never truth self._unsent: list[tuple[dict[str, Any], str]] = [] # receipts whose write failed: written first on the next drain, never read as truth self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False @@ -600,6 +611,7 @@ class BrokkrBlenderTarget: def capture_snapshot(self, context: Any, agent_commands_enabled: bool) -> dict[str, Any]: bpy = self.bpy + host_rows, host_errors = self.host_actions() scan = self._instance_scan() if any(o.type == "MESH" and len(o.modifiers) for o in bpy.data.objects) else None selected = [item.name for item in context.selected_objects if item is not None] active_object = context.active_object.name if context.active_object else "" @@ -630,8 +642,90 @@ class BrokkrBlenderTarget: "objects": [self._object_snapshot(obj, scan) for obj in bpy.data.objects], "materials": [self._material_snapshot(material) for material in bpy.data.materials], "collections": [self._collection_snapshot(collection) for collection in bpy.data.collections], + "hostActions": host_rows, + "hostActionErrors": host_errors, } + def host_actions(self) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """The one discovery of host rows: ([row + 'host' module], [{host, error}]). Each enabled add-on but this + one may carry brokkr_actions.json beside its __init__.py; the file is admitted whole or not at all. The + file is the add-on's word; what is checked here is what Brokkr can see: the operator exists and is a + Python class defined by that add-on, every field is a property of it of the matching type whose RNA hard + limits contain the row's bounds, and result is a WindowManager string property. Only the parse is cached + (on path, mtime and size); the live checks run each time, so a disabled add-on or an unregistered operator + is gone at the next intent. A name two files claim fails ownership in all but its owner.""" + rows: list[dict[str, Any]] = [] + errors: list[dict[str, Any]] = [] + own = __package__ or "" + modules = [m for m in self.bpy.context.preferences.addons.keys() if m != own] + for module in modules: + try: + document = self._host_document(module) + except _NoHostFile: + continue + except Exception as error: + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + continue + try: + for row in document["actions"]: + self._check_host_row(module, row) + except Exception as error: + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + continue + rows.extend({**row, "host": module} for row in document["actions"]) + return rows, errors + + def _host_document(self, module: str) -> dict[str, Any]: + loaded = sys.modules.get(module) + source = getattr(loaded, "__file__", None) + path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None + if path is None or not path.is_file(): + self._host_files.pop(module, None) + raise _NoHostFile() + info = path.stat() + stamp = (str(path), info.st_mtime_ns, info.st_size) + cached = self._host_files.get(module) + if cached is None or cached[0] != stamp: + try: + document = json.loads(path.read_text(encoding="utf-8")) + at.check_host(document, at.table()["charsets"]) + cached = (stamp, document) + except Exception as error: + cached = (stamp, str(error)) + self._host_files[module] = cached + if isinstance(cached[1], str): + raise ValueError(cached[1]) + return cached[1] + + def _check_host_row(self, module: str, row: dict[str, Any]) -> None: + bpy = self.bpy + name = row["name"] + first, second = name.split(".") + operator = getattr(getattr(bpy.ops, first), second) + owner = getattr(bpy.types, operator.idname(), None) + owned = getattr(owner, "__module__", None) + if not isinstance(owner, type) or not isinstance(owned, str) or not (owned == module or owned.startswith(module + ".")): + raise ValueError(f"{name} is not an operator defined by {module}") + properties = {p.identifier: p for p in operator.get_rna_type().properties} + kinds = {"string": "STRING", "number": "FLOAT", "integer": "INT", "boolean": "BOOLEAN"} + for field in row["fields"]: + prop = properties.get(field["name"]) + where = f"{name}.{field['name']}" + if prop is None: + raise ValueError(f"{where} is not a property of the operator") + enum = field.get("enum") + if prop.type != ("ENUM" if enum is not None else kinds[field["type"]]): + raise ValueError(f"{where} is {prop.type} in the operator, not {field['type']}") + if enum is not None and {item.identifier for item in prop.enum_items} != set(enum): + raise ValueError(f"{where} enum differs from the operator's") + if field["type"] in ("number", "integer") and not (prop.hard_min <= field["minimum"] and field["maximum"] <= prop.hard_max): + raise ValueError(f"{where} bounds exceed the operator's own limits") + result = row.get("result") + if result is not None: + prop = bpy.types.WindowManager.bl_rna.properties.get(result) + if prop is None or prop.type != "STRING": + raise ValueError(f"{name} result {result} is not a string property of WindowManager") + 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. @@ -639,7 +733,8 @@ class BrokkrBlenderTarget: valid), then Edit Mode. 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); the table's editModeSafe actions write nothing - and change no mode. A refusal at admission is 'denied': nothing ran, no undo step.""" + and change no mode. Host add-on rows (host_actions) are admitted by the same table check and run through + the same turn. A refusal at admission is 'denied': nothing ran, no undo step.""" command_id = command.get("commandId") requested_by = command.get("requestedBy") action = command.get("action", "") @@ -653,8 +748,9 @@ class BrokkrBlenderTarget: denial = "Intent has no requestedBy of the form '/'." else: try: - command = at.validate(command) - row = at.entry(action) + host, _ = self.host_actions() + command = at.validate(command, host) + row = at.entry(action, host) except at.IntentInvalid as error: denial = str(error) if not denial and not row["editModeSafe"] and self._edit_mode_object() is not None: @@ -671,7 +767,7 @@ class BrokkrBlenderTarget: self._wrote = True try: try: - receipt = self._dispatch(context, command) + receipt = self._dispatch(context, command, row) 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 @@ -707,16 +803,59 @@ class BrokkrBlenderTarget: else: self.bpy.ops.ed.undo_push(message=label) - def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - """Only run_intent calls it, with an intent the table admitted: the handler is '_' + the action's name, - on NodeActions for the node actions and on this target for the rest. It owns refusal, failure and the undo step.""" + def _dispatch(self, context: Any, command: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]: + """Only run_intent calls it, with an intent the table admitted: a host row runs its operator; otherwise the + handler is '_' + the action's name, on NodeActions for the node actions and on this target for the rest. + It owns refusal, failure and the undo step.""" action = command["action"] + if "host" in row: + return self._run_host_operator(context, command, row) if hasattr(self.nodes, "_" + action): message, name = self.nodes.execute(action, command) self._wrote = self.nodes.changed return self._receipt(command, "accepted", message, name) return getattr(self, "_" + action)(context, command) + def _run_host_operator(self, context: Any, command: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]: + """A host add-on's own operator, called with exactly the declared fields. FINISHED is accepted; CANCELLED + is failed and wrote nothing; an argument Blender will not convert raises ActionRefused before anything + ran; an ERROR report or exception is RuntimeError, failed (run_intent pushes '(failed)' for a changesScene + row). A row's result property is cleared before and copied, capped, into the receipt.""" + bpy = self.bpy + name = row["name"] + skip = set(at.table()["envelope"]) + kwargs = {k: v for k, v in command.items() if k not in skip} + result = row.get("result") + manager = bpy.context.window_manager + if result: + setattr(manager, result, "") + first, second = name.split(".") + operator = getattr(getattr(bpy.ops, first), second) + windows = manager.windows + try: + if windows: + with bpy.context.temp_override(window=windows[0]): + outcome = operator("EXEC_DEFAULT", False, **kwargs) + else: + outcome = operator("EXEC_DEFAULT", False, **kwargs) + except TypeError as error: + raise sa.ActionRefused(f"Operator {name} refused its arguments: {_first_line(str(error))}") from None + except RuntimeError as error: + raise RuntimeError(_first_line(str(error))) from None + text = "" + if result: + text = getattr(manager, result, "") or "" + if len(text) > HOST_RESULT_LIMIT: + text = text[:HOST_RESULT_LIMIT] + " [truncated]" + if "FINISHED" in outcome: + self._wrote = bool(row["changesScene"]) + receipt = self._receipt(command, "accepted", f"Operator {name} finished.", "") + else: + self._wrote = False + receipt = self._receipt(command, "failed", f"Operator {name} cancelled; nothing changed.", "") + receipt["hostResult"] = text + return receipt + def _createObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: object_type = command["objectType"] name = command.get("name") or f"Brokkr {object_type.title()}" @@ -1410,6 +1549,7 @@ class BrokkrBlenderTarget: "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", "undoLabel": "", "lookPath": "", + "hostResult": "", "observedAt": _now(), } diff --git a/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py b/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py new file mode 100644 index 0000000..671d78c --- /dev/null +++ b/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py @@ -0,0 +1,72 @@ +"""A legacy host add-on for Brokkr's host-action tests. It knows nothing of Brokkr: its brokkr_actions.json is +the whole contract. apply is registered but left out of that file, the shape of an operator only a human runs.""" +bl_info = {"name": "Brokkr host fixture", "blender": (4, 2, 0), "category": "Development"} + +import bpy + + +class BROKKR_HOST_FIXTURE_OT_add_empty(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.add_empty" + bl_label = "Fixture add empty" + bl_options = {"REGISTER", "UNDO"} + name: bpy.props.StringProperty(default="Fixture") + size: bpy.props.FloatProperty(default=1.0, min=0.0, max=100.0) + + def execute(self, context): + empty = bpy.data.objects.new(self.name, None) + empty.empty_display_size = self.size + context.scene.collection.objects.link(empty) + return {"FINISHED"} + + +class BROKKR_HOST_FIXTURE_OT_report(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.report" + bl_label = "Fixture report" + bl_options = {"REGISTER"} + + def execute(self, context): + context.window_manager.brokkr_host_fixture_result = f"objects: {len(bpy.data.objects)}\nscenes: {len(bpy.data.scenes)}" + return {"FINISHED"} + + +class BROKKR_HOST_FIXTURE_OT_refuse(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.refuse" + bl_label = "Fixture refuse" + + def execute(self, context): + self.report({"ERROR"}, "the fixture refuses") + return {"CANCELLED"} + + +class BROKKR_HOST_FIXTURE_OT_cancel(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.cancel" + bl_label = "Fixture cancel" + + def execute(self, context): + return {"CANCELLED"} + + +class BROKKR_HOST_FIXTURE_OT_apply(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.apply" + bl_label = "Fixture apply" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + bpy.data.objects.new("Applied", None) + return {"FINISHED"} + + +classes = (BROKKR_HOST_FIXTURE_OT_add_empty, BROKKR_HOST_FIXTURE_OT_report, BROKKR_HOST_FIXTURE_OT_refuse, + BROKKR_HOST_FIXTURE_OT_cancel, BROKKR_HOST_FIXTURE_OT_apply) + + +def register(): + bpy.types.WindowManager.brokkr_host_fixture_result = bpy.props.StringProperty() + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) + del bpy.types.WindowManager.brokkr_host_fixture_result diff --git a/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json b/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json new file mode 100644 index 0000000..160f67a --- /dev/null +++ b/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json @@ -0,0 +1,37 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_host_fixture.add_empty", + "doc": "Add an empty named for the agent.", + "changesScene": true, + "editModeSafe": false, + "fields": [ + {"name": "name", "type": "string", "required": true, "minLength": 1, "maxLength": 63, "doc": "the empty's name"}, + {"name": "size", "type": "number", "minimum": 0.1, "maximum": 10, "default": 1, "doc": "display size"} + ] + }, + { + "name": "brokkr_host_fixture.report", + "doc": "Write a report of the scene without changing it.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_host_fixture_result", + "fields": [] + }, + { + "name": "brokkr_host_fixture.refuse", + "doc": "Report an error and cancel.", + "changesScene": false, + "editModeSafe": true, + "fields": [] + }, + { + "name": "brokkr_host_fixture.cancel", + "doc": "Cancel without a report.", + "changesScene": false, + "editModeSafe": true, + "fields": [] + } + ] +} diff --git a/surfaces/blender/tests/host_action_cases.json b/surfaces/blender/tests/host_action_cases.json new file mode 100644 index 0000000..91836a9 --- /dev/null +++ b/surfaces/blender/tests/host_action_cases.json @@ -0,0 +1,21 @@ +[ + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E"}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 0.1}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 10}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": null, "note": "n", "requestedBy": "a/b", "commandId": "x"}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {}, "expect": "name is required."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": ""}, "expect": "name must have at least 1 characters."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "name must have at most 63 characters."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": 5}, "expect": "name must be a string."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 0.05}, "expect": "size must be between 0.1 and 10."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 10.5}, "expect": "size must be between 0.1 and 10."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": true}, "expect": "size must be a finite number."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "bogus": 1}, "expect": "brokkr_host_fixture.add_empty has no field 'bogus'; its fields: name, size."}, + {"action": "brokkr_host_fixture.report", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.report", "fields": {"name": "E"}, "expect": "brokkr_host_fixture.report has no field 'name'; its fields: none."}, + {"action": "brokkr_host_fixture.refuse", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.cancel", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.apply", "fields": {}, "expect": "Unsupported Blender command action: brokkr_host_fixture.apply"}, + {"action": "wm.save_mainfile", "fields": {}, "expect": "Unsupported Blender command action: wm.save_mainfile"}, + {"action": "createObject", "fields": {}, "expect": "ok"} +] diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py index 858920a..f3a5f6e 100644 --- a/surfaces/blender/tests/test_action_table.py +++ b/surfaces/blender/tests/test_action_table.py @@ -14,6 +14,8 @@ at = ts.at bt = ts.bt na = ts.bt.na CASES = json.loads((Path(__file__).with_name("action_cases.json")).read_text(encoding="utf-8")) +HOST_FILE = json.loads((Path(__file__).parent / "fixtures" / "brokkr_host_fixture" / "brokkr_actions.json").read_text(encoding="utf-8")) +HOST_CASES = json.loads((Path(__file__).with_name("host_action_cases.json")).read_text(encoding="utf-8")) def validate(action, fields): @@ -24,6 +26,72 @@ def validate(action, fields): return "ok" +class HostTableTests(unittest.TestCase): + """A host add-on's brokkr_actions.json adds rows; the same messages as for built-ins.""" + + def charsets(self): + return at.table()["charsets"] + + def host_file(self, **row): + base = copy.deepcopy(HOST_FILE) + base["actions"][0].update(row) + return base + + def test_the_fixture_file_is_admitted(self): + at.check_host(HOST_FILE, self.charsets()) + + def wrong_cases(self): + wrong = [] + for case in HOST_CASES: + try: + at.validate({"action": case["action"], **case["fields"]}, HOST_FILE["actions"]) + got = "ok" + except at.IntentInvalid as error: + got = str(error) + if got != case["expect"]: + wrong.append((case["action"], case["fields"], case["expect"], got)) + return wrong + + def test_every_host_case_yields_exactly_its_expected_message_or_ok(self): + self.assertEqual(self.wrong_cases(), []) + + def test_a_mutant_that_skips_host_rows_or_lets_an_undeclared_field_through_fails_a_case(self): + original = at.entry + with mock.patch.object(at, "entry", lambda action, host=(): original(action)): + self.assertTrue(self.wrong_cases()) + with mock.patch.object(at, "_fields", lambda *args: None): + self.assertTrue(self.wrong_cases()) + + def test_check_host_refuses_non_scalar_fields_bad_names_and_foreign_keys(self): + field = {"name": "f", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}} + for bad, why in ( + (self.host_file(fields=[field]), "array"), + (self.host_file(fields=[{"name": "f", "type": "object"}]), "object"), + (self.host_file(fields=[{"name": "f", "type": "any"}]), "any"), + (self.host_file(name="undotted"), "undotted"), + (self.host_file(name="Upper.case"), "uppercase"), + (self.host_file(fields=[{"name": "f", "type": "string", "chars": "nope"}]), "charset"), + (self.host_file(result="not an identifier"), "result"), + (self.host_file(fields=[{"name": "f", "type": "number"}]), "unbounded"), + ({**HOST_FILE, "envelope": []}, "envelope key"), + ({**HOST_FILE, "charsets": {}}, "charsets key"), + ({**HOST_FILE, "schema": at.SCHEMA}, "schema"), + ): + with self.assertRaises(at.TableInvalid, msg=why): + at.check_host(bad, self.charsets()) + twice = copy.deepcopy(HOST_FILE) + twice["actions"].append(copy.deepcopy(twice["actions"][0])) + with self.assertRaises(at.TableInvalid): + at.check_host(twice, self.charsets()) + + def test_a_host_row_never_shadows_a_built_in(self): + shadow = [{"name": "createObject", "doc": "", "changesScene": True, "editModeSafe": True, "fields": []}] + self.assertIs(at.entry("createObject", shadow), at.entry("createObject")) + self.assertEqual(at.entry("brokkr_host_fixture.report", HOST_FILE["actions"])["name"], "brokkr_host_fixture.report") + self.assertIsNone(at.entry("brokkr_host_fixture.report")) + self.assertTrue(all("." not in a["name"] for a in at.table()["actions"])) + + class ParityFixtureTests(unittest.TestCase): """action_cases.json is also run by brokkr-ctl's actions.rs: one table, two interpreters, one set of messages.""" diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index b9fa12e..6578b4b 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -232,6 +232,228 @@ class AgentTurnTests(unittest.TestCase): self.assertNotIn("requires CultLib's Python packages", str(caught.exception)) +FIXTURE = Path(__file__).parent / "fixtures" / "brokkr_host_fixture" +HOST = "brokkr_host_fixture" +NS = ts.NS + + +def types_module(name, file): + import types + module = types.ModuleType(name) + module.__file__ = str(file) + return module + + +class HostOp: + """bpy.ops..: callable with idname() and get_rna_type(), recording its calls.""" + + def __init__(self, name, props, behave): + self.cls = type(f"BROKKR_HOST_FIXTURE_OT_{name}", (), {"__module__": HOST}) + self.props = props + self.behave = behave + self.calls = [] + + def idname(self): + return self.cls.__name__ + + def get_rna_type(self): + return NS(properties=self.props) + + def __call__(self, mode, undo, **kwargs): + assert (mode, undo) == ("EXEC_DEFAULT", False) + self.calls.append(kwargs) + return self.behave(self, kwargs) + + +def prop(identifier, kind, lo=0.0, hi=1e30, enum=()): + return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum]) + + +def raising(error): + def behave(op, kwargs): + raise error + return behave + + +class HostActionTests(unittest.TestCase): + """Host rows from a host add-on's brokkr_actions.json, discovered through a fake bpy, run by run_intent.""" + + def setUp(self): + ts.ActionTests.setUp(self) + self.dir = Path(self.tmp.name) / HOST + self.dir.mkdir() + (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + patch = unittest.mock.patch.dict(sys.modules, {HOST: types_module(HOST, self.dir / "__init__.py")}) + patch.start() + self.addCleanup(patch.stop) + bpy = self.bpy + self.ops = { + "add_empty": HostOp("add_empty", [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 100.0)], self.finish), + "report": HostOp("report", [], self.write_report), + "refuse": HostOp("refuse", [], raising(RuntimeError("Error: the fixture refuses"))), + "cancel": HostOp("cancel", [], lambda op, kw: {"CANCELLED"}), + "apply": HostOp("apply", [], self.finish), + } + bpy.ops.brokkr_host_fixture = NS(**self.ops) + bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING")})), + **{op.idname(): op.cls for op in self.ops.values()}) + bpy.context.preferences.addons = {HOST: object(), "brokkr_bridge": object()} + bpy.context.window_manager.brokkr_host_fixture_result = "stale" + self.report_text = "objects: 3" + + def finish(self, op, kwargs): + return {"FINISHED"} + + def write_report(self, op, kwargs): + self.bpy.context.window_manager.brokkr_host_fixture_result = self.report_text + return {"FINISHED"} + + run_action = ts.ActionTests.run_action + + def send(self, operator, **fields): + return self.run_action(action=f"{HOST}.{operator}", **fields) + + def test_a_changing_host_operator_runs_with_exactly_its_declared_fields_and_is_one_undo_step(self): + receipt = self.send("add_empty", name="E", size=2) + self.assertEqual(receipt["status"], "accepted", receipt) + self.assertEqual(receipt["message"], f"Operator {HOST}.add_empty finished.") + self.assertEqual(receipt["hostResult"], "") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 2}]) + self.assertEqual(len(self.bpy.undo.pushes), 1) + self.assertTrue(self.bpy.undo.pushes[0].startswith("Brokkr nibu/hands: brokkr_host_fixture.add_empty ")) + self.assertEqual(receipt["undoLabel"], self.bpy.undo.pushes[0]) + + def test_the_default_is_filled_and_an_undeclared_field_never_reaches_the_operator(self): + self.assertEqual(self.send("add_empty", name="E")["status"], "accepted") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) + denied = self.send("add_empty", name="E", location=[1, 2, 3]) + self.assertEqual(denied["status"], "denied") + self.assertEqual(len(self.ops["add_empty"].calls), 1) + + def test_a_non_changing_operator_pushes_no_undo_step_and_returns_its_result(self): + receipt = self.send("report") + self.assertEqual((receipt["status"], receipt["hostResult"]), ("accepted", "objects: 3")) + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.run_action(action="createObject")["hostResult"], "") # a built-in's receipt carries the field empty + + def test_the_result_is_cleared_before_the_call_and_capped_after(self): + seen = [] + self.ops["report"].behave = lambda op, kw: (seen.append(self.bpy.context.window_manager.brokkr_host_fixture_result), {"CANCELLED"})[1] + self.assertEqual(self.send("report")["hostResult"], "") + self.assertEqual(seen, [""]) # 'stale' was cleared first + self.ops["report"].behave = self.write_report + self.report_text = "x" * (bt.HOST_RESULT_LIMIT + 50) + text = self.send("report")["hostResult"] + self.assertEqual(text, "x" * bt.HOST_RESULT_LIMIT + " [truncated]") + self.report_text = "y" * bt.HOST_RESULT_LIMIT + self.assertEqual(self.send("report")["hostResult"], "y" * bt.HOST_RESULT_LIMIT) + + def test_cancelled_is_failed_with_no_push(self): + receipt = self.send("cancel") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", f"Operator {HOST}.cancel cancelled; nothing changed.")) + self.ops["add_empty"].behave = lambda op, kw: {"CANCELLED"} + self.assertEqual(self.send("add_empty", name="E")["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_conversion_error_is_failed_and_pushes_nothing(self): + self.ops["add_empty"].behave = raising(TypeError('keyword "size" could not be converted')) + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("refused its arguments", receipt["message"]) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_runtime_error_is_failed_with_its_first_line_and_pushes_failed_only_for_a_changing_row(self): + receipt = self.send("refuse") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Error: the fixture refuses")) + self.assertEqual(self.bpy.undo.pushes, []) + self.ops["add_empty"].behave = raising(RuntimeError("Traceback...\nboom")) + receipt = self.send("add_empty", name="E") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Traceback...")) + self.assertEqual(len(self.bpy.undo.pushes), 1) + self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) + + def test_a_human_only_operator_and_a_c_operator_are_unsupported_and_leave_no_trace(self): + for action in (f"{HOST}.apply", "wm.save_mainfile", "brokkr.stop_agents"): + receipt = self.run_action(action=action) + self.assertEqual(receipt["status"], "denied", action) + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertEqual(self.ops["apply"].calls, []) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_host_row_is_refused_in_edit_mode_unless_it_is_edit_mode_safe(self): + self.bpy.mesh.mode = "EDIT" + self.assertEqual(self.send("add_empty", name="E")["status"], "denied") + self.assertEqual(self.send("report")["status"], "accepted") + + def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_human_only_row(self): + self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0), background=False) + context = NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT") + snapshot = self.target.capture_snapshot(context, True) + names = [row["name"] for row in snapshot["hostActions"]] + self.assertEqual(names, [f"{HOST}.{n}" for n in ("add_empty", "report", "refuse", "cancel")]) + self.assertEqual({row["host"] for row in snapshot["hostActions"]}, {HOST}) + self.assertEqual(snapshot["hostActionErrors"], []) + + def refused(self): + rows, errors = self.target.host_actions() + self.assertEqual(rows, []) + self.assertEqual([e["host"] for e in errors], [HOST]) + self.assertIn("brokkr_actions.json", errors[0]["error"]) + self.assertEqual(self.send("report")["status"], "denied") # none of its rows is admitted + return errors[0]["error"] + + def test_a_row_naming_another_add_ons_operator_refuses_the_whole_file(self): + self.ops["report"].cls.__module__ = "other_addon" + self.assertIn("not an operator defined by", self.refused()) + self.ops["report"].cls.__module__ = HOST + ".sub" + self.assertEqual(len(self.target.host_actions()[0]), 4) # a submodule is its own + + def test_a_c_operator_refuses_the_whole_file(self): + self.bpy.types = NS(**{**vars(self.bpy.types), self.ops["cancel"].idname(): None}) + self.refused() + + def test_rna_disagreement_refuses_the_whole_file(self): + self.ops["add_empty"].props = [prop("name", "STRING")] # size missing + self.assertIn("size is not a property", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "INT", 0, 100)] + self.assertIn("is INT in the operator", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.5, 100.0)] # hard min above the row's 0.1 + self.assertIn("bounds exceed", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 5.0)] # hard max below the row's 10 + self.assertIn("bounds exceed", self.refused()) + + def test_a_result_that_is_not_a_window_manager_string_refuses_the_whole_file(self): + self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"] = NS(type="INT") + self.assertIn("not a string property", self.refused()) + self.bpy.types.WindowManager.bl_rna.properties.clear() + self.refused() + + def test_a_malformed_file_refuses_itself_and_a_changed_file_is_read_again(self): + path = self.dir / "brokkr_actions.json" + good = path.read_text(encoding="utf-8") + path.write_text(good.replace("host_actions.v0", "host_actions.v9"), encoding="utf-8") + self.assertIn("schema", self.refused()) + path.write_text(good, encoding="utf-8") + self.assertEqual(len(self.target.host_actions()[0]), 4) + path.write_text("not json", encoding="utf-8") + self.refused() + + def test_disabling_the_add_on_makes_its_action_unsupported_at_the_next_intent(self): + self.assertEqual(self.send("report")["status"], "accepted") + self.bpy.context.preferences.addons.pop(HOST) + receipt = self.send("report") + self.assertEqual(receipt["status"], "denied") + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertEqual(self.target.host_actions(), ([], [])) + + def test_an_add_on_without_the_file_is_not_a_host_and_this_add_on_is_never_read(self): + (self.dir / "brokkr_actions.json").unlink() + self.assertEqual(self.target.host_actions(), ([], [])) + self.bpy.context.preferences.addons["brokkr_bridge"] = object() + self.assertEqual(self.target.host_actions(), ([], [])) + + class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" def __init__(self, intents, receipts=()): diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py index 884bca2..bf2baef 100644 --- a/surfaces/blender/tests/test_material_actions.py +++ b/surfaces/blender/tests/test_material_actions.py @@ -60,7 +60,7 @@ 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()) + bpy.context = NS(window_manager=NS(windows=[object()]), preferences=NS(addons={}), 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 diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 2a24752..6d4a762 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -174,7 +174,7 @@ 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()) + bpy.context = NS(window_manager=NS(windows=[object()]), preferences=NS(addons={}), 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 diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index d9abebc..0281ba3 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -80,7 +80,7 @@ class FakeUndo: self.pushes = [] self.overrides = [] self.window = object() - bpy.context = NS(window_manager=NS(windows=[self.window]), + bpy.context = NS(window_manager=NS(windows=[self.window]), preferences=NS(addons={}), 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)) diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 5e732d9..ea796b7 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -364,7 +364,7 @@ class NoPreferenceWritesTests(unittest.TestCase): # the sink toggle is the human's: no intent or action code reaches add-on preferences for name in ("scene_actions.py", "node_actions.py", "blender_target.py"): source = (BRIDGE / name).read_text(encoding="utf-8") - self.assertEqual(re.findall(r"[.]preferences\b|\bprefs\b", source), [], name) + self.assertEqual(re.findall(r"[.]preferences\b(?![.]addons[.]keys\(\))|\bprefs\b", source), [], name) if __name__ == "__main__": -- 2.47.3 From 7b47fa5b8319f148e42353750283f5b5de5d26a6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:11:51 +0100 Subject: [PATCH 2/6] brokkr-ctl: host rows from the host snapshot in validate, send --help and status Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/actions.rs | 65 +++++++++++++++++++--- brokkr-ctl/src/blender.rs | 79 ++++++++++++++++++++++++--- brokkr-ctl/tests/cli.rs | 111 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 240 insertions(+), 15 deletions(-) diff --git a/brokkr-ctl/src/actions.rs b/brokkr-ctl/src/actions.rs index 590b29c..40a3d40 100644 --- a/brokkr-ctl/src/actions.rs +++ b/brokkr-ctl/src/actions.rs @@ -2,7 +2,9 @@ //! refuses. The owner is the add-on's `actions.json` (schema brokkr.blender.actions.v0); this module reads //! it as data and implements the same vocabulary and message text as `action_table.py`, pinned to it by //! the shared fixture `surfaces/blender/tests/action_cases.json`. Anything that reaches the store is still -//! decided by the add-on. +//! decided by the add-on. Host add-ons' rows (`brokkr.blender.host_actions.v0`) are not embedded: they come +//! from the add-on's host snapshot (`hostActions`), are searched after the built-ins, and are pinned by +//! `surfaces/blender/tests/host_action_cases.json`; a stale snapshot can only make ctl refuse early. use serde_json::{Map, Value}; use std::sync::LazyLock; @@ -20,8 +22,12 @@ fn actions() -> &'static [Value] { table()["actions"].as_array().map_or(&[], Vec::as_slice) } -fn entry(name: &str) -> Option<&'static Value> { - actions().iter().find(|a| a["name"] == name) +/// The built-in row of that name, else the first host row of that name. +fn entry<'a>(name: &str, host: &'a [Value]) -> Option<&'a Value> { + actions() + .iter() + .chain(host) + .find(|a| a["name"] == name) } /// The names brokkr-ctl writes itself: `--set` cannot name them, and the table does not validate them. @@ -66,9 +72,9 @@ pub fn number_text(value: f64) -> String { } /// Refuses an intent the table refuses, with the add-on's message; nothing is normalized (the add-on fills defaults). -pub fn validate(command: &Map) -> Result<(), String> { +pub fn validate(command: &Map, host: &[Value]) -> Result<(), String> { let action = command.get("action").and_then(Value::as_str).unwrap_or(""); - let Some(row) = entry(action) else { + let Some(row) = entry(action, host) else { return Err(format!("Unsupported Blender command action: {action}")); }; let present: Map = command @@ -286,8 +292,13 @@ fn check_string(spec: &Value, text: &str, path: &str) -> Result<(), String> { /// The actions section of `send --help`: every action with its fields, built from the table. pub fn help() -> String { + help_rows(actions()) +} + +/// The help body for any rows: the built-ins, or the host rows a snapshot carries. +pub fn help_rows(rows: &[Value]) -> String { let mut text = String::new(); - for action in actions() { + for action in rows { text.push_str(&format!( " {}: {}\n", action["name"].as_str().unwrap_or(""), @@ -408,7 +419,7 @@ mod tests { for case in &cases { let mut command = case["fields"].as_object().unwrap().clone(); command.insert("action".into(), case["action"].clone()); - let got = validate(&command).err().unwrap_or_else(|| "ok".to_string()); + let got = validate(&command, &[]).err().unwrap_or_else(|| "ok".to_string()); if Some(got.as_str()) != case["expect"].as_str() { wrong.push(format!( "{} {} expected {} got {got}", @@ -425,12 +436,50 @@ mod tests { ); } + /// The host rows a fixture add-on publishes, run through the same validator as the add-on's + /// HostTableTests: one set of messages for host rows too. + #[test] + fn the_host_parity_fixture_yields_the_add_ons_messages() { + let file: Value = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json" + )) + .unwrap(); + let host = file["actions"].as_array().unwrap().clone(); + let cases: Vec = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/host_action_cases.json" + )) + .unwrap(); + assert!(cases.len() >= 15, "{} cases", cases.len()); + let mut wrong = Vec::new(); + for case in &cases { + let mut command = case["fields"].as_object().unwrap().clone(); + command.insert("action".into(), case["action"].clone()); + let got = validate(&command, &host) + .err() + .unwrap_or_else(|| "ok".to_string()); + if Some(got.as_str()) != case["expect"].as_str() { + wrong.push(format!( + "{} {} expected {} got {got}", + case["action"], case["fields"], case["expect"] + )); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); + // Without the snapshot's rows the same host action is unsupported: ctl never invents rows. + let mut command = Map::new(); + command.insert("action".into(), "brokkr_host_fixture.report".into()); + assert_eq!( + validate(&command, &[]).unwrap_err(), + "Unsupported Blender command action: brokkr_host_fixture.report" + ); + } + #[test] fn a_non_string_action_is_unsupported_and_the_envelope_is_the_tables() { let mut command = Map::new(); command.insert("action".into(), Value::from(3)); assert_eq!( - validate(&command).unwrap_err(), + validate(&command, &[]).unwrap_err(), "Unsupported Blender command action: " ); assert_eq!( diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index dc47866..8a604ba 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -115,7 +115,7 @@ pub fn run(args: &[String]) -> Result { } let options = parse(rest)?; if options.help { - print!("{}", if sub == "send" { send_help() } else { group_help() }); + print!("{}", if sub == "send" { send_help(&options) } else { group_help() }); return Ok(0); } match sub.as_str() { @@ -214,6 +214,7 @@ fn build_intent( requested_by: &str, note: &str, sets: &[String], + host: &[Value], ) -> Result { let mut map = Map::new(); for set in sets { @@ -232,7 +233,7 @@ fn build_intent( map.insert("action".into(), action.into()); map.insert("requestedBy".into(), requested_by.into()); map.insert("note".into(), note.into()); - actions::validate(&map).map_err(|message| anyhow!(message))?; + actions::validate(&map, host).map_err(|message| anyhow!(message))?; Ok(Value::Object(map)) } @@ -240,7 +241,8 @@ fn send(options: &Options, action: &str) -> Result { let requested_by = requested_by(options)?; let mut store = open_store(options)?; let command_id = uuid::Uuid::now_v7().simple().to_string(); - let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets)?; + let (host, _) = host_rows(&store)?; + let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets, &host)?; store.push(&CultCacheEnvelope { key: format!("{INTENT_PREFIX}{command_id}"), r#type: INTENT_SCHEMA.to_string(), @@ -339,6 +341,27 @@ fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> R Ok(0) } +/// The host snapshot as the add-on last published it, if any. +fn snapshot(store: &SingleFileMessagePackBackingStore) -> Result> { + for envelope in store.pull_all()? { + if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { + return Ok(Some(decode(&envelope)?)); + } + } + Ok(None) +} + +/// The host rows the add-on published and when (`observedAt`); empty before any snapshot. A display and +/// early-refusal copy: the add-on admits or denies the intent itself. +fn host_rows(store: &SingleFileMessagePackBackingStore) -> Result<(Vec, String)> { + let Some(snapshot) = snapshot(store)? else { + return Ok((Vec::new(), String::new())); + }; + let rows = snapshot["hostActions"].as_array().cloned().unwrap_or_default(); + let observed = snapshot["observedAt"].as_str().unwrap_or("").to_string(); + Ok((rows, observed)) +} + fn status(store: &SingleFileMessagePackBackingStore) -> Result { for envelope in store.pull_all()? { if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { @@ -358,6 +381,20 @@ fn status(store: &SingleFileMessagePackBackingStore) -> Result { print_field(key, value); } } + let names: Vec<&str> = snapshot["hostActions"] + .as_array() + .into_iter() + .flatten() + .filter_map(|row| row["name"].as_str()) + .collect(); + println!("hostActions: {}", names.join(", ")); + for error in snapshot["hostActionErrors"].as_array().into_iter().flatten() { + println!( + "hostActionErrors: {}: {}", + error["host"].as_str().unwrap_or(""), + error["error"].as_str().unwrap_or("") + ); + } return Ok(0); } } @@ -378,6 +415,10 @@ fn print_fields(value: &Value) { fn print_field(key: &str, value: &Value) { match value { + Value::String(text) if text.contains('\n') => { + println!("{key}:"); + text.lines().for_each(|line| println!(" {line}")); + } Value::String(text) => println!("{key}: {text}"), other => println!("{key}: {other}"), } @@ -433,7 +474,9 @@ the add-on decides the rest and its refusal comes back in the receipt. .to_string() } -pub fn send_help() -> String { +/// `send --help`: the built-ins, then, when a store is named (--store or $BROKKR_BLENDER_STORE), the host +/// rows its snapshot carries. It never fails for lack of a store. +fn send_help(options: &Options) -> String { let mut text = String::from( "\ brokkr-ctl blender send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] @@ -446,9 +489,31 @@ actions: ", ); text.push_str(&actions::help()); + text.push_str(&host_help(options)); text } +fn host_help(options: &Options) -> String { + let named = options.store.is_some() || std::env::var_os("BROKKR_BLENDER_STORE").is_some(); + if !named { + return "\nhost actions: add --store (or set BROKKR_BLENDER_STORE) to list the actions host add-ons publish.\n" + .to_string(); + } + match open_store(options).and_then(|store| host_rows(&store)) { + Err(error) => format!("\nhost actions: unavailable ({error}).\n"), + Ok((_, observed)) if observed.is_empty() => { + "\nhost actions: the store holds no host snapshot yet.\n".to_string() + } + Ok((rows, observed)) if rows.is_empty() => { + format!("\nhost actions (published by the add-on at {observed}): none.\n") + } + Ok((rows, observed)) => format!( + "\nhost actions (published by the add-on at {observed}):\n{}", + actions::help_rows(&rows) + ), + } +} + #[cfg(test)] mod tests { use super::*; @@ -462,17 +527,17 @@ mod tests { #[test] fn intent_carries_reserved_fields_and_refuses_overrides() { let sets = vec!["objectType=\"MESH\"".to_string(), "location=[0,0,1]".to_string()]; - let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets).unwrap(); + let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets, &[]).unwrap(); assert_eq!(intent["requestedBy"], "nibu/hands"); assert_eq!(intent["objectType"], "MESH"); assert_eq!(intent["location"][2], 1); for bad in ["requestedBy=\"x\"", "commandId=\"x\"", "action=\"x\"", "novalue", "k=notjson"] { assert!( - build_intent("createObject", "abc", "a/b", "", &[bad.to_string()]).is_err(), + build_intent("createObject", "abc", "a/b", "", &[bad.to_string()], &[]).is_err(), "{bad}" ); } - assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err()); + assert!(build_intent("../x", "abc", "a/b", "", &[], &[]).is_err()); } #[test] diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 9936d7f..1cd8847 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -502,3 +502,114 @@ fn a_json_payload_is_refused_not_guessed() { let output = ctl(&path, &["wait", "j", "--timeout", "1"], None); assert_eq!(output.status.code(), Some(1)); } + +/// A store whose snapshot carries the fixture add-on's rows the way the add-on publishes them, plus one refused file. +fn host_store(dir: &Path) -> PathBuf { + let path = store_with_receipts(dir, &[("seed", "accepted")]); + let file: Value = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json" + )) + .unwrap(); + let rows: Vec = file["actions"] + .as_array() + .unwrap() + .iter() + .map(|row| { + let mut row = row.clone(); + row["host"] = json!("brokkr_host_fixture"); + row + }) + .collect(); + let snapshot = json!({ + "observedAt": "2026-11-28T10:00:00.000000+00:00", "mode": "OBJECT", + "hostActions": rows, + "hostActionErrors": [{"host": "broken_addon", "error": "brokkr_actions.json: host schema must be brokkr.blender.host_actions.v0"}], + }); + push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); + path +} + +fn help_text(args: &[&str], store: Option<&Path>) -> String { + let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")); + command.arg("blender").args(args).env_remove("BROKKR_BLENDER_STORE"); + if let Some(store) = store { + command.arg("--store").arg(store); + } + stdout(&command.output().unwrap()) +} + +#[test] +fn send_help_with_a_store_lists_the_host_rows_with_their_bounds() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let text = help_text(&["send", "--help"], Some(&path)); + assert!(text.contains("host actions (published by the add-on at 2026-11-28T10:00:00.000000+00:00):"), "{text}"); + for needle in ["brokkr_host_fixture.add_empty", "size: number 0.1..10", "name: string", "brokkr_host_fixture.report"] { + assert!(text.contains(needle), "{needle} in {text}"); + } + assert!(!text.contains("brokkr_host_fixture.apply"), "human-only is absence"); + assert!(text.contains("createObject"), "the built-ins are still listed"); +} + +#[test] +fn send_help_without_a_store_says_host_actions_need_one_and_with_no_snapshot_says_so() { + let text = help_text(&["send", "--help"], None); + assert!(text.contains("host actions: add --store"), "{text}"); + assert!(text.contains("createObject")); + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + assert!(help_text(&["send", "--help"], Some(&path)).contains("the store holds no host snapshot yet")); +} + +#[test] +fn a_host_intent_out_of_bounds_exits_1_and_leaves_the_store_byte_identical() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let before = std::fs::read(&path).unwrap(); + let cases: [(&[&str], &str); 3] = [ + (&["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=99"], "size must be between 0.1 and 10."), + (&["send", "brokkr_host_fixture.add_empty"], "name is required."), + (&["send", "brokkr_host_fixture.report", "--set", "x=1"], "has no field 'x'"), + ]; + for (args, message) in cases { + let mut args = args.to_vec(); + args.extend(["--agent", "hands", "--no-wait"]); + let output = ctl(&path, &args, Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{args:?}"); + assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{args:?}"); + assert_eq!(std::fs::read(&path).unwrap(), before, "{args:?} wrote to the store"); + } +} + +#[test] +fn a_human_only_operator_is_unsupported_and_a_published_host_action_is_written() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let before = std::fs::read(&path).unwrap(); + let output = ctl(&path, &["send", "brokkr_host_fixture.apply", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("Unsupported Blender command action: brokkr_host_fixture.apply")); + assert_eq!(std::fs::read(&path).unwrap(), before); + let sent = ctl(&path, &["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=2", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(sent.status.code(), Some(0), "{}", String::from_utf8_lossy(&sent.stderr)); + let id = stdout(&sent).trim().strip_prefix("commandId: ").unwrap().to_string(); + let store = SingleFileMessagePackBackingStore::new(&path); + let intent = store.pull_all().unwrap().into_iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + let value: Value = rmp_serde::from_slice(&intent.payload).unwrap(); + assert_eq!((value["action"].as_str(), value["size"].as_i64()), (Some("brokkr_host_fixture.add_empty"), Some(2))); +} + +#[test] +fn status_names_the_host_actions_and_each_refused_file_and_a_multiline_result_prints_indented() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let text = stdout(&ctl(&path, &["status"], None)); + assert!(text.contains("hostActions: brokkr_host_fixture.add_empty, brokkr_host_fixture.report"), "{text}"); + assert!(text.contains("hostActionErrors: broken_addon: brokkr_actions.json: host schema must be"), "{text}"); + push( + &path, + &[envelope_at(RECEIPT, "blender/receipts/h", &json!({"commandId": "h", "status": "accepted", "hostResult": "objects: 3\nscenes: 1", "observedAt": "2026-11-28T10:00:01+00:00"}))], + ); + let receipt = stdout(&ctl(&path, &["wait", "h"], None)); + assert!(receipt.contains("hostResult:\n objects: 3\n scenes: 1\n"), "{receipt}"); +} -- 2.47.3 From 740a2c84c31b701cd693b13e9d0ecdd370b746d6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:12:09 +0100 Subject: [PATCH 3/6] install.md: host add-on actions Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/docs/install.md | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 1bd94b9..cbb17fe 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -246,6 +246,43 @@ Behaviour the table does not say, per action: object, or an undo or redo). Selection totals are the mesh's own counts and the index scan stops at the cap. They are observations: no intent is refused because of them. +### Host add-on actions + +A host add-on (Aetheria's `aetheria_ships`, say) lets agents run some of its own operators by putting a file +`brokkr_actions.json` beside its `__init__.py`: `{"schema": "brokkr.blender.host_actions.v0", "actions": [row]}`. +The add-on imports nothing from Brokkr and registers nothing; the file is the whole contract. +`surfaces/blender/tests/fixtures/brokkr_host_fixture/` is a worked example. + +A row is a built-in row (`name`, `doc`, `changesScene`, `editModeSafe`, `fields`) plus an optional `result`. +`name` is the `bl_idname` of an operator the same add-on registers (`addon.operator`, lower case, one dot, so +it never equals a built-in name). Fields are scalar only: `string` (with `enum`, `minLength`, `maxLength`, +`chars`, `prefixes`, `forbid`), `number` or `integer` (both with `minimum` and `maximum`) and `boolean`, +with `required` and `default` as for built-ins; no arrays, objects or free JSON, and no `envelope` or +`charsets` keys. The messages are the built-in ones. + +Brokkr admits a file whole or not at all, at every intent and snapshot (a changed file is re-read; a +disabled add-on's actions are unknown at its next intent). Beyond the file's own shape it checks that each +named operator exists and is a Python class defined by that add-on's module, that every field is a property +of the operator of the matching type (a string with an `enum` is an enum property with the same +identifiers), that the operator's RNA hard limits contain the row's bounds, and that `result` names a +`StringProperty` on `bpy.types.WindowManager`. A refused file is reported in the host snapshot as +`hostActionErrors` (`brokkr-ctl blender status` prints each) and none of its rows runs. + +An admitted action goes through the same agent turn as a built-in: Edit Mode refusal for rows that are not +`editModeSafe`, one labelled undo step when `changesScene`, a receipt. The operator is called with +`'EXEC_DEFAULT'` and exactly the declared fields. It runs on Blender's main thread, so a long operator +blocks the interface for as long as her own button would. `FINISHED` is `accepted`; `CANCELLED` is `failed` +with nothing pushed; an argument Blender will not convert, or an `ERROR` report or exception, is `failed` +(with the first line of the error). `result` is how an operator returns text (a dry-run's change lines): the +agent turn clears that WindowManager property before the call and copies it, up to 16000 characters and then +`[truncated]`, into the receipt's `hostResult` (empty for every other action). + +The admitted rows are published in the host snapshot as `hostActions` (each with its `host` module). +`brokkr-ctl blender send --help --store ` lists them after the built-ins, `send` refuses an intent +they refuse before writing anything, and the add-on still decides. Human-only is absence: an operator only a +person may run (one that applies a change to a game's data) is left out of the file, so an intent naming it +is `Unsupported Blender command action`, as `runPython` is; the person still presses her own button. + The scene actions were run against Blender 5.2.3 LTS headless with `surfaces/blender/tests/live/headless_smoke.py` (usage in its docstring). One real failure it found: Blender's `engine` enum is dynamic, so `bl_rna` lists only -- 2.47.3 From c1aacd9f7b2066c8ac7595ff2b7ec1659722b70b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:16:29 +0100 Subject: [PATCH 4/6] live/host_action.py: GUI Blender 5.3 proof of host rows, undo steps, results and human-only absence Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/tests/cli.rs | 2 +- surfaces/blender/tests/live/host_action.py | 241 ++++++++++++++++++ .../tests/live/host_action.result.json | 218 ++++++++++++++++ surfaces/blender/tests/test_agent_turn.py | 4 +- 4 files changed, 462 insertions(+), 3 deletions(-) create mode 100644 surfaces/blender/tests/live/host_action.py create mode 100644 surfaces/blender/tests/live/host_action.result.json diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 1cd8847..6e3d124 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -582,7 +582,7 @@ fn a_host_intent_out_of_bounds_exits_1_and_leaves_the_store_byte_identical() { } #[test] -fn a_human_only_operator_is_unsupported_and_a_published_host_action_is_written() { +fn an_operator_left_out_of_the_file_is_unsupported_and_a_published_host_action_is_written() { let dir = tempfile::tempdir().unwrap(); let path = host_store(dir.path()); let before = std::fs::read(&path).unwrap(); diff --git a/surfaces/blender/tests/live/host_action.py b/surfaces/blender/tests/live/host_action.py new file mode 100644 index 0000000..898137a --- /dev/null +++ b/surfaces/blender/tests/live/host_action.py @@ -0,0 +1,241 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, that a host add-on's brokkr_actions.json adds +rows the agent turn admits, runs and undoes like a built-in, and that an operator left out of the file stays human-only. + + BROKKR_SCRATCH= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python host_action.py -- + +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. It copies tests/fixtures/brokkr_host_fixture into BLENDER_USER_SCRIPTS/addons and +enables it there; it writes nothing else outside BROKKR_SCRATCH. Every intent is put into the node database as +brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). Proves, with wm.undo_stack as the counter: + + * the snapshot lists the fixture's four rows (host, no apply) and no hostActionErrors; + * add_empty is accepted as exactly one new undo step, undo removes the empty, redo brings it back; + * report is accepted with hostResult equal to what the operator wrote, no new step, humanEditSeq unchanged; + * refuse is failed with the operator's text and cancel is failed, each with no new step; + * apply (registered, left out of the file) and wm.save_mainfile are denied Unsupported with no step, the scene + unchanged and no 'Applied' object. + +Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import shutil +import sys +import traceback +from pathlib import Path + +import bpy + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own folders are used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if os.path.normcase(os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != os.path.normcase(os.path.abspath(os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") +if os.path.normcase(os.path.abspath(bpy.utils.user_resource("SCRIPTS"))) != os.path.normcase(os.path.abspath(os.environ["BLENDER_USER_SCRIPTS"])): + raise SystemExit("Blender's scripts folder is not BLENDER_USER_SCRIPTS; refusing to touch it") + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +HOST = "brokkr_host_fixture" +FIXTURE = Path(__file__).resolve().parents[1] / "fixtures" / HOST +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": []} + +addons_dir = Path(os.environ["BLENDER_USER_SCRIPTS"]) / "addons" +addons_dir.mkdir(parents=True, exist_ok=True) +if (addons_dir / HOST).exists(): + shutil.rmtree(addons_dir / HOST) +shutil.copytree(FIXTURE, addons_dir / HOST, ignore=shutil.ignore_patterns("__pycache__")) +bpy.utils.refresh_script_paths() + +bpy.ops.preferences.addon_enable(module=MODULE) +bpy.ops.preferences.addon_enable(module=HOST) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +prefs = bpy.context.preferences.addons[MODULE].preferences +bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "live.blend")) +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" +prefs.auto_drain_commands = True # the sink +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +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 steps_now(): + return [s.name for s in bpy.context.window_manager.undo_stack.steps] + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def redo(): + with win(): + bpy.ops.ed.redo() + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +N = [0] + + +def queue(**cmd): + N[0] += 1 + cid = "host-%04d" % N[0] + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA, requestedBy="nibu/hands") + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + return cid + + +def receipt(cid): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{cid}") + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=40): + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("the drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def send(key, **fields): + S[key + ":before"] = {"steps": steps_now(), "names": names(), "seq": adapter.human_edit_seq} + S[key] = queue(**fields) + + +def done(key): + return lambda: receipt(S[key]) is not None + + +def same_world(key): + before = S[key + ":before"] + return (steps_now() == before["steps"] and names() == before["names"] and adapter.human_edit_seq == before["seq"]) + + +def snapshot_check(): + snapshot = adapter.capture_snapshot(bpy.context, True) + rows = snapshot["hostActions"] + expect = [f"{HOST}.{n}" for n in ("add_empty", "report", "refuse", "cancel")] + check("the snapshot lists the fixture's four rows with their host and none other (apply is left out)", + sorted(r["name"] for r in rows) == sorted(expect) and {r["host"] for r in rows} == {HOST}, [r["name"] for r in rows]) + check("the snapshot carries no hostActionErrors", snapshot["hostActionErrors"] == [], snapshot["hostActionErrors"]) + check("the operators are registered by the legacy add-on, apply included", + all(hasattr(getattr(bpy.ops, HOST), n) for n in ("add_empty", "report", "refuse", "cancel", "apply"))) + + +def add_check(): + r = receipt(S["add"]) + before = S["add:before"] + after = steps_now() + check("add_empty is accepted", r["status"] == "accepted", r) + check("add_empty is exactly one new undo step carrying the receipt's label", + len(after) == len(before["steps"]) + 1 and after[-1] == r["undoLabel"] and r["undoLabel"].startswith(f"Brokkr nibu/hands: {HOST}.add_empty "), + {"before": before["steps"][-2:], "after": after[-2:], "label": r["undoLabel"]}) + check("add_empty made the empty with the declared name and size", + "LiveEmpty" in bpy.data.objects and abs(bpy.data.objects["LiveEmpty"].empty_display_size - 2.0) < 1e-6, names()) + check("add_empty is the agent's write: humanEditSeq did not move", adapter.human_edit_seq == before["seq"]) + S["add:names"] = names() + undo() + check("one undo removes the empty", "LiveEmpty" not in bpy.data.objects, names()) + redo() + check("redo brings it back", names() == S["add:names"], names()) + + +def report_check(): + r = receipt(S["report"]) + expect = f"objects: {len(bpy.data.objects)}\nscenes: {len(bpy.data.scenes)}" + check("report is accepted with hostResult equal to what the operator wrote", r["status"] == "accepted" and r["hostResult"] == expect, [r["status"], r["hostResult"], expect]) + check("report pushed no undo step, added no object and left humanEditSeq alone", same_world("report"), [steps_now()[-2:], S["report:before"]["steps"][-2:]]) + + +def failure_check(key, text): + def run(): + r = receipt(S[key]) + check(f"{key} is failed{' with ' + repr(text) if text else ''}", r["status"] == "failed" and text in r["message"], r) + check(f"{key} pushed no undo step and changed nothing", same_world(key) and r["undoLabel"] == "", r["undoLabel"]) + return run + + +def denied_check(key, action): + def run(): + r = receipt(S[key]) + check(f"{action} is denied Unsupported", r["status"] == "denied" and "Unsupported Blender command action" in r["message"], r) + check(f"{action} ran nothing: no step, no new object, no 'Applied'", same_world(key) and "Applied" not in bpy.data.objects, names()) + return run + + +steps = [ + once(snapshot_check), + once(lambda: send("add", action=f"{HOST}.add_empty", name="LiveEmpty", size=2)), until(done("add")), once(add_check), + once(lambda: send("report", action=f"{HOST}.report")), until(done("report")), once(report_check), + once(lambda: send("refuse", action=f"{HOST}.refuse")), until(done("refuse")), once(failure_check("refuse", "the fixture refuses")), + once(lambda: send("cancel", action=f"{HOST}.cancel")), until(done("cancel")), once(failure_check("cancel", "cancelled; nothing changed")), + once(lambda: send("apply", action=f"{HOST}.apply")), until(done("apply")), once(denied_check("apply", f"{HOST}.apply")), + once(lambda: send("save", action="wm.save_mainfile")), until(done("save")), once(denied_check("save", "wm.save_mainfile")), +] +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/host_action.result.json b/surfaces/blender/tests/live/host_action.result.json new file mode 100644 index 0000000..a493c29 --- /dev/null +++ b/surfaces/blender/tests/live/host_action.result.json @@ -0,0 +1,218 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "the snapshot lists the fixture's four rows with their host and none other (apply is left out)", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel" + ] + }, + { + "name": "the snapshot carries no hostActionErrors", + "ok": true, + "detail": [] + }, + { + "name": "the operators are registered by the legacy add-on, apply included", + "ok": true, + "detail": null + }, + { + "name": "add_empty is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0001", + "action": "brokkr_host_fixture.add_empty", + "status": "accepted", + "message": "Operator brokkr_host_fixture.add_empty finished.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:08.910684+00:00" + } + }, + { + "name": "add_empty is exactly one new undo step carrying the receipt's label", + "ok": true, + "detail": { + "before": [ + "Original" + ], + "after": [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ], + "label": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + } + }, + { + "name": "add_empty made the empty with the declared name and size", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "add_empty is the agent's write: humanEditSeq did not move", + "ok": true, + "detail": null + }, + { + "name": "one undo removes the empty", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "redo brings it back", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "report is accepted with hostResult equal to what the operator wrote", + "ok": true, + "detail": [ + "accepted", + "objects: 4\nscenes: 1", + "objects: 4\nscenes: 1" + ] + }, + { + "name": "report pushed no undo step, added no object and left humanEditSeq alone", + "ok": true, + "detail": [ + [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ], + [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ] + ] + }, + { + "name": "refuse is failed with 'the fixture refuses'", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0003", + "action": "brokkr_host_fixture.refuse", + "status": "failed", + "message": "Error: the fixture refuses", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:13.022948+00:00" + } + }, + { + "name": "refuse pushed no undo step and changed nothing", + "ok": true, + "detail": "" + }, + { + "name": "cancel is failed with 'cancelled; nothing changed'", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0004", + "action": "brokkr_host_fixture.cancel", + "status": "failed", + "message": "Operator brokkr_host_fixture.cancel cancelled; nothing changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:14.080400+00:00" + } + }, + { + "name": "cancel pushed no undo step and changed nothing", + "ok": true, + "detail": "" + }, + { + "name": "brokkr_host_fixture.apply is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0005", + "action": "brokkr_host_fixture.apply", + "status": "denied", + "message": "Unsupported Blender command action: brokkr_host_fixture.apply", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:16.137129+00:00" + } + }, + { + "name": "brokkr_host_fixture.apply ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "wm.save_mainfile is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0006", + "action": "wm.save_mainfile", + "status": "denied", + "message": "Unsupported Blender command action: wm.save_mainfile", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T05:15:18.194603+00:00" + } + }, + { + "name": "wm.save_mainfile ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + } + ], + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 6578b4b..60afb83 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -372,7 +372,7 @@ class HostActionTests(unittest.TestCase): self.assertEqual(len(self.bpy.undo.pushes), 1) self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) - def test_a_human_only_operator_and_a_c_operator_are_unsupported_and_leave_no_trace(self): + def test_an_operator_left_out_of_the_file_and_a_c_operator_are_unsupported_and_leave_no_trace(self): for action in (f"{HOST}.apply", "wm.save_mainfile", "brokkr.stop_agents"): receipt = self.run_action(action=action) self.assertEqual(receipt["status"], "denied", action) @@ -385,7 +385,7 @@ class HostActionTests(unittest.TestCase): self.assertEqual(self.send("add_empty", name="E")["status"], "denied") self.assertEqual(self.send("report")["status"], "accepted") - def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_human_only_row(self): + def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_left_out_row(self): self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") self.bpy.app = NS(version=(5, 3, 0), background=False) context = NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT") -- 2.47.3 From 26efb1b31a9814e5697ea7104785db8d3e64ee89 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 06:19:04 +0100 Subject: [PATCH 5/6] Host operator: drop the redundant _wrote writes; tests pin the envelope and the own add-on never read as a host Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/blender_target.py | 4 +--- surfaces/blender/tests/test_agent_turn.py | 11 ++++++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 8bde4b0..1c78e9b 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -847,11 +847,9 @@ class BrokkrBlenderTarget: text = getattr(manager, result, "") or "" if len(text) > HOST_RESULT_LIMIT: text = text[:HOST_RESULT_LIMIT] + " [truncated]" - if "FINISHED" in outcome: - self._wrote = bool(row["changesScene"]) + if "FINISHED" in outcome: # run_intent pushes an undo step for an accepted changesScene row only receipt = self._receipt(command, "accepted", f"Operator {name} finished.", "") else: - self._wrote = False receipt = self._receipt(command, "failed", f"Operator {name} cancelled; nothing changed.", "") receipt["hostResult"] = text return receipt diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 60afb83..8b8174b 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -326,9 +326,14 @@ class HostActionTests(unittest.TestCase): def test_the_default_is_filled_and_an_undeclared_field_never_reaches_the_operator(self): self.assertEqual(self.send("add_empty", name="E")["status"], "accepted") self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) + self.ops["add_empty"].calls.clear() + self.assertEqual(self.send("add_empty", name="E", note="why")["status"], "accepted") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) # the envelope never reaches the operator + self.ops["add_empty"].calls.clear() + self.ops["add_empty"].calls.append({}) denied = self.send("add_empty", name="E", location=[1, 2, 3]) self.assertEqual(denied["status"], "denied") - self.assertEqual(len(self.ops["add_empty"].calls), 1) + self.assertEqual(len(self.ops["add_empty"].calls), 1) # only the seeded marker: the denied intent ran nothing def test_a_non_changing_operator_pushes_no_undo_step_and_returns_its_result(self): receipt = self.send("report") @@ -452,6 +457,10 @@ class HostActionTests(unittest.TestCase): self.assertEqual(self.target.host_actions(), ([], [])) self.bpy.context.preferences.addons["brokkr_bridge"] = object() self.assertEqual(self.target.host_actions(), ([], [])) + (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + with unittest.mock.patch.object(sys.modules["brokkr_bridge"], "__file__", str(self.dir / "__init__.py"), create=True): + self.bpy.context.preferences.addons.pop(HOST) # a file sits beside this add-on itself: still not read as a host's + self.assertEqual(self.target.host_actions(), ([], [])) class FakeNode: -- 2.47.3 From fb9696b6394b794100ceb752fb787936cff62813 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 07:07:18 +0100 Subject: [PATCH 6/6] Host actions: files are read only by the human's reload, never on an intent Reload Host Actions operator (refuses inside an agent turn) and one startup read; envelope-named fields, unknown row keys, read-only results and UNDO operators on non-changing rows refuse the file; a failed poll or unclearable result refuses before any undo step; tests pin the ownership prefix, enum, snapshot errors and the guards; live proof extended; docs say the flags are the host's word. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/__init__.py | 29 ++++ .../blender/brokkr_bridge/action_table.py | 3 + .../blender/brokkr_bridge/blender_target.py | 115 ++++++++------- surfaces/blender/docs/install.md | 27 +++- surfaces/blender/tests/live/host_action.py | 47 +++++- .../tests/live/host_action.result.json | 110 +++++++++++++- surfaces/blender/tests/test_action_table.py | 7 + surfaces/blender/tests/test_addon_ui.py | 31 ++++ surfaces/blender/tests/test_agent_turn.py | 134 +++++++++++++++++- 9 files changed, 434 insertions(+), 69 deletions(-) diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index c9db1ec..0801c16 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -389,6 +389,7 @@ class BROKKR_PT_status(bpy.types.Panel): row = layout.row(align=True) row.operator("brokkr.capture_snapshot", icon="FILE_REFRESH") + layout.operator("brokkr.reload_host_actions", icon="FILE_REFRESH") row.operator("brokkr.drain_commands", icon="PLAY") layout.prop(prefs, "auto_drain_commands") @@ -495,6 +496,23 @@ class BROKKR_OT_stop_agents(bpy.types.Operator): return {"FINISHED"} +class BROKKR_OT_reload_host_actions(bpy.types.Operator): + bl_idname = "brokkr.reload_host_actions" + bl_label = "Reload Host Actions" + bl_description = ("Read each enabled add-on's brokkr_actions.json again. Only this button does: an agent cannot cause " + "a re-read, so an edited file admits nothing until you press it") + + def execute(self, context): + try: + found = target().reload_host_actions() + except PermissionError as exc: # inside an agent turn: a human acts here, never an agent + self.report({"ERROR"}, str(exc)) + return {"CANCELLED"} + rows, errors = target().host_actions() + self.report({"INFO"}, f"{found} host file(s) read; {len(rows)} host action(s) admitted, {len(errors)} file(s) refused.") + return {"FINISHED"} + + class BROKKR_OT_drain_commands(bpy.types.Operator): bl_idname = "brokkr.drain_commands" bl_label = "Drain Commands" @@ -741,6 +759,7 @@ classes = ( BROKKR_PT_status, BROKKR_OT_stop_agents, BROKKR_OT_capture_snapshot, + BROKKR_OT_reload_host_actions, BROKKR_OT_drain_commands, BROKKR_OT_start_server, BROKKR_OT_stop_server, @@ -752,6 +771,15 @@ classes = ( ) +def _load_host_actions_once(): + """One read of the host files shortly after startup, when the other add-ons are enabled (not an intent's doing).""" + try: + target().reload_host_actions() + except Exception: + pass + return None + + def register(): for cls in classes: bpy.utils.register_class(cls) @@ -762,6 +790,7 @@ def register(): getattr(bpy.app.handlers, name).append(handler) if not bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.register(_auto_drain_commands, first_interval=1.0, persistent=True) + bpy.app.timers.register(_load_host_actions_once, first_interval=3.0) def unregister(): diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py index 48a888f..eba7e82 100644 --- a/surfaces/blender/brokkr_bridge/action_table.py +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -132,9 +132,12 @@ def check_host(document: Any, charsets: dict[str, Any]) -> None: if "result" in row and not (isinstance(row["result"], str) and row["result"].isidentifier()): raise TableInvalid(f"{name}.result must be an identifier") fields = {} + envelope = table()["envelope"] for field in row["fields"]: if not isinstance(field, dict) or not isinstance(field.get("name"), str) or field["name"] in fields: raise TableInvalid(f"{name} has a missing or repeated field name") + if field["name"] in envelope: + raise TableInvalid(f"{name}.{field['name']} is an envelope key; Brokkr writes it, so the operator would never receive the agent's value") fields[field["name"]] = field for field in fields.values(): where = f"{name}.{field['name']}" diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 1c78e9b..e030c89 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib import ctypes import functools import json @@ -102,10 +103,6 @@ CAPABILITIES = ( ) -class _NoHostFile(Exception): - """The add-on has no brokkr_actions.json: it is not a host.""" - - def _first_line(text: str) -> str: return text.strip().splitlines()[0] if text.strip() else "failed" @@ -131,7 +128,7 @@ class BrokkrBlenderTarget: 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() - self._host_files: dict[str, tuple[tuple, Any]] = {} # module -> (file stamp, parsed document or error text): a cache of reads, never truth + self._host_docs: dict[str, Any] = {} # module -> parsed host document or the error that refused it; written only by reload_host_actions self._unsent: list[tuple[dict[str, Any], str]] = [] # receipts whose write failed: written first on the next drain, never read as truth self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts self._receipts_loaded = False @@ -646,25 +643,50 @@ class BrokkrBlenderTarget: "hostActionErrors": host_errors, } + def reload_host_actions(self) -> int: + """Read every enabled add-on's brokkr_actions.json (this add-on excepted) into the stored host documents, + replacing what was stored: the one place a host file is read. A human act: the panel's Reload Host Actions + button, and once shortly after this add-on registers. An intent never reaches it (an agent turn cannot + cause a re-read: this refuses inside one), so a file rewritten to list another operator admits nothing + until she reloads. A file is stored parsed and checked, or as the error that refused it; the live checks in + host_actions still run at every intent. Returns the number of host files found.""" + if self.agent_turn: + raise PermissionError("Host actions are reloaded by the human only, never inside an agent turn.") + own = __package__ or "" + docs: dict[str, Any] = {} + for module in self.bpy.context.preferences.addons.keys(): + if module == own: + continue + source = getattr(sys.modules.get(module), "__file__", None) + path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None + if path is None or not path.is_file(): + continue + try: + document = json.loads(path.read_text(encoding="utf-8")) + at.check_host(document, at.table()["charsets"]) + docs[module] = document + except Exception as error: + docs[module] = str(error) + self._host_docs = docs + return len(docs) + def host_actions(self) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - """The one discovery of host rows: ([row + 'host' module], [{host, error}]). Each enabled add-on but this - one may carry brokkr_actions.json beside its __init__.py; the file is admitted whole or not at all. The - file is the add-on's word; what is checked here is what Brokkr can see: the operator exists and is a - Python class defined by that add-on, every field is a property of it of the matching type whose RNA hard - limits contain the row's bounds, and result is a WindowManager string property. Only the parse is cached - (on path, mtime and size); the live checks run each time, so a disabled add-on or an unregistered operator - is gone at the next intent. A name two files claim fails ownership in all but its owner.""" + """The host rows admitted now: ([row + 'host' module], [{host, error}]), from the documents the last + reload stored (no file is read here). A document is admitted whole or not at all. The file is the add-on's + word; what is checked here, at every call, is what Brokkr can see: the add-on is still enabled, the operator + exists and is a Python class defined by that add-on (module equal to it or under it: 'aeth_ships' is not + under 'aeth'), every field is a property of it of the matching type whose RNA hard limits contain the row's + bounds, a row that changes nothing names no operator that pushes undo itself (bl_options UNDO), and result + is a writable WindowManager string property. A disabled add-on or an unregistered operator is gone at the + next intent. A name two files claim fails ownership in all but its owner.""" rows: list[dict[str, Any]] = [] errors: list[dict[str, Any]] = [] - own = __package__ or "" - modules = [m for m in self.bpy.context.preferences.addons.keys() if m != own] - for module in modules: - try: - document = self._host_document(module) - except _NoHostFile: + enabled = set(self.bpy.context.preferences.addons.keys()) + for module, document in self._host_docs.items(): + if module not in enabled: continue - except Exception as error: - errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + if isinstance(document, str): + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {document}")}) continue try: for row in document["actions"]: @@ -675,28 +697,6 @@ class BrokkrBlenderTarget: rows.extend({**row, "host": module} for row in document["actions"]) return rows, errors - def _host_document(self, module: str) -> dict[str, Any]: - loaded = sys.modules.get(module) - source = getattr(loaded, "__file__", None) - path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None - if path is None or not path.is_file(): - self._host_files.pop(module, None) - raise _NoHostFile() - info = path.stat() - stamp = (str(path), info.st_mtime_ns, info.st_size) - cached = self._host_files.get(module) - if cached is None or cached[0] != stamp: - try: - document = json.loads(path.read_text(encoding="utf-8")) - at.check_host(document, at.table()["charsets"]) - cached = (stamp, document) - except Exception as error: - cached = (stamp, str(error)) - self._host_files[module] = cached - if isinstance(cached[1], str): - raise ValueError(cached[1]) - return cached[1] - def _check_host_row(self, module: str, row: dict[str, Any]) -> None: bpy = self.bpy name = row["name"] @@ -706,6 +706,8 @@ class BrokkrBlenderTarget: owned = getattr(owner, "__module__", None) if not isinstance(owner, type) or not isinstance(owned, str) or not (owned == module or owned.startswith(module + ".")): raise ValueError(f"{name} is not an operator defined by {module}") + if "UNDO" in getattr(owner, "bl_options", ()) and not row["changesScene"]: + raise ValueError(f"{name} pushes undo itself (bl_options UNDO) but the row says changesScene is false") properties = {p.identifier: p for p in operator.get_rna_type().properties} kinds = {"string": "STRING", "number": "FLOAT", "integer": "INT", "boolean": "BOOLEAN"} for field in row["fields"]: @@ -723,8 +725,8 @@ class BrokkrBlenderTarget: result = row.get("result") if result is not None: prop = bpy.types.WindowManager.bl_rna.properties.get(result) - if prop is None or prop.type != "STRING": - raise ValueError(f"{name} result {result} is not a string property of WindowManager") + if prop is None or prop.type != "STRING" or prop.is_readonly: + raise ValueError(f"{name} result {result} is not a writable string property of WindowManager") 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. @@ -827,21 +829,32 @@ class BrokkrBlenderTarget: kwargs = {k: v for k, v in command.items() if k not in skip} result = row.get("result") manager = bpy.context.window_manager - if result: - setattr(manager, result, "") first, second = name.split(".") operator = getattr(getattr(bpy.ops, first), second) windows = manager.windows + override = bpy.context.temp_override(window=windows[0]) if windows else contextlib.nullcontext() + # Everything that can refuse before the operator runs does so here, as ActionRefused: no undo step is pushed. try: - if windows: - with bpy.context.temp_override(window=windows[0]): - outcome = operator("EXEC_DEFAULT", False, **kwargs) - else: + with override: + runnable = operator.poll() + except Exception as error: + raise sa.ActionRefused(f"Operator {name} cannot run here: {_first_line(str(error))}") from None + if not runnable: + raise sa.ActionRefused(f"Operator {name} cannot run in this context (its poll failed); nothing changed.") + if result: + try: + setattr(manager, result, "") + except Exception as error: + raise sa.ActionRefused(f"Operator {name} result {result} cannot be cleared: {_first_line(str(error))}") from None + try: + with override: outcome = operator("EXEC_DEFAULT", False, **kwargs) except TypeError as error: raise sa.ActionRefused(f"Operator {name} refused its arguments: {_first_line(str(error))}") from None except RuntimeError as error: - raise RuntimeError(_first_line(str(error))) from None + lines = [line for line in str(error).splitlines() if line.strip()] + cause = lines[-1] if lines and "Traceback" in lines[0] else (lines[0] if lines else "failed") # a traceback's cause is its last line + raise RuntimeError(cause.strip()) from None text = "" if result: text = getattr(manager, result, "") or "" diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index cbb17fe..9ef449e 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -260,13 +260,26 @@ it never equals a built-in name). Fields are scalar only: `string` (with `enum`, with `required` and `default` as for built-ins; no arrays, objects or free JSON, and no `envelope` or `charsets` keys. The messages are the built-in ones. -Brokkr admits a file whole or not at all, at every intent and snapshot (a changed file is re-read; a -disabled add-on's actions are unknown at its next intent). Beyond the file's own shape it checks that each -named operator exists and is a Python class defined by that add-on's module, that every field is a property -of the operator of the matching type (a string with an `enum` is an enum property with the same -identifiers), that the operator's RNA hard limits contain the row's bounds, and that `result` names a -`StringProperty` on `bpy.types.WindowManager`. A refused file is reported in the host snapshot as -`hostActionErrors` (`brokkr-ctl blender status` prints each) and none of its rows runs. +Brokkr admits a file whole or not at all, and reads it only when a human asks: once shortly after Brokkr +registers, and whenever she presses `Reload Host Actions` in the Brokkr panel. No intent, snapshot or agent +turn re-reads a file (the operator refuses inside a turn), so rewriting `brokkr_actions.json` to list +another operator admits nothing until she reloads; press it after enabling a host add-on or editing its +file. A file is checked when it is read, and the live checks below run at every intent and snapshot, so a +disabled add-on's actions are unknown at its next intent. A field may not be named like an envelope key +(`schema`, `commandId`, `action`, `requestedBy`, `note`): Brokkr writes those itself, so the operator would +never receive the agent's value. The live checks: each named operator exists and is a Python class defined by +that add-on's module (the module itself or under it: `aetheria_ships` is not `aetheria`'s), every field is a +property of the operator of the matching type (a string with an `enum` is an enum property with the same +identifiers), the operator's RNA hard limits contain the row's bounds, a row with `changesScene` false names +no operator whose `bl_options` has `UNDO`, and `result` names a writable `StringProperty` on +`bpy.types.WindowManager`. A refused file is reported in the host snapshot as `hostActionErrors` +(`brokkr-ctl blender status` prints each) and none of its rows runs. + +`changesScene` and `editModeSafe` are the host's word: Brokkr cannot see what an operator writes. A row that +claims to change nothing but writes gets no undo step and no Edit Mode refusal, so keep the flags honest. An +operator that calls `bpy.ops.ed.undo_push` itself adds that step to Brokkr's own (two for one action), or +one with `changesScene` false; that is a documented limit, not checked. A `poll` that fails, or a result +property that cannot be cleared, refuses before anything runs and pushes no undo step. An admitted action goes through the same agent turn as a built-in: Edit Mode refusal for rows that are not `editModeSafe`, one labelled undo step when `changesScene`, a receipt. The operator is called with diff --git a/surfaces/blender/tests/live/host_action.py b/surfaces/blender/tests/live/host_action.py index 898137a..930a51a 100644 --- a/surfaces/blender/tests/live/host_action.py +++ b/surfaces/blender/tests/live/host_action.py @@ -17,7 +17,10 @@ brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). Pro * report is accepted with hostResult equal to what the operator wrote, no new step, humanEditSeq unchanged; * refuse is failed with the operator's text and cancel is failed, each with no new step; * apply (registered, left out of the file) and wm.save_mainfile are denied Unsupported with no step, the scene - unchanged and no 'Applied' object. + unchanged and no 'Applied' object; + * the file is then rewritten to list apply: apply and the reload operator sent as intents are still denied (no + re-read on an intent), the operator refuses inside an agent turn, and only the human's reload (this driver + calling bpy.ops.brokkr.reload_host_actions outside a turn) admits apply, as one undo step. Writes .result.json, then quits Blender. """ @@ -66,6 +69,7 @@ prefs.debug_mirror_root = "" prefs.auto_drain_commands = True # the sink prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) adapter = addon.target() +bpy.ops.brokkr.reload_host_actions() # the human's button: the host files are read here def check(name, ok, detail=None): @@ -204,6 +208,42 @@ def denied_check(key, action): return run +def rewrite_listing_apply(): + path = addons_dir / HOST / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"].append({"name": f"{HOST}.apply", "doc": "applies", "changesScene": True, "editModeSafe": False, "fields": []}) + path.write_text(json.dumps(document), encoding="utf-8") + + +def reload_refused_in_a_turn(): + adapter.agent_turn = True + try: + try: + bpy.ops.brokkr.reload_host_actions() + refused = False + except RuntimeError as error: + refused = "human only" in str(error) + finally: + adapter.agent_turn = False + check("the Reload Host Actions operator refuses inside an agent turn", refused) + names_now = [r["name"] for r in adapter.host_actions()[0]] + check("and re-read nothing: the edited file's apply row is still not admitted", f"{HOST}.apply" not in names_now, names_now) + + +def human_reload_check(): + bpy.ops.brokkr.reload_host_actions() + names_now = [r["name"] for r in adapter.host_actions()[0]] + check("the human's reload admits the edited file's apply row", f"{HOST}.apply" in names_now, names_now) + + +def applied_check(): + r = receipt(S["apply2"]) + after = steps_now() + before = S["apply2:before"] + check("apply is accepted after the human's reload as one labelled undo step", + r["status"] == "accepted" and len(after) == len(before["steps"]) + 1 and after[-1] == r["undoLabel"] and "Applied" in bpy.data.objects, r) + + steps = [ once(snapshot_check), once(lambda: send("add", action=f"{HOST}.add_empty", name="LiveEmpty", size=2)), until(done("add")), once(add_check), @@ -212,6 +252,11 @@ steps = [ once(lambda: send("cancel", action=f"{HOST}.cancel")), until(done("cancel")), once(failure_check("cancel", "cancelled; nothing changed")), once(lambda: send("apply", action=f"{HOST}.apply")), until(done("apply")), once(denied_check("apply", f"{HOST}.apply")), once(lambda: send("save", action="wm.save_mainfile")), until(done("save")), once(denied_check("save", "wm.save_mainfile")), + once(rewrite_listing_apply), + once(lambda: send("apply1", action=f"{HOST}.apply")), until(done("apply1")), once(denied_check("apply1", f"{HOST}.apply after the file was edited")), + once(lambda: send("reload", action="brokkr.reload_host_actions")), until(done("reload")), once(denied_check("reload", "brokkr.reload_host_actions")), + once(reload_refused_in_a_turn), once(human_reload_check), + once(lambda: send("apply2", action=f"{HOST}.apply")), until(done("apply2")), once(applied_check), ] i = 0 diff --git a/surfaces/blender/tests/live/host_action.result.json b/surfaces/blender/tests/live/host_action.result.json index a493c29..5ef9544 100644 --- a/surfaces/blender/tests/live/host_action.result.json +++ b/surfaces/blender/tests/live/host_action.result.json @@ -37,7 +37,7 @@ "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:08.910684+00:00" + "observedAt": "2026-11-28T06:03:04.276267+00:00" } }, { @@ -126,7 +126,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:13.022948+00:00" + "observedAt": "2026-11-28T06:03:08.396168+00:00" } }, { @@ -149,7 +149,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:14.080400+00:00" + "observedAt": "2026-11-28T06:03:10.456189+00:00" } }, { @@ -172,7 +172,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:16.137129+00:00" + "observedAt": "2026-11-28T06:03:12.513224+00:00" } }, { @@ -200,7 +200,7 @@ "undoLabel": "", "lookPath": "", "hostResult": "", - "observedAt": "2026-11-28T05:15:18.194603+00:00" + "observedAt": "2026-11-28T06:03:14.572017+00:00" } }, { @@ -212,6 +212,106 @@ "Light", "LiveEmpty" ] + }, + { + "name": "brokkr_host_fixture.apply after the file was edited is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0007", + "action": "brokkr_host_fixture.apply", + "status": "denied", + "message": "Unsupported Blender command action: brokkr_host_fixture.apply", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:16.631534+00:00" + } + }, + { + "name": "brokkr_host_fixture.apply after the file was edited ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "brokkr.reload_host_actions is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0008", + "action": "brokkr.reload_host_actions", + "status": "denied", + "message": "Unsupported Blender command action: brokkr.reload_host_actions", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:18.693145+00:00" + } + }, + { + "name": "brokkr.reload_host_actions ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "the Reload Host Actions operator refuses inside an agent turn", + "ok": true, + "detail": null + }, + { + "name": "and re-read nothing: the edited file's apply row is still not admitted", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel" + ] + }, + { + "name": "the human's reload admits the edited file's apply row", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel", + "brokkr_host_fixture.apply" + ] + }, + { + "name": "apply is accepted after the human's reload as one labelled undo step", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0009", + "action": "brokkr_host_fixture.apply", + "status": "accepted", + "message": "Operator brokkr_host_fixture.apply finished.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.apply ost-0009", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:21.755767+00:00" + } } ], "ok": true diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py index f3a5f6e..af2938b 100644 --- a/surfaces/blender/tests/test_action_table.py +++ b/surfaces/blender/tests/test_action_table.py @@ -79,6 +79,13 @@ class HostTableTests(unittest.TestCase): ): with self.assertRaises(at.TableInvalid, msg=why): at.check_host(bad, self.charsets()) + for key in ("note", "action", "commandId", "requestedBy", "schema"): # Brokkr writes these: the operator would never receive the agent's value + with self.assertRaises(at.TableInvalid, msg=key): + at.check_host(self.host_file(fields=[{"name": key, "type": "string"}]), self.charsets()) + with self.assertRaises(at.TableInvalid): + at.check_host(self.host_file(unknown=1), self.charsets()) + with self.assertRaises(at.TableInvalid): + at.check_host(self.host_file(fields=[{"name": "a", "type": "string"}, {"name": "b", "type": "string", "only": {"field": "a", "in": ["x"]}}]), self.charsets()) twice = copy.deepcopy(HOST_FILE) twice["actions"].append(copy.deepcopy(twice["actions"][0])) with self.assertRaises(at.TableInvalid): diff --git a/surfaces/blender/tests/test_addon_ui.py b/surfaces/blender/tests/test_addon_ui.py index 74c8a24..2240371 100644 --- a/surfaces/blender/tests/test_addon_ui.py +++ b/surfaces/blender/tests/test_addon_ui.py @@ -113,6 +113,37 @@ class CopyOperatorTests(unittest.TestCase): self.assertIn(addon.BROKKR_OT_copy_session_token, addon.classes) +class ReloadHostActionsTests(unittest.TestCase): + """The panel's Reload Host Actions button is the human's: it reads the files; it refuses inside an agent turn.""" + + def press(self, target): + operator = addon.BROKKR_OT_reload_host_actions() + operator.reported = None + with mock.patch.object(addon, "_target", target): + return operator.execute(None), operator.reported + + def test_pressed_it_reloads_and_reports_the_counts(self): + target = bt.BrokkrBlenderTarget(NS()) + target.reload_host_actions = mock.Mock(return_value=2) + target.host_actions = mock.Mock(return_value=([{"name": "a.b"}], [])) + result, reported = self.press(target) + self.assertEqual(result, {"FINISHED"}) + target.reload_host_actions.assert_called_once_with() + self.assertIn("2 host file(s) read; 1 host action(s) admitted", reported[1]) + + def test_inside_an_agent_turn_it_refuses_and_reads_nothing(self): + target = bt.BrokkrBlenderTarget(NS()) + target.agent_turn = True + target._host_docs = {"kept": {}} + result, reported = self.press(target) + self.assertEqual((result, reported[0]), ({"CANCELLED"}, {"ERROR"})) + self.assertEqual(target._host_docs, {"kept": {}}) + + def test_it_is_registered_and_drawn_in_the_panel(self): + self.assertIn(addon.BROKKR_OT_reload_host_actions, addon.classes) + self.assertIn("brokkr.reload_host_actions", (ADDON / "__init__.py").read_text(encoding="utf-8")) + + class PanelTests(unittest.TestCase): def test_the_panel_never_draws_the_token(self): target = running_target() diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py index 8b8174b..17b80e3 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -1,6 +1,7 @@ """run_intent: admission, one labelled undo step, receipts. A fake bpy records ops calls.""" from __future__ import annotations +import json import re import sys import tempfile @@ -252,6 +253,10 @@ class HostOp: self.props = props self.behave = behave self.calls = [] + self.pollable = True + + def poll(self): + return self.pollable def idname(self): return self.cls.__name__ @@ -266,7 +271,7 @@ class HostOp: def prop(identifier, kind, lo=0.0, hi=1e30, enum=()): - return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum]) + return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum], is_readonly=False) def raising(error): @@ -295,11 +300,12 @@ class HostActionTests(unittest.TestCase): "apply": HostOp("apply", [], self.finish), } bpy.ops.brokkr_host_fixture = NS(**self.ops) - bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING")})), + bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING", is_readonly=False)})), **{op.idname(): op.cls for op in self.ops.values()}) bpy.context.preferences.addons = {HOST: object(), "brokkr_bridge": object()} bpy.context.window_manager.brokkr_host_fixture_result = "stale" self.report_text = "objects: 3" + self.target.reload_host_actions() # the human's act: the files are read here and nowhere else def finish(self, op, kwargs): return {"FINISHED"} @@ -373,7 +379,7 @@ class HostActionTests(unittest.TestCase): self.assertEqual(self.bpy.undo.pushes, []) self.ops["add_empty"].behave = raising(RuntimeError("Traceback...\nboom")) receipt = self.send("add_empty", name="E") - self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Traceback...")) + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "boom")) self.assertEqual(len(self.bpy.undo.pushes), 1) self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) @@ -430,20 +436,65 @@ class HostActionTests(unittest.TestCase): def test_a_result_that_is_not_a_window_manager_string_refuses_the_whole_file(self): self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"] = NS(type="INT") - self.assertIn("not a string property", self.refused()) + self.assertIn("not a writable string property", self.refused()) self.bpy.types.WindowManager.bl_rna.properties.clear() self.refused() - def test_a_malformed_file_refuses_itself_and_a_changed_file_is_read_again(self): + def test_a_malformed_file_refuses_itself_and_a_reload_reads_the_changed_file(self): path = self.dir / "brokkr_actions.json" good = path.read_text(encoding="utf-8") path.write_text(good.replace("host_actions.v0", "host_actions.v9"), encoding="utf-8") + self.target.reload_host_actions() self.assertIn("schema", self.refused()) path.write_text(good, encoding="utf-8") + self.target.reload_host_actions() self.assertEqual(len(self.target.host_actions()[0]), 4) path.write_text("not json", encoding="utf-8") + self.target.reload_host_actions() self.refused() + def listing_apply(self): + path = self.dir / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"].append({"name": f"{HOST}.apply", "doc": "applies", "changesScene": True, "editModeSafe": False, "fields": []}) + path.write_text(json.dumps(document), encoding="utf-8") + + def test_an_edited_file_admits_nothing_until_a_human_reload(self): + self.assertEqual(self.send("apply")["status"], "denied") + self.listing_apply() + for _ in range(3): # the file changed; intents and snapshots come and go + receipt = self.send("apply") + self.assertEqual(receipt["status"], "denied", receipt) + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertNotIn(f"{HOST}.apply", [r["name"] for r in self.target.host_actions()[0]]) + self.assertEqual(self.ops["apply"].calls, []) + self.assertEqual(self.bpy.undo.pushes, []) + self.target.reload_host_actions() # she presses the button + self.assertEqual(self.send("apply")["status"], "accepted") + self.assertEqual(len(self.ops["apply"].calls), 1) + + def test_a_reload_inside_an_agent_turn_is_refused_whatever_asks_for_it(self): + self.target.agent_turn = True + try: + with self.assertRaises(PermissionError): + self.target.reload_host_actions() + finally: + self.target.agent_turn = False + self.assertEqual(self.send("reload_host_actions")["status"], "denied") # not an action at all + self.assertEqual(self.run_action(action="brokkr.reload_host_actions")["status"], "denied") + self.listing_apply() + self.ops["add_empty"].behave = lambda op, kw: self.target.reload_host_actions() # a host operator that tries + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("human only", receipt["message"]) + self.assertEqual(self.send("apply")["status"], "denied") # the attempt re-read nothing + + def test_a_reload_drops_what_the_files_no_longer_say(self): + (self.dir / "brokkr_actions.json").unlink() + self.assertEqual(len(self.target.host_actions()[0]), 4) # until she reloads + self.assertEqual(self.target.reload_host_actions(), 0) + self.assertEqual(self.target.host_actions(), ([], [])) + def test_disabling_the_add_on_makes_its_action_unsupported_at_the_next_intent(self): self.assertEqual(self.send("report")["status"], "accepted") self.bpy.context.preferences.addons.pop(HOST) @@ -454,14 +505,87 @@ class HostActionTests(unittest.TestCase): def test_an_add_on_without_the_file_is_not_a_host_and_this_add_on_is_never_read(self): (self.dir / "brokkr_actions.json").unlink() + self.target.reload_host_actions() self.assertEqual(self.target.host_actions(), ([], [])) self.bpy.context.preferences.addons["brokkr_bridge"] = object() + self.target.reload_host_actions() self.assertEqual(self.target.host_actions(), ([], [])) (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) with unittest.mock.patch.object(sys.modules["brokkr_bridge"], "__file__", str(self.dir / "__init__.py"), create=True): self.bpy.context.preferences.addons.pop(HOST) # a file sits beside this add-on itself: still not read as a host's + self.assertEqual(self.target.reload_host_actions(), 0) self.assertEqual(self.target.host_actions(), ([], [])) + def test_a_sibling_add_on_whose_name_starts_with_the_hosts_is_not_the_host(self): + # aetheria_ships' operator is not aetheria's: the ownership guard is module equality or module + '.', never a bare prefix + self.ops["report"].cls.__module__ = HOST + "_ships" + self.assertIn("not an operator defined by", self.refused()) + self.ops["report"].cls.__module__ = HOST + "x.sub" + self.refused() + self.ops["report"].cls.__module__ = HOST + self.assertEqual(len(self.target.host_actions()[0]), 4) + + def rewrite_row(self, **changes): + path = self.dir / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"][0].update(changes) + path.write_text(json.dumps(document), encoding="utf-8") + self.target.reload_host_actions() + + def test_a_file_with_an_unknown_row_key_or_an_only_is_refused_whole(self): + self.rewrite_row(unknown=1) + self.assertIn("no key", self.refused()) + self.rewrite_row(unknown=None) # restore: a null is still a key + path = self.dir / "brokkr_actions.json" + path.write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + self.rewrite_row(fields=[{"name": "name", "type": "string"}, {"name": "size", "type": "number", "minimum": 0.1, "maximum": 10, + "only": {"field": "name", "in": ["a"]}}]) + self.assertIn("no 'only'", self.refused()) + + def test_an_enum_field_must_list_the_operators_identifiers(self): + field = {"name": "kind", "type": "string", "enum": ["A", "B"]} + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 100.0), prop("kind", "ENUM", enum=("A", "B"))] + self.rewrite_row(fields=[{"name": "name", "type": "string"}, field]) + self.assertEqual(len(self.target.host_actions()[0]), 4) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("kind", "ENUM", enum=("A", "C"))] + self.assertIn("enum differs", self.refused()) + + def test_a_refused_file_is_reported_in_the_snapshot(self): + self.ops["report"].cls.__module__ = "other_addon" + self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0), background=False) + snapshot = self.target.capture_snapshot(NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT"), True) + self.assertEqual(snapshot["hostActions"], []) + self.assertEqual([e["host"] for e in snapshot["hostActionErrors"]], [HOST]) + self.assertIn("not an operator defined by", snapshot["hostActionErrors"][0]["error"]) + + def test_a_poll_that_fails_refuses_before_the_operator_and_before_any_undo_step(self): + self.ops["add_empty"].pollable = False + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("poll failed", receipt["message"]) + self.assertEqual((self.ops["add_empty"].calls, self.bpy.undo.pushes), ([], [])) + + def test_a_poll_that_raises_refuses_too(self): + self.ops["add_empty"].poll = raising(RuntimeError("Operator bpy.ops.x.poll() failed, context is incorrect")) + receipt = self.send("add_empty", name="E") + self.assertEqual((receipt["status"], self.ops["add_empty"].calls, self.bpy.undo.pushes), ("failed", [], [])) + + def test_a_read_only_result_property_refuses_the_whole_file_at_load(self): + self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"].is_readonly = True + self.assertIn("writable string property", self.refused()) + + def test_an_operator_that_pushes_undo_itself_may_not_be_a_row_that_changes_nothing(self): + self.ops["report"].cls.bl_options = {"REGISTER", "UNDO"} # report says changesScene false + self.assertIn("bl_options UNDO", self.refused()) + self.ops["report"].cls.bl_options = {"REGISTER"} + self.ops["add_empty"].cls.bl_options = {"REGISTER", "UNDO"} # a changing row may + self.assertEqual(len(self.target.host_actions()[0]), 4) + + def test_a_runtime_error_names_its_cause_not_the_traceback_header(self): + self.ops["add_empty"].behave = raising(RuntimeError("Error: Python: Traceback (most recent call last):" + chr(10) + " File x.py, line 1" + chr(10) + "ValueError: boom")) + self.assertEqual(self.send("add_empty", name="E")["message"], "ValueError: boom") + class FakeNode: """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" -- 2.47.3