diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs index 36e7245..be25999 100644 --- a/brokkr-ctl/src/blender.rs +++ b/brokkr-ctl/src/blender.rs @@ -335,7 +335,7 @@ fn status(store: &SingleFileMessagePackBackingStore) -> Result { "activeObjectName", "selectedObjectNames", "objectCount", - "sink", + "agentCommandsEnabled", ] { if let Some(value) = snapshot.get(key) { print_field(key, value); @@ -401,7 +401,7 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what Write one intent, then wait for its receipt and print it. `send --help` lists actions. wait [--timeout secs] Wait for a receipt and print it. receipts [--last n] Print stored receipts, oldest first. - status Print the host snapshot summary. + status Print the host snapshot summary, agentCommandsEnabled included. Every command needs --store or $BROKKR_BLENDER_STORE (the add-on's .ccmp). send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '/'. diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs index 6161f6b..4ea7f24 100644 --- a/brokkr-ctl/tests/cli.rs +++ b/brokkr-ctl/tests/cli.rs @@ -326,12 +326,12 @@ fn receipts_sort_by_observed_time_not_by_key() { fn status_prints_the_snapshot_summary() { let dir = tempfile::tempdir().unwrap(); let path = store_with_receipts(dir.path(), &[]); - let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "sink": {"enabled": true}}); + let snapshot = json!({"mode": "OBJECT", "activeScene": "Scene", "objectCount": 3, "selectedObjectNames": ["Cube"], "agentCommandsEnabled": false}); push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); let output = ctl(&path, &["status"], None); assert_eq!(output.status.code(), Some(0)); let text = stdout(&output); - for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "sink: {\"enabled\":true}"] { + for line in ["mode: OBJECT", "activeScene: Scene", "objectCount: 3", "selectedObjectNames: [\"Cube\"]", "agentCommandsEnabled: false"] { assert!(text.contains(line), "{line} in {text}"); } } diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 8a81707..1a4b5d2 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -31,6 +31,22 @@ def target(): return _target +def _sink_changed(prefs): + """The sink toggle moved: the stored host snapshot says so, so brokkr-ctl status never reads a stale toggle. + A node nothing has opened yet holds no snapshot to correct.""" + adapter = target() + if adapter.node_open: + adapter.publish_snapshot(bpy.context, prefs.cultmesh_cache_path, prefs.cultlib_py_src, + prefs.debug_mirror_root, prefs.auto_drain_commands) + + +def _redraw(): + for window in bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D": + area.tag_redraw() + + class BrokkrPreferences(bpy.types.AddonPreferences): bl_idname = __name__ @@ -84,7 +100,9 @@ class BrokkrPreferences(bpy.types.AddonPreferences): auto_drain_commands: bpy.props.BoolProperty( name="Auto Drain Commands", default=False, - description="Poll and execute pending Brokkr Blender command intents on a timer", + update=lambda self, context: _sink_changed(self), + description="The command sink: poll and run queued agent intents on a timer. Only the operator turns it on, " + "and Stop agents turns it off; no agent intent can write it", ) serve_host: bpy.props.StringProperty( @@ -333,6 +351,10 @@ class BROKKR_PT_status(bpy.types.Panel): prefs = context.preferences.addons[__name__].preferences adapter = target() + stop = layout.row() + stop.scale_y = 1.6 + stop.operator("brokkr.stop_agents", icon="CANCEL") + layout.label(text=f"Provider: {PROVIDER_ID}") layout.label(text=f"Tool: {TOOL_KIND}") layout.label(text=f"Broker: {prefs.broker_uri}") @@ -409,10 +431,20 @@ class BROKKR_PT_status(bpy.types.Panel): layout.label(text=f"Materials: {adapter.last_snapshot.get('materialCount', 0)}") layout.label(text=f"Selected: {len(adapter.last_snapshot.get('selectedObjectNames', []))}") - if adapter.last_receipt: - layout.separator() - layout.label(text=f"Last receipt: {adapter.last_receipt.get('status', '')}") - layout.label(text=adapter.last_receipt.get("message", "")) + if adapter.node_open and not adapter.receipts_loaded: + adapter.load_recent_receipts(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + agents_box = layout.box() + agents_box.label(text="Agents") + agents_box.label(text=f"Agent commands: {'on' if prefs.auto_drain_commands else 'off'}") + active = adapter.active_agents() + agents_box.label(text=f"Active: {', '.join(active)}" if active else "Active: none in the last 5 minutes") + agents_box.label(text=f"Pending: {adapter.pending_count}") + for item in adapter.recent_receipts(): + agents_box.label(text=f"{item.get('requestedBy') or '?'} {item.get('action', '')} {item.get('status', '')}") + if item.get("note"): + agents_box.label(text=f" {item['note']}") + if item.get("undoLabel"): + agents_box.label(text=f" {item['undoLabel']}") if adapter.last_auto_drain_error: layout.separator() @@ -438,11 +470,31 @@ class BROKKR_OT_capture_snapshot(bpy.types.Operator): prefs.cultmesh_cache_path, prefs.cultlib_py_src, prefs.debug_mirror_root, + prefs.auto_drain_commands, ) self.report({"INFO"}, f"Brokkr mirrored Blender snapshot: {snapshot['observedAt']}") return {"FINISHED"} +class BROKKR_OT_stop_agents(bpy.types.Operator): + bl_idname = "brokkr.stop_agents" + bl_label = "Stop agents" + bl_description = ("Turn agent commands off and give every pending intent a 'stopped' receipt without running it. " + "An action already running finishes as one undo step; Ctrl+Z takes it back") + + def execute(self, context): + prefs = context.preferences.addons[__name__].preferences + prefs.auto_drain_commands = False + try: + stopped = target().stop_pending("stopped by the operator", prefs.cultmesh_cache_path, + prefs.cultlib_py_src, prefs.debug_mirror_root) + except Exception as exc: + self.report({"ERROR"}, f"Agent commands are off, but pending intents could not be stopped: {exc}") + return {"CANCELLED"} + self.report({"INFO"}, f"Agent commands off; {stopped} pending intent(s) stopped.") + return {"FINISHED"} + + class BROKKR_OT_drain_commands(bpy.types.Operator): bl_idname = "brokkr.drain_commands" bl_label = "Drain Commands" @@ -616,39 +668,49 @@ def _auto_capture(scene, depsgraph): prefs.preferences.cultmesh_cache_path, prefs.preferences.cultlib_py_src, prefs.preferences.debug_mirror_root, + prefs.preferences.auto_drain_commands, ) +BUSY_INTERVAL = 0.05 # one intent per tick: Stop is a UI event, and it lands between two intents +IDLE_INTERVAL = 1.0 + + def _auto_drain_commands(): context = bpy.context addon = context.preferences.addons.get(__name__) adapter = target() if not addon: - return 1.0 + return IDLE_INTERVAL prefs = addon.preferences - if not prefs.auto_drain_commands: - adapter.last_auto_drain_error = "" - return 1.0 - + ran = 0 + pending_before = adapter.pending_count try: - adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) - adapter.drain_commands( - context, - prefs.cultmesh_cache_path, - prefs.cultlib_py_src, - prefs.debug_mirror_root, - ) + if adapter.node_open: + adapter.count_pending(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + if prefs.auto_drain_commands: + adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) + ran = len(adapter.drain_commands( + context, + prefs.cultmesh_cache_path, + prefs.cultlib_py_src, + prefs.debug_mirror_root, + limit=1, + )) adapter.last_auto_drain_error = "" except Exception as exc: adapter.last_auto_drain_error = str(exc) - return 1.0 + if ran or adapter.pending_count != pending_before: + _redraw() + return BUSY_INTERVAL if ran else IDLE_INTERVAL classes = ( BrokkrPreferences, BROKKR_PT_status, + BROKKR_OT_stop_agents, BROKKR_OT_capture_snapshot, BROKKR_OT_drain_commands, BROKKR_OT_start_server, diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 8302a69..33a332a 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -9,13 +9,14 @@ import re import sys import uuid from array import array -from datetime import datetime, timezone +from collections import deque +from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any, Iterable from . import node_actions as na from . import scene_actions as sa -from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, purge_command_intents +from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending PROVIDER_ID = "brokkr.blender_editor" TOOL_KIND = "blender-editor" @@ -63,6 +64,9 @@ REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") # out: it separates the '.denied' suffix). COMMAND_ID_SHAPE = re.compile(r"^[A-Za-z0-9_-]{1,128}$") NOTE_LIMIT = 200 +ACTIVE_AGENT_WINDOW = timedelta(minutes=5) # an agent is active when a receipt of its own is this recent +RECEIPTS_SHOWN = 8 +RECEIPTS_KEPT = 64 # the display cache; the node holds the receipts EVALUATED_POSITION_CAP = 256 EVALUATED_VERTEX_LIMIT = 1_000_000 @@ -99,7 +103,6 @@ class BrokkrBlenderTarget: def __init__(self, bpy_module: Any): self.bpy = bpy_module self.last_snapshot: dict[str, Any] | None = None - self.last_receipt: dict[str, Any] | None = None self.last_sync_receipt: dict[str, Any] | None = None self.last_auto_drain_error: str = "" self._node_key: tuple[str, str, str] | None = None @@ -115,6 +118,9 @@ 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._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts + self._receipts_loaded = False + self.pending_count = 0 # display cache: intents queued in the node def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -133,8 +139,9 @@ class BrokkrBlenderTarget: cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "", + agent_commands_enabled: bool = False, ) -> dict[str, Any]: - snapshot = self.capture_snapshot(context) + snapshot = self.capture_snapshot(context, agent_commands_enabled) node, documents = self._open_node(cache_path, cultlib_py_src) node.database.put(documents["host_snapshot"], "blender/host/current", snapshot) if debug_mirror_root: @@ -148,16 +155,16 @@ class BrokkrBlenderTarget: cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "", + limit: int | None = None, ) -> list[dict[str, Any]]: + """Run queued intents, oldest key first: all of them, or at most `limit`, the rest staying queued.""" node, documents = self._open_node(cache_path, cultlib_py_src) snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] - self._receipted.update( - r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() - if isinstance(r.get("commandId"), str)) + self._seed_receipted(snapshot) - for command_key, command in sorted(commands.items()): + for command_key, command in sorted(commands.items())[:limit]: command_id = command.get("commandId") valid = _valid_command_id(command_id) reused = valid and command_id in self._receipted @@ -183,12 +190,86 @@ class BrokkrBlenderTarget: debug_mirror_root: str = "", key_suffix: str = "", ) -> None: - command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node, documents = self._open_node(cache_path, cultlib_py_src) + self._put_receipt(node, documents, receipt, debug_mirror_root, key_suffix) + + def _put_receipt(self, node: Any, documents: dict[str, Any], receipt: dict[str, Any], + debug_mirror_root: str = "", key_suffix: str = "") -> None: + """The one place a receipt is written: the node, the debug export, and the panel's display cache.""" + command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node.database.put(documents["command_receipt"], f"blender/receipts/{command_id}", receipt) if debug_mirror_root: self._write_debug_document(debug_mirror_root, f"blender/receipts/{command_id}.json", receipt) - self.last_receipt = receipt + self.note_receipt(receipt) + + def _seed_receipted(self, snapshot: dict[str, Any]) -> None: + self._receipted.update( + r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() + if isinstance(r.get("commandId"), str)) + + def stop_pending(self, reason: str, cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "") -> int: + """The Stop button's path: every queued intent gets a 'stopped' receipt and leaves the queue unrun.""" + node, documents = self._open_node(cache_path, cultlib_py_src) + return self._stop_pending(node, documents, reason, debug_mirror_root) + + def _stop_pending(self, node: Any, documents: dict[str, Any], reason: str, debug_mirror_root: str = "") -> int: + """Stop, server start and server stop all take intents off the queue here and nowhere else.""" + if node is None: + return 0 + self._seed_receipted(node.database.snapshot()) + + def write(queue_key: str, intent: dict[str, Any], why: str) -> None: + valid = _valid_command_id(intent.get("commandId")) + reused = valid and intent["commandId"] in self._receipted + receipt = self._receipt(intent, "stopped", f"Stopped ({why}); the intent was not run and nothing was changed.", "") + if not valid: + receipt["message"] += f" (queue key {queue_key})" + self._put_receipt(node, documents, receipt, debug_mirror_root, ".stopped" if reused else "") + if valid: + self._receipted.add(intent["commandId"]) # the id is spent: the sender resends under a new one + + return stop_pending(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, write, reason) + + def note_receipt(self, receipt: dict[str, Any]) -> None: + self._recent.append(receipt) + + def recent_receipts(self) -> list[dict[str, Any]]: + """The last few receipts, newest first.""" + return list(self._recent)[::-1][:RECEIPTS_SHOWN] + + def active_agents(self) -> list[str]: + """Distinct requestedBy among receipts from the last five minutes, in order of first appearance.""" + cutoff = datetime.now(timezone.utc) - ACTIVE_AGENT_WINDOW + agents: dict[str, None] = {} + for item in self._recent: + who, seen = item.get("requestedBy"), _parse_time(item.get("observedAt")) + if who and seen is not None and seen >= cutoff: + agents[who] = None + return list(agents) + + def load_recent_receipts(self, cache_path: str, cultlib_py_src: str) -> None: + """Rebuild the display cache from the node's receipts, once: it replaces what this session noted, since each of those was written to the node.""" + if self._receipts_loaded: + return + node, _documents = self._open_node(cache_path, cultlib_py_src) + stored = sorted(node.database.snapshot().get(COMMAND_RECEIPT_SCHEMA, {}).values(), + key=lambda r: str(r.get("observedAt", ""))) + self._recent = deque(stored, maxlen=RECEIPTS_KEPT) # the node holds every receipt this session noted + self._receipts_loaded = True + + def count_pending(self, cache_path: str, cultlib_py_src: str) -> int: + node, _documents = self._open_node(cache_path, cultlib_py_src) + node.database.pull() + self.pending_count = len(node.database.snapshot().get(COMMAND_INTENT_SCHEMA, {})) + return self.pending_count + + @property + def receipts_loaded(self) -> bool: + return self._receipts_loaded + + @property + def node_open(self) -> bool: + return self._node is not None def refresh_sync_receipt( self, @@ -387,7 +468,7 @@ class BrokkrBlenderTarget: self.stop_server() self._cultmesh_module = "" - purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA) + self._stop_pending(node, documents, "server started") cultmesh, _cultcache = _load_cultmesh(cultlib_py_src) self._cultmesh_module = str(getattr(cultmesh, "__file__", "") or "") verse_catalog = cultmesh.CultMesh.create_verse_catalog() @@ -458,7 +539,7 @@ class BrokkrBlenderTarget: finally: try: if was_running and self._node is not None: - purge_command_intents(self._node, self._documents["command_intent"], COMMAND_INTENT_SCHEMA) + self._stop_pending(self._node, self._documents, "server stopped") finally: self._server = None self._server_key = None @@ -490,7 +571,7 @@ class BrokkrBlenderTarget: "cultmeshModule": self._cultmesh_module, } - def capture_snapshot(self, context: Any) -> dict[str, Any]: + def capture_snapshot(self, context: Any, agent_commands_enabled: bool) -> dict[str, Any]: bpy = self.bpy 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] @@ -513,6 +594,7 @@ class BrokkrBlenderTarget: "collectionCount": len(bpy.data.collections), "materialCount": len(bpy.data.materials), "imageCount": len(bpy.data.images), + "agentCommandsEnabled": bool(agent_commands_enabled), "capabilities": list(CAPABILITIES), "scenes": [self._scene_snapshot(scene) for scene in bpy.data.scenes], "objects": [self._object_snapshot(obj, scan) for obj in bpy.data.objects], @@ -1249,6 +1331,14 @@ def missing_gl_library() -> str | None: return None +def _parse_time(value: Any) -> datetime | None: + try: + parsed = datetime.fromisoformat(value) + except (TypeError, ValueError): + return None + return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) + + def _now() -> str: return datetime.now(timezone.utc).isoformat() diff --git a/surfaces/blender/brokkr_bridge/server_guard.py b/surfaces/blender/brokkr_bridge/server_guard.py index 0dbba80..ff91c12 100644 --- a/surfaces/blender/brokkr_bridge/server_guard.py +++ b/surfaces/blender/brokkr_bridge/server_guard.py @@ -3,7 +3,7 @@ Stdlib only, no bpy: everything here is unit-testable without Blender. Always on: a non-loopback bind needs an explicit allow (check_bind), and command -intents queued before a start or stop are purged (purge_command_intents). +intents queued before a start or stop are stopped with a receipt each (stop_pending). Opt-in: a per-session token, checked on every document put and delete when the user turns it on in the add-on preferences (SessionGuard, guarded_server_class). """ @@ -12,7 +12,7 @@ from __future__ import annotations import hmac import ipaddress import secrets -from typing import Any +from typing import Any, Callable PUT_SCHEMA_VERSIONS = ("cultnet.document_put_raw.v0", "cultnet.document_delete.v0") TOKEN_FIELD = "sessionToken" @@ -90,12 +90,17 @@ def guarded_server_class(base: type, guard: SessionGuard) -> type: return GuardedServer -def purge_command_intents(node: Any, command_document: Any, command_schema: str) -> int: - """Delete every queued command intent from the node. Returns how many were removed.""" - removed = 0 +def stop_pending(node: Any, command_document: Any, command_schema: str, + write_receipt: Callable[[str, dict[str, Any], str], None], reason: str) -> int: + """Take every queued command intent off the node without running it: write_receipt(queue key, intent, reason) + first, then delete the intent. An intent whose receipt cannot be written stays queued and the error + propagates, so nothing leaves the queue unreceipted. Returns how many were stopped. Stop, server start + and server stop all come through here; `reason` says why, for the receipt.""" + stopped = 0 if node is not None: node.database.pull() - for key in list(node.database.snapshot().get(command_schema, {})): + for key, intent in list(node.database.snapshot().get(command_schema, {}).items()): + write_receipt(key, intent, reason) node.database.delete(command_document, key) - removed += 1 - return removed + stopped += 1 + return stopped diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index d85ab16..c04ad92 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -69,13 +69,27 @@ at `0` to bind a free local port, or set a fixed port when another runtime needs a stable endpoint. The panel reports the active `cultnet://host:port` endpoint after `Start Server`. +## Stop and the Agents panel + +`Stop agents` sits at the top of the Brokkr panel. It turns `Auto Drain Commands` (the command sink) off, then gives +every pending intent a `stopped` receipt without running it: the same path as `Start Server` and `Stop Server`. +Only the operator turns the sink on; no intent writes add-on preferences. The timer runs one intent per tick, so +Stop lands between two intents; an action already running finishes as one undo step, and `Ctrl+Z` takes it back. +A stopped intent's id is spent: the agent resends under a new id once the operator turns the sink back on. + +The `Agents` section lists the agents active in the last five minutes (distinct `requestedBy` among receipts), +the number of pending intents, and the last eight receipts as ` ` with their note and +undo label. It is a display cache of the node's receipts, rebuilt from the node on first draw. The host snapshot +carries `agentCommandsEnabled`, which `brokkr-ctl blender status` prints. + ## Server Safety Always on: -- `Start Server` and `Stop Server` purge queued command intents: every - `brokkr.blender.command_intent.v0` record in the node. Intents queued before a - start never run under the new session. +- `Start Server` and `Stop Server` stop queued command intents: each + `brokkr.blender.command_intent.v0` record in the node gets a receipt with status `stopped` that names the + reason, then leaves the queue unrun. Intents queued before a start never run under the new session, and the + sender (`brokkr-ctl wait`, exit 3) learns they were stopped. - After `Start Server` the panel shows the bind address, port and the file `cultmesh_py` was actually loaded from (its `__file__`, not the preference). - A `Serve Host` that is not loopback (`0.0.0.0`, a LAN address, a hostname diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index 62df949..9d86395 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -37,7 +37,7 @@ def ok(t, **cmd): r = act(t, **cmd); check("%s %s" % (cmd["action"], cmd.get("id") or cmd.get("treeKey") or cmd.get("objectName") or ""), r["status"] == "accepted", r["message"]); return r def evaluated(t, name): - snap = t.capture_snapshot(bpy.context) + snap = t.capture_snapshot(bpy.context, False) return [o for o in snap["objects"] if o["name"] == name][0]["evaluated"] def native_tree(build): @@ -254,7 +254,7 @@ def heavy(n, instanced): else: links = [("grid", "Mesh", "gout", "Geometry")] graph(tt, "Heavy", GEO_OUT, nodes, links); host(tt, "HeavyHost", "Heavy") - t0 = time.time(); snap = tt.capture_snapshot(bpy.context); dt = time.time() - t0 + t0 = time.time(); snap = tt.capture_snapshot(bpy.context, False); dt = time.time() - t0 return dt, [o for o in snap["objects"] if o["name"] == "HeavyHost"][0]["evaluated"] dt, ev = heavy(2000, True) R["capture_2000_grid_instanced_seconds"] = round(dt, 3) diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py index f8127d9..c7dc47d 100644 --- a/surfaces/blender/tests/live/gn_recreation.py +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -104,7 +104,7 @@ getattr(hob.modifiers["GN"].properties.inputs, ident).__setattr__("value", 5) before = len(evaluated_verts(hob)) r = act(t, action="setObjectCustomProperty", targetObjectName="ParamHost", propertyName=ident, value=12) after = len(evaluated_verts(hob)) -snap = t.capture_snapshot(bpy.context) +snap = t.capture_snapshot(bpy.context, False) ho = [o for o in snap["objects"] if o["name"] == "ParamHost"][0] gap("custom_property_does_not_drive_modifier", receipt=r["status"], verts_before=before, verts_after=after, identifier=ident, snapshot_modifier=ho["modifiers"], snapshot_mesh=ho["mesh"], @@ -153,7 +153,7 @@ g.links.new(grid.outputs["Mesh"], dis.inputs["Mesh"]); g.links.new(dis.outputs[" g.links.new(cone.outputs["Mesh"], iop.inputs["Instance"]); g.links.new(iop.outputs["Instances"], gout.inputs["Geometry"]) ob = host("ScatterHost", g); native = sorted(evaluated_instances(ob)) # what Brokkr can see of that object -snap = t.capture_snapshot(bpy.context); so = [o for o in snap["objects"] if o["name"] == "ScatterHost"][0] +snap = t.capture_snapshot(bpy.context, False); so = [o for o in snap["objects"] if o["name"] == "ScatterHost"][0] gap("snapshot_not_evaluated", brokkr_sees=so["mesh"], modifiers=so["modifiers"], evaluated_instances=len(native), repro="host object with Distribute->InstanceOnPoints: snapshot mesh.vertexCount=0, no instance count, no positions") # (a) replay the native points through actions (needs a side channel that is not Brokkr) diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py new file mode 100644 index 0000000..e23f990 --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.py @@ -0,0 +1,254 @@ +"""Live proof, in GUI Blender with the add-on enabled, of Stop and presence, with real brokkr-ctl sends. + + BROKKR_SCRATCH= + BROKKR_CTL= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --factory-startup --python stop_presence.py -- + +The driver stands in for the operator's hands only: it ticks the sink preference on and runs the add-on's own +"Stop agents" operator. Every intent is sent by brokkr-ctl; the add-on's timer drains them. Undo is read only here. +Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import re +import subprocess +import sys +import traceback +from pathlib import Path + +import bpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "notes": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +prefs = bpy.context.preferences.addons[MODULE].preferences +CACHE = str(SCRATCH / "stop.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +prefs.auto_drain_commands = False +adapter = addon.target() +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=CACHE, BROKKR_AGENT="hands") +S = {"ids": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def ctl(*args): + done = subprocess.run([CTL, "blender", *args], env=ENV, capture_output=True, text=True, timeout=30) + return done.returncode, done.stdout + + +def send(name, note): + code, out = ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", f'name="{name}"', + "--note", note, "--no-wait") + match = re.search(r"commandId:\s*(\S+)", out) + assert code == 0 and match, (code, out) + return match.group(1) + + +def receipts(): + node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) + return {r["commandId"]: r for r in node.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).values()} + + +def pending(): + node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) + return list(node.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})) + + +def empties(prefix): + return sorted(o.name for o in bpy.data.objects if o.name.startswith(prefix)) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +class Recorder: + """A layout that records the panel's labels and operators; the real BROKKR_PT_status.draw runs against it.""" + def __init__(self): + self.labels, self.operators = [], [] + + def __getattr__(self, name): + if name == "label": + return lambda text="", **kw: self.labels.append(text) + if name == "operator": + return lambda idname, **kw: self.operators.append(idname) + return lambda *a, **kw: self + + +def panel(): + layout = Recorder() + addon.BROKKR_PT_status.draw(type("Drawn", (), {"layout": layout})(), bpy.context) + return layout + + +# ---- steps ------------------------------------------------------------------------------------------------- + +def s_setup(): + with win(): + bpy.ops.brokkr.start_server() + bpy.ops.brokkr.capture_snapshot() + code, out = ctl("status") + check("setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", + adapter.server_status()["running"] and code == 0 and "agentCommandsEnabled: false" in out, out) + + +def s_burst(): + S["ids"] = [send(f"B{n:02d}", "burst") for n in range(12)] + adapter.count_pending(CACHE, prefs.cultlib_py_src) + check("burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", + len(pending()) == 12 and not empties("B") and adapter.pending_count == 12, [len(pending()), empties("B")]) + + +def s_sink_on(): + prefs.auto_drain_commands = True # the operator ticks the sink + code, out = ctl("status") + check("sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", "agentCommandsEnabled: true" in out, out) + + +def started(): + return len(receipts()) >= 2 + + +def s_stop(): + S["at_stop"] = sorted(receipts()) + S["panel_before"] = panel().labels # what she sees the moment before she presses Stop, mid-burst + with win(): + S["stop_result"] = bpy.ops.brokkr.stop_agents() + S["after_stop_pending"] = pending() + + +def s_after_stop(): + rs = receipts() + ours = {i: rs.get(i) for i in S["ids"]} + states = {i: (r or {}).get("status") for i, r in ours.items()} + accepted = [i for i, s in states.items() if s == "accepted"] + stopped = [i for i, s in states.items() if s == "stopped"] + R["notes"]["states"] = states + R["notes"]["at_stop_receipted"] = len(S["at_stop"]) + check("stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", + len(accepted) + len(stopped) == 12 and len(stopped) >= 1 and len(accepted) >= 2, states) + check("stop: the queue is empty and the sink is off", pending() == [] and prefs.auto_drain_commands is False + and S["stop_result"] == {"FINISHED"}, [pending(), S["stop_result"]]) + check("stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", + len(empties("B")) == len(accepted), [empties("B"), len(accepted)]) + check("stop: each accepted intent is one labelled undo step the receipt names", + all(rs[i]["undoLabel"].startswith("Brokkr nibu/hands: createObject ") for i in accepted), + [rs[i]["undoLabel"] for i in accepted][:3]) + check("stop: stopped receipts say who, what and why, and were never given an undo label", + all(rs[i]["requestedBy"] == "nibu/hands" and rs[i]["action"] == "createObject" and rs[i]["undoLabel"] == "" + and "stopped by the operator" in rs[i]["message"] for i in stopped), [rs[i]["message"] for i in stopped][:1]) + exits = {} + for i in S["ids"]: + code, out = ctl("wait", i, "--timeout", "5") + exits[i] = (states[i], code) + R["notes"]["wait_exits"] = exits + check("stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", + all(code == (0 if st == "accepted" else 3) for st, code in exits.values()), sorted(set(exits.values()))) + code, out = ctl("status") + check("stop: brokkr-ctl status now reads agentCommandsEnabled: false", "agentCommandsEnabled: false" in out, out) + S["accepted"], S["stopped"] = accepted, stopped + + +def s_undo(): + before = len(empties("B")) + with win(): + bpy.ops.ed.undo() + after = len(empties("B")) + check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - after == 1, [before, after]) + + +def s_panel(): + before = "\n".join(S["panel_before"]) + R["notes"]["panel_before_stop"] = S["panel_before"] + check("panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", + "Active: nibu/hands" in before and "Agent commands: on" in before and re.search(r"Pending: [1-9]", before) + and "nibu/hands createObject accepted" in before and "burst" in before + and "Brokkr nibu/hands: createObject" in before + and before.count("createObject accepted") == len(S["at_stop"]), before) # each receipt listed once + layout = panel() + text = "\n".join(layout.labels) + R["notes"]["panel_labels"] = layout.labels + check("panel after Stop: Stop agents is the first operator drawn", layout.operators[:1] == ["brokkr.stop_agents"], layout.operators[:3]) + check("panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", + "Agent commands: off" in text and "Pending: 0" in text and "nibu/hands createObject stopped" in text, text) + + +def s_server_stop(): + S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] + check("server stop: three intents queued behind a running server, sink off", len(pending()) == 3) + with win(): + bpy.ops.brokkr.stop_server() + rs = receipts() + check("server stop: the same path gives each a stopped receipt naming 'server stopped'", + pending() == [] and all(rs[i]["status"] == "stopped" and "server stopped" in rs[i]["message"] for i in S["ids2"]) + and not empties("S"), [rs[i]["message"] for i in S["ids2"]][:1]) + + +def s_server_start(): + S["ids3"] = [send(f"T{n}", "server-start") for n in range(2)] + with win(): + bpy.ops.brokkr.start_server() + rs = receipts() + exits = [ctl("wait", i, "--timeout", "5")[0] for i in S["ids3"]] + check("server start: intents queued while stopped get stopped receipts naming 'server started', wait exits 3", + pending() == [] and all(rs[i]["status"] == "stopped" and "server started" in rs[i]["message"] for i in S["ids3"]) + and exits == [3, 3] and not empties("T"), [exits, [rs[i]["message"] for i in S["ids3"]][:1]]) + + +def s_final(): + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + with win(): + bpy.ops.brokkr.stop_server() + + +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) + + +# The add-on's own timer drains between our ticks. Stop is pressed as soon as two receipts exist, so the burst +# is cut in the middle. +def runner(): + global i + try: + if i >= len(steps): + write() + bpy.ops.wm.quit_blender() + return None + step = steps[i] + if step == "wait-two": + if started(): + s_stop() + i += 1 + return 0.005 + step() + i += 1 + write() + return 0.5 if step is not s_sink_on else 0.005 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + write() + bpy.ops.wm.quit_blender() + return None + + +steps = [s_setup, s_burst, s_sink_on, "wait-two", s_after_stop, s_undo, s_panel, s_server_stop, s_server_start, s_final] +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/stop_presence.result.json b/surfaces/blender/tests/live/stop_presence.result.json new file mode 100644 index 0000000..6bbb5cb --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -0,0 +1,280 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", + "ok": true, + "detail": "observedAt: 2026-11-27T20:37:49.797904+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" + }, + { + "name": "burst: 12 brokkr-ctl sends queue while the sink is off; nothing ran", + "ok": true, + "detail": [ + 12, + [] + ] + }, + { + "name": "sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", + "ok": true, + "detail": "observedAt: 2026-11-27T20:37:51.169335+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" + }, + { + "name": "stop: every one of the 12 intents has a receipt, each accepted or stopped, none missing", + "ok": true, + "detail": { + "01a21eba859d7b21aa7e23791e640a17": "accepted", + "01a21eba85d175a083c1e8e542bbed1d": "accepted", + "01a21eba860f74f1b73c707054d48792": "stopped", + "01a21eba864b7881ba64c540fc461d4d": "stopped", + "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", + "01a21eba86f2722093b458840f45af3a": "stopped", + "01a21eba87577fc1b50a0de908986e13": "stopped", + "01a21eba87b87f919b2dfac978be3b57": "stopped", + "01a21eba881c7a9286a621369083ac7b": "stopped", + "01a21eba886a7833ae7ff3224cdc4e29": "stopped", + "01a21eba88d978f3b5db769bb462f99b": "stopped", + "01a21eba897772009d540695cd6453cc": "stopped" + } + }, + { + "name": "stop: the queue is empty and the sink is off", + "ok": true, + "detail": [ + [], + "{'FINISHED'}" + ] + }, + { + "name": "stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", + "ok": true, + "detail": [ + [ + "B00", + "B01" + ], + 2 + ] + }, + { + "name": "stop: each accepted intent is one labelled undo step the receipt names", + "ok": true, + "detail": [ + "Brokkr nibu/hands: createObject 1e640a17", + "Brokkr nibu/hands: createObject 42bbed1d" + ] + }, + { + "name": "stop: stopped receipts say who, what and why, and were never given an undo label", + "ok": true, + "detail": [ + "Stopped (stopped by the operator); the intent was not run and nothing was changed." + ] + }, + { + "name": "stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", + "ok": true, + "detail": [ + [ + "accepted", + 0 + ], + [ + "stopped", + 3 + ] + ] + }, + { + "name": "stop: brokkr-ctl status now reads agentCommandsEnabled: false", + "ok": true, + "detail": "observedAt: 2026-11-27T20:37:52.309838+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + }, + { + "name": "stop + Ctrl+Z: one undo takes back the last agent step, nothing else", + "ok": true, + "detail": [ + 2, + 1 + ] + }, + { + "name": "panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", + "ok": true, + "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: on\nActive: nibu/hands\nPending: 11\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 42bbed1d\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 1e640a17" + }, + { + "name": "panel after Stop: Stop agents is the first operator drawn", + "ok": true, + "detail": [ + "brokkr.stop_agents", + "brokkr.capture_snapshot", + "brokkr.drain_commands" + ] + }, + { + "name": "panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", + "ok": true, + "detail": "Provider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:53223\nBind: 127.0.0.1:53223\ncultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 5\nMaterials: 2\nSelected: 1\nAgents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst" + }, + { + "name": "server stop: three intents queued behind a running server, sink off", + "ok": true, + "detail": null + }, + { + "name": "server stop: the same path gives each a stopped receipt naming 'server stopped'", + "ok": true, + "detail": [ + "Stopped (server stopped); the intent was not run and nothing was changed." + ] + }, + { + "name": "server start: intents queued while stopped get stopped receipts naming 'server started', wait exits 3", + "ok": true, + "detail": [ + [ + 3, + 3 + ], + [ + "Stopped (server started); the intent was not run and nothing was changed." + ] + ] + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "states": { + "01a21eba859d7b21aa7e23791e640a17": "accepted", + "01a21eba85d175a083c1e8e542bbed1d": "accepted", + "01a21eba860f74f1b73c707054d48792": "stopped", + "01a21eba864b7881ba64c540fc461d4d": "stopped", + "01a21eba86a97292a71e1ca6d8acb2d8": "stopped", + "01a21eba86f2722093b458840f45af3a": "stopped", + "01a21eba87577fc1b50a0de908986e13": "stopped", + "01a21eba87b87f919b2dfac978be3b57": "stopped", + "01a21eba881c7a9286a621369083ac7b": "stopped", + "01a21eba886a7833ae7ff3224cdc4e29": "stopped", + "01a21eba88d978f3b5db769bb462f99b": "stopped", + "01a21eba897772009d540695cd6453cc": "stopped" + }, + "at_stop_receipted": 2, + "wait_exits": { + "01a21eba859d7b21aa7e23791e640a17": [ + "accepted", + 0 + ], + "01a21eba85d175a083c1e8e542bbed1d": [ + "accepted", + 0 + ], + "01a21eba860f74f1b73c707054d48792": [ + "stopped", + 3 + ], + "01a21eba864b7881ba64c540fc461d4d": [ + "stopped", + 3 + ], + "01a21eba86a97292a71e1ca6d8acb2d8": [ + "stopped", + 3 + ], + "01a21eba86f2722093b458840f45af3a": [ + "stopped", + 3 + ], + "01a21eba87577fc1b50a0de908986e13": [ + "stopped", + 3 + ], + "01a21eba87b87f919b2dfac978be3b57": [ + "stopped", + 3 + ], + "01a21eba881c7a9286a621369083ac7b": [ + "stopped", + 3 + ], + "01a21eba886a7833ae7ff3224cdc4e29": [ + "stopped", + 3 + ], + "01a21eba88d978f3b5db769bb462f99b": [ + "stopped", + 3 + ], + "01a21eba897772009d540695cd6453cc": [ + "stopped", + 3 + ] + }, + "panel_before_stop": [ + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: cultnet://127.0.0.1:53223", + "Bind: 127.0.0.1:53223", + "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 3", + "Materials: 2", + "Selected: 1", + "Agents", + "Agent commands: on", + "Active: nibu/hands", + "Pending: 11", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject 42bbed1d", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject 1e640a17" + ], + "panel_labels": [ + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: cultnet://127.0.0.1:53223", + "Bind: 127.0.0.1:53223", + "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 5", + "Materials: 2", + "Selected: 1", + "Agents", + "Agent commands: off", + "Active: nibu/hands", + "Pending: 0", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst" + ] + }, + "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 cf78e9b..b052cc9 100644 --- a/surfaces/blender/tests/test_agent_turn.py +++ b/surfaces/blender/tests/test_agent_turn.py @@ -236,6 +236,10 @@ class FakeNode: self.puts = [] self.deleted = [] self.database = self + self.runtime_id = "fake" + + def pull(self): + pass def snapshot(self): return {k: dict(v) for k, v in self.docs.items()} diff --git a/surfaces/blender/tests/test_server_guard.py b/surfaces/blender/tests/test_server_guard.py index d726162..e4490fa 100644 --- a/surfaces/blender/tests/test_server_guard.py +++ b/surfaces/blender/tests/test_server_guard.py @@ -131,7 +131,10 @@ class FakeDatabase: self.pulls += 1 def snapshot(self): - return {self.schema: {k: {} for k in self.keys}, "other.v0": {"keep": {}}} + return {self.schema: {k: {"commandId": k} for k in self.keys}, "other.v0": {"keep": {}}} + + def put(self, document, key, value): + pass def delete(self, document, key): self.deleted.append((document, key)) @@ -143,16 +146,32 @@ class FakeNode: self.database = FakeDatabase(bt.COMMAND_INTENT_SCHEMA, keys) -class PurgeTests(unittest.TestCase): - def test_purge_removes_queued_intents(self): +class StopPendingTests(unittest.TestCase): + def test_stop_pending_receipts_each_intent_then_deletes_it(self): node = FakeNode(["c1", "c2"]) - removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA) + events = [] + removed = sg.stop_pending(node, "DOC", bt.COMMAND_INTENT_SCHEMA, + lambda key, intent, reason: events.append(("receipt", key, intent["commandId"], reason)), + "why") self.assertEqual(removed, 2) self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) + self.assertEqual(events, [("receipt", "c1", "c1", "why"), ("receipt", "c2", "c2", "why")]) - def test_purge_without_a_node_is_quiet(self): - self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA), 0) + def test_an_intent_whose_receipt_cannot_be_written_is_not_deleted(self): + node = FakeNode(["c1", "c2"]) + def writer(key, intent, reason): + if key == "c2": + raise OSError("disk full") + with self.assertRaises(OSError): + sg.stop_pending(node, "DOC", bt.COMMAND_INTENT_SCHEMA, writer, "why") + self.assertEqual(node.database.deleted, [("DOC", "c1")]) + self.assertEqual(node.database.keys, ["c2"]) + + def test_stop_pending_without_a_node_is_quiet(self): + self.assertEqual(sg.stop_pending(None, "DOC", bt.COMMAND_INTENT_SCHEMA, lambda k, i, r: 1 / 0, "why"), 0) + +class StopServerTests(unittest.TestCase): def test_stop_server_purges_and_revokes(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) stopped = [] @@ -161,7 +180,7 @@ class PurgeTests(unittest.TestCase): guard = target._guard old = guard.token target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} target.stop_server() self.assertEqual(stopped, [True]) self.assertEqual(target._node.database.keys, []) @@ -178,7 +197,7 @@ class PurgeTests(unittest.TestCase): guard = target._guard old = guard.token target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} with self.assertRaises(OSError): target.stop_server() self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) @@ -195,7 +214,7 @@ class PurgeTests(unittest.TestCase): def test_stop_server_with_no_server_running_purges_nothing(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} target.stop_server() self.assertEqual(target._node.database.keys, ["c1"]) @@ -272,6 +291,22 @@ class RealServerTests(unittest.TestCase): fresh.database.pull() return list(fresh.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})) + def receipt_states(self): + """commandId -> (status, reason) of the receipts a fresh node reads from disk.""" + cultmesh, cultcache = bt._load_cultmesh(PACKAGES) + fresh = cultmesh.CultMesh.start_node(self.cache, runtime_id="receipt-reader") + fresh.database.register_document(cultcache.define_document_type(bt.COMMAND_RECEIPT_SCHEMA)) + fresh.database.pull() + found = fresh.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).values() + return {r["commandId"]: (r["status"], r["message"]) for r in found} + + def assertStopped(self, reason): + states = self.receipt_states() + self.assertEqual(list(states), ["q1"]) + status, message = states["q1"] + self.assertEqual(status, "stopped") + self.assertIn(reason, message) + def test_start_purges_intents_queued_in_the_node_and_they_stay_gone_after_reopening(self): self.queue_intent() self.assertEqual(len(self.queued(self.cache)), 1) @@ -279,12 +314,14 @@ class RealServerTests(unittest.TestCase): node, _ = self.target._open_node(self.cache, PACKAGES) self.assertEqual(list(node.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})), []) self.assertEqual(self.queued(self.cache), []) + self.assertStopped("server started") def test_stop_purges_intents_queued_while_running_and_they_stay_gone_after_reopening(self): self.start() self.queue_intent() self.target.stop_server() self.assertEqual(self.queued(self.cache), []) + self.assertStopped("server stopped") def test_allow_true_goes_through_start_server_and_unticking_stops_it(self): status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py new file mode 100644 index 0000000..6e77f68 --- /dev/null +++ b/surfaces/blender/tests/test_stop_presence.py @@ -0,0 +1,313 @@ +"""Stop and presence: one human control turns the sink off and receipts every pending intent as stopped; +the panel's agent activity is derived from receipts. A fake bpy and a fake node database; no Blender. +""" +from __future__ import annotations + +import re +import types +import unittest +import unittest.mock +from collections import deque +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import test_agent_turn as tat +import test_scene_actions as ts +import test_addon_ui as ui + +bt = ts.bt +NS = types.SimpleNamespace +addon = ui.addon +BRIDGE = Path(bt.__file__).parent +DOCS = {"command_intent": "i", "command_receipt": "r"} + + +class StopFixture(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + intent = tat.DrainTests.intent + + def patched(self, node): + patch = unittest.mock.patch.object(self.target, "_open_node", return_value=(node, DOCS)) + patch.start() + self.addCleanup(patch.stop) + + +class StopPendingTests(StopFixture): + def queue(self): + return tat.FakeNode({f"blender/commands/{n}": self.intent(n, requestedBy=who) + for n, who in (("q-1", "nibu/hands"), ("q-2", "nibu/hands"), ("q-3", "nibu/soul"))}) + + def test_stop_receipts_every_pending_intent(self): + node = self.queue() + self.patched(node) + stopped = self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(stopped, 3) + receipts = dict(node.puts) + self.assertEqual(sorted(receipts), [f"blender/receipts/q-{n}" for n in (1, 2, 3)]) + for key, receipt in receipts.items(): + self.assertEqual(receipt["status"], "stopped", key) + self.assertIn("stopped by the operator", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(receipt["action"], "createObject") + self.assertEqual(receipts["blender/receipts/q-3"]["requestedBy"], "nibu/soul") + self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA])) + self.assertEqual(self.bpy.created, []) # none dispatched + self.assertEqual(self.bpy.undo.pushes, []) + + def test_every_intent_is_receipted_before_it_is_deleted(self): + node = self.queue() + events = [] + node.put = lambda document, key, value: events.append(("put", key)) + node.delete = lambda document, key: events.append(("delete", key)) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + for n in (1, 2, 3): + self.assertLess(events.index(("put", f"blender/receipts/q-{n}")), + events.index(("delete", f"blender/commands/q-{n}"))) + + def test_a_failed_receipt_write_leaves_the_intent_queued(self): + node = self.queue() + + def put(document, key, value): + raise OSError("disk full") + node.put = put + self.patched(node) + with self.assertRaises(OSError): + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(node.deleted, []) # no silent delete + + def test_a_stopped_id_is_spent_and_a_reused_id_keeps_its_original_receipt(self): + old = {"blender/receipts/q-1": {"commandId": "q-1", "status": "accepted"}} + node = tat.FakeNode({"blender/commands/a": self.intent("q-1"), "blender/commands/b": self.intent("q-2")}, old) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + keys = [k for k, _ in node.puts] + self.assertNotIn("blender/receipts/q-1", keys) # write-once: the accepted receipt stands + self.assertIn("blender/receipts/q-1.stopped", keys) + self.assertIn("blender/receipts/q-2", keys) + later = self.run_action(action="createObject", objectType="EMPTY", commandId="q-2") + self.assertEqual(later["status"], "denied") # the sender resends under a new id + self.assertEqual(self.bpy.created, []) + + def test_a_malformed_id_is_receipted_under_a_fresh_key_naming_the_queue_key(self): + node = tat.FakeNode({"blender/commands/odd": self.intent(["x"])}) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + ((key, receipt),) = node.puts + self.assertNotIn("[", key) + self.assertEqual(receipt["status"], "stopped") + self.assertIn("blender/commands/odd", receipt["message"]) + self.assertEqual(node.deleted, ["blender/commands/odd"]) + + def test_stop_with_nothing_pending_writes_nothing(self): + node = tat.FakeNode({}) + self.patched(node) + self.assertEqual(self.target.stop_pending("stopped by the operator", "cache", "src"), 0) + self.assertEqual((node.puts, node.deleted), ([], [])) + + def test_server_stop_and_start_receipt_with_their_own_reasons(self): + node = self.queue() + self.target._node, self.target._documents = node, DOCS + self.target._server = NS(stop=lambda: None) + self.target.stop_server() + self.assertEqual({v["status"] for _, v in node.puts}, {"stopped"}) + self.assertTrue(all("server stopped" in v["message"] for _, v in node.puts)) + self.assertEqual(len(node.deleted), 3) + + def test_start_server_receipts_stale_intents(self): + node = self.queue() + self.patched(node) + with unittest.mock.patch.object(bt, "_load_cultmesh", side_effect=RuntimeError("stop here")): + with self.assertRaises(RuntimeError): + self.target.start_server("cache", "src", "127.0.0.1", 0, 10, 1 << 20) + self.assertEqual({v["status"] for _, v in node.puts}, {"stopped"}) + self.assertTrue(all("server started" in v["message"] for _, v in node.puts)) + self.assertEqual(len(node.deleted), 3) + + +class DrainLimitTests(StopFixture): + def test_a_limited_drain_runs_that_many_and_leaves_the_rest_queued_for_stop(self): + node = tat.FakeNode({f"blender/commands/{n}": self.intent(n) for n in ("b-1", "b-2", "b-3")}) + node.delete = lambda document, key: (node.deleted.append(key), node.docs[bt.COMMAND_INTENT_SCHEMA].pop(key)) + self.patched(node) + receipts = self.target.drain_commands(self.context, "cache", "src", limit=1) + self.assertEqual([r["commandId"] for r in receipts], ["b-1"]) + self.assertEqual(node.deleted, ["blender/commands/b-1"]) + self.target.stop_pending("stopped by the operator", "cache", "src") + stopped = {v["commandId"]: v["status"] for _, v in node.puts} + self.assertEqual(stopped, {"b-1": "accepted", "b-2": "stopped", "b-3": "stopped"}) + self.assertEqual(len(self.bpy.created), 1) + + +class SnapshotTests(StopFixture): + def test_the_snapshot_carries_the_sink_toggle(self): + self.bpy.data = NS(objects=[], scenes=[], materials=[], images=[], collections=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0)) + context = NS(selected_objects=[], active_object=None, scene=self.bpy.scene, mode="OBJECT") + for enabled in (True, False): + self.assertIs(self.target.capture_snapshot(context, enabled)["agentCommandsEnabled"], enabled) + + +def receipt(agent, action, status, minutes_ago=0, note="", undo="", key="k"): + when = datetime.now(timezone.utc) - timedelta(minutes=minutes_ago) + return {"commandId": key, "requestedBy": agent, "action": action, "status": status, "note": note, + "undoLabel": undo, "observedAt": when.isoformat(), "message": ""} + + +class PresenceTests(StopFixture): + def test_active_agents_are_distinct_requesters_in_the_last_five_minutes(self): + self.target.note_receipt(receipt("nibu/hands", "createObject", "accepted", 1)) + self.target.note_receipt(receipt("nibu/hands", "addNode", "accepted", 2)) + self.target.note_receipt(receipt("nibu/soul", "selectObject", "stopped", 4)) + self.target.note_receipt(receipt("nibu/eyes", "selectObject", "accepted", 6)) + self.assertEqual(self.target.active_agents(), ["nibu/hands", "nibu/soul"]) + + def test_recent_receipts_are_the_last_eight_newest_first(self): + for n in range(12): + self.target.note_receipt(receipt("nibu/hands", f"a{n}", "accepted", key=f"k{n}")) + self.assertEqual([r["action"] for r in self.target.recent_receipts()], [f"a{n}" for n in range(11, 3, -1)]) + + def test_publish_receipt_and_stop_both_fill_the_display_cache(self): + node = tat.FakeNode({"blender/commands/s-1": self.intent("s-1")}) + self.patched(node) + self.target.publish_receipt("cache", "src", receipt("nibu/hands", "createObject", "accepted", key="p-1")) + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual({r["commandId"]: r["status"] for r in self.target.recent_receipts()}, + {"p-1": "accepted", "s-1": "stopped"}) + + def test_first_load_rebuilds_the_cache_from_the_node_once(self): + stored = {f"blender/receipts/{n}": receipt("nibu/hands", "createObject", "accepted", n, key=f"n{n}") + for n in range(1, 4)} + node = tat.FakeNode({}, stored) + self.patched(node) + self.target.load_recent_receipts("cache", "src") + self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1", "n2", "n3"]) + node.docs[bt.COMMAND_RECEIPT_SCHEMA]["blender/receipts/x"] = receipt("a/b", "x", "accepted", key="x") + self.target.load_recent_receipts("cache", "src") + self.assertEqual(len(self.target.recent_receipts()), 3) # loaded once + + def test_loading_after_receipts_were_noted_lists_each_receipt_once(self): + stored = {"blender/receipts/n1": receipt("nibu/hands", "createObject", "accepted", 1, key="n1")} + node = tat.FakeNode({}, stored) + self.patched(node) + self.target.note_receipt(stored["blender/receipts/n1"]) # written by this session before the first draw + self.target.load_recent_receipts("cache", "src") + self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1"]) + + def test_pending_count_comes_from_the_node(self): + node = tat.FakeNode({"blender/commands/a": self.intent("a"), "blender/commands/b": self.intent("b")}) + self.patched(node) + self.assertEqual(self.target.count_pending("cache", "src"), 2) + + +class PanelAndOperatorTests(unittest.TestCase): + def setUp(self): + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + self.prefs = unittest.mock.MagicMock(auto_drain_commands=True, cultmesh_cache_path="cache", + cultlib_py_src="src", debug_mirror_root="", broker_uri="b") + self.context = NS(preferences=NS(addons={"brokkr_addon": NS(preferences=self.prefs)})) + + def test_stop_agents_turns_the_sink_off_and_receipts_the_queue(self): + node = tat.FakeNode({"blender/commands/a": {"commandId": "a-1", "requestedBy": "x/y", "action": "createObject"}}) + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, DOCS)): + operator = addon.BROKKR_OT_stop_agents() + result = operator.execute(self.context) + self.assertEqual(result, {"FINISHED"}) + self.assertFalse(self.prefs.auto_drain_commands) + self.assertEqual([v["status"] for _, v in node.puts], ["stopped"]) + self.assertIn("stopped by the operator", node.puts[0][1]["message"]) + + def test_stop_agents_is_registered_and_first_in_the_panel(self): + self.assertIn(addon.BROKKR_OT_stop_agents, addon.classes) + layout = unittest.mock.MagicMock() + panel = addon.BROKKR_PT_status() + panel.layout = layout + panel.draw(self.context) + first = [c for c in layout.mock_calls if c[0] == "operator" or c[0].endswith(".operator")][0] + self.assertEqual(first.args[0], "brokkr.stop_agents") + + def test_the_sink_preference_defaults_off_and_says_only_the_operator_turns_it_on(self): + prop = addon.BrokkrPreferences.__annotations__["auto_drain_commands"] + self.assertIs(prop.kwargs["default"], False) + self.assertIn("operator", prop.kwargs["description"].lower()) + self.assertTrue(callable(prop.kwargs.get("update"))) # the stored snapshot follows the toggle + + def test_toggling_the_sink_republishes_the_stored_snapshot_once_a_node_is_open(self): + update = addon.BrokkrPreferences.__annotations__["auto_drain_commands"].kwargs["update"] + addon.bpy.context = NS() + with unittest.mock.patch.object(self.target, "publish_snapshot") as publish: + update(self.prefs, None) + publish.assert_not_called() # nothing has opened a node: no snapshot to correct + self.target._node = object() + self.prefs.auto_drain_commands = False + update(self.prefs, None) + self.assertEqual(publish.call_args.args[-1], False) + + def test_the_agents_section_lists_agents_pending_and_receipts(self): + self.target.note_receipt(receipt("nibu/hands", "createObject", "accepted", 1, note="a cube", + undo="Brokkr nibu/hands: createObject abcd1234")) + self.target.note_receipt(receipt("nibu/soul", "setLight", "stopped", 2)) + self.target.pending_count = 3 + self.target._receipts_loaded = True + layout = unittest.mock.MagicMock() + panel = addon.BROKKR_PT_status() + panel.layout = layout + panel.draw(self.context) + texts = [str(c.kwargs.get("text", "")) for c in layout.mock_calls if c.kwargs] + joined = "\n".join(texts) + self.assertIn("Agents", joined) + self.assertIn("nibu/hands", joined) + self.assertIn("nibu/soul setLight stopped", joined) + self.assertIn("nibu/hands createObject accepted", joined) + self.assertIn("a cube", joined) + self.assertIn("Brokkr nibu/hands: createObject abcd1234", joined) + self.assertRegex(joined, r"Pending: 3") + self.assertNotIn("Last receipt", joined) + + +class TimerTests(unittest.TestCase): + def setUp(self): + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + self.prefs = NS(auto_drain_commands=True, cultmesh_cache_path="c", cultlib_py_src="s", debug_mirror_root="", + import_dir="", output_dir="") + patch = unittest.mock.patch.object(addon, "_redraw") + self.redraws = patch.start() + self.addCleanup(patch.stop) + addon.bpy.context = NS(preferences=NS(addons=NS(get=lambda name: NS(preferences=self.prefs)))) + self.drains = [] + self.target.drain_commands = lambda *a, **k: self.drains.append(k) or [1] * self.ran + self.target.count_pending = lambda *a: 0 + self.target.configure_action_dirs = lambda *a: None + + def test_the_timer_drains_one_intent_per_tick_so_stop_lands_between_them(self): + self.ran = 1 + interval = addon._auto_drain_commands() + self.assertEqual(self.drains[0].get("limit"), 1) + self.assertLess(interval, 0.22) # more may be queued: come back soon (bound: geometric mean of the 0.05 shipped and the 1.0 idle reading) + + def test_an_empty_tick_goes_back_to_the_idle_interval(self): + self.ran = 0 + self.assertEqual(addon._auto_drain_commands(), 1.0) + + def test_with_the_sink_off_the_timer_runs_nothing(self): + self.prefs.auto_drain_commands = False + self.ran = 1 + self.assertEqual(addon._auto_drain_commands(), 1.0) + self.assertEqual(self.drains, []) + + +class NoPreferenceWritesTests(unittest.TestCase): + def test_no_action_writes_preferences(self): + # 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) + + +if __name__ == "__main__": + unittest.main()