From fb9696b6394b794100ceb752fb787936cff62813 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 07:07:18 +0100 Subject: [PATCH] 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."""