From 17584e40f967e0d489d63b2f56c45c4e5ead0677 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:31:22 +0100 Subject: [PATCH 1/4] Wheel METADATA is the published file's bytes (rebuild, new sha256); a real unlinkSockets removal pins one undo step build-msgpack-wheel.py read METADATA through read_text, which folded CRLF and changed the hash PyPI's RECORD lists. The test compares the wheel's METADATA hash with the installed distribution's RECORD and failed first; the unlink test fails against a mutant that never reports a change. Co-Authored-By: Claude Sonnet 5.5 --- .../wheels/msgpack-1.2.2-py3-none-any.whl | Bin 15448 -> 15493 bytes surfaces/blender/docs/install.md | 4 ++-- .../blender/tests/test_extension_wheel.py | 16 ++++++++++++++++ surfaces/blender/tests/test_node_actions.py | 6 +++++- tools/build-msgpack-wheel.py | 2 +- 5 files changed, 24 insertions(+), 4 deletions(-) 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 832d5453b3cd50d71b8902c0428d829b228c0c84..641dbcd4defc52d93da2caa7c3dbd742c463e507 100644 GIT binary patch delta 3977 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 diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index 6452905..d85ab16 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 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/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" -- 2.47.3 From 044ac094b5ca6c036c6dec7e5283bea60d4b557e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:38:17 +0100 Subject: [PATCH 2/4] Stop agents: one human control turns the sink off and receipts every pending intent as stopped; presence in the panel purge_command_intents becomes stop_pending: a stopped receipt per intent, written before the intent is deleted. Stop agents, server start and server stop share that path. The timer runs one intent per tick so Stop lands between two. The panel's Agents section (active agents, pending count, last eight receipts) reads a display cache filled where receipts are written; the host snapshot carries agentCommandsEnabled, which brokkr-ctl status prints. Live proof on stock Blender 5.3 with real brokkr-ctl sends: tests/live/stop_presence.py. Co-Authored-By: Claude Sonnet 5.5 --- brokkr-ctl/src/blender.rs | 4 +- brokkr-ctl/tests/cli.rs | 4 +- surfaces/blender/brokkr_bridge/__init__.py | 98 +++++- .../blender/brokkr_bridge/blender_target.py | 116 ++++++- .../blender/brokkr_bridge/server_guard.py | 21 +- surfaces/blender/docs/install.md | 20 +- surfaces/blender/tests/live/gn_actions.py | 4 +- surfaces/blender/tests/live/gn_recreation.py | 4 +- surfaces/blender/tests/live/stop_presence.py | 254 ++++++++++++++ .../tests/live/stop_presence.result.json | 280 ++++++++++++++++ surfaces/blender/tests/test_agent_turn.py | 4 + surfaces/blender/tests/test_server_guard.py | 55 ++- surfaces/blender/tests/test_stop_presence.py | 313 ++++++++++++++++++ 13 files changed, 1118 insertions(+), 59 deletions(-) create mode 100644 surfaces/blender/tests/live/stop_presence.py create mode 100644 surfaces/blender/tests/live/stop_presence.result.json create mode 100644 surfaces/blender/tests/test_stop_presence.py 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() -- 2.47.3 From 861edd3195a95ce68fa60d72320379570d0c2e75 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:53:10 +0100 Subject: [PATCH 3/4] Stop: a sink-off add-on answers arriving intents stopped; Agents under Stop; pending zero after Stop; survivors pinned Soul s1: post-stop-queue-runs (ruling sink-off-answers-stopped), agents-section-buried, pending-stale-after-stop, stop-survivors-unpinned. The live harness now sends a concurrent burst with the sink on, cuts it with Stop, and shows a later send answered stopped at once (wait exit 3) with nothing firing on re-enable. Co-Authored-By: Claude Sonnet 5.5 --- docs/live-collab-target.md | 4 +- surfaces/blender/brokkr_bridge/__init__.py | 53 ++-- .../blender/brokkr_bridge/blender_target.py | 4 +- surfaces/blender/docs/install.md | 7 +- surfaces/blender/tests/live/stop_presence.py | 125 ++++++--- .../tests/live/stop_presence.result.json | 249 +++++++++++------- surfaces/blender/tests/test_stop_presence.py | 43 ++- 7 files changed, 320 insertions(+), 165 deletions(-) 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 1a4b5d2..5495956 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -355,6 +355,21 @@ class BROKKR_PT_status(bpy.types.Panel): 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}") @@ -431,21 +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.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() layout.label(text="Auto drain error:") @@ -688,16 +688,19 @@ def _auto_drain_commands(): pending_before = adapter.pending_count try: 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, - )) + 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) diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 33a332a..82be6e2 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -228,7 +228,9 @@ class BrokkrBlenderTarget: 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) + 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) diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index c04ad92..0b5917c 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -75,9 +75,12 @@ after `Start Server`. 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. +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 lists the agents active in the last five minutes (distinct `requestedBy` among receipts), +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. diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py index e23f990..a9b176d 100644 --- a/surfaces/blender/tests/live/stop_presence.py +++ b/surfaces/blender/tests/live/stop_presence.py @@ -16,6 +16,7 @@ import os import re import subprocess import sys +import time import traceback from pathlib import Path @@ -50,14 +51,22 @@ def ctl(*args): return done.returncode, done.stdout +SEND = ["send", "createObject", "--set", 'objectType="EMPTY"'] + + def send(name, note): - code, out = ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", f'name="{name}"', - "--note", note, "--no-wait") + 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()} @@ -96,6 +105,8 @@ def panel(): # ---- steps ------------------------------------------------------------------------------------------------- +BURST = 20 + def s_setup(): with win(): @@ -107,16 +118,10 @@ def s_setup(): 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) + S["procs"] = [spawn(f"B{n:02d}", "burst") for n in range(BURST)] def started(): @@ -128,68 +133,103 @@ def s_stop(): 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() - + 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() - 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"] + 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 - 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: 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 were never given an undo label", + 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"] 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) + 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) - S["accepted"], S["stopped"] = accepted, stopped -def s_undo(): +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() - after = len(empties("B")) - check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - after == 1, [before, after]) + 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: 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) + 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) # each receipt listed once + 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_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) + 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() @@ -225,7 +265,7 @@ def write(): # 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. +# is cut in the middle; sends that arrive after it meet a sink that is off. def runner(): global i try: @@ -239,10 +279,14 @@ def runner(): s_stop() i += 1 return 0.005 + if step in ("wait-done", "wait-late"): + if (finished if step == "wait-done" else late_done)(): + i += 1 + return 0.1 step() i += 1 write() - return 0.5 if step is not s_sink_on else 0.005 + return 0.005 if step is s_burst else 0.5 except Exception: R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) write() @@ -250,5 +294,6 @@ def runner(): 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] +steps = [s_setup, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, 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 index 6bbb5cb..bb6f00b 100644 --- a/surfaces/blender/tests/live/stop_presence.result.json +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -5,55 +5,53 @@ { "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, - [] - ] + "detail": "observedAt: 2026-11-27T20:52:54.171327+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" }, { "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" + "detail": "observedAt: 2026-11-27T20:52:54.505375+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", + "name": "stop: every one of the 20 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" + "01a21ec852a07e139e33eba7c8c21251": "accepted", + "01a21ec852b27442b17daac0eef61b81": "accepted", + "01a21ec852b47ae08561010021792ee2": "stopped", + "01a21ec852b77eb393c0f081d680b1d3": "stopped", + "01a21ec852ce78c0b66a2c2ce666f185": "stopped", + "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", + "01a21ec852ce7582bff08d6a81921ee4": "stopped", + "01a21ec852e57a009ad0e186af6f0cfa": "stopped", + "01a21ec852e57cb3859bf2d738ef586a": "stopped", + "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", + "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", + "01a21ec8530772339db47b279044d6f5": "stopped", + "01a21ec853237550b1855dd0f0f27269": "stopped", + "01a21ec853347ac1b822f5d61ae8afcb": "stopped", + "01a21ec853457d418b3bd09272666916": "stopped", + "01a21ec853447c328eac215160e935d8": "stopped", + "01a21ec8535375309be1eec02df779f4": "stopped", + "01a21ec853577ba393761e10d99a14d5": "stopped", + "01a21ec853617913965abb873a2228b9": "stopped", + "01a21ec853617d41884613d8831720fe": "stopped" } }, { - "name": "stop: the queue is empty and the sink is off", + "name": "stop: the queue is empty, the sink is off, Pending read 0 the moment Stop returned", "ok": true, "detail": [ [], - "{'FINISHED'}" + "{'FINISHED'}", + 0 ] }, { - "name": "stop: exactly the accepted intents ran, in key order, and the stopped ones left no object", + "name": "stop: exactly the accepted intents ran and the stopped ones left no object", "ok": true, "detail": [ - [ - "B00", - "B01" - ], + 2, 2 ] }, @@ -61,15 +59,15 @@ "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" + "Brokkr nibu/hands: createObject c8c21251", + "Brokkr nibu/hands: createObject eef61b81" ] }, { - "name": "stop: stopped receipts say who, what and why, and were never given an undo label", + "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 not run and nothing was changed." + "Stopped (stopped by the operator); the intent was " ] }, { @@ -89,7 +87,25 @@ { "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" + "detail": "observedAt: 2026-11-27T20:52:55.144050+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.6096086502075195, + "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+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", @@ -100,9 +116,9 @@ ] }, { - "name": "panel mid-burst: the agent is active, intents are pending, accepted receipts show note and undo label", + "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": "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" + "detail": "Agents\nAgent commands: on\nActive: nibu/hands\nPending: 18\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject eef61b81\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject c8c21251\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\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" }, { "name": "panel after Stop: Stop agents is the first operator drawn", @@ -116,12 +132,12 @@ { "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" + "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: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\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: 4\nMaterials: 2\nSelected: 1" }, { - "name": "server stop: three intents queued behind a running server, sink off", + "name": "server stop: three intents queued behind a running server, sink on", "ok": true, - "detail": null + "detail": 3 }, { "name": "server stop: the same path gives each a stopped receipt naming 'server stopped'", @@ -151,115 +167,149 @@ ], "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" + "01a21ec852a07e139e33eba7c8c21251": "accepted", + "01a21ec852b27442b17daac0eef61b81": "accepted", + "01a21ec852b47ae08561010021792ee2": "stopped", + "01a21ec852b77eb393c0f081d680b1d3": "stopped", + "01a21ec852ce78c0b66a2c2ce666f185": "stopped", + "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", + "01a21ec852ce7582bff08d6a81921ee4": "stopped", + "01a21ec852e57a009ad0e186af6f0cfa": "stopped", + "01a21ec852e57cb3859bf2d738ef586a": "stopped", + "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", + "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", + "01a21ec8530772339db47b279044d6f5": "stopped", + "01a21ec853237550b1855dd0f0f27269": "stopped", + "01a21ec853347ac1b822f5d61ae8afcb": "stopped", + "01a21ec853457d418b3bd09272666916": "stopped", + "01a21ec853447c328eac215160e935d8": "stopped", + "01a21ec8535375309be1eec02df779f4": "stopped", + "01a21ec853577ba393761e10d99a14d5": "stopped", + "01a21ec853617913965abb873a2228b9": "stopped", + "01a21ec853617d41884613d8831720fe": "stopped" }, - "at_stop_receipted": 2, + "stop_reasons": [ + "Stopped (stopped by the operator); the intent wa" + ], "wait_exits": { - "01a21eba859d7b21aa7e23791e640a17": [ + "01a21ec852a07e139e33eba7c8c21251": [ "accepted", 0 ], - "01a21eba85d175a083c1e8e542bbed1d": [ + "01a21ec852b27442b17daac0eef61b81": [ "accepted", 0 ], - "01a21eba860f74f1b73c707054d48792": [ + "01a21ec852b47ae08561010021792ee2": [ "stopped", 3 ], - "01a21eba864b7881ba64c540fc461d4d": [ + "01a21ec852b77eb393c0f081d680b1d3": [ "stopped", 3 ], - "01a21eba86a97292a71e1ca6d8acb2d8": [ + "01a21ec852ce78c0b66a2c2ce666f185": [ "stopped", 3 ], - "01a21eba86f2722093b458840f45af3a": [ + "01a21ec852cd7d30b8ec875ee4a9272e": [ "stopped", 3 ], - "01a21eba87577fc1b50a0de908986e13": [ + "01a21ec852ce7582bff08d6a81921ee4": [ "stopped", 3 ], - "01a21eba87b87f919b2dfac978be3b57": [ + "01a21ec852e57a009ad0e186af6f0cfa": [ "stopped", 3 ], - "01a21eba881c7a9286a621369083ac7b": [ + "01a21ec852e57cb3859bf2d738ef586a": [ "stopped", 3 ], - "01a21eba886a7833ae7ff3224cdc4e29": [ + "01a21ec852ec72c0bfd939a5bb39fde3": [ "stopped", 3 ], - "01a21eba88d978f3b5db769bb462f99b": [ + "01a21ec852ec78c28d7e16c9edc4cc07": [ "stopped", 3 ], - "01a21eba897772009d540695cd6453cc": [ + "01a21ec8530772339db47b279044d6f5": [ + "stopped", + 3 + ], + "01a21ec853237550b1855dd0f0f27269": [ + "stopped", + 3 + ], + "01a21ec853347ac1b822f5d61ae8afcb": [ + "stopped", + 3 + ], + "01a21ec853457d418b3bd09272666916": [ + "stopped", + 3 + ], + "01a21ec853447c328eac215160e935d8": [ + "stopped", + 3 + ], + "01a21ec8535375309be1eec02df779f4": [ + "stopped", + 3 + ], + "01a21ec853577ba393761e10d99a14d5": [ + "stopped", + 3 + ], + "01a21ec853617913965abb873a2228b9": [ + "stopped", + 3 + ], + "01a21ec853617d41884613d8831720fe": [ "stopped", 3 ] }, + "late": { + "exit": 3, + "seconds": 0.61, + "out": "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+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 eef61b81", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject c8c21251", "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", + "Server: cultnet://127.0.0.1:55445", + "Bind: 127.0.0.1:55445", "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" + "Selected: 1" ], "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", + " late", "nibu/hands createObject stopped", " burst", "nibu/hands createObject stopped", @@ -273,7 +323,20 @@ "nibu/hands createObject stopped", " burst", "nibu/hands createObject stopped", - " burst" + " burst", + "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:55445", + "Bind: 127.0.0.1:55445", + "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: 4", + "Materials: 2", + "Selected: 1" ] }, "ok": true diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 6e77f68..1126a2a 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -195,6 +195,24 @@ class PresenceTests(StopFixture): 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) @@ -259,6 +277,11 @@ class PanelAndOperatorTests(unittest.TestCase): 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) @@ -279,10 +302,13 @@ class TimerTests(unittest.TestCase): 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.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: 0 + 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 @@ -294,11 +320,22 @@ class TimerTests(unittest.TestCase): self.ran = 0 self.assertEqual(addon._auto_drain_commands(), 1.0) - def test_with_the_sink_off_the_timer_runs_nothing(self): + 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_off_and_no_node_open_the_timer_opens_nothing(self): + self.prefs.auto_drain_commands = False + self.target._node = None + addon._auto_drain_commands() + self.assertEqual((self.stops, self.drains, self.counts), ([], [], [])) class NoPreferenceWritesTests(unittest.TestCase): -- 2.47.3 From 6c2da2f5343c9af4fc279880efdf4a1c5af0f71e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:04:33 +0100 Subject: [PATCH 4/4] Stop: the timer opens the node when the sink is on or a store already exists; an idle session makes no store Soul s2 node-gate-unpinned-sink-on: in a default install nothing opened the node, so the sink-on drain never started and a sink-off send got no answer. Live harness now starts from a default install with no snapshot published, and a second Blender on the same store proves the sink-off, node-closed answer. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_bridge/__init__.py | 4 +- .../blender/brokkr_bridge/blender_target.py | 3 + .../live/stop_presence.closed.result.json | 28 +++ surfaces/blender/tests/live/stop_presence.py | 60 ++++-- .../tests/live/stop_presence.result.json | 172 ++++++++++-------- surfaces/blender/tests/test_stop_presence.py | 25 ++- 6 files changed, 198 insertions(+), 94 deletions(-) create mode 100644 surfaces/blender/tests/live/stop_presence.closed.result.json diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index 5495956..4926385 100644 --- a/surfaces/blender/brokkr_bridge/__init__.py +++ b/surfaces/blender/brokkr_bridge/__init__.py @@ -687,7 +687,9 @@ def _auto_drain_commands(): ran = 0 pending_before = adapter.pending_count try: - if adapter.node_open: + # 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( diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 82be6e2..363e017 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -265,6 +265,9 @@ class BrokkrBlenderTarget: 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 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 index a9b176d..b1889f8 100644 --- a/surfaces/blender/tests/live/stop_presence.py +++ b/surfaces/blender/tests/live/stop_presence.py @@ -5,6 +5,7 @@ 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. @@ -109,18 +110,30 @@ 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.start_server() - bpy.ops.brokkr.capture_snapshot() + bpy.ops.brokkr.capture_snapshot() # she presses Capture, so brokkr-ctl status has a snapshot to read 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) + check("the stored snapshot says agentCommandsEnabled: true", code == 0 and "agentCommandsEnabled: true" in out, out) def s_burst(): - 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) S["procs"] = [spawn(f"B{n:02d}", "burst") for n in range(BURST)] @@ -227,6 +240,11 @@ def s_panel(): 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())) @@ -279,8 +297,11 @@ def runner(): s_stop() i += 1 return 0.005 - if step in ("wait-done", "wait-late"): - if (finished if step == "wait-done" else late_done)(): + 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() @@ -294,6 +315,23 @@ def runner(): return None -steps = [s_setup, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, s_panel, - s_server_stop, s_server_start, s_final] +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 index bb6f00b..ab9f8ee 100644 --- a/surfaces/blender/tests/live/stop_presence.result.json +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -3,39 +3,55 @@ "module": "bl_ext.user_default.brokkr_bridge", "checks": [ { - "name": "setup: server up, sink off, brokkr-ctl status shows agentCommandsEnabled: false", + "name": "setup: default install, no node open and no store file", "ok": true, - "detail": "observedAt: 2026-11-27T20:52:54.171327+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: false\n" + "detail": [ + false, + false + ] }, { - "name": "sink on: the stored snapshot follows the toggle (agentCommandsEnabled: true)", + "name": "idle: with the sink off and no store, the timer has still opened no node and made no store", "ok": true, - "detail": "observedAt: 2026-11-27T20:52:54.505375+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" + "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": { - "01a21ec852a07e139e33eba7c8c21251": "accepted", - "01a21ec852b27442b17daac0eef61b81": "accepted", - "01a21ec852b47ae08561010021792ee2": "stopped", - "01a21ec852b77eb393c0f081d680b1d3": "stopped", - "01a21ec852ce78c0b66a2c2ce666f185": "stopped", - "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", - "01a21ec852ce7582bff08d6a81921ee4": "stopped", - "01a21ec852e57a009ad0e186af6f0cfa": "stopped", - "01a21ec852e57cb3859bf2d738ef586a": "stopped", - "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", - "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", - "01a21ec8530772339db47b279044d6f5": "stopped", - "01a21ec853237550b1855dd0f0f27269": "stopped", - "01a21ec853347ac1b822f5d61ae8afcb": "stopped", - "01a21ec853457d418b3bd09272666916": "stopped", - "01a21ec853447c328eac215160e935d8": "stopped", - "01a21ec8535375309be1eec02df779f4": "stopped", - "01a21ec853577ba393761e10d99a14d5": "stopped", - "01a21ec853617913965abb873a2228b9": "stopped", - "01a21ec853617d41884613d8831720fe": "stopped" + "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" } }, { @@ -59,8 +75,8 @@ "name": "stop: each accepted intent is one labelled undo step the receipt names", "ok": true, "detail": [ - "Brokkr nibu/hands: createObject c8c21251", - "Brokkr nibu/hands: createObject eef61b81" + "Brokkr nibu/hands: createObject 0116e4e8", + "Brokkr nibu/hands: createObject e58a845e" ] }, { @@ -87,15 +103,15 @@ { "name": "stop: brokkr-ctl status now reads agentCommandsEnabled: false", "ok": true, - "detail": "observedAt: 2026-11-27T20:52:55.144050+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + "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.6096086502075195, - "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + 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" ] }, { @@ -118,7 +134,7 @@ { "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 eef61b81\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject c8c21251\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\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" + "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", @@ -132,7 +148,7 @@ { "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: cultnet://127.0.0.1:55445\nBind: 127.0.0.1:55445\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: 4\nMaterials: 2\nSelected: 1" + "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", @@ -167,108 +183,108 @@ ], "notes": { "states": { - "01a21ec852a07e139e33eba7c8c21251": "accepted", - "01a21ec852b27442b17daac0eef61b81": "accepted", - "01a21ec852b47ae08561010021792ee2": "stopped", - "01a21ec852b77eb393c0f081d680b1d3": "stopped", - "01a21ec852ce78c0b66a2c2ce666f185": "stopped", - "01a21ec852cd7d30b8ec875ee4a9272e": "stopped", - "01a21ec852ce7582bff08d6a81921ee4": "stopped", - "01a21ec852e57a009ad0e186af6f0cfa": "stopped", - "01a21ec852e57cb3859bf2d738ef586a": "stopped", - "01a21ec852ec72c0bfd939a5bb39fde3": "stopped", - "01a21ec852ec78c28d7e16c9edc4cc07": "stopped", - "01a21ec8530772339db47b279044d6f5": "stopped", - "01a21ec853237550b1855dd0f0f27269": "stopped", - "01a21ec853347ac1b822f5d61ae8afcb": "stopped", - "01a21ec853457d418b3bd09272666916": "stopped", - "01a21ec853447c328eac215160e935d8": "stopped", - "01a21ec8535375309be1eec02df779f4": "stopped", - "01a21ec853577ba393761e10d99a14d5": "stopped", - "01a21ec853617913965abb873a2228b9": "stopped", - "01a21ec853617d41884613d8831720fe": "stopped" + "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": { - "01a21ec852a07e139e33eba7c8c21251": [ + "01a21ed27e2e74e1b8e725800116e4e8": [ "accepted", 0 ], - "01a21ec852b27442b17daac0eef61b81": [ + "01a21ed27e347fc1a9335eece58a845e": [ "accepted", 0 ], - "01a21ec852b47ae08561010021792ee2": [ + "01a21ed27e51773392985e0e1859abec": [ "stopped", 3 ], - "01a21ec852b77eb393c0f081d680b1d3": [ + "01a21ed27e6d7b53a39ad7e8d7316c8b": [ "stopped", 3 ], - "01a21ec852ce78c0b66a2c2ce666f185": [ + "01a21ed27e6f78c1a05ed37723e2b309": [ "stopped", 3 ], - "01a21ec852cd7d30b8ec875ee4a9272e": [ + "01a21ed27e6d76f1bb533bed0a748a13": [ "stopped", 3 ], - "01a21ec852ce7582bff08d6a81921ee4": [ + "01a21ed27e6d7c1092c429ea773c8fc1": [ "stopped", 3 ], - "01a21ec852e57a009ad0e186af6f0cfa": [ + "01a21ed27e6f7d33a2055b67edc92f18": [ "stopped", 3 ], - "01a21ec852e57cb3859bf2d738ef586a": [ + "01a21ed27e8272e195d68ac7f7fdf699": [ "stopped", 3 ], - "01a21ec852ec72c0bfd939a5bb39fde3": [ + "01a21ed27e897ba19eba4c3b3093126d": [ "stopped", 3 ], - "01a21ec852ec78c28d7e16c9edc4cc07": [ + "01a21ed27e9379e3831640c51caf5f7a": [ "stopped", 3 ], - "01a21ec8530772339db47b279044d6f5": [ + "01a21ed27ea270008ef42324ca91b333": [ "stopped", 3 ], - "01a21ec853237550b1855dd0f0f27269": [ + "01a21ed27e9472d3930a123edde8b2fd": [ "stopped", 3 ], - "01a21ec853347ac1b822f5d61ae8afcb": [ + "01a21ed27ed57222bce4b3537264e29c": [ "stopped", 3 ], - "01a21ec853457d418b3bd09272666916": [ + "01a21ed27ea674d1bb4f93ccf3f84df2": [ "stopped", 3 ], - "01a21ec853447c328eac215160e935d8": [ + "01a21ed27ed07ea180078e4a1d81fc24": [ "stopped", 3 ], - "01a21ec8535375309be1eec02df779f4": [ + "01a21ed27eb37ea3ac2277d337e6fad9": [ "stopped", 3 ], - "01a21ec853577ba393761e10d99a14d5": [ + "01a21ed27ed07f63aa4a193a340243bd": [ "stopped", 3 ], - "01a21ec853617913965abb873a2228b9": [ + "01a21ed27ed070408f8bd458009ab441": [ "stopped", 3 ], - "01a21ec853617d41884613d8831720fe": [ + "01a21ed27ed27ba1ae1e97b2320d6264": [ "stopped", 3 ] @@ -276,7 +292,7 @@ "late": { "exit": 3, "seconds": 0.61, - "out": "commandId: 01a21ec8598f754383d402238c3af85d\naction: createObject\ncommandId: 01a21ec8598f754383d402238c3af85d\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T20:52:56.732437+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + "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", @@ -285,17 +301,15 @@ "Pending: 18", "nibu/hands createObject accepted", " burst", - " Brokkr nibu/hands: createObject eef61b81", + " Brokkr nibu/hands: createObject e58a845e", "nibu/hands createObject accepted", " burst", - " Brokkr nibu/hands: createObject c8c21251", + " 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: cultnet://127.0.0.1:55445", - "Bind: 127.0.0.1:55445", - "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Server: stopped", "Object Sync", "Timeline / Cinemachine", "Ad Hoc Sync Var", @@ -328,9 +342,7 @@ "Tool: blender-editor", "Broker: cultmesh://brokkr", "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", - "Server: cultnet://127.0.0.1:55445", - "Bind: 127.0.0.1:55445", - "cultmesh_py loaded from: F:\\aeth-wt\\brokkr-pins-cultlib\\packages\\cultmesh-py\\src\\cultmesh_py\\__init__.py", + "Server: stopped", "Object Sync", "Timeline / Cinemachine", "Ad Hoc Sync Var", diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py index 1126a2a..4583ce0 100644 --- a/surfaces/blender/tests/test_stop_presence.py +++ b/surfaces/blender/tests/test_stop_presence.py @@ -4,6 +4,7 @@ the panel's agent activity is derived from receipts. A fake bpy and a fake node from __future__ import annotations import re +import tempfile import types import unittest import unittest.mock @@ -331,10 +332,30 @@ class TimerTests(unittest.TestCase): self.assertEqual(self.drains, []) self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) - def test_with_the_sink_off_and_no_node_open_the_timer_opens_nothing(self): + 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 - addon._auto_drain_commands() + 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), ([], [], [])) -- 2.47.3