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/docs/live-collab-target.md b/docs/live-collab-target.md index 2853e5a..545df3d 100644 --- a/docs/live-collab-target.md +++ b/docs/live-collab-target.md @@ -119,7 +119,9 @@ This is scene-level only; the `.cc` keeps its revision refusal (phase two). **Stop is one control, and only the human holds it.** Stop turns the command sink off and gives every pending intent a `stopped` receipt without running it. An action already running finishes as one undo step, so Stop plus Ctrl+Z always returns her -scene. No intent can turn the sink on; intents queued before Stop never run. +scene. No intent can turn the sink on; intents queued before Stop never run, and an intent that +arrives while the sink is off gets a `stopped` receipt at once (`brokkr-live:ruling:sink-off-answers-stopped`), +so nothing queues to fire on re-enable. **The agent sees her view and her edits.** `look` is a read intent: it captures her 3D view to a scratch PNG named by command id (`brush-tree:ruling:look-files-are-scratch`) diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 8a81707..4926385 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,25 @@ 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") + + 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']}") + layout.label(text=f"Provider: {PROVIDER_ID}") layout.label(text=f"Tool: {TOOL_KIND}") layout.label(text=f"Broker: {prefs.broker_uri}") @@ -409,11 +446,6 @@ 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.last_auto_drain_error: layout.separator() layout.label(text="Auto drain error:") @@ -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,54 @@ 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, - ) + # The sink on, a node open, or a store already on disk: any running Blender answers within a tick, and + # an idle session never creates a store. + if prefs.auto_drain_commands or adapter.node_open or adapter.store_exists(prefs.cultmesh_cache_path): + 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.count_pending(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + else: # the add-on owns the sink, so it answers: nothing queues to fire on re-enable + adapter.stop_pending("agent commands are off", prefs.cultmesh_cache_path, + prefs.cultlib_py_src, prefs.debug_mirror_root) 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..363e017 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,91 @@ 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 + + stopped = stop_pending(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, write, reason) + self.pending_count = 0 + return stopped + + 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 + + def store_exists(self, cache_path: str) -> bool: + return Path(self.resolve_cache_path(cache_path)).is_file() + + @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 +473,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 +544,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 +576,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 +599,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 +1336,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/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl index 832d545..641dbcd 100644 Binary files a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl and b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl differ diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 6452905..0b5917c 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -46,12 +46,12 @@ newer, any OS). msgpack then runs its pure-Python fallback, which CultLib `9fc4b Wheel provenance: msgpack 1.2.2 as installed on the build host (CPython 3.13, the PyPI release; nothing was downloaded), repacked by `tools/build-msgpack-wheel.py` from its `msgpack/__init__.py`, `exceptions.py`, -`ext.py` and `fallback.py` (the `_cmsgpack` C extension is left out) with the package's METADATA and +`ext.py` and `fallback.py` (the `_cmsgpack` C extension is left out) with the package's METADATA (read as bytes, so its hash is the one PyPI's RECORD lists) and Apache-2.0 `COPYING`. The repack is deterministic; rebuild and compare: ```text python tools/build-msgpack-wheel.py -sha256 0b53d2ea2e21782a670fc152bb104d97623cfa337940518016a6b7ded369af42 msgpack-1.2.2-py3-none-any.whl +sha256 91d288892c9622ffe1b3f1430a66956f93ae5964b4dcacf00c4eb93f3f4f65af msgpack-1.2.2-py3-none-any.whl ``` In a plain add-on directory install the wheel is not unpacked: put `msgpack` into Blender's Python @@ -69,13 +69,30 @@ 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. While the sink is off the add-on answers every intent that arrives with a +`stopped` receipt ("agent commands are off") at once, so `brokkr-ctl wait` exits 3 and nothing queues to fire when +the operator turns the sink back on. The answer needs a node the add-on has opened (a running server or a published +snapshot). + +The `Agents` section sits directly under Stop agents and 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.closed.result.json b/surfaces/blender/tests/live/stop_presence.closed.result.json new file mode 100644 index 0000000..2fa8684 --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.closed.result.json @@ -0,0 +1,28 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "phase two: a store on disk from phase one, sink off, no snapshot published this session", + "ok": true, + "detail": null + }, + { + "name": "phase two: a send to a sink-off Blender with a closed node is answered stopped at once (exit 3)", + "ok": true, + "detail": [ + 3, + 1.2883892059326172, + "commandId: 01a21ed2b9747d53bc380f32f2057a09\naction: createObject\ncommandId: 01a21ed2b9747d53bc380f32f2057a09\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: closed\nobjectName: \nobservedAt: 2026-11-27T21:04:17.259806+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + ] + } + ], + "notes": { + "closed": { + "exit": 3, + "seconds": 1.29, + "out": "commandId: 01a21ed2b9747d53bc380f32f2057a09\naction: createObject\ncommandId: 01a21ed2b9747d53bc380f32f2057a09\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: closed\nobjectName: \nobservedAt: 2026-11-27T21:04:17.259806+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py new file mode 100644 index 0000000..b1889f8 --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.py @@ -0,0 +1,337 @@ +"""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 -- + Run a second Blender on the same store with BROKKR_PHASE=closed for the sink-off, node-closed answer. + +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 time +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 + + +SEND = ["send", "createObject", "--set", 'objectType="EMPTY"'] + + +def send(name, note): + code, out = ctl(*SEND, "--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 spawn(name, note): + """A brokkr-ctl send that runs beside Blender's timers: the sender is another process, as an agent is.""" + return subprocess.Popen([CTL, "blender", *SEND, "--set", f'name="{name}"', "--note", note, "--no-wait"], + env=ENV, stdout=subprocess.PIPE, text=True) + + +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 ------------------------------------------------------------------------------------------------- +BURST = 20 + + +def s_setup(): + """A default install: no server, no snapshot, Auto Capture off, sink off. An idle session makes no store.""" + check("setup: default install, no node open and no store file", not adapter.node_open and not Path(CACHE).exists(), + [adapter.node_open, Path(CACHE).exists()]) + + +def s_idle_check(): + check("idle: with the sink off and no store, the timer has still opened no node and made no store", + not adapter.node_open and not Path(CACHE).exists(), [adapter.node_open, Path(CACHE).exists()]) + prefs.auto_drain_commands = True # the operator ticks the sink + + +def node_opened(): + return adapter.node_open + + +def s_open(): + check("sink on with the node closed: the timer opened the node itself (an empty node writes no file until something is put)", adapter.node_open, None) + with win(): + bpy.ops.brokkr.capture_snapshot() # she presses Capture, so brokkr-ctl status has a snapshot to read + code, out = ctl("status") + check("the stored snapshot says agentCommandsEnabled: true", code == 0 and "agentCommandsEnabled: true" in out, out) + + +def s_burst(): + S["procs"] = [spawn(f"B{n:02d}", "burst") for n in range(BURST)] + + +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["pending_after_stop"] = adapter.pending_count + + +def finished(): + return all(p.poll() is not None for p in S["procs"]) and pending() == [] + + +def s_after_stop(): + ids = [] + for proc in S["procs"]: + match = re.search(r"commandId:\s*(\S+)", proc.stdout.read()) + ids.append(match.group(1)) + S["ids"] = ids + rs = receipts() + states = {i: (rs.get(i) or {}).get("status") for i in ids} + accepted = [i for i, st in states.items() if st == "accepted"] + stopped = [i for i, st in states.items() if st == "stopped"] + R["notes"]["states"] = states + check("stop: every one of the 20 intents has a receipt, each accepted or stopped, none missing", + len(accepted) + len(stopped) == BURST and len(stopped) >= 1 and len(accepted) >= 2, states) + check("stop: the queue is empty, the sink is off, Pending read 0 the moment Stop returned", + pending() == [] and prefs.auto_drain_commands is False and S["stop_result"] == {"FINISHED"} + and S["pending_after_stop"] == 0, [pending(), S["stop_result"], S["pending_after_stop"]]) + check("stop: exactly the accepted intents ran and the stopped ones left no object", + len(empties("B")) == len(accepted), [len(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 never carry 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"] or "agent commands are off" in rs[i]["message"]) + for i in stopped), sorted({rs[i]["message"][:50] for i in stopped})) + R["notes"]["stop_reasons"] = sorted({rs[i]["message"][:48] for i in stopped}) + exits = {i: (states[i], ctl("wait", i, "--timeout", "5")[0]) for i in ids} + 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) + + +def s_late(): + """An agent that never saw Stop sends again and waits: the add-on's timer answers at once, nothing queues.""" + S["late_began"] = time.time() + S["late"] = subprocess.Popen([CTL, "blender", *SEND, "--set", 'name="Late"', "--note", "late", "--timeout", "10"], + env=ENV, stdout=subprocess.PIPE, text=True) + + +def late_done(): + return S["late"].poll() is not None + + +def s_late_check(): + took = time.time() - S["late_began"] + out = S["late"].stdout.read() + code = S["late"].returncode + R["notes"]["late"] = {"exit": code, "seconds": round(took, 2), "out": out} + check("sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", + code == 3 and took < 5 and "agent commands are off" in out and pending() == [] and not empties("Late"), + [code, took, out]) + S["receipt_count"] = len(receipts()) + prefs.auto_drain_commands = True # she turns the sink back on + + +def s_reenabled(): + check("re-enable: nothing queued fires; the late intent never runs", + pending() == [] and not empties("Late") and len(receipts()) == S["receipt_count"], + [pending(), empties("Late"), len(receipts()) - S["receipt_count"]]) + before = len(empties("B")) + with win(): + bpy.ops.ed.undo() + check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - len(empties("B")) == 1, + [before, len(empties("B"))]) + + +def s_panel(): + before = "\n".join(S["panel_before"]) + R["notes"]["panel_before_stop"] = S["panel_before"] + check("panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", + S["panel_before"].index("Agents") < S["panel_before"].index("Provider: brokkr.blender_editor") + and "Active: nibu/hands" in before and "Agent commands: on" in 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) + prefs.auto_drain_commands = False + 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) + prefs.auto_drain_commands = True + + +def s_server_up(): + with win(): + bpy.ops.brokkr.start_server() + + +def s_server_stop(): + S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] # the sender blocks Blender's thread: they cannot drain yet + check("server stop: three intents queued behind a running server, sink on", len(pending()) == 3, len(pending())) + 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; sends that arrive after it meet a sink that is off. +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 + if step in ("wait-done", "wait-late", "wait-store", "wait-idle"): + if step == "wait-idle": + S["idle"] = S.get("idle", 0) + 1 + if {"wait-done": finished, "wait-late": late_done, "wait-store": node_opened, + "wait-idle": lambda: S.get("idle", 0) >= 15}[step](): + i += 1 + return 0.1 + step() + i += 1 + write() + return 0.005 if step is s_burst else 0.5 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + write() + bpy.ops.wm.quit_blender() + return None + + +if os.environ.get("BROKKR_PHASE") == "closed": + # Phase two, a fresh Blender on the phase-one store: sink off, no node opened, a store on disk. A send must + # be answered stopped within a tick. + def s_closed(): + check("phase two: a store on disk from phase one, sink off, no snapshot published this session", + Path(CACHE).exists() and not prefs.auto_drain_commands and adapter.last_snapshot is None, None) + S["late_began"] = time.time() + S["late"] = subprocess.Popen([CTL, "blender", *SEND, "--set", 'name="Closed"', "--note", "closed", "--timeout", "10"], + env=ENV, stdout=subprocess.PIPE, text=True) + + def s_closed_check(): + out, code, took = S["late"].stdout.read(), S["late"].returncode, time.time() - S["late_began"] + R["notes"]["closed"] = {"exit": code, "seconds": round(took, 2), "out": out} + check("phase two: a send to a sink-off Blender with a closed node is answered stopped at once (exit 3)", + code == 3 and took < 5 and "agent commands are off" in out and not empties("Closed"), [code, took, out]) + steps = [s_closed, "wait-late", s_closed_check] +else: + steps = [s_setup, "wait-idle", s_idle_check, "wait-store", s_open, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, s_panel, + s_server_up, 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..ab9f8ee --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -0,0 +1,355 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "setup: default install, no node open and no store file", + "ok": true, + "detail": [ + false, + false + ] + }, + { + "name": "idle: with the sink off and no store, the timer has still opened no node and made no store", + "ok": true, + "detail": [ + false, + false + ] + }, + { + "name": "sink on with the node closed: the timer opened the node itself (an empty node writes no file until something is put)", + "ok": true, + "detail": null + }, + { + "name": "the stored snapshot says agentCommandsEnabled: true", + "ok": true, + "detail": "observedAt: 2026-11-27T21:04:00.546944+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 20 intents has a receipt, each accepted or stopped, none missing", + "ok": true, + "detail": { + "01a21ed27e2e74e1b8e725800116e4e8": "accepted", + "01a21ed27e347fc1a9335eece58a845e": "accepted", + "01a21ed27e51773392985e0e1859abec": "stopped", + "01a21ed27e6d7b53a39ad7e8d7316c8b": "stopped", + "01a21ed27e6f78c1a05ed37723e2b309": "stopped", + "01a21ed27e6d76f1bb533bed0a748a13": "stopped", + "01a21ed27e6d7c1092c429ea773c8fc1": "stopped", + "01a21ed27e6f7d33a2055b67edc92f18": "stopped", + "01a21ed27e8272e195d68ac7f7fdf699": "stopped", + "01a21ed27e897ba19eba4c3b3093126d": "stopped", + "01a21ed27e9379e3831640c51caf5f7a": "stopped", + "01a21ed27ea270008ef42324ca91b333": "stopped", + "01a21ed27e9472d3930a123edde8b2fd": "stopped", + "01a21ed27ed57222bce4b3537264e29c": "stopped", + "01a21ed27ea674d1bb4f93ccf3f84df2": "stopped", + "01a21ed27ed07ea180078e4a1d81fc24": "stopped", + "01a21ed27eb37ea3ac2277d337e6fad9": "stopped", + "01a21ed27ed07f63aa4a193a340243bd": "stopped", + "01a21ed27ed070408f8bd458009ab441": "stopped", + "01a21ed27ed27ba1ae1e97b2320d6264": "stopped" + } + }, + { + "name": "stop: the queue is empty, the sink is off, Pending read 0 the moment Stop returned", + "ok": true, + "detail": [ + [], + "{'FINISHED'}", + 0 + ] + }, + { + "name": "stop: exactly the accepted intents ran and the stopped ones left no object", + "ok": true, + "detail": [ + 2, + 2 + ] + }, + { + "name": "stop: each accepted intent is one labelled undo step the receipt names", + "ok": true, + "detail": [ + "Brokkr nibu/hands: createObject 0116e4e8", + "Brokkr nibu/hands: createObject e58a845e" + ] + }, + { + "name": "stop: stopped receipts say who, what and why, and never carry an undo label", + "ok": true, + "detail": [ + "Stopped (stopped by the operator); the intent was " + ] + }, + { + "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-27T21:04:01.582528+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + }, + { + "name": "sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", + "ok": true, + "detail": [ + 3, + 0.6054728031158447, + "commandId: 01a21ed2867e7733982b0eaf93547dcc\naction: createObject\ncommandId: 01a21ed2867e7733982b0eaf93547dcc\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T21:04:03.327292+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + ] + }, + { + "name": "re-enable: nothing queued fires; the late intent never runs", + "ok": true, + "detail": [ + [], + [], + 0 + ] + }, + { + "name": "stop + Ctrl+Z: one undo takes back the last agent step, nothing else", + "ok": true, + "detail": [ + 2, + 1 + ] + }, + { + "name": "panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", + "ok": true, + "detail": "Agents\nAgent commands: on\nActive: nibu/hands\nPending: 18\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject e58a845e\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 0116e4e8\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: stopped\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1" + }, + { + "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": "Agents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n late\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\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: stopped\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 4\nMaterials: 2\nSelected: 1" + }, + { + "name": "server stop: three intents queued behind a running server, sink on", + "ok": true, + "detail": 3 + }, + { + "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": { + "01a21ed27e2e74e1b8e725800116e4e8": "accepted", + "01a21ed27e347fc1a9335eece58a845e": "accepted", + "01a21ed27e51773392985e0e1859abec": "stopped", + "01a21ed27e6d7b53a39ad7e8d7316c8b": "stopped", + "01a21ed27e6f78c1a05ed37723e2b309": "stopped", + "01a21ed27e6d76f1bb533bed0a748a13": "stopped", + "01a21ed27e6d7c1092c429ea773c8fc1": "stopped", + "01a21ed27e6f7d33a2055b67edc92f18": "stopped", + "01a21ed27e8272e195d68ac7f7fdf699": "stopped", + "01a21ed27e897ba19eba4c3b3093126d": "stopped", + "01a21ed27e9379e3831640c51caf5f7a": "stopped", + "01a21ed27ea270008ef42324ca91b333": "stopped", + "01a21ed27e9472d3930a123edde8b2fd": "stopped", + "01a21ed27ed57222bce4b3537264e29c": "stopped", + "01a21ed27ea674d1bb4f93ccf3f84df2": "stopped", + "01a21ed27ed07ea180078e4a1d81fc24": "stopped", + "01a21ed27eb37ea3ac2277d337e6fad9": "stopped", + "01a21ed27ed07f63aa4a193a340243bd": "stopped", + "01a21ed27ed070408f8bd458009ab441": "stopped", + "01a21ed27ed27ba1ae1e97b2320d6264": "stopped" + }, + "stop_reasons": [ + "Stopped (stopped by the operator); the intent wa" + ], + "wait_exits": { + "01a21ed27e2e74e1b8e725800116e4e8": [ + "accepted", + 0 + ], + "01a21ed27e347fc1a9335eece58a845e": [ + "accepted", + 0 + ], + "01a21ed27e51773392985e0e1859abec": [ + "stopped", + 3 + ], + "01a21ed27e6d7b53a39ad7e8d7316c8b": [ + "stopped", + 3 + ], + "01a21ed27e6f78c1a05ed37723e2b309": [ + "stopped", + 3 + ], + "01a21ed27e6d76f1bb533bed0a748a13": [ + "stopped", + 3 + ], + "01a21ed27e6d7c1092c429ea773c8fc1": [ + "stopped", + 3 + ], + "01a21ed27e6f7d33a2055b67edc92f18": [ + "stopped", + 3 + ], + "01a21ed27e8272e195d68ac7f7fdf699": [ + "stopped", + 3 + ], + "01a21ed27e897ba19eba4c3b3093126d": [ + "stopped", + 3 + ], + "01a21ed27e9379e3831640c51caf5f7a": [ + "stopped", + 3 + ], + "01a21ed27ea270008ef42324ca91b333": [ + "stopped", + 3 + ], + "01a21ed27e9472d3930a123edde8b2fd": [ + "stopped", + 3 + ], + "01a21ed27ed57222bce4b3537264e29c": [ + "stopped", + 3 + ], + "01a21ed27ea674d1bb4f93ccf3f84df2": [ + "stopped", + 3 + ], + "01a21ed27ed07ea180078e4a1d81fc24": [ + "stopped", + 3 + ], + "01a21ed27eb37ea3ac2277d337e6fad9": [ + "stopped", + 3 + ], + "01a21ed27ed07f63aa4a193a340243bd": [ + "stopped", + 3 + ], + "01a21ed27ed070408f8bd458009ab441": [ + "stopped", + 3 + ], + "01a21ed27ed27ba1ae1e97b2320d6264": [ + "stopped", + 3 + ] + }, + "late": { + "exit": 3, + "seconds": 0.61, + "out": "commandId: 01a21ed2867e7733982b0eaf93547dcc\naction: createObject\ncommandId: 01a21ed2867e7733982b0eaf93547dcc\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T21:04:03.327292+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + }, + "panel_before_stop": [ + "Agents", + "Agent commands: on", + "Active: nibu/hands", + "Pending: 18", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject e58a845e", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject 0116e4e8", + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: stopped", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 3", + "Materials: 2", + "Selected: 1" + ], + "panel_labels": [ + "Agents", + "Agent commands: off", + "Active: nibu/hands", + "Pending: 0", + "nibu/hands createObject stopped", + " late", + "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", + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: stopped", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 4", + "Materials: 2", + "Selected: 1" + ] + }, + "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_extension_wheel.py b/surfaces/blender/tests/test_extension_wheel.py index 36c3b0d..362e32f 100644 --- a/surfaces/blender/tests/test_extension_wheel.py +++ b/surfaces/blender/tests/test_extension_wheel.py @@ -3,6 +3,7 @@ from __future__ import annotations import base64 import hashlib +import importlib.metadata import re import tomllib import unittest @@ -33,6 +34,21 @@ class ExtensionWheelTests(unittest.TestCase): self.assertEqual(digest, "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode(), name) self.assertEqual(int(size), len(data), name) + def test_wheel_metadata_is_the_published_files_bytes(self): + """RECORD in the installed (PyPI) msgpack hashes its METADATA byte for byte; the wheel must carry the same bytes.""" + try: + dist = importlib.metadata.distribution("msgpack") + except importlib.metadata.PackageNotFoundError: + self.skipTest("msgpack is not installed here") + wheel = ADDON / self.manifest["wheels"][0] + if dist.version != "1.2.2": + self.skipTest(f"installed msgpack is {dist.version}") + expected = next(f for f in dist.files if f.name == "METADATA" and f.parent.name.endswith(".dist-info")).hash + with zipfile.ZipFile(wheel) as z: + data = z.read("msgpack-1.2.2.dist-info/METADATA") + digest = "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + self.assertEqual(digest, f"{expected.mode}={expected.value}") + def test_install_doc_records_the_wheel_hash(self): wheel = ADDON / self.manifest["wheels"][0] recorded = re.findall(r"\b[0-9a-f]{64}\b", INSTALL.read_text(encoding="utf-8")) diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index f69cc07..eff659b 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -565,7 +565,11 @@ class NodeActionTests(unittest.TestCase): self.assertEqual(len(self.bpy.undo.pushes), pushes) # nothing changed: no undo step self.assertEqual(empty["undoLabel"], "") self.assertEqual(len(tree.links), 2) - self.assertIn("Removed 1", self.accepted(action="unlinkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A")["message"]) + pushes = len(self.bpy.undo.pushes) + removal = self.accepted(action="unlinkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A") + self.assertIn("Removed 1", removal["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes + 1) # a real removal is one undo step + self.assertEqual(removal["undoLabel"], self.bpy.undo.pushes[-1]) self.assertEqual(len(tree.links), 1) self.accepted(action="unlinkSockets", treeKey="G", toNode="c", toSocket="Size") self.assertEqual(len(tree.links), 0) 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..4583ce0 --- /dev/null +++ b/surfaces/blender/tests/test_stop_presence.py @@ -0,0 +1,371 @@ +"""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 tempfile +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_many_agents_inside_the_window_are_all_active_beyond_eight_receipts(self): + for n in range(20): + self.target.note_receipt(receipt(f"nibu/a{n}", "createObject", "accepted", 1, key=f"m{n}")) + self.assertEqual(len(self.target.active_agents()), 20) + + def test_a_receipt_time_without_a_zone_is_read_as_utc(self): + fresh = receipt("nibu/naive", "createObject", "accepted", 1) + fresh["observedAt"] = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + self.target.note_receipt(fresh) + self.assertEqual(self.target.active_agents(), ["nibu/naive"]) + + def test_pending_reads_zero_the_moment_stop_returns(self): + node = tat.FakeNode({"blender/commands/a": self.intent("a-1"), "blender/commands/b": self.intent("b-1")}) + self.patched(node) + self.assertEqual(self.target.count_pending("cache", "src"), 2) + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(self.target.pending_count, 0) + + 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) + agents_at = [i for i, c in enumerate(layout.mock_calls) if c.kwargs.get("text") == "Agents"][0] + first_sync = [i for i, c in enumerate(layout.mock_calls) if c.args[:1] == ("brokkr.publish_object_sync",)][0] + first_other = [i for i, c in enumerate(layout.mock_calls) if str(c.kwargs.get("text", "")).startswith("Provider")][0] + self.assertLess(agents_at, first_other) # directly under Stop agents, above everything else + self.assertLess(agents_at, first_sync) + 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.counts, self.stops = [], [], [] + self.ran = 0 + self.target.drain_commands = lambda *a, **k: self.drains.append(k) or [1] * self.ran + self.target.count_pending = lambda *a: self.counts.append(a) or 0 + self.target.stop_pending = lambda *a: self.stops.append(a) or 0 + self.target.configure_action_dirs = lambda *a: None + self.target._node = object() + + 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_on_the_timer_keeps_the_pending_count_moving(self): + addon._auto_drain_commands() + self.assertEqual(len(self.counts), 1) + + def test_with_the_sink_off_every_arriving_intent_is_answered_stopped_not_queued(self): + self.prefs.auto_drain_commands = False + self.ran = 1 + self.assertEqual(addon._auto_drain_commands(), 1.0) + self.assertEqual(self.drains, []) + self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) + + def test_with_the_sink_on_and_no_node_open_the_timer_still_drains(self): + self.target._node = None + self.ran = 1 + addon._auto_drain_commands() + self.assertEqual(len(self.drains), 1) + + def test_with_the_sink_off_and_an_existing_store_a_closed_node_still_answers_stopped(self): + self.prefs.auto_drain_commands = False + self.target._node = None + with tempfile.TemporaryDirectory() as tmp: + store = Path(tmp) / "node.ccmp" + store.write_bytes(b"") + self.prefs.cultmesh_cache_path = str(store) + addon._auto_drain_commands() + self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) + + def test_an_idle_session_creates_no_store_and_answers_nothing(self): + self.prefs.auto_drain_commands = False + self.target._node = None + with tempfile.TemporaryDirectory() as tmp: + store = Path(tmp) / "node.ccmp" + self.prefs.cultmesh_cache_path = str(store) + addon._auto_drain_commands() + self.assertFalse(store.exists()) + self.assertEqual((self.stops, self.drains, self.counts), ([], [], [])) + + +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() diff --git a/tools/build-msgpack-wheel.py b/tools/build-msgpack-wheel.py index a6d67af..6dbf28e 100644 --- a/tools/build-msgpack-wheel.py +++ b/tools/build-msgpack-wheel.py @@ -11,7 +11,7 @@ version = dist.version site = pathlib.Path(dist.locate_file("")) files = {f"msgpack/{name}": (site / "msgpack" / name).read_bytes() for name in PURE} info = f"msgpack-{version}.dist-info" -files[f"{info}/METADATA"] = dist.read_text("METADATA").encode() +files[f"{info}/METADATA"] = (site / info / "METADATA").read_bytes() # bytes: read_text would fold CRLF and change the hash PyPI's RECORD lists files[f"{info}/top_level.txt"] = b"msgpack\n" files[f"{info}/licenses/COPYING"] = (site / info / "licenses" / "COPYING").read_bytes() files[f"{info}/WHEEL"] = b"Wheel-Version: 1.0\nGenerator: brokkr tools/build-msgpack-wheel.py\nRoot-Is-Purelib: true\nTag: py3-none-any\n"