diff --git a/Cargo.lock b/Cargo.lock index 6736cc7..1c9d7f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,15 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -29,6 +38,28 @@ version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "brokkr-ctl" +version = "0.1.0" +dependencies = [ + "anyhow", + "cultcache-rs", + "rmp-serde", + "serde_json", + "tempfile", + "uuid", + "windows-sys 0.61.2", +] + [[package]] name = "brokkr-daemon" version = "0.1.0" @@ -83,10 +114,29 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cultcache-rs" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=c2a9a6e526390808ef195759056fda0b9a55d8a3#c2a9a6e526390808ef195759056fda0b9a55d8a3" +version = "0.3.1" +source = "git+https://github.com/GameCult/CultLib.git?rev=9fc4bdda6a8620f846b58e89ddf476f4676d3e89#9fc4bdda6a8620f846b58e89ddf476f4676d3e89" dependencies = [ "anyhow", "chrono", @@ -97,20 +147,33 @@ dependencies = [ "serde", "serde_bytes", "serde_json", + "serde_stacker", + "sha2", + "stacker", "uuid", "windows-sys 0.59.0", ] [[package]] name = "cultcache-rs-derive" -version = "0.1.0" -source = "git+https://github.com/GameCult/CultLib.git?rev=c2a9a6e526390808ef195759056fda0b9a55d8a3#c2a9a6e526390808ef195759056fda0b9a55d8a3" +version = "0.2.0" +source = "git+https://github.com/GameCult/CultLib.git?rev=9fc4bdda6a8620f846b58e89ddf476f4676d3e89#9fc4bdda6a8620f846b58e89ddf476f4676d3e89" dependencies = [ "proc-macro2", "quote", "syn", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -179,6 +242,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.4.2" @@ -311,6 +384,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -342,6 +424,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quote" version = "1.0.45" @@ -463,6 +555,28 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_stacker" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a" +dependencies = [ + "serde", + "serde_core", + "stacker", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -475,6 +589,19 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "syn" version = "2.0.117" @@ -499,6 +626,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -522,6 +655,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12" diff --git a/Cargo.toml b/Cargo.toml index 37f910c..5645f78 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,10 @@ [workspace] resolver = "2" members = [ - "brokkr-daemon" + "brokkr-daemon", + "brokkr-ctl", ] +[workspace.dependencies] +cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "9fc4bdda6a8620f846b58e89ddf476f4676d3e89", package = "cultcache-rs" } + diff --git a/Directory.Build.props b/Directory.Build.props index c8a3c67..0b65fe5 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,8 +2,8 @@ $(CULTLIB_ROOT) $(MSBuildThisFileDirectory)..\CultLib - - 42dce3611a81adc5c5fac54cadbaa5637d6022d3 + + 9fc4bdda6a8620f846b58e89ddf476f4676d3e89 C:\Program Files\Git\cmd\git.exe git diff --git a/Directory.Build.targets b/Directory.Build.targets index 46d436a..624e78a 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,6 +1,6 @@ + worktree of that revision: git worktree add , detached (in CultLib). --> @@ -17,7 +17,7 @@ + Text="CultLib must be revision $(CultLibRevision); found $([System.String]::Copy($(ActualCultLibRevision)).Trim()). Set CultLibRoot to a clean worktree of that revision." /> - cache.TryGet(new CultRecordKey("unity/host/current"), out BrokkrHostSnapshot? host) ? host : null; + private static BrokkrHostSnapshot? ReadHostSnapshot(CultCache cache) + { + if (!cache.TryGet(new CultRecordKey("unity/host/current"), out BrokkrHostSnapshot? host)) return null; + host.RefuseDefaultLists(); + return host; + } private static Dictionary Parse(string[] args) { diff --git a/brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs b/brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs new file mode 100644 index 0000000..4a7fc06 --- /dev/null +++ b/brokkr-contracts.Tests/BrokkrHostSnapshotTests.cs @@ -0,0 +1,60 @@ +using System.Collections.Immutable; +using GameCult.Brokkr; +using MessagePack; + +namespace Brokkr.Contracts.Tests; + +public sealed class BrokkrHostSnapshotTests +{ + // Captured before the lists became ImmutableArray holders: the record payload must not change. + private const string PayloadHex = + "DC0013D92567616D6563756C742E62726F6B6B722E746F6F6C5F686F73745F736E617073686F742E7630B362726F6B6B722E756E6974795F656469746F72AC756E6974792D656469746F72A170A174A0A0A000900090919EA16FA0A0A0C2A00000A09195A163A0A0C29195A178A0A0A131C2A0A0A0909196A161A0A0C2C2A0C2C2C2C2C2"; + + private static BrokkrHostSnapshot Populated() => new() + { + projectPath = "p", + observedAt = "t", + sceneObjects = ImmutableArray.Create(new BrokkrGameObjectSnapshot + { + objectId = "o", + components = ImmutableArray.Create(new BrokkrComponentSnapshot + { + componentId = "c", + properties = ImmutableArray.Create(new BrokkrSerializedPropertySnapshot { path = "x", value = "1" }) + }) + }), + assets = ImmutableArray.Create(new BrokkrAssetSnapshot { path = "a" }) + }; + + [Fact] + public void ListsAreWholeValuesWithTheSameBytesAsArrays() => + Assert.Equal(PayloadHex, Convert.ToHexString(MessagePackSerializer.Serialize(Populated()))); + + [Fact] + public void PopulatedSnapshotIsAccepted() => Populated().RefuseDefaultLists(); + + [Theory] + [InlineData(12)] + [InlineData(13)] + public void NilListsDecodeToDefaultAndAreRefused(int key) + { + var fields = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(Populated())); + fields[key] = null; + var snapshot = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(fields)); + + var error = Assert.Throws(snapshot.RefuseDefaultLists); + Assert.Contains("default", error.Message); + } + + [Fact] + public void DefaultNestedListsAreRefused() + { + var snapshot = Populated(); + snapshot.sceneObjects[0].components = default; + Assert.Throws(snapshot.RefuseDefaultLists); + + snapshot = Populated(); + snapshot.sceneObjects[0].components[0].properties = default; + Assert.Throws(snapshot.RefuseDefaultLists); + } +} diff --git a/brokkr-contracts.Tests/EditorProbe.cs b/brokkr-contracts.Tests/EditorProbe.cs index 1445697..45fb41e 100644 --- a/brokkr-contracts.Tests/EditorProbe.cs +++ b/brokkr-contracts.Tests/EditorProbe.cs @@ -9,7 +9,7 @@ namespace Brokkr.Contracts.Tests; // The scenario harness: an editor without Unity. It opens the store exactly as BrokkrCultMeshMirror does (a CultMesh // node with StartServer=false over a directory store, no shard log) and runs one service tick in the // service order: pull, drain pending intents through BrokkrCommandDrain (the same class the service uses), host -// snapshot, soft flush. "Executing" an intent only records it, so the scenarios measure delivery and once-only +// snapshot, flush. "Executing" an intent only records it, so the scenarios measure delivery and once-only // execution, not Unity. It is also a thin IBrokkrCommandStore in front of the real BrokkrCommandStore, with knobs to // make writes fail and to land a writer between the enable's pull and its commit. internal sealed class EditorProbe : IDisposable, IBrokkrCommandStore @@ -132,7 +132,7 @@ internal sealed class EditorProbe : IDisposable, IBrokkrCommandStore projectPath = "probe", agentCommandsEnabled = AgentCommandsEnabled }); - await node.FlushAsync(soft: true); + await node.FlushAsync(); return handled; } diff --git a/brokkr-ctl/Cargo.toml b/brokkr-ctl/Cargo.toml new file mode 100644 index 0000000..b74147e --- /dev/null +++ b/brokkr-ctl/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "brokkr-ctl" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +anyhow = "1" +cultcache-rs = { workspace = true } +rmp-serde = "1.3" +serde_json = "1" +uuid = { version = "1", features = ["v7"] } + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] } + +[dev-dependencies] +tempfile = "3" diff --git a/brokkr-ctl/src/actions.rs b/brokkr-ctl/src/actions.rs new file mode 100644 index 0000000..40a3d40 --- /dev/null +++ b/brokkr-ctl/src/actions.rs @@ -0,0 +1,505 @@ +//! The Blender action table, embedded: `send --help` is built from it and `send` refuses an intent it +//! refuses. The owner is the add-on's `actions.json` (schema brokkr.blender.actions.v0); this module reads +//! it as data and implements the same vocabulary and message text as `action_table.py`, pinned to it by +//! the shared fixture `surfaces/blender/tests/action_cases.json`. Anything that reaches the store is still +//! decided by the add-on. Host add-ons' rows (`brokkr.blender.host_actions.v0`) are not embedded: they come +//! from the add-on's host snapshot (`hostActions`), are searched after the built-ins, and are pinned by +//! `surfaces/blender/tests/host_action_cases.json`; a stale snapshot can only make ctl refuse early. + +use serde_json::{Map, Value}; +use std::sync::LazyLock; + +const TABLE_JSON: &str = include_str!("../../surfaces/blender/brokkr_bridge/actions.json"); + +static TABLE: LazyLock = + LazyLock::new(|| serde_json::from_str(TABLE_JSON).expect("actions.json is valid JSON")); + +pub fn table() -> &'static Value { + &TABLE +} + +fn actions() -> &'static [Value] { + table()["actions"].as_array().map_or(&[], Vec::as_slice) +} + +/// The built-in row of that name, else the first host row of that name. +fn entry<'a>(name: &str, host: &'a [Value]) -> Option<&'a Value> { + actions() + .iter() + .chain(host) + .find(|a| a["name"] == name) +} + +/// The names brokkr-ctl writes itself: `--set` cannot name them, and the table does not validate them. +pub fn envelope() -> Vec<&'static str> { + table()["envelope"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect() +} + +fn type_words(kind: &str) -> &'static str { + match kind { + "string" => "a string", + "number" => "a finite number", + "integer" => "a whole number", + "boolean" => "true or false", + "array" => "an array", + "object" => "an object", + _ => "a value", + } +} + +fn join(items: &Value) -> String { + items + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect::>() + .join(", ") +} + +/// A bound as messages and help print it: whole values without a fraction, others as the shortest digits. +pub fn number_text(value: f64) -> String { + if value == value.trunc() { + format!("{}", value as i128) + } else { + format!("{value}") + } +} + +/// Refuses an intent the table refuses, with the add-on's message; nothing is normalized (the add-on fills defaults). +pub fn validate(command: &Map, host: &[Value]) -> Result<(), String> { + let action = command.get("action").and_then(Value::as_str).unwrap_or(""); + let Some(row) = entry(action, host) else { + return Err(format!("Unsupported Blender command action: {action}")); + }; + let present: Map = command + .iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + fields( + row["fields"].as_array().map_or(&[], Vec::as_slice), + &present, + None, + action, + &envelope(), + ) +} + +fn fields( + specs: &[Value], + values: &Map, + parent: Option<&str>, + whole: &str, + skip: &[&str], +) -> Result<(), String> { + let declared: Vec<&str> = specs.iter().filter_map(|s| s["name"].as_str()).collect(); + let mut unknown: Vec<&String> = values + .keys() + .filter(|k| !skip.contains(&k.as_str()) && !declared.contains(&k.as_str())) + .collect(); + unknown.sort(); + if let Some(key) = unknown.first() { + let listed = if declared.is_empty() { + "none".to_string() + } else { + declared.join(", ") + }; + return Err(format!( + "{whole} has no field '{key}'; its fields: {listed}." + )); + } + for spec in specs { + let name = spec["name"].as_str().unwrap_or(""); + let path = parent.map_or_else(|| name.to_string(), |p| format!("{p}.{name}")); + let Some(value) = values.get(name) else { + if spec["required"] == true { + return Err(format!("{path} is required.")); + } + continue; + }; + if let Some(only) = spec.get("only") { + let sibling = only["field"].as_str().and_then(|f| values.get(f)); + let allowed = only["in"].as_array().map_or(&[][..], Vec::as_slice); + if !sibling.is_some_and(|v| allowed.contains(v)) { + return Err(format!( + "{path} applies only when {} is one of {}.", + only["field"].as_str().unwrap_or(""), + join(&only["in"]) + )); + } + } + check_value(spec, value, &path)?; + } + Ok(()) +} + +fn check_value(spec: &Value, value: &Value, path: &str) -> Result<(), String> { + let kind = spec["type"].as_str().unwrap_or(""); + match kind { + "any" => {} + "number" | "integer" => check_number(spec, value, path, kind)?, + "string" => { + let Some(text) = value.as_str() else { + return Err(format!("{path} must be {}.", type_words(kind))); + }; + if let Some(allowed) = spec.get("enum") { + if !allowed + .as_array() + .is_some_and(|list| list.iter().any(|e| e.as_str() == Some(text))) + { + return Err(format!("{path} must be one of {}.", join(allowed))); + } + } else { + check_string(spec, text, path)?; + } + } + "boolean" => { + if !value.is_boolean() { + return Err(format!("{path} must be {}.", type_words(kind))); + } + } + "array" => { + let Some(items) = value.as_array() else { + return Err(format!("{path} must be {}.", type_words(kind))); + }; + if spec["minItems"] + .as_u64() + .is_some_and(|n| (items.len() as u64) < n) + { + return Err(format!( + "{path} must have at least {} items.", + spec["minItems"] + )); + } + if spec["maxItems"] + .as_u64() + .is_some_and(|n| (items.len() as u64) > n) + { + return Err(format!( + "{path} must have at most {} items.", + spec["maxItems"] + )); + } + let item_spec = &spec["items"]; + for (index, item) in items.iter().enumerate() { + if item.is_null() { + return Err(format!( + "{path}[{index}] must be {}.", + type_words(item_spec["type"].as_str().unwrap_or("")) + )); + } + check_value(item_spec, item, &format!("{path}[{index}]"))?; + } + } + "object" => { + let Some(map) = value.as_object() else { + return Err(format!("{path} must be {}.", type_words(kind))); + }; + if let Some(properties) = spec["properties"].as_array() { + let present: Map = map + .iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + fields(properties, &present, Some(path), path, &[])?; + } + } + _ => {} + } + Ok(()) +} + +fn check_number(spec: &Value, value: &Value, path: &str, kind: &str) -> Result<(), String> { + let wrong = || format!("{path} must be {}.", type_words(kind)); + let Value::Number(number) = value else { + return Err(wrong()); + }; + let x = number + .as_f64() + .filter(|x| x.is_finite()) + .ok_or_else(wrong)?; + if kind == "integer" && !(number.is_i64() || number.is_u64() || x == x.trunc()) { + return Err(wrong()); + } + let (min, max) = ( + spec["minimum"].as_f64().unwrap_or(f64::MIN), + spec["maximum"].as_f64().unwrap_or(f64::MAX), + ); + if x < min || x > max { + return Err(format!( + "{path} must be between {} and {}.", + number_text(min), + number_text(max) + )); + } + Ok(()) +} + +fn check_string(spec: &Value, text: &str, path: &str) -> Result<(), String> { + let length = text.chars().count() as u64; + if spec["minLength"].as_u64().is_some_and(|n| length < n) { + return Err(format!( + "{path} must have at least {} characters.", + spec["minLength"] + )); + } + if spec["maxLength"].as_u64().is_some_and(|n| length > n) { + return Err(format!( + "{path} must have at most {} characters.", + spec["maxLength"] + )); + } + if let Some(name) = spec["chars"].as_str() { + let set = &table()["charsets"][name]; + let allowed = set["allowed"].as_str().unwrap_or(""); + if text.chars().any(|c| !allowed.contains(c)) { + return Err(format!( + "{path} may contain only {}.", + set["text"].as_str().unwrap_or("") + )); + } + } + if let Some(prefixes) = spec["prefixes"].as_array() { + let fits = prefixes + .iter() + .filter_map(Value::as_str) + .any(|p| text.starts_with(p) && text.chars().count() > p.chars().count()); + if !fits { + return Err(format!( + "{path} must start with one of {} and have at least one more character.", + join(&spec["prefixes"]) + )); + } + } + for part in spec["forbid"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if text.contains(part) { + return Err(format!("{path} may not contain '{part}'.")); + } + } + Ok(()) +} + +/// The actions section of `send --help`: every action with its fields, built from the table. +pub fn help() -> String { + help_rows(actions()) +} + +/// The help body for any rows: the built-ins, or the host rows a snapshot carries. +pub fn help_rows(rows: &[Value]) -> String { + let mut text = String::new(); + for action in rows { + text.push_str(&format!( + " {}: {}\n", + action["name"].as_str().unwrap_or(""), + action["doc"].as_str().unwrap_or("") + )); + field_lines( + &mut text, + action["fields"].as_array().map_or(&[], Vec::as_slice), + 6, + ); + } + text +} + +fn field_lines(text: &mut String, specs: &[Value], indent: usize) { + for spec in specs { + let mut line = format!( + "{}{}: {}", + " ".repeat(indent), + spec["name"].as_str().unwrap_or(""), + describe(spec) + ); + if spec["required"] == true { + line.push_str(", required"); + } + if let Some(default) = spec.get("default") { + line.push_str(&format!(", default {default}")); + } + if let Some(only) = spec.get("only") { + line.push_str(&format!( + ", only when {} is {}", + only["field"].as_str().unwrap_or(""), + join(&only["in"]).replace(", ", "|") + )); + } + if let Some(doc) = spec["doc"].as_str() { + line.push_str(&format!(" ({doc})")); + } + text.push_str(&line); + text.push('\n'); + if let Some(properties) = spec["items"]["properties"].as_array() { + field_lines(text, properties, indent + 4); + } + } +} + +fn describe(spec: &Value) -> String { + let kind = spec["type"].as_str().unwrap_or(""); + let mut parts = vec![match kind { + "any" => "json".to_string(), + "boolean" => "bool".to_string(), + other => other.to_string(), + }]; + if let Some(values) = spec.get("enum") { + parts.push(join(values).replace(", ", "|")); + } + if let (Some(min), Some(max)) = (spec["minimum"].as_f64(), spec["maximum"].as_f64()) { + parts.push(format!("{}..{}", number_text(min), number_text(max))); + } + if spec.get("minLength").is_some() || spec.get("maxLength").is_some() { + let min = spec["minLength"].as_u64().unwrap_or(0); + parts.push(match spec["maxLength"].as_u64() { + Some(max) => format!("{min}..{max} characters"), + None => format!("at least {min} characters"), + }); + } + if let Some(name) = spec["chars"].as_str() { + parts.push( + table()["charsets"][name]["text"] + .as_str() + .unwrap_or("") + .to_string(), + ); + } + if spec.get("prefixes").is_some() { + parts.push(format!( + "starts with {}", + join(&spec["prefixes"]).replace(", ", "|") + )); + } + if spec.get("forbid").is_some() { + parts.push(format!( + "without {}", + join(&spec["forbid"]).replace(", ", "|") + )); + } + if kind == "array" { + let (min, max) = (spec["minItems"].as_u64(), spec["maxItems"].as_u64()); + let count = match (min, max) { + (Some(a), Some(b)) if a == b => format!("{a} items"), + (Some(a), Some(b)) => format!("{a}..{b} items"), + (Some(a), None) => format!("at least {a} items"), + (None, Some(b)) => format!("at most {b} items"), + (None, None) => String::new(), + }; + parts.push(format!("[{}]", describe(&spec["items"]))); + if !count.is_empty() { + parts.push(count); + } + } + parts.join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The same cases the add-on's test_action_table runs through action_table.py: one table, two + /// interpreters, one set of messages. + #[test] + fn the_parity_fixture_yields_the_add_ons_messages() { + let cases: Vec = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/action_cases.json" + )) + .unwrap(); + assert!(cases.len() > 200, "{} cases", cases.len()); + let mut wrong = Vec::new(); + for case in &cases { + let mut command = case["fields"].as_object().unwrap().clone(); + command.insert("action".into(), case["action"].clone()); + let got = validate(&command, &[]).err().unwrap_or_else(|| "ok".to_string()); + if Some(got.as_str()) != case["expect"].as_str() { + wrong.push(format!( + "{} {} expected {} got {got}", + case["action"], case["fields"], case["expect"] + )); + } + } + assert!( + wrong.is_empty(), + "{} of {} differ:\n{}", + wrong.len(), + cases.len(), + wrong.join("\n") + ); + } + + /// The host rows a fixture add-on publishes, run through the same validator as the add-on's + /// HostTableTests: one set of messages for host rows too. + #[test] + fn the_host_parity_fixture_yields_the_add_ons_messages() { + let file: Value = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json" + )) + .unwrap(); + let host = file["actions"].as_array().unwrap().clone(); + let cases: Vec = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/host_action_cases.json" + )) + .unwrap(); + assert!(cases.len() >= 15, "{} cases", cases.len()); + let mut wrong = Vec::new(); + for case in &cases { + let mut command = case["fields"].as_object().unwrap().clone(); + command.insert("action".into(), case["action"].clone()); + let got = validate(&command, &host) + .err() + .unwrap_or_else(|| "ok".to_string()); + if Some(got.as_str()) != case["expect"].as_str() { + wrong.push(format!( + "{} {} expected {} got {got}", + case["action"], case["fields"], case["expect"] + )); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); + // Without the snapshot's rows the same host action is unsupported: ctl never invents rows. + let mut command = Map::new(); + command.insert("action".into(), "brokkr_host_fixture.report".into()); + assert_eq!( + validate(&command, &[]).unwrap_err(), + "Unsupported Blender command action: brokkr_host_fixture.report" + ); + } + + #[test] + fn a_non_string_action_is_unsupported_and_the_envelope_is_the_tables() { + let mut command = Map::new(); + command.insert("action".into(), Value::from(3)); + assert_eq!( + validate(&command, &[]).unwrap_err(), + "Unsupported Blender command action: " + ); + assert_eq!( + envelope(), + ["schema", "commandId", "action", "requestedBy", "note"] + ); + } + + #[test] + fn numbers_print_the_way_the_add_on_prints_them() { + for (value, text) in [ + (0.0, "0"), + (4.0, "4"), + (1e7, "10000000"), + (0.001, "0.001"), + (0.0001, "0.0001"), + (1e9, "1000000000"), + (-1e9, "-1000000000"), + ] { + assert_eq!(number_text(value), text); + } + } +} diff --git a/brokkr-ctl/src/blender.rs b/brokkr-ctl/src/blender.rs new file mode 100644 index 0000000..8a604ba --- /dev/null +++ b/brokkr-ctl/src/blender.rs @@ -0,0 +1,569 @@ +//! `brokkr-ctl blender`: a caller of the Blender add-on's store. It writes one intent +//! document per `send` and reads receipts and the host snapshot. The add-on decides. + +use anyhow::{Context, Result, anyhow, bail}; +use crate::actions; +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore}; +use serde_json::{Map, Value}; +use std::path::PathBuf; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +pub const INTENT_SCHEMA: &str = "brokkr.blender.command_intent.v0"; +pub const RECEIPT_SCHEMA: &str = "brokkr.blender.command_receipt.v0"; +pub const SNAPSHOT_SCHEMA: &str = "brokkr.blender.host_snapshot.v0"; +const INTENT_PREFIX: &str = "blender/commands/"; +const RECEIPT_PREFIX: &str = "blender/receipts/"; +const SNAPSHOT_KEY: &str = "blender/host/current"; +const DEFAULT_TIMEOUT_SECS: u64 = 60; +const POLL: Duration = Duration::from_millis(200); +const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600); + +/// What a receipt (or its absence) says; the exit code derives from it and from nothing else. +pub enum Outcome { + Accepted, + Failed, + Stopped, + Timeout, +} + +impl Outcome { + pub fn code(&self) -> i32 { + match self { + Outcome::Accepted => 0, + Outcome::Failed => 2, + Outcome::Stopped => 3, + Outcome::Timeout => 4, + } + } + + pub fn from_status(status: &str) -> Outcome { + match status { + "accepted" => Outcome::Accepted, + "stopped" => Outcome::Stopped, + _ => Outcome::Failed, // denied, failed, and any status this tool does not know + } + } +} + +#[derive(Default)] +struct Options { + store: Option, + agent: Option, + note: String, + sets: Vec, + no_wait: bool, + timeout: Option, + help: bool, + last: Option, + positional: Vec, +} + +fn parse(args: &[String]) -> Result { + let mut options = Options::default(); + let mut iter = args.iter(); + while let Some(arg) = iter.next() { + let mut value = |name: &str| { + iter.next() + .cloned() + .ok_or_else(|| anyhow!("{name} needs a value")) + }; + match arg.as_str() { + "--store" => options.store = Some(PathBuf::from(value("--store")?)), + "--agent" => options.agent = Some(value("--agent")?), + "--note" => options.note = value("--note")?, + "--set" => options.sets.push(value("--set")?), + "--no-wait" => options.no_wait = true, + "--help" | "-h" => options.help = true, + "--timeout" => { + let raw = value("--timeout")?; + let secs: f64 = raw + .parse() + .map_err(|_| anyhow!("--timeout wants seconds, got {raw:?}"))?; + options.timeout = Some( + Duration::try_from_secs_f64(secs) + .ok() + .filter(|limit| *limit <= MAX_TIMEOUT) + .ok_or_else(|| { + anyhow!("--timeout wants seconds between 0 and {}", MAX_TIMEOUT.as_secs()) + })?, + ); + } + "--last" => { + let raw = value("--last")?; + options.last = Some( + raw.parse() + .map_err(|_| anyhow!("--last wants a count, got {raw:?}"))?, + ); + } + flag if flag.starts_with("--") => bail!("unknown option {flag}"), + _ => options.positional.push(arg.clone()), + } + } + Ok(options) +} + +/// Runs one `blender` subcommand and returns the process exit code. +pub fn run(args: &[String]) -> Result { + let Some((sub, rest)) = args.split_first() else { + print!("{}", group_help()); + return Ok(1); + }; + if matches!(sub.as_str(), "--help" | "-h" | "help") { + print!("{}", group_help()); + return Ok(0); + } + let options = parse(rest)?; + if options.help { + print!("{}", if sub == "send" { send_help(&options) } else { group_help() }); + return Ok(0); + } + match sub.as_str() { + "send" => send(&options, one_positional(&options, "send [--set key=json]...")?), + "look" => { + if !options.positional.is_empty() || !options.sets.is_empty() { + bail!("usage: brokkr-ctl blender look [--note text] [--agent name] [--no-wait] [--timeout secs]"); + } + send(&options, "look") + } + "wait" => { + let id = one_positional(&options, "wait ")?; + let store = open_store(&options)?; + wait_for_receipt(&store, id, timeout(&options)) + } + "receipts" => receipts(&open_store(&options)?, options.last), + "status" => status(&open_store(&options)?), + other => bail!("unknown subcommand {other:?}; try `brokkr-ctl blender --help`"), + } +} + +fn one_positional<'a>(options: &'a Options, usage: &str) -> Result<&'a str> { + match options.positional.as_slice() { + [one] => Ok(one), + _ => bail!("usage: brokkr-ctl blender {usage}"), + } +} + +fn timeout(options: &Options) -> Duration { + options.timeout.unwrap_or(Duration::from_secs(DEFAULT_TIMEOUT_SECS)) +} + +/// The add-on creates its store; naming a path that is not there is a typo, not a request +/// to make a second store. +fn open_store(options: &Options) -> Result { + let path = options + .store + .clone() + .or_else(|| std::env::var_os("BROKKR_BLENDER_STORE").map(PathBuf::from)) + .ok_or_else(|| anyhow!("no store: pass --store or set BROKKR_BLENDER_STORE"))?; + // The add-on resolves its store against the blend file; ctl cannot know that, so it takes none. + if !path.is_absolute() { + bail!("store {} must be an absolute path", path.display()); + } + // A staged replace swaps the path itself, which would turn a link into a diverged copy. + let meta = std::fs::symlink_metadata(&path) + .map_err(|_| anyhow!("store {} does not exist; the add-on creates it", path.display()))?; + if meta.file_type().is_symlink() || !meta.is_file() { + bail!("store {} must be the add-on's regular file, not a link", path.display()); + } + // The same swap would leave a second name on the old bytes. + if link_count(&path)? > 1 { + bail!("store {} has more than one hard link; it must be the add-on's only name for the file", path.display()); + } + Ok(SingleFileMessagePackBackingStore::new(path)) +} + +#[cfg(unix)] +fn link_count(path: &std::path::Path) -> Result { + use std::os::unix::fs::MetadataExt; + Ok(std::fs::metadata(path)?.nlink()) +} + +/// std's `number_of_links` is unstable, so ask the handle. +#[cfg(windows)] +fn link_count(path: &std::path::Path) -> Result { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle}; + let file = std::fs::File::open(path)?; + let mut info = std::mem::MaybeUninit::::zeroed(); + // SAFETY: the handle is live for the call and `info` is a writable BY_HANDLE_FILE_INFORMATION. + let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle() as _, info.as_mut_ptr()) }; + if ok == 0 { + return Err(std::io::Error::last_os_error().into()); + } + // SAFETY: the call succeeded, so it filled the struct. + Ok(u64::from(unsafe { info.assume_init() }.nNumberOfLinks)) +} + +fn requested_by(options: &Options) -> Result { + let instance = std::env::var("EUREKA_INSTANCE").unwrap_or_default(); + let agent = options + .agent + .clone() + .or_else(|| std::env::var("BROKKR_AGENT").ok()) + .unwrap_or_default(); + if instance.trim().is_empty() || agent.trim().is_empty() { + bail!("an intent must be attributed: set EUREKA_INSTANCE and pass --agent or set BROKKR_AGENT"); + } + Ok(format!("{}/{}", instance.trim(), agent.trim())) +} + +fn build_intent( + action: &str, + command_id: &str, + requested_by: &str, + note: &str, + sets: &[String], + host: &[Value], +) -> Result { + let mut map = Map::new(); + for set in sets { + let (key, raw) = set + .split_once('=') + .ok_or_else(|| anyhow!("--set wants key=json, got {set:?}"))?; + if key.is_empty() || actions::envelope().contains(&key) { + bail!("--set cannot name {key:?}: it is written by brokkr-ctl"); + } + let value: Value = serde_json::from_str(raw) + .with_context(|| format!("--set {key}: {raw:?} is not JSON (strings need quotes)"))?; + map.insert(key.to_string(), value); + } + map.insert("schema".into(), INTENT_SCHEMA.into()); + map.insert("commandId".into(), command_id.into()); + map.insert("action".into(), action.into()); + map.insert("requestedBy".into(), requested_by.into()); + map.insert("note".into(), note.into()); + actions::validate(&map, host).map_err(|message| anyhow!(message))?; + Ok(Value::Object(map)) +} + +fn send(options: &Options, action: &str) -> Result { + let requested_by = requested_by(options)?; + let mut store = open_store(options)?; + let command_id = uuid::Uuid::now_v7().simple().to_string(); + let (host, _) = host_rows(&store)?; + let intent = build_intent(action, &command_id, &requested_by, &options.note, &options.sets, &host)?; + store.push(&CultCacheEnvelope { + key: format!("{INTENT_PREFIX}{command_id}"), + r#type: INTENT_SCHEMA.to_string(), + payload: rmp_serde::to_vec(&intent)?, + stored_at: iso_now(), + schema_id: Some(INTENT_SCHEMA.to_string()), + })?; + println!("commandId: {command_id}"); + if options.no_wait { + return Ok(0); + } + wait_for_receipt(&store, &command_id, timeout(options)) +} + +fn read_receipt(store: &SingleFileMessagePackBackingStore, id: &str) -> Result> { + let key = format!("{RECEIPT_PREFIX}{id}"); + for envelope in store.pull_all()? { + if envelope.key == key && envelope.r#type == RECEIPT_SCHEMA { + return Ok(Some(decode(&envelope)?)); + } + } + Ok(None) +} + +fn wait_for_receipt( + store: &SingleFileMessagePackBackingStore, + id: &str, + limit: Duration, +) -> Result { + match poll_until(limit, POLL, || read_receipt(store, id))? { + Some(receipt) => { + print_fields(&receipt); + let status = receipt.get("status").and_then(Value::as_str).unwrap_or(""); + Ok(Outcome::from_status(status).code()) + } + None => { + println!("status: timeout"); + // The add-on deletes an intent when it claims it, before it runs, so the queue says which timeout this is. + let key = format!("{INTENT_PREFIX}{id}"); + let queued = store + .pull_all()? + .iter() + .any(|e| e.key == key && e.r#type == INTENT_SCHEMA); + println!( + "message: {}", + if queued { + "the intent is still queued: Blender has not claimed it (is Agent Commands on and the add-on running?); it has not run" + } else { + "Blender claimed the intent but wrote no receipt: it may or may not have run; look at the scene before sending it again" + } + ); + Ok(Outcome::Timeout.code()) + } + } +} + +/// Reads until `read` yields a value or `limit` passes, sleeping `poll` between reads. +fn poll_until( + limit: Duration, + poll: Duration, + mut read: impl FnMut() -> Result>, +) -> Result> { + let started = Instant::now(); + loop { + if let Some(found) = read()? { + return Ok(Some(found)); + } + if started.elapsed() >= limit { + return Ok(None); + } + thread::sleep(poll); + } +} + +fn receipts(store: &SingleFileMessagePackBackingStore, last: Option) -> Result { + let mut found = Vec::new(); + for envelope in store.pull_all()? { + if envelope.key.starts_with(RECEIPT_PREFIX) && envelope.r#type == RECEIPT_SCHEMA { + found.push(decode(&envelope)?); + } + } + found.sort_by_key(|receipt| { + receipt + .get("observedAt") + .and_then(Value::as_str) + .unwrap_or("") + .to_string() + }); + let skip = last.map_or(0, |n| found.len().saturating_sub(n)); + for (index, receipt) in found.iter().skip(skip).enumerate() { + if index > 0 { + println!(); + } + print_fields(receipt); + } + Ok(0) +} + +/// The host snapshot as the add-on last published it, if any. +fn snapshot(store: &SingleFileMessagePackBackingStore) -> Result> { + for envelope in store.pull_all()? { + if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { + return Ok(Some(decode(&envelope)?)); + } + } + Ok(None) +} + +/// The host rows the add-on published and when (`observedAt`); empty before any snapshot. A display and +/// early-refusal copy: the add-on admits or denies the intent itself. +fn host_rows(store: &SingleFileMessagePackBackingStore) -> Result<(Vec, String)> { + let Some(snapshot) = snapshot(store)? else { + return Ok((Vec::new(), String::new())); + }; + let rows = snapshot["hostActions"].as_array().cloned().unwrap_or_default(); + let observed = snapshot["observedAt"].as_str().unwrap_or("").to_string(); + Ok((rows, observed)) +} + +fn status(store: &SingleFileMessagePackBackingStore) -> Result { + for envelope in store.pull_all()? { + if envelope.key == SNAPSHOT_KEY && envelope.r#type == SNAPSHOT_SCHEMA { + let snapshot = decode(&envelope)?; + for key in [ + "observedAt", + "blenderVersion", + "projectPath", + "mode", + "activeScene", + "activeObjectName", + "selectedObjectNames", + "objectCount", + "agentCommandsEnabled", + ] { + if let Some(value) = snapshot.get(key) { + print_field(key, value); + } + } + let names: Vec<&str> = snapshot["hostActions"] + .as_array() + .into_iter() + .flatten() + .filter_map(|row| row["name"].as_str()) + .collect(); + println!("hostActions: {}", names.join(", ")); + for error in snapshot["hostActionErrors"].as_array().into_iter().flatten() { + println!( + "hostActionErrors: {}: {}", + error["host"].as_str().unwrap_or(""), + error["error"].as_str().unwrap_or("") + ); + } + return Ok(0); + } + } + bail!("the store holds no host snapshot yet; is the add-on's server running?") +} + +fn decode(envelope: &CultCacheEnvelope) -> Result { + cultcache_rs::decode_payload::(&envelope.payload) + .with_context(|| format!("{} is not one MessagePack value", envelope.key)) +} + +fn print_fields(value: &Value) { + match value.as_object() { + Some(map) => map.iter().for_each(|(key, value)| print_field(key, value)), + None => println!("value: {value}"), + } +} + +fn print_field(key: &str, value: &Value) { + match value { + Value::String(text) if text.contains('\n') => { + println!("{key}:"); + text.lines().for_each(|line| println!(" {line}")); + } + Value::String(text) => println!("{key}: {text}"), + other => println!("{key}: {other}"), + } +} + +/// UTC, microseconds, `+00:00`: the form the Python node stamps. +fn iso_now() -> String { + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); + iso_from(now.as_secs() as i64, now.subsec_micros()) +} + +fn iso_from(secs: i64, micros: u32) -> String { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + // Howard Hinnant's civil_from_days. + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{micros:06}+00:00", + rem / 3_600, + rem % 3_600 / 60, + rem % 60 + ) +} + +pub fn group_help() -> String { + "\ +brokkr-ctl blender: send typed intents to the live Blender add-on and read what it did. + + send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] + Write one intent, then wait for its receipt and print it. `send --help` lists actions. + look [--note text] [--agent name] [--no-wait] [--timeout secs] + `send look`: capture the 3D view she is looking at. The receipt prints lookPath (a PNG), her + Edit Mode selection, and how many edits she made since this agent last looked. + wait [--timeout secs] Wait for a receipt and print it. + receipts [--last n] Print stored receipts, oldest first. + 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 '/'. +Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout, +1 usage or store error. On timeout a message says whether the intent is still queued (not run) or was claimed by +Blender with no receipt (it may or may not have run). send refuses an intent the action table refuses (exit 1, nothing written); +the add-on decides the rest and its refusal comes back in the receipt. +" + .to_string() +} + +/// `send --help`: the built-ins, then, when a store is named (--store or $BROKKR_BLENDER_STORE), the host +/// rows its snapshot carries. It never fails for lack of a store. +fn send_help(options: &Options) -> String { + let mut text = String::from( + "\ +brokkr-ctl blender send [--set key=json]... [--note text] [--agent name] [--no-wait] [--timeout secs] + +--set takes JSON: --set objectType='\"MESH\"' --set location='[0,0,1]'. brokkr-ctl writes schema, +commandId, action, requestedBy and note itself; --set cannot name them. Below is the add-on's action +table (actions.json): every field an action reads; null means absent; a field not listed is refused. + +actions: +", + ); + text.push_str(&actions::help()); + text.push_str(&host_help(options)); + text +} + +fn host_help(options: &Options) -> String { + let named = options.store.is_some() || std::env::var_os("BROKKR_BLENDER_STORE").is_some(); + if !named { + return "\nhost actions: add --store (or set BROKKR_BLENDER_STORE) to list the actions host add-ons publish.\n" + .to_string(); + } + match open_store(options).and_then(|store| host_rows(&store)) { + Err(error) => format!("\nhost actions: unavailable ({error}).\n"), + Ok((_, observed)) if observed.is_empty() => { + "\nhost actions: the store holds no host snapshot yet.\n".to_string() + } + Ok((rows, observed)) if rows.is_empty() => { + format!("\nhost actions (published by the add-on at {observed}): none.\n") + } + Ok((rows, observed)) => format!( + "\nhost actions (published by the add-on at {observed}):\n{}", + actions::help_rows(&rows) + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn iso_matches_the_python_form() { + assert_eq!(iso_from(0, 0), "1970-01-01T00:00:00.000000+00:00"); + assert_eq!(iso_from(1_795_800_558, 813_099), "2026-11-27T17:29:18.813099+00:00"); + } + + #[test] + fn intent_carries_reserved_fields_and_refuses_overrides() { + let sets = vec!["objectType=\"MESH\"".to_string(), "location=[0,0,1]".to_string()]; + let intent = build_intent("createObject", "abc", "nibu/hands", "n", &sets, &[]).unwrap(); + assert_eq!(intent["requestedBy"], "nibu/hands"); + assert_eq!(intent["objectType"], "MESH"); + assert_eq!(intent["location"][2], 1); + for bad in ["requestedBy=\"x\"", "commandId=\"x\"", "action=\"x\"", "novalue", "k=notjson"] { + assert!( + build_intent("createObject", "abc", "a/b", "", &[bad.to_string()], &[]).is_err(), + "{bad}" + ); + } + assert!(build_intent("../x", "abc", "a/b", "", &[], &[]).is_err()); + } + + #[test] + fn polling_sleeps_between_reads_and_stops_at_the_limit() { + let mut reads = 0; + let found: Option = poll_until(Duration::from_millis(400), Duration::from_millis(100), || { + reads += 1; + Ok(None) + }) + .unwrap(); + assert_eq!(found, None); + assert!((2..=6).contains(&reads), "{reads} reads: the sleep paces them"); + let mut reads = 0; + let found = poll_until(Duration::from_secs(5), Duration::from_millis(100), || { + reads += 1; + Ok((reads == 3).then_some("receipt")) + }) + .unwrap(); + assert_eq!((found, reads), (Some("receipt"), 3)); + } + + #[test] + fn statuses_map_to_exit_codes() { + for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] { + assert_eq!(Outcome::from_status(status).code(), code, "{status}"); + } + assert_eq!(Outcome::Timeout.code(), 4); + } +} diff --git a/brokkr-ctl/src/main.rs b/brokkr-ctl/src/main.rs new file mode 100644 index 0000000..41f1afc --- /dev/null +++ b/brokkr-ctl/src/main.rs @@ -0,0 +1,25 @@ +//! brokkr-ctl: command-line hands for Brokkr's creative-tool surfaces. + +mod actions; +mod blender; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let code = match args.split_first() { + Some((group, rest)) if group == "blender" => blender::run(rest), + Some((flag, _)) if matches!(flag.as_str(), "--help" | "-h" | "help") => { + print!( + "brokkr-ctl ...\n\ngroups:\n blender send intents to the live Blender add-on (`brokkr-ctl blender --help`)\n" + ); + Ok(0) + } + _ => Err(anyhow::anyhow!("usage: brokkr-ctl blender ...")), + }; + match code { + Ok(code) => std::process::exit(code), + Err(error) => { + eprintln!("error: {error:#}"); + std::process::exit(1); + } + } +} diff --git a/brokkr-ctl/tests/cli.rs b/brokkr-ctl/tests/cli.rs new file mode 100644 index 0000000..6e3d124 --- /dev/null +++ b/brokkr-ctl/tests/cli.rs @@ -0,0 +1,615 @@ +//! brokkr-ctl against a real single-file store, read back through cultcache-rs. + +use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, SingleFileMessagePackBackingStore}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const INTENT: &str = "brokkr.blender.command_intent.v0"; +const RECEIPT: &str = "brokkr.blender.command_receipt.v0"; + +fn envelope(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.to_string(), + r#type: schema.to_string(), + payload: rmp_serde::to_vec(payload).unwrap(), + stored_at: "2026-11-27T00:00:00.000000+00:00".to_string(), + schema_id: Some(schema.to_string()), + } +} + +/// A store the way the add-on leaves it: a file that already exists, holding other records. +fn store_with_receipts(dir: &Path, statuses: &[(&str, &str)]) -> PathBuf { + let path = dir.join("blender-editor.ccmp"); + let mut store = SingleFileMessagePackBackingStore::new(&path); + for (id, status) in statuses { + let receipt = json!({"schema": RECEIPT, "commandId": id, "status": status, "observedAt": "2026-11-27T00:00:00+00:00"}); + store + .push(&envelope(RECEIPT, &format!("blender/receipts/{id}"), &receipt)) + .unwrap(); + } + path +} + +fn ctl(store: &Path, args: &[&str], instance: Option<&str>) -> Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")); + command + .arg("blender") + .args(args) + .arg("--store") + .arg(store) + .env_remove("BROKKR_AGENT") + .env_remove("BROKKR_BLENDER_STORE") + .env_remove("EUREKA_INSTANCE"); + if let Some(instance) = instance { + command.env("EUREKA_INSTANCE", instance); + } + command.output().unwrap() +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[test] +fn send_writes_a_pullable_intent() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let output = ctl( + &path, + &["send", "createObject", "--set", "objectType=\"MESH\"", "--set", "location=[0,0,1]", "--note", "a cube", "--agent", "hands", "--no-wait"], + Some("nibu"), + ); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + assert_eq!(id.len(), 32); + + let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = envelopes + .iter() + .find(|e| e.key == format!("blender/commands/{id}")) + .expect("intent key"); + assert_eq!(intent.r#type, INTENT); + assert_eq!(intent.schema_id.as_deref(), Some(INTENT)); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); + assert_eq!( + payload, + json!({"schema": INTENT, "commandId": id, "action": "createObject", "requestedBy": "nibu/hands", + "note": "a cube", "objectType": "MESH", "location": [0, 0, 1]}) + ); + assert!(envelopes.iter().any(|e| e.key == "blender/receipts/seed"), "other records survive the write"); +} + +/// `look` is `send look`: one intent, no fields, the same receipt wait. +#[test] +fn look_sends_the_look_action_and_prints_the_receipts_look_path() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let output = ctl(&path, &["look", "--agent", "hands", "--note", "checking the view", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = envelopes.iter().find(|e| e.key == format!("blender/commands/{id}")).expect("intent key"); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); + assert_eq!( + payload, + json!({"schema": INTENT, "commandId": id, "action": "look", "requestedBy": "nibu/hands", + "note": "checking the view"}) + ); + // the add-on's receipt for it prints like any other: lookPath and the perception fields are plain lines + let mut store = SingleFileMessagePackBackingStore::new(&path); + let receipt = json!({"schema": RECEIPT, "commandId": id, "status": "accepted", "lookPath": "C:/out/look/x.png", + "humanEditSeq": 3, "editSelection": [{"name": "Cube", "vertices": [0, 2]}]}); + store.push(&envelope(RECEIPT, &format!("blender/receipts/{id}"), &receipt)).unwrap(); + let waited = ctl(&path, &["wait", &id, "--timeout", "5"], None); + assert_eq!(waited.status.code(), Some(0)); + let text = stdout(&waited); + assert!(text.contains("lookPath: C:/out/look/x.png"), "{text}"); + assert!(text.contains("humanEditSeq: 3") && text.contains("\"vertices\":[0,2]"), "{text}"); +} + +#[test] +fn look_takes_no_fields_and_no_second_action() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + for extra in [vec!["--set", "x=1"], vec!["createObject"]] { + let mut args = vec!["look", "--agent", "hands", "--no-wait"]; + args.extend(extra.iter()); + assert_eq!(ctl(&path, &args, Some("nibu")).status.code(), Some(1), "{extra:?}"); + } + let store = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + assert!(!store.iter().any(|e| e.key.starts_with("blender/commands/")), "a refused look writes nothing"); +} + +#[test] +fn the_group_help_names_look() { + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "--help"]).output().unwrap(); + assert!(stdout(&output).contains("look")); +} + +#[test] +fn an_intent_without_instance_or_agent_is_refused_and_writes_nothing() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let before = std::fs::read(&path).unwrap(); + for (instance, agent) in [(None, Some("hands")), (Some("nibu"), None), (None, None), (Some(" "), Some("hands"))] { + let mut args = vec!["send", "createObject", "--no-wait"]; + if let Some(agent) = agent { + args.extend(["--agent", agent]); + } + let output = ctl(&path, &args, instance); + assert_eq!(output.status.code(), Some(1), "{instance:?} {agent:?}"); + } + assert_eq!(std::fs::read(&path).unwrap(), before); +} + +#[test] +fn a_missing_store_is_not_created() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("nope.ccmp"); + let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1)); + assert!(!path.exists()); +} + +#[test] +fn wait_matches_the_exact_receipt_key() { + let dir = tempfile::tempdir().unwrap(); + // receipts whose keys merely end with, or start with, the waited id are other commands' receipts + let path = store_with_receipts(dir.path(), &[("xr1", "accepted"), ("r1x", "accepted")]); + let output = ctl(&path, &["wait", "r1", "--timeout", "0.3"], None); + assert_eq!(output.status.code(), Some(4), "{}", stdout(&output)); + assert!(stdout(&output).contains("status: timeout")); +} + +/// Exit 4 is two situations the sender must tell apart: the intent was never claimed (still in the queue, not run), +/// or Blender claimed it (deleted it from the queue) and no receipt landed (it may have run). +#[test] +fn a_timeout_says_whether_the_intent_is_still_queued_or_was_claimed() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let sent = ctl(&path, &["send", "createObject", "--agent", "hands", "--timeout", "0.3"], Some("nibu")); + assert_eq!(sent.status.code(), Some(4)); + let text = stdout(&sent); + assert!(text.contains("status: timeout") && text.contains("still queued") && text.contains("it has not run"), "{text}"); + let id = text.lines().find_map(|l| l.strip_prefix("commandId: ")).unwrap().to_string(); + // Blender claims it: the intent leaves the queue, and no receipt is written + let mut store = SingleFileMessagePackBackingStore::new(&path); + let queued = store.pull_all().unwrap().into_iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + store.delete(&queued).unwrap(); + let waited = ctl(&path, &["wait", &id, "--timeout", "0.3"], None); + assert_eq!(waited.status.code(), Some(4)); + let text = stdout(&waited); + assert!(text.contains("claimed the intent but wrote no receipt") && text.contains("may or may not have run"), "{text}"); +} + +#[test] +fn exit_code_follows_the_receipt() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts( + dir.path(), + &[("a", "accepted"), ("d", "denied"), ("f", "failed"), ("s", "stopped")], + ); + for (id, code) in [("a", 0), ("d", 2), ("f", 2), ("s", 3)] { + let output = ctl(&path, &["wait", id, "--timeout", "5"], None); + assert_eq!(output.status.code(), Some(code), "{id}"); + assert!(stdout(&output).contains(&format!("commandId: {id}"))); + } + let output = ctl(&path, &["wait", "missing", "--timeout", "0.3"], None); + assert_eq!(output.status.code(), Some(4)); + assert!(stdout(&output).contains("status: timeout")); +} + +#[test] +fn receipts_lists_the_last_n_oldest_first() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted"), ("b", "failed")]); + let output = ctl(&path, &["receipts"], None); + assert_eq!(output.status.code(), Some(0)); + let text = stdout(&output); + assert!(text.contains("commandId: a") && text.contains("commandId: b")); + let one = ctl(&path, &["receipts", "--last", "1"], None); + assert!(!stdout(&one).contains("commandId: a")); +} + +#[test] +fn status_without_a_snapshot_is_a_store_error() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + assert_eq!(ctl(&path, &["status"], None).status.code(), Some(1)); +} + +#[test] +fn send_help_lists_the_actions() { + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")) + .args(["blender", "send", "--help"]) + .output() + .unwrap(); + let text = stdout(&output); + for action in ["createObject", "renderStill", "setModifierInput", "exportGltf"] { + assert!(text.contains(action), "{action}"); + } +} + +fn envelope_at(schema: &str, key: &str, payload: &Value) -> CultCacheEnvelope { + envelope(schema, key, payload) +} + +fn push(path: &Path, entries: &[CultCacheEnvelope]) { + let mut store = SingleFileMessagePackBackingStore::new(path); + for entry in entries { + store.push(entry).unwrap(); + } +} + +#[test] +fn intents_sent_in_order_sort_in_send_order() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let mut sent = Vec::new(); + for _ in 0..8 { + let output = ctl(&path, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(0)); + sent.push(format!("blender/commands/{}", stdout(&output).trim().strip_prefix("commandId: ").unwrap())); + } + let mut sorted = sent.clone(); + sorted.sort(); + assert_eq!(sent, sorted, "the add-on drains by sorted key"); +} + +#[test] +fn an_absurd_timeout_is_a_usage_error_not_a_panic() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + for value in ["1e300", "inf", "nan", "-1", "abc"] { + let output = ctl(&path, &["wait", "x", "--timeout", value], None); + assert_eq!(output.status.code(), Some(1), "{value}"); + } +} + +#[test] +fn help_words_as_option_values_do_not_swallow_the_command() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let output = ctl( + &path, + &["send", "createObject", "--note", "-h", "--agent", "--help", "--no-wait"], + Some("nibu"), + ); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let id = stdout(&output).trim().strip_prefix("commandId: ").unwrap().to_string(); + let found = SingleFileMessagePackBackingStore::new(&path).pull_all().unwrap(); + let intent = found.iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + let payload: Value = cultcache_rs::decode_payload(&intent.payload).unwrap(); + assert_eq!(payload["note"], "-h"); + assert_eq!(payload["requestedBy"], "nibu/--help"); + // a real help flag still prints help and sends nothing + let help = ctl(&path, &["send", "createObject", "--help"], Some("nibu")); + assert_eq!(help.status.code(), Some(0)); + assert!(stdout(&help).contains("actions:")); +} + +#[test] +fn a_relative_store_path_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let output = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")) + .current_dir(dir.path()) + .args(["blender", "receipts", "--store", path.file_name().unwrap().to_str().unwrap()]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("absolute")); +} + +#[test] +fn a_symlinked_store_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let link = dir.path().join("link.ccmp"); + #[cfg(windows)] + let made = std::os::windows::fs::symlink_file(&path, &link); + #[cfg(unix)] + let made = std::os::unix::fs::symlink(&path, &link); + if made.is_err() { + eprintln!("skipped: no symlink privilege"); + return; + } + assert_eq!(ctl(&link, &["receipts"], None).status.code(), Some(1)); +} + +#[test] +fn a_hard_linked_store_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("a", "accepted")]); + let link = dir.path().join("second-name.ccmp"); + std::fs::hard_link(&path, &link).unwrap(); + let before = std::fs::read(&path).unwrap(); + for name in [&path, &link] { + let output = ctl(name, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{}", name.display()); + assert!(String::from_utf8_lossy(&output.stderr).contains("hard link")); + } + assert_eq!(std::fs::read(&path).unwrap(), before); +} + +#[test] +fn the_timeout_cap_is_one_day_inclusive() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + // --help returns after parsing, so a legal timeout does not wait + let at_cap = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400"], None); + assert_eq!(at_cap.status.code(), Some(0)); + let over = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400.5"], None); + assert_eq!(over.status.code(), Some(1)); +} + +#[test] +fn short_help_is_a_flag() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let output = ctl(&path, &["send", "createObject", "-h"], Some("nibu")); + assert_eq!(output.status.code(), Some(0)); + assert!(stdout(&output).contains("actions:")); + let group = ctl(&path, &["receipts", "-h"], None); + assert!(stdout(&group).contains("brokkr-ctl blender:")); +} + +#[test] +fn receipts_only_come_from_the_receipt_keys_and_type() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("real", "accepted")]); + let fake = json!({"commandId": "fake", "status": "accepted"}); + push( + &path, + &[ + envelope_at(RECEIPT, "elsewhere/fake", &fake), + envelope_at(INTENT, "blender/receipts/wrongtype", &fake), + envelope_at(RECEIPT, "nested/blender/receipts/fake2", &fake), + ], + ); + let listed = stdout(&ctl(&path, &["receipts"], None)); + assert!(listed.contains("commandId: real")); + assert!(!listed.contains("fake"), "{listed}"); + let waited = ctl(&path, &["wait", "wrongtype", "--timeout", "0.3"], None); + assert_eq!(waited.status.code(), Some(4)); +} + +#[test] +fn receipts_sort_by_observed_time_not_by_key() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + push( + &path, + &[ + envelope_at(RECEIPT, "blender/receipts/a", &json!({"commandId": "a", "observedAt": "2026-11-27T10:00:02+00:00"})), + envelope_at(RECEIPT, "blender/receipts/b", &json!({"commandId": "b", "observedAt": "2026-11-27T10:00:01+00:00"})), + ], + ); + let text = stdout(&ctl(&path, &["receipts"], None)); + assert!(text.find("commandId: b").unwrap() < text.find("commandId: a").unwrap(), "{text}"); +} + +#[test] +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"], "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\"]", "agentCommandsEnabled: false"] { + assert!(text.contains(line), "{line} in {text}"); + } +} + +fn table() -> Value { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge/actions.json"); + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() +} + +fn bound(value: &Value) -> String { + let x = value.as_f64().unwrap(); + if x == x.trunc() { format!("{}", x as i64) } else { format!("{x}") } +} + +fn every_name(specs: &Value, out: &mut Vec) { + for spec in specs.as_array().unwrap() { + out.push(spec["name"].as_str().unwrap().to_string()); + if let Some(values) = spec["enum"].as_array() { + out.extend(values.iter().map(|v| v.as_str().unwrap().to_string())); + } + if let (Some(min), Some(max)) = (spec.get("minimum"), spec.get("maximum")) { + out.push(format!("{}..{}", bound(min), bound(max))); + } + if let Some(items) = spec.get("items") { + if let (Some(min), Some(max)) = (items.get("minimum"), items.get("maximum")) { + out.push(format!("{}..{}", bound(min), bound(max))); + } + if let Some(properties) = items.get("properties") { + every_name(properties, out); + } + } + } +} + +/// Help is the embedded table, not a copy: every action, field, enum value and bound in actions.json is +/// in `send --help`, and the help lists no action the table does not have. +#[test] +fn help_names_every_action_field_enum_value_and_bound_of_the_table() { + let help = stdout( + &Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")).args(["blender", "send", "--help"]).output().unwrap(), + ); + let table = table(); + let mut listed = Vec::new(); + for action in table["actions"].as_array().unwrap() { + let name = action["name"].as_str().unwrap(); + assert!(help.lines().any(|l| l.starts_with(&format!(" {name}: "))), "help lacks {name}"); + let mut wanted = Vec::new(); + every_name(&action["fields"], &mut wanted); + let section: Vec<&str> = help + .lines() + .skip_while(|l| !l.starts_with(&format!(" {name}: "))) + .skip(1) + .take_while(|l| l.starts_with(" ")) + .collect(); + let section = section.join(" +"); + for word in wanted { + assert!(section.contains(&word), "{name}: help lacks {word} +{section}"); + } + listed.push(name.to_string()); + } + for line in help.lines().filter(|l| l.starts_with(" ") && !l.starts_with(" ")) { + let name = line.trim().split(':').next().unwrap(); + assert!(listed.iter().any(|a| a == name), "help lists unknown {name}"); + } + assert!(help.contains("cameraType: string PERSP|ORTHO|PANO"), "{help}"); + assert!(help.contains("resolutionX: integer 4..16384"), "{help}"); +} + +#[test] +fn an_intent_the_table_refuses_exits_1_and_writes_nothing() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + let before = std::fs::read(&path).unwrap(); + let cases: [(&[&str], &str); 5] = [ + (&["send", "setCamera", "--set", "targetObjectName=\"Cam\"", "--set", "cameraType=\"CUSTOM\""], "cameraType must be one of PERSP, ORTHO, PANO."), + (&["send", "renderStill", "--set", "outputPath=\"a.png\"", "--set", "resolutionX=2"], "resolutionX must be between 4 and 16384."), + (&["send", "createObject", "--set", "bogus=1"], "createObject has no field 'bogus'"), + (&["send", "runPython"], "Unsupported Blender command action: runPython"), + (&["send", "deleteObject"], "targetObjectName is required."), + ]; + for (args, message) in cases { + let mut args = args.to_vec(); + args.extend(["--agent", "hands", "--no-wait"]); + let output = ctl(&path, &args, Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{args:?}"); + assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{args:?}: {}", String::from_utf8_lossy(&output.stderr)); + assert_eq!(std::fs::read(&path).unwrap(), before, "{args:?} wrote to the store"); + } +} + +#[test] +fn a_json_payload_is_refused_not_guessed() { + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[]); + let mut json_receipt = envelope(RECEIPT, "blender/receipts/j", &json!({"commandId": "j", "status": "accepted"})); + json_receipt.payload = serde_json::to_vec(&json!({"commandId": "j", "status": "accepted"})).unwrap(); + push(&path, &[json_receipt]); + let output = ctl(&path, &["wait", "j", "--timeout", "1"], None); + assert_eq!(output.status.code(), Some(1)); +} + +/// A store whose snapshot carries the fixture add-on's rows the way the add-on publishes them, plus one refused file. +fn host_store(dir: &Path) -> PathBuf { + let path = store_with_receipts(dir, &[("seed", "accepted")]); + let file: Value = serde_json::from_str(include_str!( + "../../surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json" + )) + .unwrap(); + let rows: Vec = file["actions"] + .as_array() + .unwrap() + .iter() + .map(|row| { + let mut row = row.clone(); + row["host"] = json!("brokkr_host_fixture"); + row + }) + .collect(); + let snapshot = json!({ + "observedAt": "2026-11-28T10:00:00.000000+00:00", "mode": "OBJECT", + "hostActions": rows, + "hostActionErrors": [{"host": "broken_addon", "error": "brokkr_actions.json: host schema must be brokkr.blender.host_actions.v0"}], + }); + push(&path, &[envelope_at("brokkr.blender.host_snapshot.v0", "blender/host/current", &snapshot)]); + path +} + +fn help_text(args: &[&str], store: Option<&Path>) -> String { + let mut command = Command::new(env!("CARGO_BIN_EXE_brokkr-ctl")); + command.arg("blender").args(args).env_remove("BROKKR_BLENDER_STORE"); + if let Some(store) = store { + command.arg("--store").arg(store); + } + stdout(&command.output().unwrap()) +} + +#[test] +fn send_help_with_a_store_lists_the_host_rows_with_their_bounds() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let text = help_text(&["send", "--help"], Some(&path)); + assert!(text.contains("host actions (published by the add-on at 2026-11-28T10:00:00.000000+00:00):"), "{text}"); + for needle in ["brokkr_host_fixture.add_empty", "size: number 0.1..10", "name: string", "brokkr_host_fixture.report"] { + assert!(text.contains(needle), "{needle} in {text}"); + } + assert!(!text.contains("brokkr_host_fixture.apply"), "human-only is absence"); + assert!(text.contains("createObject"), "the built-ins are still listed"); +} + +#[test] +fn send_help_without_a_store_says_host_actions_need_one_and_with_no_snapshot_says_so() { + let text = help_text(&["send", "--help"], None); + assert!(text.contains("host actions: add --store"), "{text}"); + assert!(text.contains("createObject")); + let dir = tempfile::tempdir().unwrap(); + let path = store_with_receipts(dir.path(), &[("seed", "accepted")]); + assert!(help_text(&["send", "--help"], Some(&path)).contains("the store holds no host snapshot yet")); +} + +#[test] +fn a_host_intent_out_of_bounds_exits_1_and_leaves_the_store_byte_identical() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let before = std::fs::read(&path).unwrap(); + let cases: [(&[&str], &str); 3] = [ + (&["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=99"], "size must be between 0.1 and 10."), + (&["send", "brokkr_host_fixture.add_empty"], "name is required."), + (&["send", "brokkr_host_fixture.report", "--set", "x=1"], "has no field 'x'"), + ]; + for (args, message) in cases { + let mut args = args.to_vec(); + args.extend(["--agent", "hands", "--no-wait"]); + let output = ctl(&path, &args, Some("nibu")); + assert_eq!(output.status.code(), Some(1), "{args:?}"); + assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{args:?}"); + assert_eq!(std::fs::read(&path).unwrap(), before, "{args:?} wrote to the store"); + } +} + +#[test] +fn an_operator_left_out_of_the_file_is_unsupported_and_a_published_host_action_is_written() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let before = std::fs::read(&path).unwrap(); + let output = ctl(&path, &["send", "brokkr_host_fixture.apply", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("Unsupported Blender command action: brokkr_host_fixture.apply")); + assert_eq!(std::fs::read(&path).unwrap(), before); + let sent = ctl(&path, &["send", "brokkr_host_fixture.add_empty", "--set", "name=\"E\"", "--set", "size=2", "--agent", "hands", "--no-wait"], Some("nibu")); + assert_eq!(sent.status.code(), Some(0), "{}", String::from_utf8_lossy(&sent.stderr)); + let id = stdout(&sent).trim().strip_prefix("commandId: ").unwrap().to_string(); + let store = SingleFileMessagePackBackingStore::new(&path); + let intent = store.pull_all().unwrap().into_iter().find(|e| e.key == format!("blender/commands/{id}")).unwrap(); + let value: Value = rmp_serde::from_slice(&intent.payload).unwrap(); + assert_eq!((value["action"].as_str(), value["size"].as_i64()), (Some("brokkr_host_fixture.add_empty"), Some(2))); +} + +#[test] +fn status_names_the_host_actions_and_each_refused_file_and_a_multiline_result_prints_indented() { + let dir = tempfile::tempdir().unwrap(); + let path = host_store(dir.path()); + let text = stdout(&ctl(&path, &["status"], None)); + assert!(text.contains("hostActions: brokkr_host_fixture.add_empty, brokkr_host_fixture.report"), "{text}"); + assert!(text.contains("hostActionErrors: broken_addon: brokkr_actions.json: host schema must be"), "{text}"); + push( + &path, + &[envelope_at(RECEIPT, "blender/receipts/h", &json!({"commandId": "h", "status": "accepted", "hostResult": "objects: 3\nscenes: 1", "observedAt": "2026-11-28T10:00:01+00:00"}))], + ); + let receipt = stdout(&ctl(&path, &["wait", "h"], None)); + assert!(receipt.contains("hostResult:\n objects: 3\n scenes: 1\n"), "{receipt}"); +} diff --git a/brokkr-daemon/Cargo.toml b/brokkr-daemon/Cargo.toml index 5839b77..77fce12 100644 --- a/brokkr-daemon/Cargo.toml +++ b/brokkr-daemon/Cargo.toml @@ -6,7 +6,7 @@ publish = false [dependencies] anyhow = "1" -cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "c2a9a6e526390808ef195759056fda0b9a55d8a3", package = "cultcache-rs" } +cultcache-rs = { workspace = true } rmp-serde = "1.3" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index 48600c5..643cae9 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -767,7 +767,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { &source.local_position, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -843,7 +843,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "scale": source.local_scale, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -874,7 +874,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "visible": source.active_self, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -924,7 +924,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { &parent_name, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -961,7 +961,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { material, ); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!("blender/commands/{command_id}"), &command, @@ -1013,7 +1013,7 @@ fn run_sync_once(args: &SyncArgs) -> Result { "value": property.value, }); if !args.dry_run { - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.command_intent.v0", &format!( "blender/commands/{}", @@ -1368,8 +1368,8 @@ fn run_sync_once(args: &SyncArgs) -> Result { "sync/receipts/{}", receipt["receiptId"].as_str().unwrap_or("sync-receipt") ); - unity_store.put_json_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; - blender_store.put_json_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; + unity_store.put_messagepack_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; + blender_store.put_messagepack_document("brokkr.sync.receipt.v0", &receipt_key, &receipt)?; report.receipts_written += 2; } @@ -1390,9 +1390,10 @@ impl MirrorStore { fn documents(&mut self) -> Result> { let mut documents = Vec::new(); for envelope in self.store.pull_all()? { - let value = decode_payload(&envelope).with_context(|| { - format!("failed to decode {} at {}", envelope.r#type, envelope.key) - })?; + let value = + cultcache_rs::decode_payload::(&envelope.payload).with_context(|| { + format!("failed to decode {} at {}", envelope.r#type, envelope.key) + })?; documents.push(CacheDocument { key: envelope.key, value, @@ -1401,17 +1402,6 @@ impl MirrorStore { Ok(documents) } - fn put_json_document(&mut self, schema: &str, key: &str, value: &Value) -> Result<()> { - let payload = serde_json::to_vec(value)?; - self.store.push(&CultCacheEnvelope { - key: key.to_string(), - r#type: schema.to_string(), - payload, - stored_at: chrono_like_now(), - schema_id: Some(schema.to_string()), - }) - } - fn put_messagepack_document(&mut self, schema: &str, key: &str, value: &Value) -> Result<()> { let payload = rmp_serde::to_vec(value)?; self.store.push(&CultCacheEnvelope { @@ -1420,21 +1410,11 @@ impl MirrorStore { payload, stored_at: chrono_like_now(), schema_id: Some(schema.to_string()), - }) + })?; + Ok(()) } } -fn decode_payload(envelope: &CultCacheEnvelope) -> Result { - serde_json::from_slice(&envelope.payload) - .or_else(|_| rmp_serde::from_slice(&envelope.payload)) - .with_context(|| { - format!( - "payload is neither MessagePack nor JSON for {}", - envelope.key - ) - }) -} - fn parse_object_binding(value: &Value) -> Option { Some(ObjectBinding { binding_id: field_string(value, 1, "bindingId")?, @@ -2699,7 +2679,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2714,7 +2694,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2729,7 +2709,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-transform", &json!({ @@ -2746,7 +2726,7 @@ mod tests { }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2772,7 +2752,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2787,7 +2767,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2802,7 +2782,7 @@ mod tests { "authority": "unity-to-blender" }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ "objects": [] }), @@ -2815,12 +2795,12 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ "sceneObjects": [] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2834,7 +2814,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2856,7 +2836,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2883,7 +2863,7 @@ mod tests { ] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-rig", &json!({ @@ -2898,7 +2878,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2913,7 +2893,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-parent", &json!({ @@ -2929,7 +2909,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -2963,7 +2943,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -2979,7 +2959,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -2994,7 +2974,7 @@ mod tests { "authority": authority }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-material", &json!({ @@ -3010,7 +2990,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3033,7 +3013,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3048,7 +3028,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3063,7 +3043,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-active", &json!({ @@ -3079,7 +3059,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3106,7 +3086,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3131,7 +3111,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3146,7 +3126,7 @@ mod tests { "authority": "unity-to-blender" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-component-speed", &json!({ @@ -3162,7 +3142,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3189,7 +3169,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.unity.host_snapshot.v0", "unity/host/current", &json!({ @@ -3204,7 +3184,7 @@ mod tests { }] }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.object_binding.v0", "sync/bindings/objects/binding-cube", &json!({ @@ -3219,7 +3199,7 @@ mod tests { "authority": "blender-to-unity" }), )?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.var.v0", "sync/vars/var-cube-custom-intensity", &json!({ @@ -3235,7 +3215,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3261,7 +3241,7 @@ mod tests { let mut unity_store = MirrorStore::open(unity_path)?; let mut blender_store = MirrorStore::open(blender_path)?; - unity_store.put_json_document( + unity_store.put_messagepack_document( "brokkr.sync.timeline_binding.v0", "sync/bindings/timelines/timeline-camera", &json!({ @@ -3280,7 +3260,7 @@ mod tests { "enabled": true }), )?; - blender_store.put_json_document( + blender_store.put_messagepack_document( "brokkr.blender.host_snapshot.v0", "blender/host/current", &json!({ @@ -3329,4 +3309,163 @@ mod tests { ); Ok(()) } + + fn raw_envelope(key: &str, payload: Vec) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.to_string(), + r#type: "brokkr.sync.receipt.v0".to_string(), + payload, + stored_at: chrono_like_now(), + schema_id: Some("brokkr.sync.receipt.v0".to_string()), + } + } + + #[test] + fn store_read_refuses_trailing_bytes() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); + let mut raw = SingleFileMessagePackBackingStore::new(&path); + let clean = rmp_serde::to_vec(&json!({"a": 1}))?; + raw.push(&raw_envelope("k/clean", clean.clone()))?; + let documents = MirrorStore::open(&path)?.documents()?; + assert_eq!(documents.len(), 1); + assert_eq!(documents[0].value, json!({"a": 1})); + + let mut dirty = clean; + dirty.push(0xc0); + raw.push(&raw_envelope("k/dirty", dirty))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); + assert!(message.contains("k/dirty"), "{message}"); + assert!(!message.to_lowercase().contains("c0"), "{message}"); + Ok(()) + } + + #[test] + fn store_read_refuses_json_payload() -> Result<()> { + let temp = tempfile::tempdir()?; + let path = temp.path().join("store.ccmp"); + let receipt = json!({"schema": "brokkr.sync.receipt.v0", "status": "ok"}); + SingleFileMessagePackBackingStore::new(&path).push(&raw_envelope( + "sync/receipts/json", + serde_json::to_vec(&receipt)?, + ))?; + let message = format!("{:#}", MirrorStore::open(&path)?.documents().unwrap_err()); + assert!(message.contains("sync/receipts/json"), "{message}"); + Ok(()) + } + + #[test] + fn sync_once_writes_unity_active_state_to_blender_visibility_command() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + let command = MirrorStore::open(&blender_path)? + .documents()? + .into_iter() + .find(|document| document.key.starts_with("blender/commands/")) + .expect("Brokkr should emit a Blender visibility command"); + assert_eq!(command.value["action"], "setObjectVisibility"); + assert_eq!(command.value["targetObjectName"], "Cube"); + assert_eq!(command.value["visible"], true); + Ok(()) + } + + #[test] + fn sync_once_writes_an_inactive_unity_object_as_hidden_in_blender() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + MirrorStore::open(&unity_path)?.put_messagepack_document( + "brokkr.unity.host_snapshot.v0", + "unity/host/current", + &json!({ + "sceneObjects": [{ + "objectId": "unity-cube", + "name": "Cube", + "path": "/Cube", + "activeSelf": false + }] + }), + )?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + let command = MirrorStore::open(&blender_path)? + .documents()? + .into_iter() + .find(|document| document.key.starts_with("blender/commands/")) + .expect("Brokkr should emit a Blender visibility command"); + assert_eq!(command.value["action"], "setObjectVisibility"); + assert_eq!(command.value["visible"], false); + Ok(()) + } + + #[test] + fn dry_run_counts_active_state_command_but_writes_none() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_component_property_stores(&unity_path, &blender_path, "active-state")?; + + let report = run_sync_once(&SyncArgs { + unity_cache: unity_path, + blender_cache: blender_path.clone(), + dry_run: true, + })?; + + assert_eq!(report.blender_commands_written, 1, "{report:#?}"); + assert!( + MirrorStore::open(&blender_path)? + .documents()? + .iter() + .all(|document| !document.key.starts_with("blender/commands/")), + "a dry run must not write a command intent" + ); + Ok(()) + } + + #[test] + fn sync_once_writes_messagepack_receipts() -> Result<()> { + let temp = tempfile::tempdir()?; + let unity_path = temp.path().join("unity.ccmp"); + let blender_path = temp.path().join("blender.ccmp"); + seed_sync_stores(&unity_path, &blender_path, "unity-to-blender")?; + run_sync_once(&SyncArgs { + unity_cache: unity_path.clone(), + blender_cache: blender_path.clone(), + dry_run: false, + })?; + + for path in [&unity_path, &blender_path] { + let store = SingleFileMessagePackBackingStore::new(path); + let envelopes = store.pull_all()?; + let receipt = envelopes + .iter() + .find(|envelope| envelope.r#type == "brokkr.sync.receipt.v0") + .expect("store should hold the daemon sync receipt"); + let lead = receipt.payload.first().copied().unwrap_or(0); + assert!( + (0x80..=0x8f).contains(&lead) || lead == 0xde || lead == 0xdf, + "receipt payload should be a MessagePack map, led by {lead:#04x}" + ); + assert!(serde_json::from_slice::(&receipt.payload).is_err()); + assert!(cultcache_rs::decode_payload::(&receipt.payload)?.is_object()); + } + Ok(()) + } } diff --git a/docs/architecture.md b/docs/architecture.md index 9b102a9..843dbeb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -100,7 +100,7 @@ Derived State: - Unity package settings are adapter configuration, not Verse authority. - Blender add-on preferences are adapter configuration, not Verse authority. -- Blender JSON debug exports are inspection/import probes, not mirror authority. +- Blender JSON debug exports are export-only inspection output, not mirror authority and never read back as intents. - Unity and Blender sync UI fields are command/edit affordances; the `brokkr.sync.*` documents are the shared sync policy surface. - Ad hoc syncvar editors write `brokkr.sync.var.v0` policy records only; they diff --git a/docs/live-collab-target.md b/docs/live-collab-target.md new file mode 100644 index 0000000..545df3d --- /dev/null +++ b/docs/live-collab-target.md @@ -0,0 +1,294 @@ +# Brokkr live collaboration: target + +Campaign `brokkr-live` (Nibu's mind). Working branch `nibu/live-collab-target`, base +`origin/main` 5e279b2. This document holds the rationale, the design truths the +campaign produces, and the identity, lifecycle and authority table. The typed +`target` in the mind holds the labelled invariants and the not-in-scope list; the +text below is their source. Revision 2 adds phase two (the authoring surface) and +takes in the operator's rulings of 2026-11-27. + +Rulings in force: `brokkr-live:ruling:no-free-form-python`, `:act-then-undo`, +`:scene-last-writer-wins`, `:brokkr-ctl-blender-built-here`, +`:cc-is-hull-authority-scene-pushes-deltas`. + +## Why + +Operator, 2026-11-27: Brokkr "is meant to give an agent hands into the same Blender +scene I'm looking at, enabling live collaboration work". Her original vision for it: +"use Blender as an authoring environment, since it exposes typed access to all of the +assets we need over CultMesh. Certain collections within the Blender scene would +mirror their data into the exact documents Aetheria needs for its ships." + +So the campaign has two phases. **Phase one** makes the live session a collaboration: +the agent's edits are undoable and attributed, she can stop it, and it sees what she +sees. **Phase two** makes the scene an authoring surface over a ship's `.cc`: scene +collections map to the ship's records, the scene opens from the `.cc` at a known +revision, and pushes go back through AetherDb. + +Brokkr already runs inside her live Blender: a `depsgraph_update_post` handler +publishes a host snapshot and a persistent 1 s `bpy.app.timers` callback drains +command intents (`surfaces/blender/brokkr_bridge/__init__.py:610-647`, `:668-671`). +What it lacks: an agent edit is not an undo step (`nibu-body:research:blender-live-collab.brokkr-undo`); +nobody can tell who made an edit (`.brokkr-attribution-gate`); the human can stop an +agent only by unticking a preference; the agent sees names and counts, not the viewport +or the Edit Mode selection (`.brokkr-perception`); and the agent has no hands, since +`brokkr-ctl` has no source (`.brokkr-no-agent-surface`). Its strengths stay: typed, +validated actions with no free-form Python, path confinement, loopback bind and an +optional session token (`.brokkr-security`). + +## Prior art the design stands on + +- **mcp-for-blender's `UserEditRecorder`** (`.mcp4b-human-edits`): the agent learns what + the human did between its actions. We keep the idea as snapshot fields, without a + trajectory log. +- **blender-copilot** (`.copilot-undo-cancel`): one undo step per agent turn, a Stop + button, visible turns and an undo receipt, no approval gate. Its Stop cannot + interrupt a blocking native call; ours cannot either. +- **Multi-User** (`.humans-multiuser`, `.humans-others`): presence of the other party. + We show presence in a panel; human-to-human replication is theirs. +- **Blender Lab MCP and mcp-for-blender** (`.lab-official`, `.mcp4b-perception-safe`): + viewport screenshots as perception. Their arbitrary-code path is refused here + (`no-free-form-python`). +- **ceeyang/blender_mcp** (`.ceeyang-159`): 159 typed tools, every write undoable; a + typed vocabulary can be wide. +- **Aetheria's ship package path** (Aetheria origin/master 6702b01bf, packager on + `nibu/hull-packager` 7101b5cec): `AetherDb ship-authoring` (create, stats, price, + product, regenerate with a dry-run default, validate, inspect) loads a `ship.cc` + through the game's own types; `tools/blender/package_hull.py` drives the + `aetheria_ships` add-on and AetherDb from a manifest; `tools/blender/aetheria_ships/ship_cc.py` + reads and writes `ship.cc` envelopes directly, with a layout revision hash for its + layout write. +- **CultCache compare-exchange and element ids** (CultLib origin/main baf4ecf7, + `src/GameCult.Caching/CultCache.cs:2228-2235` `Expect`/`ExpectUnchanged`; + `CultElementIds.cs`). `HardpointData.Id` is a `[CultElementId]` (Aetheria + `Assets/Scripts/ServerShared/ItemData.cs:648`). + +## What probing established + +Blender 5.3.0, Starfire, GUI, `--factory-startup`, each step in its own timer tick. +Scripts in `docs/research/live-collab/`. Research notes +`brokkr-live:research:live-collab-probes.*`. + +1. **An unpushed write from a timer is not an undo step and survives undo**; the next + push absorbs it, so it is misattributed (`.timer-undo`, case A). +2. **An explicit `ed.undo_push` from a timer makes a correct step**, and undo and redo + walk it (case B). +3. **UNDO-flagged operators push their own step**; called `("EXEC_DEFAULT", False)` they + push none, and one explicit push covers several (cases C, E). This is how one intent + becomes one step. +4. **Edit Mode**: an agent bmesh write plus push is reverted by one undo, which also + left the Edit Mode the agent had entered (case D). +5. **Driving `ed.undo`/`ed.redo` from code crashed Blender 2 of 2 times** in the long + sequence, in UI draw after a memfile undo (`.programmatic-undo-crash`). +6. **The agent can see her view**: `screenshot_area` on her 3D view, median 72.5 ms at + 1574x888, about 609 KB, popups included; Edit Mode selection reads live without + leaving Edit Mode (`.look-capture`). +7. **Depsgraph updates from an agent edit arrive inside the timer turn** and name + indirect dependents; after an undo every object is listed and only the transform and + geometry flags show what changed (`.depsgraph-timing`). +8. **cultcache-rs writes the add-on's single-file `.ccmp` under the shared lock, and a + live cultmesh-py node pulls Rust writes**; no runtime has a directory store + (`.rust-store-writer`). + +Not yet probed, owed before the cut that depends on it: the latency of one AetherDb +`ship-authoring` call on Starfire (phase two decides between a CLI call per push and a +resident service on that number); reading a record's stored version through AetherDb. + +## Phase one: the live session + +**One agent turn primitive.** Every agent mutation in Blender goes through one function +in the add-on: admit (sink enabled, `requestedBy` present, id unused, action typed and +valid), run the action with every operator called `undo=False`, push exactly one undo +step labelled `Brokkr : `, write the receipt. A +refusal caught before any write pushes nothing and leaves the scene unchanged; an action +that fails after writing pushes one step labelled `(failed)`, so the partial write is one +undoable step. There is no second +writer and no script action (`no-free-form-python`): what the typed actions do not +cover waits for a new typed action. + +**The agent acts; the human undoes** (`act-then-undo`). Admitted intents apply without +asking. Blender's one linear undo stack is the shared history; agent steps sit in it, +labelled, between hers, and she takes them back with Ctrl+Z. The agent never calls +`ed.undo` or `ed.redo` (probe 5); it backs out by sending a compensating intent. + +**Last writer wins in the scene** (`scene-last-writer-wins`). An agent intent applies +even if she changed the scene since the agent looked. Her edit is never lost: it stays +in the undo history below the agent's step, and one Ctrl+Z takes the agent's step back. +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, 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`) +and returns the path. The snapshot gains the Edit Mode selection, a Blender session id, +and human-edit sequence numbers (a session counter and, per object, the last sequence +at which she changed it, from depsgraph updates outside agent turns and flagged +transform, geometry or shading). These tell the agent what she did since it last +looked; they gate nothing. + +**Presence is derived.** The panel shows active agents, the running or last intent with +its one-line `note`, and recent receipts with their undo labels, read from the intent +and receipt documents. + +**Hands are a CLI** (`brokkr-ctl-blender-built-here`). `brokkr-ctl blender` is a Rust +binary in this repo (`brush-tree:ruling:fitting-home-ruled`) that writes intents and +reads receipts and snapshots in the add-on's single-file store (probe 8), prints plain +text or paths, and whose `--help` is the schema (`brush-tree:ruling:cli-not-mcp`, +`:help-is-the-schema`). It owns no state, policy or ledger. Libby's brush-tree adds its +tree commands to the same binary later. + +## Phase two: the authoring surface + +**The `.cc` is the authority; the scene is a surface over it** +(`cc-is-hull-authority-scene-pushes-deltas`). A ship's records live in its `ship.cc`: +`HullData`, `ShipAuthoring` (model asset, anchors, schematic lines) and its product +records (`ShipAuthoringStore.Load` returns exactly these three). A Blender scene may be +bound to one `ship.cc` as its authoring surface. The scene never becomes truth: it is an +edit buffer that opens from the store and pushes back to it. + +**Collections carry roles.** Scene collections are tagged with the role they author: +hull shape (the hull source and its raster), hardpoint rows (one object per row, +carrying `aetheria.id`, the `HardpointData` element id, and its kind, cell, footprint, +rotation, armor and arc), schematic lines, and anchors. Stats, price and product live on +the binding. These are the fields the packager manifest already names +(`tools/blender/package_hull.md`), so the manifest and a push describe a ship in one +vocabulary. + +**Open reads through the game's code.** Opening runs `AetherDb ship-authoring` to read +the three records and their stored versions, builds the tagged collections, and records +on the binding the version of each record it read. Nothing reads a `.cc` by scraping +envelopes (operator 2026-11-17). + +**A push is one AetherDb call, dry-run then apply.** The surface pipes the authoring +state of its tagged collections (the manifest vocabulary, plus the record versions it +opened at) as a structural JSON dump on stdin to `AetherDb ship-authoring push `, +as the material path does (`aetheria-release:ruling:blender-dump-stdin`): never written +to disk, parsed and judged only in C#, so the schema exists once. Without `apply` AetherDb loads the store, derives the records the request +describes, validates them, and prints the per-record, per-field changes; nothing is +written. With `apply` it does the same and writes under compare-exchange on each +record's stored version (`Expect`). One CLI call per push is the starting shape; a +resident service is built only if the measured latency of that call demands it. + +**A stale revision is refused, never merged.** If any record changed in the store since +the scene opened it (another push, a CLI `stats` call, a packager `--replace`), the push +is refused with the records named; the surface reopens and the author re-applies. On a +successful apply the binding takes the new versions. + +**One owner turns a hull into records.** AetherDb's ship-authoring code (C#, the game's +own types) is the only code that derives `HullData`, `ShipAuthoring` and product records +from authoring input, and the only writer of `.cc` stores. The packager and the +authoring surface both call it. The direct envelope writes in +`aetheria_ships/ship_cc.py` (`replace_lines`, `replace_visual`, `replace_layout`, and +the first Save Layout that creates `ship.cc`) and its `layout_revision` hash are +demoted: `ship_cc.py` keeps no write path and no revision of its own, and +`package_hull.py`'s Save Layout steps become push calls. Whether the request is +the delta of the ruling, or a whole-record replace, is fork Q5 below. + +**The agent's hands reach the surface through typed actions.** Open, push dry-run and +push apply are typed Brokkr actions like any other, admitted by the same primitive; a +push changes no scene state and so pushes no undo step. Whether an agent may apply, +not only dry-run, is fork Q7. + +### Variants and CultNet deltas: not the push primitive today + +The coordinator asked whether Libby's `variants` delta records, or CultNet's deltas, +are the primitive for the push. + +- **Variants** (`variants` target, Libby's mind): a variant is a persisted record stored + as a base reference plus sparse overrides (`CultVariantDelta`, `CultVariantOverride` + with `Set`/`Insert`/`Remove` at slot plus element-id paths, + `src/GameCult.Caching/CultVariants.cs:56-112`), resolved by the cache at load, and a + plain upsert at a variant's key is refused (`variants:ruling:q1-refuse-plain-upsert`). + It describes a second document defined against a base, not a change to the base. Its + nested paths and `Insert`/`Remove` are unbuilt (`variants:follow_up:remaining-variant-cuts`, + C2b), C# alone resolves it, and Aetheria catalog content is out of its scope. +- **CultNet** (`contracts/cultnet/`): the wire has whole-document `document-put` and + `document-put-raw`, `document-delete`, and `database-change-raw` (added, updated, + removed, with the whole document and a commit id). There is no delta message. The + "delta" in `cultnet-rs/src/replication.rs:97,789-829` and `cultmesh-py/node.py:1649-1660` + is a client-side reconciliation diff (predicted minus canonical, per top-level slot, + numeric subtraction) handed to the caller to smooth a prediction; it is never sent. +- **One mechanism?** Not today. They are two unrelated things that share a word. The + operator's recollection matches the plan, not the code: variants' fork ruling 4 + (`cultnet-deltas`) says variants travel on CultNet as deltas, and + `variants:ruling:hop-subscriptions-refuse-variants` holds CultNet off variants until + that cut (C5) lands. When it does, the override vocabulary will be both the stored + variant and the wire delta. +- **Consequence for the push.** The push invents no delta format. Its addressing is the + variants override vocabulary (slot plus element id; `HardpointData.Id` is already a + `[CultElementId]`) when CultLib can apply overrides to a record in place; until then + it is a whole-record replace of the records that changed, guarded by `Expect`. Fork Q5. + +## Authority map + +- **Owner.** Phase one: the add-on's agent turn primitive owns whether and how an agent + intent changes the live scene; Blender owns scene truth and the undo stack; the human + owns the sink toggle, Stop and undo. Phase two: the `ship.cc` owns the ship; + AetherDb's ship-authoring code alone derives and writes its records. +- **Inputs.** Intent documents and the sink toggle (phase one). The tagged collections, + the binding's opened versions and the stdin dump (phase two). +- **Outputs.** One undo step per accepted mutating intent; one receipt per intent; the + refreshed snapshot; look PNG paths; AetherDb's dry-run diff or its write. +- **Derived state.** Presence; human-edit sequences; look PNGs; the scene's mapped + collections (an edit buffer over the `.cc`); the stdin dump (a pipe, not state). +- **Forbidden writers.** `execute_command` called around the primitive; operators run + with undo on inside an agent action; unpushed agent writes; `ed.undo`/`ed.redo` from + add-on code; any agent-sent Python; any reader that turns a file under + the debug-mirror root into an intent (removed in cut-live-1); `brokkr-ctl` deciding anything; + `ship_cc.py`'s envelope writes and any other direct `.cc` writer; `layout_revision` + as a revision. +- **Shared paths.** brokkr-ctl intents, panel buttons that act on the scene, sync-organ + intents and replayed intents use the one primitive. The packager, the authoring + surface's buttons and an agent's push intent use the one AetherDb push. +- **Deletion line.** The debug-mirror intent import goes before the primitive lands; + `drain_commands` stops calling `execute_command` directly. `ship_cc.py`'s write + functions and `layout_revision` go when the push lands. + +## Identity, lifecycle and authority + +| Persistent kind | What names it | What happens to it over time | Who decides | +|---|---|---|---| +| Blender command intent `brokkr.blender.command_intent.v0` (gains `requestedBy`, `note`) | `blender/commands/{commandId}`; ids single-use, minted by the writer (`brush-tree:ruling:blender-sink-mirrors-unity`) | Written once by a caller. Executed at most once or refused. Removed when its receipt is written. Never rewritten. | Callers write. The agent turn primitive alone decides admission and execution. | +| Blender command receipt `brokkr.blender.command_receipt.v0` (gains `requestedBy`, `outcome` in accepted, denied, stopped, failed, `undoLabel`, `lookPath`) | `blender/receipts/{commandId}`, one per intent | Written once, after the primitive decides. Pruned by count with Unity's cap and prune rule. | The primitive alone. Callers and the panel read. | +| Agent identity `requestedBy` | `/` stated by the caller | Carried on each intent into its receipt and undo label; not stored on its own. | The caller states it; the primitive refuses an intent without it. The session token proves admission, not identity. | +| Agent undo step | Blender undo entry `Brokkr : ` | One per accepted mutating intent; lives as Blender's stack does; never persisted by Brokkr. | Blender owns the stack; the primitive pushes; only the human undoes or redoes. | +| Blender session id | uuid minted at add-on register and on each `load_post` | Replaced when Blender restarts or a file loads. | The add-on alone. | +| Human-edit sequences (snapshot: `humanEditSeq`, per-object `lastHumanEditSeq`) | Integers within a session id | Monotonic within a session; reset with it. Information for the agent; they gate nothing. | The add-on's depsgraph and undo handlers alone. | +| Host snapshot `brokkr.blender.host_snapshot.v0` (gains Edit Mode selection, session id, sequences, sink state, authoring binding summary) | `blender/host/current`, overwritten | Refreshed on depsgraph update and after each intent. | The add-on alone. | +| Command sink toggle (`auto_drain_commands`) | Add-on preference, echoed in the snapshot | Off by default. Stop turns it off; only the human turns it on. | The human only. | +| Look PNG | `/look/{commandId}.png` | Pruned by count; never read back as truth. | The primitive writes; `look-files-are-scratch` governs. | +| Ship package store `ship.cc` (`HullData`, `ShipAuthoring`, product records) | Its path, `GameData/Mods//ship.cc`; records by their keys | Created by `ship-authoring create`; changed only by AetherDb commands, each write minting new stored versions (`variants:ruling:storedat-on-change`); replaced whole only by packager `--replace`. | AetherDb's ship-authoring code is the only writer. | +| Record version | The version CultCache's compare-exchange tests for each record key | Changes on every write that changes the record's bytes. | CultCache mints it; AetherDb reports it on open and tests it on apply. | +| Authoring binding | A custom property on the Blender scene: the `ship.cc` path relative to the `.blend`, the ship id, and the record versions opened at | Set on Open; versions replaced after each successful apply; cleared on Detach or reopen. Lives in the `.blend`. | Open, apply and Detach (human buttons or agent actions through the primitive) alone write it. | +| Collection role | A custom property on a collection: hull, hardpoints, lines or anchors | Set when the surface builds or the author tags a collection; removed on Detach. | The author; the surface's Open builds the defaults. | +| Hardpoint row identity | `aetheria.id` on the row's object, equal to `HardpointData.Id` (`[CultElementId]`) | Minted when the row is created; survives renames and moves; removing the object removes the row on the next push. | AetherDb mints for a new row; the surface carries it. | + +## Not in scope + +Human-to-human replication or several Blender instances in one session. Agents on +another host reaching the operator's Blender. Per-user or selective undo. An approval +gate (`act-then-undo`). Stale-action refusal inside the live scene +(`scene-last-writer-wins`). Any agent-sent Python (`no-free-form-python`). A 3D-view +presence overlay. The Unity surface and `brokkr-command`. The brush-tree vocabulary, +Geometry.Csg and OpenSCAD text (brush-tree owns them). Agent-initiated save and quit. +Asset libraries and generators. An MCP server. Records outside a ship package +(catalog loadouts, factions) unless Q6 rules them in. A new delta wire format. + +## Open forks (draft questions; Self admits) + +- **Q5. What a push carries.** (a) whole records that changed, under `Expect`, now; (b) + variants override paths applied in place, after CultLib builds in-place apply and + C2b; (c) (a) now with the request shaped so (b) replaces it without changing the + surface. Recommend (c). +- **Q6. Does a ship's loadout belong in its package?** A package holds hull, authoring + and products today; loadouts are catalog records. Recommend not in r2. +- **Q7. May an agent apply a push, or only dry-run?** A `.cc` write has no Ctrl+Z. + Recommend dry-run for agents, apply by her button. +- **Q8. Where the authoring surface lives.** (a) the `aetheria_ships` add-on in Aetheria, + with Brokkr giving the agent typed actions that call it; (b) Brokkr's add-on gains + Aetheria vocabulary. Recommend (a). diff --git a/docs/provider-contract.md b/docs/provider-contract.md index 8c1132f..e137bd7 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -207,28 +207,20 @@ id for each repetition. All Blender writes use `brokkr.blender.command_intent.v0` and receive `brokkr.blender.command_receipt.v0`. -- `createObject` -- `deleteObject` -- `setObjectTransform` -- `setObjectVisibility` -- `setObjectParent` -- `setObjectCustomProperty` -- `selectObject` -- `assignMaterial` -- `importGltf` -- `setCamera` -- `setLight` -- `setWorld` -- `renderStill` -- `createNodeGroup`, `addNode`, `removeNode`, `linkSockets`, `unlinkSockets`, `addModifier`, - `removeModifier`, `setModifierInput` (Geometry Nodes graphs; fields in - `surfaces/blender/docs/node-actions.md`) +The actions and their fields are one machine-readable table, +`surfaces/blender/brokkr_bridge/actions.json` (schema `brokkr.blender.actions.v0`): the add-on admits every +intent through it, and `brokkr-ctl blender send --help` prints it. It names each action's fields, types, enums, +bounds, defaults, whether the action changes the scene (one undo step), and whether it is safe in Edit Mode. An +intent the table refuses gets a `denied` receipt and changes nothing. Notes the table does not carry: +`exportGltf` writes under the add-on preference Render Output Directory, never overwriting; `look` is a read +(a PNG of her 3D view under the output directory's `look/`, her Edit Mode selection and her edit counters in the +receipt); the Geometry Nodes actions are described in `surfaces/blender/docs/node-actions.md`. Blender owns the mutation. Brokkr advertises the command surface; Verse clients write typed command intents; Blender executes recognized intents and publishes receipts. -`setObjectParent` uses `targetObjectName` and optional `parentObjectName`; an -empty parent reparents the object to the Blender scene root. +`setObjectParent` takes `targetObjectName` and an optional `parentObjectName`; an +empty or absent parent reparents the object to the Blender scene root. ## Operator Views diff --git a/docs/research/live-collab/probe_depsgraph_timing.py b/docs/research/live-collab/probe_depsgraph_timing.py new file mode 100644 index 0000000..d763e07 --- /dev/null +++ b/docs/research/live-collab/probe_depsgraph_timing.py @@ -0,0 +1,134 @@ +"""Probe: when do depsgraph updates caused by an agent edit in a timer arrive, and what do they name? + +blender --factory-startup --python probe_depsgraph_timing.py -- + +Each case runs in its own timer tick. AGENT is True only while the timer callback +runs the edit. depsgraph_update_post and undo_post log every call with AGENT's value, +the tick that was current, and the ids depsgraph.updates names. +""" +import json +import sys +import time +import traceback + +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "events": []} +AGENT = False +TICK = "setup" +T0 = time.perf_counter() + + +def ev(kind, **kw): + log["events"].append({"kind": kind, "tick": TICK, "agent": AGENT, + "ms": round((time.perf_counter() - T0) * 1000, 1), **kw}) + + +@bpy.app.handlers.persistent +def on_depsgraph(scene, depsgraph): + ups = [] + for u in depsgraph.updates: + ups.append(f"{type(u.id).__name__}:{u.id.name}" + f"{'/T' if u.is_updated_transform else ''}{'/G' if u.is_updated_geometry else ''}") + ev("depsgraph", updates=ups) + + +@bpy.app.handlers.persistent +def on_undo(scene, *_): + ev("undo_post") + + +@bpy.app.handlers.persistent +def on_redo(scene, *_): + ev("redo_post") + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return bpy.context.temp_override(window=win, area=area, region=region) + + +def setup(): + # B follows A through a Copy Location constraint: an indirect dependent of A. + a = bpy.data.objects["Cube"] + with win_ctx(): + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, 3, 0)) + b = bpy.context.active_object + b.name = "Follower" + c = b.constraints.new("COPY_LOCATION") + c.target = a + c.use_y = False + with win_ctx(): + bpy.ops.ed.undo_push(message="setup") + + +def agent(fn, flush): + global AGENT + AGENT = True + ev("turn_begin", flush=flush) + fn() + with win_ctx(): + bpy.ops.ed.undo_push(message=f"agent {TICK}") + if flush: + bpy.context.view_layer.update() + ev("turn_end") + AGENT = False + + +def move_a(x): + return lambda: setattr(bpy.data.objects["Cube"].location, "x", x) + + +def add_op(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add("EXEC_DEFAULT", False, location=(-4, 0, 0)) + + +def undo_once(): + with win_ctx(): + bpy.ops.ed.undo() + + +cases = [ + ("setup", setup), + ("idle1", lambda: None), + ("rna-noflush", lambda: agent(move_a(1.0), False)), + ("idle2", lambda: None), + ("rna-flush", lambda: agent(move_a(2.0), True)), + ("idle3", lambda: None), + ("op-noflush", lambda: agent(add_op, False)), + ("idle4", lambda: None), + ("op-flush", lambda: agent(add_op, True)), + ("idle5", lambda: None), + ("undo", undo_once), # stands in for a human Ctrl+Z (not an agent turn) + ("idle6", lambda: None), +] +i = 0 + + +def tick(): + global i, TICK + if i < len(cases): + TICK, fn = cases[i] + try: + fn() + except Exception: + ev("error", error=traceback.format_exc()) + TICK = f"after:{TICK}" + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.5 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.handlers.depsgraph_update_post.append(on_depsgraph) +bpy.app.handlers.undo_post.append(on_undo) +bpy.app.handlers.redo_post.append(on_redo) +bpy.app.timers.register(tick, first_interval=2.0) diff --git a/docs/research/live-collab/probe_look.py b/docs/research/live-collab/probe_look.py new file mode 100644 index 0000000..1e8851c --- /dev/null +++ b/docs/research/live-collab/probe_look.py @@ -0,0 +1,68 @@ +"""Probe: can a timer callback capture the 3D viewport the human sees, and read Edit Mode selection? + +blender --factory-startup --python probe_look.py -- +""" +import json +import os +import statistics +import sys +import time +import traceback + +import bmesh +import bpy + +args = sys.argv[sys.argv.index("--") + 1:] +OUT, PNG_DIR = args[0], args[1] +log = {"blender": bpy.app.version_string} + + +def ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + return win, area, region + + +def run(): + win, area, region = ctx() + log["view3d_px"] = [region.width, region.height] + times = [] + for n in range(7): + path = os.path.join(PNG_DIR, f"look-{n}.png") + t = time.perf_counter() + with bpy.context.temp_override(window=win, area=area, region=region): + r = bpy.ops.screen.screenshot_area(filepath=path) + times.append((time.perf_counter() - t) * 1000) + log.setdefault("results", []).append(list(r)) + log["screenshot_ms"] = [round(x, 1) for x in times] + log["screenshot_ms_median"] = round(statistics.median(times[1:]), 1) + log["png_bytes"] = os.path.getsize(os.path.join(PNG_DIR, "look-6.png")) + # Edit Mode selection read, live, without leaving Edit Mode. + with bpy.context.temp_override(window=win, area=area, region=region): + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="DESELECT") + bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data) + bm.verts.ensure_lookup_table() + bm.verts[0].select = True + bm.verts[3].select = True + bm.select_flush_mode() + t = time.perf_counter() + sel = [v.index for v in bmesh.from_edit_mesh(bpy.data.objects["Cube"].data).verts if v.select] + log["edit_selection_read_ms"] = round((time.perf_counter() - t) * 1000, 3) + log["edit_selected_verts"] = sel + log["mode_after_read"] = bpy.context.mode + + +def tick(): + try: + run() + except Exception: + log["error"] = traceback.format_exc() + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/docs/research/live-collab/probe_timer_undo.py b/docs/research/live-collab/probe_timer_undo.py new file mode 100644 index 0000000..57886fb --- /dev/null +++ b/docs/research/live-collab/probe_timer_undo.py @@ -0,0 +1,146 @@ +"""Probe: do edits made from a bpy.app.timers callback land on Blender's undo stack? + +Run in GUI Blender: blender --factory-startup --python probe_timer_undo.py -- [cases, e.g. AB] +Each step is its own timer tick so the event loop runs between steps, as it does +for Brokkr's 1 s drain. Results are written to the JSON path, then Blender quits. +""" +import json +import sys +import traceback + +import bmesh +import bpy + +OUT = sys.argv[sys.argv.index("--") + 1] +log = {"blender": bpy.app.version_string, "background": bpy.app.background, "steps": []} + + +def win_ctx(): + win = bpy.context.window_manager.windows[0] + area = next(a for a in win.screen.areas if a.type == "VIEW_3D") + return bpy.context.temp_override(window=win, area=area, region=area.regions[-1]) + + +def cube(): + return bpy.data.objects.get("Cube") + + +def state(tag): + c = cube() + s = { + "tag": tag, + "cube_x": round(c.location.x, 3) if c else None, + "objects": sorted(o.name for o in bpy.data.objects), + "mode": bpy.context.mode, + "mesh_v0_z": round(c.data.vertices[0].co.z, 3) if c else None, + } + if c and c.mode == "EDIT": + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + s["edit_v0_z"] = round(bm.verts[0].co.z if bm.verts else 0, 3) + log["steps"].append(s) + return s + + +def push(msg): + with win_ctx(): + r = bpy.ops.ed.undo_push(message=msg) + log["steps"].append({"tag": f"undo_push:{msg}", "result": list(r)}) + + +def undo(): + with win_ctx(): + r = bpy.ops.ed.undo() + log["steps"].append({"tag": "undo", "result": list(r)}) + + +def redo(): + with win_ctx(): + r = bpy.ops.ed.redo() + log["steps"].append({"tag": "redo", "result": list(r)}) + + +# Case A: raw RNA write from a timer, no push. Does Ctrl+Z see it as its own step? +# Case B: RNA write then an explicit undo_push from the timer. +# Case C: an UNDO-flagged operator called from a timer, no explicit push. +# Case D: Edit Mode bmesh write from a timer then undo_push. +# Case E: two operators called with undo=False, then one explicit undo_push. +ONLY = sys.argv[sys.argv.index("--") + 2] if len(sys.argv) > sys.argv.index("--") + 2 else "ABCDE" +steps = [ + lambda: (push("baseline"), state("A0 baseline")), + lambda: (setattr(cube().location, "x", 1.0), state("A1 raw write x=1, no push")), + lambda: (undo(), state("A2 after one undo")), + lambda: (push("rebase-B"), state("B0")), + lambda: (setattr(cube().location, "x", 2.0), push("agent: x=2"), state("B1 x=2 pushed")), + lambda: (setattr(cube().location, "x", 3.0), push("agent: x=3"), state("B2 x=3 pushed")), + lambda: (undo(), state("B3 after undo (expect x=2)")), + lambda: (undo(), state("B4 after second undo (expect x=0)")), + lambda: (redo(), state("B5 after redo (expect x=2)")), + lambda: (push("rebase-C"), state("C0")), + lambda: (_add_sphere(), state("C1 op add sphere, no push")), + lambda: (undo(), state("C2 after undo (sphere gone?)")), + lambda: (bpy.context.view_layer.objects.__setattr__("active", cube()), cube().select_set(True), push("rebase-D"), state("D0")), + lambda: (_edit_enter(), state("D1 edit mode")), + lambda: (_edit_write(), push("agent: edit v0"), state("D2 v0 moved, pushed")), + lambda: (undo(), state("D3 after undo (expect v0 back)")), + lambda: (undo(), state("D4 after second undo")), + lambda: (_edit_exit(), push("rebase-E"), state("E0")), + lambda: (_two_ops_one_step(), push("agent: two ops"), state("E1 two ops undo=False + one push")), + lambda: (undo(), state("E2 after one undo (expect both gone)")), + lambda: (undo(), state("E3 after second undo (expect no change)")), +] + + +def _add_sphere(): + with win_ctx(): + bpy.ops.mesh.primitive_uv_sphere_add(location=(5, 0, 0)) + + +def _edit_exit(): + if bpy.context.mode != "OBJECT": + with win_ctx(): + bpy.ops.object.mode_set(mode="OBJECT") + + +def _two_ops_one_step(): + with win_ctx(): + bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, location=(0, 4, 0)) + bpy.ops.mesh.primitive_cone_add("EXEC_DEFAULT", False, location=(0, -4, 0)) + + +def _edit_enter(): + with win_ctx(): + bpy.ops.object.mode_set(mode="EDIT") + + +def _edit_write(): + c = cube() + bm = bmesh.from_edit_mesh(c.data) + bm.verts.ensure_lookup_table() + bm.verts[0].co.z += 5.0 + bmesh.update_edit_mesh(c.data) + + +i = 0 +_all = steps +steps = [f for f, c in zip(_all, "AAABBBBBBCCCDDDDDEEEE") if c in ONLY] + + +def tick(): + global i + if i < len(steps): + try: + steps[i]() + except Exception: + log["steps"].append({"tag": f"step {i} error", "error": traceback.format_exc()}) + i += 1 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + return 0.3 + with open(OUT, "w") as f: + json.dump(log, f, indent=1) + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=2.0) diff --git a/surfaces/blender/brokkr_bridge/__init__.py b/surfaces/blender/brokkr_bridge/__init__.py index e2bcbe8..0801c16 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__ @@ -58,7 +74,7 @@ class BrokkrPreferences(bpy.types.AddonPreferences): name="Debug Export Root", subtype="DIR_PATH", default=DEFAULT_DEBUG_MIRROR_ROOT, - description="Optional JSON debug export/import root; CultMesh remains the mirror owner", + description="Optional JSON debug export root (export only); CultMesh remains the mirror owner", ) import_dir: bpy.props.StringProperty( @@ -72,7 +88,7 @@ class BrokkrPreferences(bpy.types.AddonPreferences): name="Render Output Directory", subtype="DIR_PATH", default="", - description="renderStill may only write files inside this directory; empty disables renderStill", + description="renderStill and exportGltf may only write files inside this directory; empty disables both", ) auto_capture: bpy.props.BoolProperty( @@ -84,7 +100,9 @@ class BrokkrPreferences(bpy.types.AddonPreferences): auto_drain_commands: bpy.props.BoolProperty( name="Auto Drain Commands", default=False, - description="Poll and execute pending Brokkr Blender command intents on a timer", + update=lambda self, context: _sink_changed(self), + description="The command sink: poll and run queued agent intents on a timer. Only the operator turns it on, " + "and Stop agents turns it off; no agent intent can write it", ) serve_host: bpy.props.StringProperty( @@ -333,6 +351,25 @@ class BROKKR_PT_status(bpy.types.Panel): prefs = context.preferences.addons[__name__].preferences adapter = target() + stop = layout.row() + stop.scale_y = 1.6 + stop.operator("brokkr.stop_agents", icon="CANCEL") + + if adapter.node_open and not adapter.receipts_loaded: + adapter.load_recent_receipts(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + agents_box = layout.box() + agents_box.label(text="Agents") + agents_box.label(text=f"Agent commands: {'on' if prefs.auto_drain_commands else 'off'}") + active = adapter.active_agents() + agents_box.label(text=f"Active: {', '.join(active)}" if active else "Active: none in the last 5 minutes") + agents_box.label(text=f"Pending: {adapter.pending_count}") + for item in adapter.recent_receipts(): + agents_box.label(text=f"{item.get('requestedBy') or '?'} {item.get('action', '')} {item.get('status', '')}") + if item.get("note"): + agents_box.label(text=f" {item['note']}") + if item.get("undoLabel"): + agents_box.label(text=f" {item['undoLabel']}") + layout.label(text=f"Provider: {PROVIDER_ID}") layout.label(text=f"Tool: {TOOL_KIND}") layout.label(text=f"Broker: {prefs.broker_uri}") @@ -352,6 +389,7 @@ class BROKKR_PT_status(bpy.types.Panel): row = layout.row(align=True) row.operator("brokkr.capture_snapshot", icon="FILE_REFRESH") + layout.operator("brokkr.reload_host_actions", icon="FILE_REFRESH") row.operator("brokkr.drain_commands", icon="PLAY") layout.prop(prefs, "auto_drain_commands") @@ -409,11 +447,6 @@ class BROKKR_PT_status(bpy.types.Panel): layout.label(text=f"Materials: {adapter.last_snapshot.get('materialCount', 0)}") layout.label(text=f"Selected: {len(adapter.last_snapshot.get('selectedObjectNames', []))}") - if adapter.last_receipt: - layout.separator() - layout.label(text=f"Last receipt: {adapter.last_receipt.get('status', '')}") - layout.label(text=adapter.last_receipt.get("message", "")) - if adapter.last_auto_drain_error: layout.separator() layout.label(text="Auto drain error:") @@ -438,11 +471,48 @@ 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_reload_host_actions(bpy.types.Operator): + bl_idname = "brokkr.reload_host_actions" + bl_label = "Reload Host Actions" + bl_description = ("Read each enabled add-on's brokkr_actions.json again. Only this button does: an agent cannot cause " + "a re-read, so an edited file admits nothing until you press it") + + def execute(self, context): + try: + found = target().reload_host_actions() + except PermissionError as exc: # inside an agent turn: a human acts here, never an agent + self.report({"ERROR"}, str(exc)) + return {"CANCELLED"} + rows, errors = target().host_actions() + self.report({"INFO"}, f"{found} host file(s) read; {len(rows)} host action(s) admitted, {len(errors)} file(s) refused.") + return {"FINISHED"} + + class BROKKR_OT_drain_commands(bpy.types.Operator): bl_idname = "brokkr.drain_commands" bl_label = "Drain Commands" @@ -476,7 +546,6 @@ class BROKKR_OT_start_server(bpy.types.Operator): prefs.serve_port, prefs.max_snapshot_documents, prefs.max_snapshot_bytes, - prefs.debug_mirror_root, prefs.allow_non_loopback, prefs.require_session_token, ) @@ -617,40 +686,80 @@ 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, ) +# Human-edit tracking is always on and reads no preference: it must not depend on auto_capture. Persistent, so +# opening another file does not drop them. +@bpy.app.handlers.persistent +def _track_human_edits(scene, depsgraph): + target().track_human_edits(depsgraph) + + +@bpy.app.handlers.persistent +def _track_undo_redo(scene, *_): + target().note_undo_redo() + + +@bpy.app.handlers.persistent +def _new_session(*_): + target().renew_session() + + +_PERCEPTION_HANDLERS = ( + ("depsgraph_update_post", _track_human_edits), + ("undo_post", _track_undo_redo), + ("redo_post", _track_undo_redo), + ("load_post", _new_session), +) + +BUSY_INTERVAL = 0.05 # one intent per tick: Stop is a UI event, and it lands between two intents +IDLE_INTERVAL = 1.0 + + def _auto_drain_commands(): context = bpy.context addon = context.preferences.addons.get(__name__) adapter = target() if not addon: - return 1.0 + return IDLE_INTERVAL prefs = addon.preferences - if not prefs.auto_drain_commands: - adapter.last_auto_drain_error = "" - return 1.0 - + ran = 0 + pending_before = adapter.pending_count try: - adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) - adapter.drain_commands( - context, - prefs.cultmesh_cache_path, - prefs.cultlib_py_src, - prefs.debug_mirror_root, - ) + # The sink on, a node open, or a store already on disk: any running Blender answers within a tick, and + # an idle session never creates a store. + if prefs.auto_drain_commands or adapter.node_open or adapter.store_exists(prefs.cultmesh_cache_path): + if prefs.auto_drain_commands: + adapter.configure_action_dirs(prefs.import_dir, prefs.output_dir) + ran = len(adapter.drain_commands( + context, + prefs.cultmesh_cache_path, + prefs.cultlib_py_src, + prefs.debug_mirror_root, + limit=1, + )) + adapter.count_pending(prefs.cultmesh_cache_path, prefs.cultlib_py_src) + else: # the add-on owns the sink, so it answers: nothing queues to fire on re-enable + adapter.stop_pending("agent commands are off", prefs.cultmesh_cache_path, + prefs.cultlib_py_src, prefs.debug_mirror_root) adapter.last_auto_drain_error = "" except Exception as exc: adapter.last_auto_drain_error = str(exc) - return 1.0 + if ran or adapter.pending_count != pending_before: + _redraw() + return BUSY_INTERVAL if ran else IDLE_INTERVAL classes = ( BrokkrPreferences, BROKKR_PT_status, + BROKKR_OT_stop_agents, BROKKR_OT_capture_snapshot, + BROKKR_OT_reload_host_actions, BROKKR_OT_drain_commands, BROKKR_OT_start_server, BROKKR_OT_stop_server, @@ -662,18 +771,34 @@ classes = ( ) +def _load_host_actions_once(): + """One read of the host files shortly after startup, when the other add-ons are enabled (not an intent's doing).""" + try: + target().reload_host_actions() + except Exception: + pass + return None + + def register(): for cls in classes: bpy.utils.register_class(cls) if _auto_capture not in bpy.app.handlers.depsgraph_update_post: bpy.app.handlers.depsgraph_update_post.append(_auto_capture) + for name, handler in _PERCEPTION_HANDLERS: + if handler not in getattr(bpy.app.handlers, name): + getattr(bpy.app.handlers, name).append(handler) if not bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.register(_auto_drain_commands, first_interval=1.0, persistent=True) + bpy.app.timers.register(_load_host_actions_once, first_interval=3.0) def unregister(): if _auto_capture in bpy.app.handlers.depsgraph_update_post: bpy.app.handlers.depsgraph_update_post.remove(_auto_capture) + for name, handler in _PERCEPTION_HANDLERS: + if handler in getattr(bpy.app.handlers, name): + getattr(bpy.app.handlers, name).remove(handler) if bpy.app.timers.is_registered(_auto_drain_commands): bpy.app.timers.unregister(_auto_drain_commands) global _target diff --git a/surfaces/blender/brokkr_bridge/action_table.py b/surfaces/blender/brokkr_bridge/action_table.py new file mode 100644 index 0000000..eba7e82 --- /dev/null +++ b/surfaces/blender/brokkr_bridge/action_table.py @@ -0,0 +1,279 @@ +"""The action table: which Blender intents exist, what fields each may carry, and each action's undo class. + +actions.json (schema brokkr.blender.actions.v0) owns the built-in rows; a host add-on adds rows of its own +operators in brokkr_actions.json (schema brokkr.blender.host_actions.v0: scalar fields only, no free JSON, +an optional result naming a WindowManager string property), checked by check_host and passed to validate() +and entry() as `host`. run_intent admits every intent through validate(); brokkr-ctl embeds the same file for `send --help` and early refusal, with the same rules and +message text (surfaces/blender/tests/action_cases.json pins the two). Stdlib only, no bpy. + +Vocabulary: null means absent; a required field absent is refused; a field neither declared nor in the +envelope is refused; enums match exactly; number and integer are never bool and always within the declared +minimum and maximum, integer is whole; string may declare minLength, maxLength, chars (a named charset), +prefixes (starts with one and has at least one more character) and forbid (substrings); array declares +items, minItems, maxItems; object with properties is closed and recursive, without is a free map; any is +any non-null value; only {field, in} refuses a field present unless the sibling's value is in the list; +defaults fill absent top-level fields after validation. Scene-dependent rules stay in the handlers. +""" +from __future__ import annotations + +import functools +import json +import math +import re +from pathlib import Path +from typing import Any + +TABLE_PATH = Path(__file__).with_name("actions.json") +SCHEMA = "brokkr.blender.actions.v0" +HOST_SCHEMA = "brokkr.blender.host_actions.v0" +HOST_TYPES = ("string", "number", "integer", "boolean") +HOST_NAME = re.compile(r"^[a-z0-9_]+\.[a-z0-9_]+$") +TYPES = ("string", "number", "integer", "boolean", "array", "object", "any") +TYPE_WORDS = {"string": "a string", "number": "a finite number", "integer": "a whole number", + "boolean": "true or false", "array": "an array", "object": "an object"} + + +class IntentInvalid(ValueError): + """The intent breaks a rule of the table; the message names the field path and the rule.""" + + +class TableInvalid(ValueError): + """actions.json itself is malformed.""" + + +def number_text(value: float) -> str: + """A bound as it is printed in messages: whole values without a fraction, others as the shortest digits.""" + return str(int(value)) if value == int(value) else repr(float(value)) + + +def _list(items: list) -> str: + return ", ".join(items) + + +@functools.lru_cache(maxsize=1) +def _raw() -> dict[str, Any]: + return json.loads(TABLE_PATH.read_text(encoding="utf-8")) + + +@functools.lru_cache(maxsize=1) +def table() -> dict[str, Any]: + """actions.json, loaded and checked once.""" + document = _raw() + check_table(document) + return document + + +def entry(action: Any, host: Any = ()) -> dict[str, Any] | None: + """The row for an action name: the built-in row, else the first host row of that name, else None.""" + if not isinstance(action, str): + return None + row = _by_name().get(action) + if row is not None: + return row + return next((h for h in host if h.get("name") == action), None) + + +@functools.lru_cache(maxsize=1) +def _by_name() -> dict[str, dict[str, Any]]: + return {a["name"]: a for a in table()["actions"]} + + +def check_table(document: dict[str, Any]) -> None: + """Refuse a table with an unbounded number field, an 'only' naming a missing field, an unknown charset, + a default that breaks its own field's rules, or a bound that prints differently in Python and Rust.""" + if document.get("schema") != SCHEMA: + raise TableInvalid(f"table schema must be {SCHEMA}") + charsets = document.get("charsets", {}) + names = set() + for action in document["actions"]: + if action["name"] in names: + raise TableInvalid(f"action {action['name']} is listed twice") + names.add(action["name"]) + fields = {f["name"]: f for f in action["fields"]} + if len(fields) != len(action["fields"]): + raise TableInvalid(f"{action['name']} repeats a field") + for field in action["fields"]: + _check_spec(field, f"{action['name']}.{field['name']}", charsets, fields, top=True) + if "default" in field: + try: + _value(field, field["default"], field["name"]) + except IntentInvalid as error: + raise TableInvalid(f"{action['name']}.{field['name']} default: {error}") from None + + +def check_host(document: Any, charsets: dict[str, Any]) -> None: + """Refuse a host add-on's brokkr_actions.json unless its schema is the host schema, every name is a dotted + operator id and unique, every field is scalar and passes the built-in spec checks (and its default its own + rules), and result, if present, is an identifier. Raises TableInvalid naming the row and field.""" + if not isinstance(document, dict) or document.get("schema") != HOST_SCHEMA: + raise TableInvalid(f"host schema must be {HOST_SCHEMA}") + for key in document: + if key not in ("schema", "actions"): + raise TableInvalid(f"host file has no key '{key}'") + rows = document.get("actions") + if not isinstance(rows, list): + raise TableInvalid("host file actions must be an array") + names = set() + for row in rows: + name = row.get("name") if isinstance(row, dict) else None + if not isinstance(name, str) or not HOST_NAME.match(name): + raise TableInvalid(f"host action name {name!r} must look like addon.operator (a-z, 0-9, _)") + if name in names: + raise TableInvalid(f"host action {name} is listed twice") + names.add(name) + for key in ("doc", "changesScene", "editModeSafe", "fields"): + if key not in row: + raise TableInvalid(f"{name} lacks {key}") + if not isinstance(row["fields"], list): + raise TableInvalid(f"{name} fields must be an array") + for key in row: + if key not in ("name", "doc", "changesScene", "editModeSafe", "fields", "result"): + raise TableInvalid(f"{name} has no key '{key}'") + if "result" in row and not (isinstance(row["result"], str) and row["result"].isidentifier()): + raise TableInvalid(f"{name}.result must be an identifier") + fields = {} + envelope = table()["envelope"] + for field in row["fields"]: + if not isinstance(field, dict) or not isinstance(field.get("name"), str) or field["name"] in fields: + raise TableInvalid(f"{name} has a missing or repeated field name") + if field["name"] in envelope: + raise TableInvalid(f"{name}.{field['name']} is an envelope key; Brokkr writes it, so the operator would never receive the agent's value") + fields[field["name"]] = field + for field in fields.values(): + where = f"{name}.{field['name']}" + if field.get("type") not in HOST_TYPES: + raise TableInvalid(f"{where}: a host field is one of {_list(list(HOST_TYPES))}") + if "only" in field: + raise TableInvalid(f"{where}: a host field has no 'only'") + _check_spec(field, where, charsets, fields, top=True) + if "default" in field: + try: + _value(field, field["default"], field["name"]) + except IntentInvalid as error: + raise TableInvalid(f"{where} default: {error}") from None + + +def _check_spec(spec: dict[str, Any], where: str, charsets: dict, siblings: dict, top: bool) -> None: + kind = spec.get("type") + if kind not in TYPES: + raise TableInvalid(f"{where}: unknown type {kind!r}") + if kind in ("number", "integer"): + for bound in ("minimum", "maximum"): + value = spec.get(bound) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise TableInvalid(f"{where}: a {kind} field declares {bound}") + if "e" in number_text(value): + raise TableInvalid(f"{where}: {bound} {value} does not print as plain digits") + if "chars" in spec and spec["chars"] not in charsets: + raise TableInvalid(f"{where}: charset {spec['chars']!r} is not defined") + if "only" in spec: + if not top or spec["only"]["field"] not in siblings: + raise TableInvalid(f"{where}: 'only' must name a field of the same action") + if "default" in spec and not top: + raise TableInvalid(f"{where}: only top-level fields have defaults") + if kind == "array": + _check_spec(spec["items"], where + "[]", charsets, siblings, top=False) + if kind == "object" and "properties" in spec: + inner = {p["name"]: p for p in spec["properties"]} + for prop in spec["properties"]: + _check_spec(prop, f"{where}.{prop['name']}", charsets, inner, top=False) + + +def validate(command: dict[str, Any], host: Any = ()) -> dict[str, Any]: + """The normalized copy of an intent (nulls dropped, whole numbers of integer fields as int, defaults filled), or + IntentInvalid naming the rule. It raises nothing else, whatever the document holds.""" + action = command.get("action", "") + row = entry(action, host) + if row is None: + raise IntentInvalid(f"Unsupported Blender command action: {action}") + present = {k: v for k, v in command.items() if v is not None} + _fields(row["fields"], present, None, action, set(table()["envelope"])) + result = dict(present) + for field in row["fields"]: + if field["type"] == "integer" and field["name"] in result: + result[field["name"]] = int(result[field["name"]]) # a whole float (1920.0) is the same intent; Blender refuses a float for an int property + if field["name"] not in result and "default" in field: + result[field["name"]] = field["default"] + return result + + +def _fields(specs: list[dict[str, Any]], values: dict[str, Any], parent: str | None, where: str, skip: set) -> None: + """The fields of an action (parent None) or of a closed object: unknown names first, sorted, then each + declared field in table order.""" + declared = [s["name"] for s in specs] + for key in sorted((k for k in values if k not in skip and k not in declared), key=str): # str: a store writer may mix key types + raise IntentInvalid(f"{where} has no field '{key}'; its fields: {_list(declared) or 'none'}.") + for spec in specs: + path = spec["name"] if parent is None else f"{parent}.{spec['name']}" + value = values.get(spec["name"]) + if value is None: + if spec.get("required"): + raise IntentInvalid(f"{path} is required.") + continue + only = spec.get("only") + if only is not None and values.get(only["field"]) not in only["in"]: + raise IntentInvalid(f"{path} applies only when {only['field']} is one of {_list(only['in'])}.") + _value(spec, value, path) + + +def _value(spec: dict[str, Any], value: Any, path: str) -> None: + kind = spec["type"] + if kind == "any": + return + if kind in ("number", "integer"): + _number(spec, value, path) + elif kind == "string": + if not isinstance(value, str): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if "enum" in spec: + if value not in spec["enum"]: + raise IntentInvalid(f"{path} must be one of {_list(spec['enum'])}.") + else: + _string(spec, value, path) + elif kind == "boolean": + if not isinstance(value, bool): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + elif kind == "array": + if not isinstance(value, list): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if "minItems" in spec and len(value) < spec["minItems"]: + raise IntentInvalid(f"{path} must have at least {spec['minItems']} items.") + if "maxItems" in spec and len(value) > spec["maxItems"]: + raise IntentInvalid(f"{path} must have at most {spec['maxItems']} items.") + for index, item in enumerate(value): + if item is None: + raise IntentInvalid(f"{path}[{index}] must be {TYPE_WORDS.get(spec['items']['type'], 'a value')}.") + _value(spec["items"], item, f"{path}[{index}]") + elif kind == "object": + if not isinstance(value, dict): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if "properties" in spec: + _fields(spec["properties"], {k: v for k, v in value.items() if v is not None}, path, path, frozenset()) + + +def _string(spec: dict[str, Any], value: str, path: str) -> None: + if "minLength" in spec and len(value) < spec["minLength"]: + raise IntentInvalid(f"{path} must have at least {spec['minLength']} characters.") + if "maxLength" in spec and len(value) > spec["maxLength"]: + raise IntentInvalid(f"{path} must have at most {spec['maxLength']} characters.") + if "chars" in spec: + charset = _raw()["charsets"][spec["chars"]] + if any(c not in charset["allowed"] for c in value): + raise IntentInvalid(f"{path} may contain only {charset['text']}.") + if "prefixes" in spec and not any(value.startswith(p) and len(value) > len(p) for p in spec["prefixes"]): + raise IntentInvalid(f"{path} must start with one of {_list(spec['prefixes'])} and have at least one more character.") + for part in spec.get("forbid", ()): + if part in value: + raise IntentInvalid(f"{path} may not contain '{part}'.") + + +def _number(spec: dict[str, Any], value: Any, path: str) -> None: + kind = spec["type"] + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if isinstance(value, float) and not math.isfinite(value): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if kind == "integer" and isinstance(value, float) and value != int(value): + raise IntentInvalid(f"{path} must be {TYPE_WORDS[kind]}.") + if not spec["minimum"] <= value <= spec["maximum"]: + raise IntentInvalid(f"{path} must be between {number_text(spec['minimum'])} and {number_text(spec['maximum'])}.") diff --git a/surfaces/blender/brokkr_bridge/actions.json b/surfaces/blender/brokkr_bridge/actions.json new file mode 100644 index 0000000..a605e01 --- /dev/null +++ b/surfaces/blender/brokkr_bridge/actions.json @@ -0,0 +1,144 @@ +{ + "schema": "brokkr.blender.actions.v0", + "envelope": ["schema", "commandId", "action", "requestedBy", "note"], + "charsets": { + "id": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-", "text": "letters, digits, '.', '_' or '-'"}, + "key": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ._-", "text": "letters, digits, space, '.', '_' or '-'"}, + "alnum": {"allowed": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "text": "letters and digits"} + }, + "actions": [ + {"name": "createObject", "doc": "Add an object at a location; a MESH is a cube.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectType", "type": "string", "enum": ["MESH", "LIGHT", "CAMERA", "EMPTY"], "default": "EMPTY"}, + {"name": "name", "type": "string"}, + {"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"}, + {"name": "size", "type": "number", "minimum": 0.001, "maximum": 1000000, "default": 1, "doc": "cube size, used by MESH"}, + {"name": "meshType", "type": "string", "enum": ["CUBE"], "only": {"field": "objectType", "in": ["MESH"]}}, + {"name": "lightType", "type": "string", "enum": ["POINT", "SUN", "SPOT", "AREA"], "default": "POINT", "only": {"field": "objectType", "in": ["LIGHT"]}}, + {"name": "emptyDisplayType", "type": "string", "enum": ["PLAIN_AXES", "ARROWS", "SINGLE_ARROW", "CIRCLE", "CUBE", "SPHERE", "CONE", "IMAGE"], "default": "PLAIN_AXES", "only": {"field": "objectType", "in": ["EMPTY"]}} + ]}, + {"name": "deleteObject", "doc": "Delete an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"} + ]}, + {"name": "setObjectTransform", "doc": "Set any of an object's location, rotation and scale.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"}, + {"name": "rotationEuler", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z] radians"}, + {"name": "scale", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 3, "maxItems": 3, "doc": "[x,y,z]"} + ]}, + {"name": "setObjectVisibility", "doc": "Show or hide an object in the viewport and in renders.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "visible", "type": "boolean", "default": true} + ]}, + {"name": "setObjectParent", "doc": "Parent an object to another.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "parentObjectName", "type": "string", "doc": "empty or absent clears the parent"} + ]}, + {"name": "setObjectCustomProperty", "doc": "Set one custom property on an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "propertyName", "type": "string", "default": "brokkrValue"}, + {"name": "value", "type": "any", "required": true, "doc": "any JSON value Blender accepts as a property"} + ]}, + {"name": "selectObject", "doc": "Select an object and make it active.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "clearSelection", "type": "boolean", "default": true} + ]}, + {"name": "assignMaterial", "doc": "Assign a material (created when new) to an object's slots.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "materialName", "type": "string", "default": "Brokkr Material"}, + {"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 4, "doc": "[r,g,b] or [r,g,b,a], linear; alpha defaults to 1"} + ]}, + {"name": "importGltf", "doc": "Import a .gltf or .glb from the add-on's import directory.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "filepath", "type": "string", "required": true, "doc": "relative to the add-on's import directory"} + ]}, + {"name": "exportGltf", "doc": "Write the scene, or the named objects, as .glb or .gltf into the output directory.", "changesScene": false, "editModeSafe": false, "fields": [ + {"name": "filepath", "type": "string", "required": true, "doc": ".glb or .gltf relative to the add-on's output directory"}, + {"name": "extras", "type": "boolean", "default": true}, + {"name": "yUp", "type": "boolean", "default": true}, + {"name": "applyModifiers", "type": "boolean", "default": true}, + {"name": "selection", "type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1, "doc": "object names; the whole scene when absent"} + ]}, + {"name": "setCamera", "doc": "Change a camera's lens, projection and clipping.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "lens", "type": "number", "minimum": 1, "maximum": 5000, "doc": "mm"}, + {"name": "cameraType", "type": "string", "enum": ["PERSP", "ORTHO", "PANO"]}, + {"name": "orthoScale", "type": "number", "minimum": 0.001, "maximum": 100000}, + {"name": "clipStart", "type": "number", "minimum": 0.0001, "maximum": 1000000}, + {"name": "clipEnd", "type": "number", "minimum": 0.001, "maximum": 10000000}, + {"name": "panoramaType", "type": "string", "enum": ["EQUIRECTANGULAR", "EQUIANGULAR_CUBEMAP_FACE", "MIRRORBALL", "FISHEYE_EQUIDISTANT", "FISHEYE_EQUISOLID", "FISHEYE_LENS_POLYNOMIAL", "CENTRAL_CYLINDRICAL"]}, + {"name": "active", "type": "boolean", "doc": "true makes it the scene camera"} + ]}, + {"name": "setLight", "doc": "Change a light's energy, colour and type.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "targetObjectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "energy", "type": "number", "minimum": 0, "maximum": 10000000}, + {"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 3, "doc": "[r,g,b] linear"}, + {"name": "lightType", "type": "string", "enum": ["POINT", "SUN", "SPOT", "AREA"]} + ]}, + {"name": "setWorld", "doc": "Edit the world's Background node; a world is created when there is none.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "worldName", "type": "string", "doc": "default: the scene's world"}, + {"name": "color", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}, "minItems": 3, "maxItems": 3, "doc": "[r,g,b] linear"}, + {"name": "strength", "type": "number", "minimum": 0, "maximum": 1000000} + ]}, + {"name": "renderStill", "doc": "Render the scene to a still in the output directory; settings are restored afterwards.", "changesScene": false, "editModeSafe": true, "fields": [ + {"name": "outputPath", "type": "string", "required": true, "doc": ".png, .jpg or .exr relative to the add-on's output directory"}, + {"name": "engine", "type": "string", "minLength": 1, "doc": "a render engine identifier of the running Blender"}, + {"name": "resolutionX", "type": "integer", "minimum": 4, "maximum": 16384}, + {"name": "resolutionY", "type": "integer", "minimum": 4, "maximum": 16384}, + {"name": "cameraName", "type": "string"} + ]}, + {"name": "look", "doc": "Capture the 3D view she is looking at; the receipt carries lookPath.", "changesScene": false, "editModeSafe": true, "fields": [ + ]}, + {"name": "createNodeGroup", "doc": "Create a geometry node group with an interface.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "interface", "type": "array", "required": true, "minItems": 1, "maxItems": 64, "items": {"type": "object", "properties": [{"name": "inOut", "type": "string", "required": true, "enum": ["INPUT", "OUTPUT"]}, {"name": "name", "type": "string", "required": true, "minLength": 1, "maxLength": 63}, {"name": "type", "type": "string", "required": true, "enum": ["Geometry", "Float", "Int", "Bool", "Vector"]}, {"name": "default", "type": "any", "doc": "a value of the socket's type"}]}, "doc": "sockets: {inOut, name, type, default?}"} + ]}, + {"name": "addNode", "doc": "Add a node to a geometry node group.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "id", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true, "doc": "brokkr's key for the node"}, + {"name": "blIdname", "type": "string", "required": true, "chars": "alnum", "prefixes": ["GeometryNode", "FunctionNode", "ShaderNode"], "forbid": ["Import", "Export", "Script", "Bake", "Group", "Simulation", "Repeat", "Foreach", "Viewer", "TexImage", "TexEnvironment", "ImageTexture", "InputImage", "TexIES"], "doc": "Blender's node type; file, script, cache, group and image nodes are refused"}, + {"name": "location", "type": "array", "items": {"type": "number", "minimum": -1000000000, "maximum": 1000000000}, "minItems": 2, "maxItems": 2, "default": [0, 0], "doc": "[x,y]"}, + {"name": "label", "type": "string", "maxLength": 63}, + {"name": "properties", "type": "object", "doc": "enum, bool, int or float node settings"}, + {"name": "inputs", "type": "object", "doc": "unlinked input defaults"} + ]}, + {"name": "removeNode", "doc": "Remove a node and its links.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "id", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true} + ]}, + {"name": "linkSockets", "doc": "Link one node's output socket to another's input.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "fromNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}, + {"name": "fromSocket", "type": "string", "required": true, "doc": "identifier or unique name"}, + {"name": "toNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}, + {"name": "toSocket", "type": "string", "required": true, "doc": "identifier or unique name"} + ]}, + {"name": "unlinkSockets", "doc": "Remove the links into an input socket, or only the one from a named output.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "toNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "required": true}, + {"name": "toSocket", "type": "string", "required": true}, + {"name": "fromNode", "type": "string", "chars": "id", "minLength": 1, "maxLength": 63, "doc": "with fromSocket: remove only that link"}, + {"name": "fromSocket", "type": "string"} + ]}, + {"name": "addModifier", "doc": "Add or retarget a Geometry Nodes modifier on an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "modifierType", "type": "string", "enum": ["NODES"], "default": "NODES"}, + {"name": "treeKind", "type": "string", "enum": ["geometry"], "default": "geometry"}, + {"name": "treeKey", "type": "string", "required": true, "chars": "key", "minLength": 1, "maxLength": 63, "doc": "the node group's name"}, + {"name": "modifierName", "type": "string", "chars": "key", "minLength": 1, "maxLength": 63, "default": "Brokkr GeoNodes"} + ]}, + {"name": "removeModifier", "doc": "Remove a Geometry Nodes modifier from an object.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "modifierName", "type": "string", "minLength": 1, "maxLength": 255, "forbid": ["\u0000"], "default": "Brokkr GeoNodes"} + ]}, + {"name": "setModifierInput", "doc": "Set one exposed input of a Geometry Nodes modifier.", "changesScene": true, "editModeSafe": false, "fields": [ + {"name": "objectName", "type": "string", "required": true, "doc": "the object's name"}, + {"name": "modifierName", "type": "string", "default": "Brokkr GeoNodes"}, + {"name": "socket", "type": "string", "required": true, "doc": "identifier or unique interface name"}, + {"name": "value", "type": "any", "required": true, "doc": "Float, Int, Bool or Vector"} + ]} + ] +} diff --git a/surfaces/blender/brokkr_bridge/blender_manifest.toml b/surfaces/blender/brokkr_bridge/blender_manifest.toml new file mode 100644 index 0000000..cbdf1d8 --- /dev/null +++ b/surfaces/blender/brokkr_bridge/blender_manifest.toml @@ -0,0 +1,13 @@ +schema_version = "1.0.0" +id = "brokkr_bridge" +version = "0.2.0" +name = "Brokkr Bridge" +tagline = "Brokkr command intents, receipts and snapshots over CultMesh" +maintainer = "GameCult " +type = "add-on" +blender_version_min = "5.3.0" +license = ["SPDX:GPL-3.0-or-later"] +# CultLib's cultnet-py and cultcache-py import msgpack; Blender's Python does not ship it. The wheel is one +# pure-Python msgpack 1.2.2 (no C extension), so the extension is platform-independent; CultLib 9fc4bdda +# (PR #180) decodes under msgpack's pure-Python fallback. Source and hash: docs/install.md. +wheels = ["./wheels/msgpack-1.2.2-py3-none-any.whl"] diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index 0c49412..db3a939 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -1,20 +1,36 @@ from __future__ import annotations +import contextlib import ctypes import functools import json import math import os +import re +import shutil +import signal +import struct +import subprocess import sys +import tempfile +import time import uuid +import zlib 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 +if os.name == "nt": + import msvcrt +else: + import fcntl + +from . import action_table as at 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" @@ -28,6 +44,8 @@ CULTLIB_PY_PACKAGES = ("cultcache-py", "cultnet-py", "cultmesh-py") DEFAULT_DEBUG_MIRROR_ROOT = "//.brokkr/blender-editor-debug" HOST_SNAPSHOT_SCHEMA = "brokkr.blender.host_snapshot.v0" +HOST_ACTIONS_FILE = "brokkr_actions.json" +HOST_RESULT_LIMIT = 16000 # characters of a host operator's result copied into a receipt COMMAND_INTENT_SCHEMA = "brokkr.blender.command_intent.v0" COMMAND_RECEIPT_SCHEMA = "brokkr.blender.command_receipt.v0" SYNC_SESSION_SCHEMA = "brokkr.sync.session.v0" @@ -36,12 +54,27 @@ SYNC_VAR_SCHEMA = "brokkr.sync.var.v0" SYNC_TIMELINE_BINDING_SCHEMA = "brokkr.sync.timeline_binding.v0" SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" -CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY") - -# Engines that draw through the GL stack. A headless Linux Blender without libEGL aborts the whole -# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. +# Engines that draw through the GL stack. A headless Blender with no usable GL device aborts the whole +# process inside bpy.ops.render.render for these (no receipt); CYCLES renders on the CPU. Whether it +# will is found by rendering one pixel in a child Blender (gl_render_failure), not by guessing at libraries. GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") -GL_RUNTIME_LIBRARY = "libEGL.so.1" +GL_PROBE_TIMEOUT_SECONDS = 120 +EXPORT_STAGE_PREFIX = ".brokkr-export-" +LEGACY_STAGE_LOCK = ".brokkr-lock" # older layout: the lock file inside the stage folder +STAGE_LOCK_SUFFIX = ".lock" # the lock file sits beside its stage folder: .lock +STAGE_JOURNAL = ".brokkr-journal" + +LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch) +LOOK_KEPT = 20 # the newest captures that stay after each look +EDIT_SELECTION_CAP = 4096 # indices listed per element kind and object; the total stays true beside the list +REQUESTED_BY_SHAPE = re.compile(r"^[A-Za-z0-9._-]+/[A-Za-z0-9._-]+$") +# A commandId becomes part of a receipt key, so it is a short string of key-safe characters ('.' is left +# 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 @@ -72,13 +105,16 @@ CAPABILITIES = ( ) +def _first_line(text: str) -> str: + return text.strip().splitlines()[0] if text.strip() else "failed" + + class BrokkrBlenderTarget: """Blender-owned adapter target for Brokkr mirror documents.""" 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 @@ -88,10 +124,24 @@ class BrokkrBlenderTarget: self._server: Any | None = None self._guard: SessionGuard | None = None self._cultmesh_module: str = "" - self._debug_mirror_root: str = "" self.import_dir: str = "" self.output_dir: str = "" self.nodes = na.NodeActions(bpy_module) + self.agent_turn = False # true only inside run_intent + self._wrote = True # run_intent: false when an accepted action changed nothing + self._receipted: set[str] = set() + self._host_docs: dict[str, Any] = {} # module -> parsed host document or the error that refused it; written only by reload_host_actions + self._unsent: list[tuple[dict[str, Any], str]] = [] # receipts whose write failed: written first on the next drain, never read as truth + self._recent: deque[dict[str, Any]] = deque(maxlen=RECEIPTS_KEPT) # display cache of the node's receipts + self._receipts_loaded = False + self.pending_count = 0 # display cache: intents queued in the node + # What she did, as observed: nothing reads these back to admit or refuse an intent (scene-last-writer-wins). + self.session_id = uuid.uuid4().hex + self.human_edit_seq = 0 + self._last_human_edit: dict[str, int] = {} # object name -> human_edit_seq when she last changed it + self._looked: dict[str, int] = {} # requestedBy -> human_edit_seq at that agent's last look + self.scene_update_seq = 0 # every depsgraph update, hers or the agent's: what a capture reflects + self._coarse = {"seq": 0, "why": ""} # the latest human edit whose per-object stamps are not precise def configure_action_dirs(self, import_dir: str, output_dir: str) -> None: """The directories importGltf and renderStill may touch; empty leaves that action disabled.""" @@ -110,8 +160,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: @@ -125,20 +176,41 @@ class BrokkrBlenderTarget: cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "", + limit: int | None = None, ) -> list[dict[str, Any]]: - node, documents = self._open_node(cache_path, cultlib_py_src) - if debug_mirror_root: - self._import_debug_command_files(node, documents["command_intent"], debug_mirror_root) + """Run queued intents, oldest key first: all of them, or at most `limit`, the rest staying queued. + At most once: an intent is deleted from the node before it runs, so a failed receipt write or a + crash can never run it again. A receipt that could not be written is held and written first on + the next drain; the intent is not on the queue to be re-run.""" + node, documents = self._open_node(cache_path, cultlib_py_src) + for receipt, suffix in list(self._unsent): + self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, key_suffix=suffix) + self._unsent.pop(0) snapshot = node.database.snapshot() commands = snapshot.get(COMMAND_INTENT_SCHEMA, {}) receipts: list[dict[str, Any]] = [] + self._seed_receipted(snapshot) - for command_key, command in sorted(commands.items()): - receipt = self.execute_command(context, command) - self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root) - node.database.delete(documents["command_intent"], command_key) + 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 + node.database.delete(documents["command_intent"], command_key) # claimed: nothing below can run it twice + receipt = self.run_intent(context, command) + if not valid: + # No safe key exists for this id: the denial is receipted under a fresh key and names the + # queue key, so the intent leaves the queue and its sender can still find the refusal. + receipt["message"] += f" (queue key {command_key})" + # Receipts are write-once: a reused id's denial goes under '.denied', never over the + # original. The sender learns of it by reading that key (and the drain's returned list). + suffix = ".denied" if reused else "" receipts.append(receipt) + try: + self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root, key_suffix=suffix) + except Exception: + self._unsent.append((receipt, suffix)) + raise return receipts @@ -148,13 +220,93 @@ class BrokkrBlenderTarget: cultlib_py_src: str, receipt: dict[str, Any], debug_mirror_root: str = "", + key_suffix: str = "", ) -> None: - command_id = receipt.get("commandId") or uuid.uuid4().hex node, documents = self._open_node(cache_path, cultlib_py_src) + self._put_receipt(node, documents, receipt, debug_mirror_root, key_suffix) + + def _put_receipt(self, node: Any, documents: dict[str, Any], receipt: dict[str, Any], + debug_mirror_root: str = "", key_suffix: str = "") -> None: + """The one place a receipt is written: the node, the debug export, and the panel's display cache.""" + command_id = (receipt.get("commandId") or uuid.uuid4().hex) + key_suffix node.database.put(documents["command_receipt"], f"blender/receipts/{command_id}", receipt) if debug_mirror_root: self._write_debug_document(debug_mirror_root, f"blender/receipts/{command_id}.json", receipt) - self.last_receipt = receipt + self.note_receipt(receipt) + + def _seed_receipted(self, snapshot: dict[str, Any]) -> None: + self._receipted.update( + r["commandId"] for r in snapshot.get(COMMAND_RECEIPT_SCHEMA, {}).values() + if isinstance(r.get("commandId"), str)) + + def stop_pending(self, reason: str, cache_path: str, cultlib_py_src: str, debug_mirror_root: str = "") -> int: + """The Stop button's path: every queued intent gets a 'stopped' receipt and leaves the queue unrun.""" + node, documents = self._open_node(cache_path, cultlib_py_src) + return self._stop_pending(node, documents, reason, debug_mirror_root) + + def _stop_pending(self, node: Any, documents: dict[str, Any], reason: str, debug_mirror_root: str = "") -> int: + """Stop, server start and server stop all take intents off the queue here and nowhere else.""" + if node is None: + return 0 + self._seed_receipted(node.database.snapshot()) + + def write(queue_key: str, intent: dict[str, Any], why: str) -> None: + valid = _valid_command_id(intent.get("commandId")) + reused = valid and intent["commandId"] in self._receipted + receipt = self._receipt(intent, "stopped", f"Stopped ({why}); the intent was not run and nothing was changed.", "") + if not valid: + receipt["message"] += f" (queue key {queue_key})" + self._put_receipt(node, documents, receipt, debug_mirror_root, ".stopped" if reused else "") + if valid: + self._receipted.add(intent["commandId"]) # the id is spent: the sender resends under a new one + + stopped = stop_pending(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, write, reason) + self.pending_count = 0 + return stopped + + def note_receipt(self, receipt: dict[str, Any]) -> None: + self._recent.append(receipt) + + def recent_receipts(self) -> list[dict[str, Any]]: + """The last few receipts, newest first.""" + return list(self._recent)[::-1][:RECEIPTS_SHOWN] + + def active_agents(self) -> list[str]: + """Distinct requestedBy among receipts from the last five minutes, in order of first appearance.""" + cutoff = datetime.now(timezone.utc) - ACTIVE_AGENT_WINDOW + agents: dict[str, None] = {} + for item in self._recent: + who, seen = item.get("requestedBy"), _parse_time(item.get("observedAt")) + if who and seen is not None and seen >= cutoff: + agents[who] = None + return list(agents) + + def load_recent_receipts(self, cache_path: str, cultlib_py_src: str) -> None: + """Rebuild the display cache from the node's receipts, once: it replaces what this session noted, since each of those was written to the node.""" + if self._receipts_loaded: + return + node, _documents = self._open_node(cache_path, cultlib_py_src) + stored = sorted(node.database.snapshot().get(COMMAND_RECEIPT_SCHEMA, {}).values(), + key=lambda r: str(r.get("observedAt", ""))) + self._recent = deque(stored, maxlen=RECEIPTS_KEPT) # the node holds every receipt this session noted + self._receipts_loaded = True + + def count_pending(self, cache_path: str, cultlib_py_src: str) -> int: + node, _documents = self._open_node(cache_path, cultlib_py_src) + node.database.pull() + self.pending_count = len(node.database.snapshot().get(COMMAND_INTENT_SCHEMA, {})) + return self.pending_count + + def store_exists(self, cache_path: str) -> bool: + return Path(self.resolve_cache_path(cache_path)).is_file() + + @property + def receipts_loaded(self) -> bool: + return self._receipts_loaded + + @property + def node_open(self) -> bool: + return self._node is not None def refresh_sync_receipt( self, @@ -328,7 +480,6 @@ class BrokkrBlenderTarget: port: int, max_snapshot_documents: int, max_snapshot_bytes: int, - debug_mirror_root: str = "", allow_non_loopback: bool = False, require_token: bool = False, ) -> dict[str, Any]: @@ -354,8 +505,7 @@ class BrokkrBlenderTarget: self.stop_server() self._cultmesh_module = "" - self._debug_mirror_root = self.resolve_debug_mirror_root(debug_mirror_root) if debug_mirror_root else "" - purge_command_intents(node, documents["command_intent"], COMMAND_INTENT_SCHEMA, self._debug_mirror_root) + 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() @@ -426,7 +576,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._debug_mirror_root) + self._stop_pending(self._node, self._documents, "server stopped") finally: self._server = None self._server_key = None @@ -458,8 +608,9 @@ 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 + host_rows, host_errors = self.host_actions() scan = self._instance_scan() if any(o.type == "MESH" and len(o.modifiers) for o in bpy.data.objects) else None selected = [item.name for item in context.selected_objects if item is not None] active_object = context.active_object.name if context.active_object else "" @@ -475,165 +626,353 @@ class BrokkrBlenderTarget: "activeScene": active_scene, "activeObjectName": active_object, "mode": context.mode, + "sessionId": self.session_id, + "humanEditSeq": self.human_edit_seq, + "editSelection": self.edit_selection(), "selectedObjectNames": selected, "sceneCount": len(bpy.data.scenes), "objectCount": len(bpy.data.objects), "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], "materials": [self._material_snapshot(material) for material in bpy.data.materials], "collections": [self._collection_snapshot(collection) for collection in bpy.data.collections], + "hostActions": host_rows, + "hostActionErrors": host_errors, } - def execute_command(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - action = command.get("action", "") - try: - if action == "createObject": - return self._create_object(context, command) - if action == "deleteObject": - return self._delete_object(context, command) - if action == "setObjectTransform": - return self._set_object_transform(context, command) - if action == "setObjectVisibility": - return self._set_object_visibility(context, command) - if action == "setObjectParent": - return self._set_object_parent(context, command) - if action == "setObjectCustomProperty": - return self._set_object_custom_property(context, command) - if action == "selectObject": - return self._select_object(context, command) - if action == "assignMaterial": - return self._assign_material(context, command) - if action == "importGltf": - return self._import_gltf(context, command) - if action == "exportGltf": - return self._export_gltf(context, command) - if action == "setCamera": - return self._set_camera(context, command) - if action == "setLight": - return self._set_light(context, command) - if action == "setWorld": - return self._set_world(context, command) - if action == "renderStill": - return self._render_still(context, command) - if action in na.NodeActions.ACTIONS: - message, name = self.nodes.execute(action, command) - return self._receipt(command, "accepted", message, name) - return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "") - except sa.ActionRefused as error: - return self._receipt(command, "failed", str(error), "") - except Exception as error: - return self._receipt(command, "failed", str(error), "") + def reload_host_actions(self) -> int: + """Read every enabled add-on's brokkr_actions.json (this add-on excepted) into the stored host documents, + replacing what was stored: the one place a host file is read. A human act: the panel's Reload Host Actions + button, and once shortly after this add-on registers. An intent never reaches it (an agent turn cannot + cause a re-read: this refuses inside one), so a file rewritten to list another operator admits nothing + until she reloads. A file is stored parsed and checked, or as the error that refused it; the live checks in + host_actions still run at every intent. Returns the number of host files found.""" + if self.agent_turn: + raise PermissionError("Host actions are reloaded by the human only, never inside an agent turn.") + own = __package__ or "" + docs: dict[str, Any] = {} + for module in self.bpy.context.preferences.addons.keys(): + if module == own: + continue + source = getattr(sys.modules.get(module), "__file__", None) + path = Path(source).with_name(HOST_ACTIONS_FILE) if source else None + if path is None or not path.is_file(): + continue + try: + document = json.loads(path.read_text(encoding="utf-8")) + at.check_host(document, at.table()["charsets"]) + docs[module] = document + except Exception as error: + docs[module] = str(error) + self._host_docs = docs + return len(docs) - def _create_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - object_type = command.get("objectType", "EMPTY") - if not isinstance(object_type, str) or object_type not in CREATABLE_OBJECT_TYPES: - shown = object_type if isinstance(object_type, str) else repr(object_type) - raise sa.ActionRefused( - f"objectType {shown!r} cannot be created; allowed: {', '.join(CREATABLE_OBJECT_TYPES)}.") - mesh_type = command.get("meshType") - if object_type == "MESH" and mesh_type is not None and ( - not isinstance(mesh_type, str) or mesh_type.upper() != "CUBE"): - raise sa.ActionRefused(f"meshType {mesh_type!r} is not available; a MESH is a CUBE.") + def host_actions(self) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """The host rows admitted now: ([row + 'host' module], [{host, error}]), from the documents the last + reload stored (no file is read here). A document is admitted whole or not at all. The file is the add-on's + word; what is checked here, at every call, is what Brokkr can see: the add-on is still enabled, the operator + exists and is a Python class defined by that add-on (module equal to it or under it: 'aeth_ships' is not + under 'aeth'), every field is a property of it of the matching type whose RNA hard limits contain the row's + bounds, a row that changes nothing names no operator that pushes undo itself (bl_options UNDO), and result + is a writable WindowManager string property. A disabled add-on or an unregistered operator is gone at the + next intent. A name two files claim fails ownership in all but its owner.""" + rows: list[dict[str, Any]] = [] + errors: list[dict[str, Any]] = [] + enabled = set(self.bpy.context.preferences.addons.keys()) + for module, document in self._host_docs.items(): + if module not in enabled: + continue + if isinstance(document, str): + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {document}")}) + continue + try: + for row in document["actions"]: + self._check_host_row(module, row) + except Exception as error: + errors.append({"host": module, "error": _first_line(f"{HOST_ACTIONS_FILE}: {error}")}) + continue + rows.extend({**row, "host": module} for row in document["actions"]) + return rows, errors + + def _check_host_row(self, module: str, row: dict[str, Any]) -> None: + bpy = self.bpy + name = row["name"] + first, second = name.split(".") + operator = getattr(getattr(bpy.ops, first), second) + owner = getattr(bpy.types, operator.idname(), None) + owned = getattr(owner, "__module__", None) + if not isinstance(owner, type) or not isinstance(owned, str) or not (owned == module or owned.startswith(module + ".")): + raise ValueError(f"{name} is not an operator defined by {module}") + if "UNDO" in getattr(owner, "bl_options", ()) and not row["changesScene"]: + raise ValueError(f"{name} pushes undo itself (bl_options UNDO) but the row says changesScene is false") + properties = {p.identifier: p for p in operator.get_rna_type().properties} + kinds = {"string": "STRING", "number": "FLOAT", "integer": "INT", "boolean": "BOOLEAN"} + for field in row["fields"]: + prop = properties.get(field["name"]) + where = f"{name}.{field['name']}" + if prop is None: + raise ValueError(f"{where} is not a property of the operator") + enum = field.get("enum") + if prop.type != ("ENUM" if enum is not None else kinds[field["type"]]): + raise ValueError(f"{where} is {prop.type} in the operator, not {field['type']}") + if enum is not None and {item.identifier for item in prop.enum_items} != set(enum): + raise ValueError(f"{where} enum differs from the operator's") + if field["type"] in ("number", "integer") and not (prop.hard_min <= field["minimum"] and field["maximum"] <= prop.hard_max): + raise ValueError(f"{where} bounds exceed the operator's own limits") + result = row.get("result") + if result is not None: + prop = bpy.types.WindowManager.bl_rna.properties.get(result) + if prop is None or prop.type != "STRING" or prop.is_readonly: + raise ValueError(f"{name} result {result} is not a writable string property of WindowManager") + + def run_intent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """The one agent turn: admit, run with operator undo off, push one labelled undo step, receipt. + + Admission order: commandId shape, id unused, requestedBy, then the action table (action known, fields + valid), then Edit Mode. While an object is in Edit Mode undo steps are edit-mesh steps, so a scene write + is not reverted by one undo and some operators leave Edit Mode + (brokkr-live:ruling:object-intents-refused-in-edit-mode); the table's editModeSafe actions write nothing + and change no mode. Host add-on rows (host_actions) are admitted by the same table check and run through + the same turn. A refusal at admission is 'denied': nothing ran, no undo step.""" + command_id = command.get("commandId") + requested_by = command.get("requestedBy") + action = command.get("action", "") + denial = "" + row = None + if not _valid_command_id(command_id): + denial = "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'." + elif command_id in self._receipted: + denial = f"commandId {command_id!r} was already receipted; ids are single-use." + elif not isinstance(requested_by, str) or not REQUESTED_BY_SHAPE.fullmatch(requested_by): + denial = "Intent has no requestedBy of the form '/'." + else: + try: + host, _ = self.host_actions() + command = at.validate(command, host) + row = at.entry(action, host) + except at.IntentInvalid as error: + denial = str(error) + if not denial and not row["editModeSafe"] and self._edit_mode_object() is not None: + denial = (f"Object {self._edit_mode_object()!r} is in Edit Mode: object-level intents are refused " + "until she leaves it; nothing was changed.") + if denial: + if _valid_command_id(command_id): + self._receipted.add(command_id) + return self._receipt(command, "denied", denial, "") + + label = f"Brokkr {requested_by}: {action} {command_id[-8:]}" # the tail: uuid v7 ids lead with a timestamp, one value per minute + push = row["changesScene"] + self.agent_turn = True + self._wrote = True + try: + try: + receipt = self._dispatch(context, command, row) + if receipt["status"] != "accepted" or not self._wrote: + push = False # a refusal, or an accepted no-op: it wrote nothing + except sa.ActionRefused as error: # raised before any write: nothing to push + receipt, push = self._receipt(command, "failed", str(error), ""), False + except Exception as error: # a partial write is one undoable step, not part of her next action + label += " (failed)" + receipt = self._receipt(command, "failed", str(error), "") + if push: + try: + self._push_undo(label) + receipt["undoLabel"] = label + except Exception as error: # the write stands; the intent is receipted, never re-run + receipt = self._receipt( + command, "failed", + f"{receipt['message']} The undo step could not be pushed ({error}); the change stands " + "but is not one undo step.", receipt["objectName"]) + finally: + self.agent_turn = False + self._receipted.add(command_id) + return receipt + + def _edit_mode_object(self) -> str | None: + for obj in self.bpy.data.objects.values(): + if getattr(obj, "mode", "OBJECT") == "EDIT": + return obj.name + return None + + def _push_undo(self, label: str) -> None: + windows = self.bpy.context.window_manager.windows + if windows: + with self.bpy.context.temp_override(window=windows[0]): + self.bpy.ops.ed.undo_push(message=label) + else: + self.bpy.ops.ed.undo_push(message=label) + + def _dispatch(self, context: Any, command: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]: + """Only run_intent calls it, with an intent the table admitted: a host row runs its operator; otherwise the + handler is '_' + the action's name, on NodeActions for the node actions and on this target for the rest. + It owns refusal, failure and the undo step.""" + action = command["action"] + if "host" in row: + return self._run_host_operator(context, command, row) + if hasattr(self.nodes, "_" + action): + message, name = self.nodes.execute(action, command) + self._wrote = self.nodes.changed + return self._receipt(command, "accepted", message, name) + return getattr(self, "_" + action)(context, command) + + def _run_host_operator(self, context: Any, command: dict[str, Any], row: dict[str, Any]) -> dict[str, Any]: + """A host add-on's own operator, called with exactly the declared fields. FINISHED is accepted; CANCELLED + is failed and wrote nothing; an argument Blender will not convert raises ActionRefused before anything + ran; an ERROR report or exception is RuntimeError, failed (run_intent pushes '(failed)' for a changesScene + row). A row's result property is cleared before and copied, capped, into the receipt.""" + bpy = self.bpy + name = row["name"] + skip = set(at.table()["envelope"]) + kwargs = {k: v for k, v in command.items() if k not in skip} + result = row.get("result") + manager = bpy.context.window_manager + first, second = name.split(".") + operator = getattr(getattr(bpy.ops, first), second) + windows = manager.windows + override = bpy.context.temp_override(window=windows[0]) if windows else contextlib.nullcontext() + # Everything that can refuse before the operator runs does so here, as ActionRefused: no undo step is pushed. + try: + with override: + runnable = operator.poll() + except Exception as error: + raise sa.ActionRefused(f"Operator {name} cannot run here: {_first_line(str(error))}") from None + if not runnable: + raise sa.ActionRefused(f"Operator {name} cannot run in this context (its poll failed); nothing changed.") + if result: + try: + setattr(manager, result, "") + except Exception as error: + raise sa.ActionRefused(f"Operator {name} result {result} cannot be cleared: {_first_line(str(error))}") from None + try: + with override: + outcome = operator("EXEC_DEFAULT", False, **kwargs) + except TypeError as error: + raise sa.ActionRefused(f"Operator {name} refused its arguments: {_first_line(str(error))}") from None + except RuntimeError as error: + lines = [line for line in str(error).splitlines() if line.strip()] + cause = lines[-1] if lines and "Traceback" in lines[0] else (lines[0] if lines else "failed") # a traceback's cause is its last line + raise RuntimeError(cause.strip()) from None + text = "" + if result: + text = getattr(manager, result, "") or "" + if len(text) > HOST_RESULT_LIMIT: + text = text[:HOST_RESULT_LIMIT] + " [truncated]" + if "FINISHED" in outcome: # run_intent pushes an undo step for an accepted changesScene row only + receipt = self._receipt(command, "accepted", f"Operator {name} finished.", "") + else: + receipt = self._receipt(command, "failed", f"Operator {name} cancelled; nothing changed.", "") + receipt["hostResult"] = text + return receipt + + def _createObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + object_type = command["objectType"] name = command.get("name") or f"Brokkr {object_type.title()}" - location = _vector(command.get("location"), 3, (0.0, 0.0, 0.0)) + location = tuple(command.get("location") or (0.0, 0.0, 0.0)) if object_type == "MESH": - self.bpy.ops.mesh.primitive_cube_add(size=float(command.get("size", 1.0)), location=location) + self.bpy.ops.mesh.primitive_cube_add("EXEC_DEFAULT", False, size=float(command["size"]), location=location) elif object_type == "LIGHT": - self.bpy.ops.object.light_add(type=command.get("lightType", "POINT"), location=location) + self.bpy.ops.object.light_add("EXEC_DEFAULT", False, type=command["lightType"], location=location) elif object_type == "CAMERA": - self.bpy.ops.object.camera_add(location=location) + self.bpy.ops.object.camera_add("EXEC_DEFAULT", False, location=location) else: # EMPTY - self.bpy.ops.object.empty_add(type=command.get("emptyDisplayType", "PLAIN_AXES"), location=location) + self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, type=command["emptyDisplayType"], location=location) obj = context.object obj.name = name return self._receipt(command, "accepted", "Blender object created.", obj.name) - def _delete_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _deleteObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") self.bpy.data.objects.remove(obj, do_unlink=True) return self._receipt(command, "accepted", "Blender object deleted.", command.get("targetObjectName", "")) - def _set_object_transform(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectTransform(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") if "location" in command: - obj.location = _vector(command["location"], 3, obj.location) + obj.location = tuple(command["location"]) if "rotationEuler" in command: - obj.rotation_euler = _vector(command["rotationEuler"], 3, obj.rotation_euler) + obj.rotation_euler = tuple(command["rotationEuler"]) if "scale" in command: - obj.scale = _vector(command["scale"], 3, obj.scale) + obj.scale = tuple(command["scale"]) return self._receipt(command, "accepted", "Blender object transform updated.", obj.name) - def _set_object_visibility(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectVisibility(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - visible = bool(command.get("visible", True)) + visible = command["visible"] obj.hide_viewport = not visible obj.hide_render = not visible return self._receipt(command, "accepted", "Blender object visibility updated.", obj.name) - def _set_object_parent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectParent(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - parent_name = command.get("parentObjectName") or command.get("parentName") or "" + parent_name = command.get("parentObjectName") or "" parent = self.bpy.data.objects.get(parent_name) if parent_name else None if parent_name and parent is None: return self._receipt(command, "failed", f"Parent Blender object was not found: {parent_name}", obj.name) + ancestor = parent + while ancestor is not None: # Blender raises for a loop after the undo step is owed: refuse it before + if ancestor.name == obj.name: + raise sa.ActionRefused(f"{obj.name!r} cannot be parented to itself or to one of its own children.") + ancestor = getattr(ancestor, "parent", None) obj.parent = parent return self._receipt(command, "accepted", "Blender object parent updated.", obj.name) - def _set_object_custom_property(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setObjectCustomProperty(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - property_name = command.get("propertyName") or "brokkrValue" + property_name = command["propertyName"] if property_name.startswith("customProperties."): property_name = property_name[len("customProperties."):] modifier_name = na.drives_modifier_input(obj, property_name) if modifier_name: return self._receipt(command, "failed", f"{property_name!r} is an input of Geometry Nodes modifier {modifier_name!r}; " "a custom property does not drive it, use setModifierInput.", obj.name) - obj[property_name] = command.get("value") + obj[property_name] = command["value"] return self._receipt(command, "accepted", "Blender custom property updated.", obj.name) - def _select_object(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _selectObject(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") - if command.get("clearSelection", True): + if command["clearSelection"]: for existing in context.selected_objects: existing.select_set(False) obj.select_set(True) context.view_layer.objects.active = obj return self._receipt(command, "accepted", "Blender object selected.", obj.name) - def _assign_material(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _assignMaterial(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_object(command) if obj is None: return self._receipt(command, "failed", "Target Blender object was not found.", "") if not (obj.data and hasattr(obj.data, "materials")): return self._receipt(command, "failed", "Target object cannot receive materials.", obj.name) - rgba = sa.color_rgba(command) # refused before anything is created or changed - material_name = command.get("materialName") or "Brokkr Material" + color = command.get("color") + rgba = (*color, 1.0)[:4] if color is not None else None # the table admits [r,g,b] or [r,g,b,a] + material_name = command["materialName"] material = self.bpy.data.materials.get(material_name) or self.bpy.data.materials.new(material_name) if rgba is not None: if not material.use_nodes or material.node_tree is None: @@ -647,8 +986,8 @@ class BrokkrBlenderTarget: obj.data.materials.append(material) return self._receipt(command, "accepted", "Blender material assigned.", obj.name) - def _import_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - name = str(command.get("filepath") or "") + def _importGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + name = command["filepath"] path = sa.resolve_inside(self.import_dir, name, "import") sa.require_gltf(path) stamped = sa.fingerprint([path]) # before the parse, so a swap during it shows @@ -662,30 +1001,23 @@ class BrokkrBlenderTarget: (sa.fingerprint([path]), sa.fingerprint(existing)) != checked: raise sa.ActionRefused("Import file changed while it was being checked.") before = set(self.bpy.data.objects.keys()) - self.bpy.ops.import_scene.gltf(filepath=str(path)) + self.bpy.ops.import_scene.gltf("EXEC_DEFAULT", False, filepath=str(path)) added = sorted(set(self.bpy.data.objects.keys()) - before) return self._receipt(command, "accepted", f"Imported {len(added)} object(s) from {path.name}.", added[0] if added else "") - def _export_gltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _exportGltf(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: """Write the scene (or the named objects) as .glb or .gltf under the output directory.""" - name = command.get("filepath") - if not isinstance(name, str): - raise sa.ActionRefused("filepath must be a string.") + name = command["filepath"] + if self.output_dir: + _sweep_stale_stages(Path(self.output_dir).resolve()) path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) suffix = path.suffix.lower() if suffix not in sa.GLTF_EXTENSIONS: raise sa.ActionRefused(f"Export path must end in {' or '.join(sa.GLTF_EXTENSIONS)}.") - options = {} - for field, key in (("extras", "export_extras"), ("yUp", "export_yup"), ("applyModifiers", "export_apply")): - value = command.get(field, True) - if not isinstance(value, bool): - raise sa.ActionRefused(f"{field} must be true or false.") - options[key] = value + options = {"export_extras": command["extras"], "export_yup": command["yUp"], "export_apply": command["applyModifiers"]} names = command.get("selection") chosen = [] if names is not None: - if not isinstance(names, list) or not names or not all(isinstance(n, str) and n for n in names): - raise sa.ActionRefused("selection must be a non-empty list of object names.") missing = [n for n in names if n not in self.bpy.data.objects] if missing: raise sa.ActionRefused(f"Selection object was not found: {missing[0]}") @@ -695,30 +1027,91 @@ class BrokkrBlenderTarget: off_layer = [o.name for o in chosen if o.name not in context.view_layer.objects] if off_layer: raise sa.ActionRefused(f"Selection object is not in the active view layer: {off_layer[0]}") - binary = path.with_suffix(".bin") - if suffix == ".gltf" and os.path.lexists(binary): - raise sa.ActionRefused("output path already exists; output actions never overwrite: " + binary.name) - path.parent.mkdir(parents=True, exist_ok=True) - # Re-check after the folders exist and just before use (residual TOCTOU as in renderStill). - if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: - raise sa.ActionRefused("Output path changed while it was being checked.") - # The selection is touched only when one was asked for, and only on view-layer objects. - objects = list(context.view_layer.objects.values()) if chosen else [] - saved = [(obj, obj.select_get()) for obj in objects] + # The exporter writes into a fresh staging folder beside the target, never onto the output + # directory: it may also write a .bin and texture files whose names Brokkr does not choose. Only + # after it finishes does every file move into place, each refused if its name is taken, so no + # existing file is overwritten and a failed export leaves nothing behind (not even new folders). + made = [] + for folder in (path.parent, *path.parent.parents): + if folder.exists() or folder == Path(self.output_dir).resolve(): + break + made.append(folder) + stage = None + lock_fd = None + moved: list[tuple[Path, Path]] = [] + new_dirs: list[Path] = [] try: - for obj in objects: - obj.select_set(obj in chosen) - result = self.bpy.ops.export_scene.gltf( - filepath=str(path), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", - use_selection=bool(chosen), **options) - finally: - for obj, state in saved: - if obj.name in self.bpy.data.objects: - obj.select_set(state) - if "FINISHED" not in result: - raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}") - if not path.is_file(): - raise sa.ActionRefused("glTF export wrote no file.") + path.parent.mkdir(parents=True, exist_ok=True) + # Re-check after the folders exist and just before use (residual TOCTOU as in renderStill). + if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: + raise sa.ActionRefused("Output path changed while it was being checked.") + stage, lock_fd = _open_stage(path.parent) + staged = stage / path.name + # The selection is touched only when one was asked for, and only on view-layer objects. + objects = list(context.view_layer.objects.values()) if chosen else [] + saved = [(obj, obj.select_get()) for obj in objects] + try: + for obj in objects: + obj.select_set(obj in chosen) + result = self.bpy.ops.export_scene.gltf("EXEC_DEFAULT", False, + filepath=str(staged), export_format="GLB" if suffix == ".glb" else "GLTF_SEPARATE", + use_selection=bool(chosen), **options) + finally: + for obj, state in saved: + if obj.name in self.bpy.data.objects: + obj.select_set(state) + if "FINISHED" not in result: + raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}") + if not staged.is_file(): + raise sa.ActionRefused("glTF export wrote no file.") + written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file()) + taken = [str(f) for f in written if os.path.lexists(path.parent / f)] + if taken: + raise sa.ActionRefused("output path already exists; output actions never overwrite: " + taken[0]) + for relative in written: + target = path.parent / relative + for folder in (target.parent, *target.parent.parents): + if folder.exists() or folder == path.parent: + break + new_dirs.append(folder) + target.parent.mkdir(parents=True, exist_ok=True) + os.rename(stage / relative, target) + moved.append((stage / relative, target)) + except BaseException as failure: + # A move that fails partway is rolled back: the target is the whole new export or untouched. + stuck = [] + for source, target in reversed(moved): + try: + os.rename(target, source) + except OSError: + stuck.append(target) + if stage is not None and stuck: + # The rollback itself failed: keep the stage with a journal of the files left in the + # target. The journal is written while the lock is held, so no sweep can take the stage + # first; once the lock is released the next export's sweep removes them and the retry works. + try: + (stage / STAGE_JOURNAL).write_text( + "\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8") + finally: + os.close(lock_fd) + raise sa.ActionRefused( + "glTF export failed and could not be rolled back; files left in the output directory: " + + ", ".join(t.relative_to(Path(self.output_dir).resolve()).as_posix() for t in stuck) + + ". The next export removes them.") from failure + if stage is not None: + _close_stage(stage, lock_fd) + for folder in sorted(set(new_dirs), key=lambda f: -len(f.parts)): + try: + folder.rmdir() + except OSError: + pass + for folder in made: # deepest first: only the folders this call made, only if still empty + try: + folder.rmdir() + except OSError: + pass + raise + _close_stage(stage, lock_fd) return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "") def _resolve_typed(self, command: dict[str, Any], object_type: str) -> Any: @@ -729,58 +1122,40 @@ class BrokkrBlenderTarget: raise sa.ActionRefused(f"Target Blender object is not a {object_type}.") return obj - def _set_camera(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setCamera(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_typed(command, "CAMERA") camera = obj.data - # Validate everything before changing anything, so a refused intent leaves the camera alone. - lens = sa.number(command, "lens", 1.0, sa.MAX_LENS_MM) - camera_type = sa.choice(command, "cameraType", sa.CAMERA_TYPES) - ortho_scale = sa.number(command, "orthoScale", 0.001, 100000.0) - clip_start = sa.number(command, "clipStart", 0.0001, 1.0e6) - clip_end = sa.number(command, "clipEnd", 0.001, 1.0e7) - panorama_type = sa.choice(command, "panoramaType", self._panorama_types(camera)) - if lens is not None: - camera.lens = lens - if camera_type is not None: - camera.type = camera_type - if ortho_scale is not None: - camera.ortho_scale = ortho_scale - if clip_start is not None: - camera.clip_start = clip_start - if clip_end is not None: - camera.clip_end = clip_end - if panorama_type is not None: - # Blender 4.2 moved panorama_type from camera.cycles to the camera itself. - holder = camera if hasattr(camera, "panorama_type") else camera.cycles - holder.panorama_type = panorama_type + # Nothing below can be refused: the table checked every value, so a camera is never half set. + if "lens" in command: + camera.lens = command["lens"] + if "cameraType" in command: + camera.type = command["cameraType"] + if "orthoScale" in command: + camera.ortho_scale = command["orthoScale"] + if "clipStart" in command: + camera.clip_start = command["clipStart"] + if "clipEnd" in command: + camera.clip_end = command["clipEnd"] + if "panoramaType" in command: + camera.panorama_type = command["panoramaType"] # on the camera since Blender 4.2 if command.get("active"): context.scene.camera = obj return self._receipt(command, "accepted", "Blender camera updated.", obj.name) - def _panorama_types(self, camera: Any) -> tuple[str, ...]: - holder = camera if hasattr(camera, "panorama_type") else getattr(camera, "cycles", camera) - try: - return tuple(item.identifier for item in holder.bl_rna.properties["panorama_type"].enum_items) - except (KeyError, AttributeError): - return ("EQUIRECTANGULAR", "EQUIDISTANT", "FISHEYE_EQUISOLID", "MIRRORBALL") - - def _set_light(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _setLight(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: obj = self._resolve_typed(command, "LIGHT") - energy = sa.number(command, "energy", 0.0, 1.0e7) - light_color = sa.color(command) - light_type = sa.choice(command, "lightType", sa.LIGHT_TYPES) - if energy is not None: - obj.data.energy = energy - if light_color is not None: - obj.data.color = light_color - if light_type is not None: - obj.data.type = light_type + if "energy" in command: + obj.data.energy = command["energy"] + if "color" in command: + obj.data.color = tuple(command["color"]) + if "lightType" in command: + obj.data.type = command["lightType"] return self._receipt(command, "accepted", "Blender light updated.", obj.name) - def _set_world(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: - world_color = sa.color(command) - strength = sa.number(command, "strength", 0.0, 1.0e6) - name = str(command.get("worldName") or "") + def _setWorld(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + world_color = command.get("color") + strength = command.get("strength") + name = command.get("worldName") or "" scene = context.scene world = self.bpy.data.worlds.get(name) if name else scene.world if world is None: @@ -796,22 +1171,19 @@ class BrokkrBlenderTarget: background.inputs["Strength"].default_value = strength return self._receipt(command, "accepted", "Blender world updated.", world.name) - def _render_still(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + def _renderStill(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: scene = context.scene render = scene.render - name = str(command.get("outputPath") or "") + name = command["outputPath"] path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) file_format = sa.still_format(path) # The engine enum is dynamic (Cycles and add-on engines register at runtime), and RNA's # enum_items on a dynamic enum lists only its static defaults, so the running Blender is # asked by assignment below and a TypeError there is the refusal. - engine = command.get("engine") - if engine is not None and (not isinstance(engine, str) or not engine.strip()): - raise sa.ActionRefused("engine must be a render engine identifier.") - engine = engine.strip().upper() if engine else None - width = sa.integer(command, "resolutionX", 1, sa.MAX_RESOLUTION) - height = sa.integer(command, "resolutionY", 1, sa.MAX_RESOLUTION) - camera_name = str(command.get("cameraName") or "") + engine = command.get("engine") # an identifier, exactly as given: a name Blender does not have is a TypeError below + width = command.get("resolutionX") + height = command.get("resolutionY") + camera_name = command.get("cameraName") or "" camera = None if camera_name: camera = self.bpy.data.objects.get(camera_name) @@ -827,11 +1199,11 @@ class BrokkrBlenderTarget: except TypeError: raise sa.ActionRefused(f"engine {engine} is not available in this Blender.") from None if render.engine in GL_RENDER_ENGINES and getattr(getattr(self.bpy, "app", None), "background", False): - missing = missing_gl_library() - if missing: + failure = gl_render_failure(getattr(self.bpy.app, "binary_path", ""), render.engine) + if failure: raise sa.ActionRefused( - f"engine {render.engine} needs {missing}, which this headless Blender cannot load " - "(rendering would abort the process); use engine CYCLES.") + f"engine {render.engine} cannot render in this headless Blender ({failure}); " + "rendering would abort the process; use engine CYCLES.") if width is not None: render.resolution_x = width if height is not None: @@ -848,14 +1220,187 @@ class BrokkrBlenderTarget: path.parent.mkdir(parents=True, exist_ok=True) if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: raise sa.ActionRefused("Output path changed while it was being checked.") - self.bpy.ops.render.render(write_still=True) + self.bpy.ops.render.render("EXEC_DEFAULT", False, write_still=True) finally: (render.engine, render.resolution_x, render.resolution_y, render.filepath, render.image_settings.file_format, scene.camera) = saved return self._receipt(command, "accepted", f"Rendered still to {path.name}.", scene.name) + # ---- perception: what she sees and what she did ---------------------------------------------------------- + + def renew_session(self) -> None: + """A new session id and zeroed counters: names mean something else in a freshly loaded file.""" + self.session_id = uuid.uuid4().hex + self.human_edit_seq = 0 + self._last_human_edit.clear() + self._looked.clear() + self.scene_update_seq = 0 + self._coarse = {"seq": 0, "why": ""} + + def track_human_edits(self, depsgraph: Any) -> None: + """A depsgraph update outside an agent turn is hers. What changed is read from each update's flags, never + from presence in the list: an update also names what only depends on the change.""" + self.scene_update_seq += 1 + if self.agent_turn: + return + changed = [u.id.name for u in depsgraph.updates + if u.id.id_type == "OBJECT" and (u.is_updated_transform or u.is_updated_geometry or u.is_updated_shading)] + if not changed: + return + self.human_edit_seq += 1 + for name in changed: + self._last_human_edit[name] = self.human_edit_seq + if len(changed) >= 2 and len(changed) == len(self.bpy.data.objects): + self._coarse = {"seq": self.human_edit_seq, "why": "all objects flagged"} # an add or a link does this + + def note_undo_redo(self) -> None: + """An undo or redo cannot be narrowed to objects from its updates, so it moves the session counter only.""" + self.human_edit_seq += 1 + self._coarse = {"seq": self.human_edit_seq, "why": "undo or redo flags all objects"} + + def last_human_edit_seq(self, name: str) -> int: + return self._last_human_edit.get(name, 0) + + def edit_selection(self) -> list[dict[str, Any]]: + """Her selection in every object in Edit Mode, read live from the edit mesh without leaving the mode.""" + editing = [obj for obj in self.bpy.data.objects if getattr(obj, "mode", "OBJECT") == "EDIT"] + entries: list[dict[str, Any]] = [] + if not editing: + return entries + import bmesh # exists only inside Blender; nothing is imported when no object is being edited + for obj in editing: + if obj.type != "MESH": + entries.append({"name": obj.name, "type": obj.type, "unsupported": True}) + continue + mesh = bmesh.from_edit_mesh(obj.data) + entry: dict[str, Any] = {"name": obj.name, "type": obj.type} + # The totals are the mesh's own counts; the scan stops at the cap or when every selected one is found. + for key, elements, total in (("vertices", mesh.verts, obj.data.total_vert_sel), + ("edges", mesh.edges, obj.data.total_edge_sel), + ("faces", mesh.faces, obj.data.total_face_sel)): + chosen: list[int] = [] + want = min(total, EDIT_SELECTION_CAP) + if want: + for index, element in enumerate(elements): + if element.select: + chosen.append(index) + if len(chosen) == want: + break + entry[key] = chosen + entry[key + "Total"] = total + entries.append(entry) + return entries + + def _viewport(self) -> tuple[Any, Any, Any]: + """The window, area and WINDOW region of the largest 3D view: the only pixels look may read.""" + best = None + for window in self.bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D" and (best is None or area.width * area.height > best[1].width * best[1].height): + best = (window, area) + region = next((r for r in best[1].regions if r.type == "WINDOW"), None) if best else None + if region is None: + raise sa.ActionRefused("No 3D viewport is open to look at.") + return best[0], best[1], region + + def _look(self, context: Any, command: dict[str, Any]) -> dict[str, Any]: + """Capture her 3D view to /look/.png. screenshot_area reads Blender's own framebuffer + for the area it is overridden to, so the desktop and other applications are never in the picture; a menu or + popup Blender draws over the view is, as she sees it.""" + name = f"{LOOK_DIR}/{command['commandId']}.png" + path = sa.resolve_inside(self.output_dir, name, "output", new_file=True) + window, area, region = self._viewport() + path.parent.mkdir(parents=True, exist_ok=True) + if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path: + raise sa.ActionRefused("Output path changed while it was being checked.") + source = "region" if self._windows_drawn() else "offscreen" + if source == "region": + with self.bpy.context.temp_override(window=window, area=area, region=region): + result = self.bpy.ops.screen.screenshot_area("EXEC_DEFAULT", False, filepath=str(path)) + if "FINISHED" not in result or not path.is_file(): + raise sa.ActionRefused("Blender did not write the capture.") + else: # a minimised window stops redrawing, so its framebuffer is a stale frame: draw the view itself + try: + width, height, rgba = self._render_view_offscreen(window, area, region) + path.write_bytes(_png_bytes(width, height, rgba)) + except Exception: + path.unlink(missing_ok=True) + raise sa.ActionRefused("Blender is not drawing its window and the view could not be rendered offscreen.") from None + self._prune_looks(path.parent) + requested_by = command["requestedBy"] + since = self._looked.get(requested_by, 0) + self._looked[requested_by] = self.human_edit_seq + coarse = self._coarse["seq"] > since + receipt = self._receipt(command, "accepted", f"Captured the 3D view to {LOOK_DIR}/{path.name}.", "") + receipt.update({ + "lookPath": str(path), + "captureSource": source, + "sceneUpdateSeq": self.scene_update_seq, + "sessionId": self.session_id, + "humanEditSeq": self.human_edit_seq, + "humanEditsSinceLook": self.human_edit_seq - since, + "editedSinceLook": sorted(n for n, seq in self._last_human_edit.items() if seq > since), + "editedSinceLookCoarse": coarse, + "editedSinceLookNote": (f"Coarse: {self._coarse['why']}; editedSinceLook may name objects she did not touch." + if coarse else ""), + "editSelection": self.edit_selection(), + }) + self._wrote = False + return receipt + + def _windows_drawn(self) -> bool: + """False when every Blender window of this process is minimised, so none is redrawing. Only Windows can + say; elsewhere a window is taken as drawn.""" + if sys.platform != "win32": + return True + from ctypes import wintypes + user32 = ctypes.windll.user32 + iconic: list[bool] = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _lparam): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + name = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, name, 64) + if owner.value == os.getpid() and name.value == "GHOST_WindowClass" and user32.IsWindowVisible(hwnd): + iconic.append(bool(user32.IsIconic(hwnd))) + return True + + user32.EnumWindows(visit, 0) + return not iconic or not all(iconic) + + def _render_view_offscreen(self, window: Any, area: Any, region: Any) -> tuple[int, int, bytes]: + """The 3D view's own viewpoint drawn into an offscreen buffer of the region's size: RGBA bytes, bottom row + first. Overlays and popups are not drawn.""" + import gpu # only inside Blender + space = area.spaces.active + rv3d = space.region_3d + width, height = region.width, region.height + context = self.bpy.context + offscreen = gpu.types.GPUOffScreen(width, height) + try: + offscreen.draw_view3d(context.scene, context.view_layer, space, region, rv3d.view_matrix, + rv3d.window_matrix, do_color_management=True) + with offscreen.bind(): + buffer = gpu.state.active_framebuffer_get().read_color(0, 0, width, height, 4, 0, "UBYTE") + return width, height, bytes(buffer) + finally: + offscreen.free() + + @staticmethod + def _prune_looks(directory: Path) -> None: + """Keep the newest LOOK_KEPT captures: plain .png files directly in the look directory, nothing else.""" + found = [] + with os.scandir(directory) as entries: + for entry in entries: + if entry.name.lower().endswith(".png") and entry.is_file(follow_symlinks=False): + found.append((entry.stat(follow_symlinks=False).st_mtime_ns, entry.name, entry.path)) + for _mtime, _name, old in sorted(found)[:-LOOK_KEPT]: + os.unlink(old) + def _resolve_object(self, command: dict[str, Any]) -> Any: - name = command.get("targetObjectName") or command.get("objectName") + name = command.get("targetObjectName") return self.bpy.data.objects.get(name) if name else None def _scene_snapshot(self, scene: Any) -> dict[str, Any]: @@ -881,6 +1426,7 @@ class BrokkrBlenderTarget: "scale": _to_list(obj.scale), "visible": bool(obj.visible_get()), "selected": bool(obj.select_get()), + "lastHumanEditSeq": self.last_human_edit_seq(obj.name), "parentName": obj.parent.name if obj.parent else "", "collections": [collection.name for collection in obj.users_collection], "materials": [slot.material.name for slot in obj.material_slots if slot.material], @@ -1008,11 +1554,16 @@ class BrokkrBlenderTarget: def _receipt(self, command: dict[str, Any], status: str, message: str, object_name: str) -> dict[str, Any]: return { "schema": COMMAND_RECEIPT_SCHEMA, - "commandId": command.get("commandId") or uuid.uuid4().hex, + "commandId": command["commandId"] if _valid_command_id(command.get("commandId")) else uuid.uuid4().hex, "action": command.get("action", ""), "status": status, "message": message, "objectName": object_name, + "requestedBy": command["requestedBy"] if isinstance(command.get("requestedBy"), str) else "", + "note": command["note"][:NOTE_LIMIT] if isinstance(command.get("note"), str) else "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", "observedAt": _now(), } @@ -1026,16 +1577,7 @@ class BrokkrBlenderTarget: return self._node, self._documents cultmesh, cultcache = _load_cultmesh(cultlib_py_src) - documents = { - "host_snapshot": cultcache.define_document_type(HOST_SNAPSHOT_SCHEMA), - "command_intent": cultcache.define_document_type(COMMAND_INTENT_SCHEMA), - "command_receipt": cultcache.define_document_type(COMMAND_RECEIPT_SCHEMA), - "sync_session": cultcache.define_document_type(SYNC_SESSION_SCHEMA), - "sync_object_binding": cultcache.define_document_type(SYNC_OBJECT_BINDING_SCHEMA), - "sync_var": cultcache.define_document_type(SYNC_VAR_SCHEMA), - "sync_timeline_binding": cultcache.define_document_type(SYNC_TIMELINE_BINDING_SCHEMA), - "sync_receipt": cultcache.define_document_type(SYNC_RECEIPT_SCHEMA), - } + documents = bridge_documents(cultcache) node = cultmesh.CultMesh.start_node(path, runtime_id=runtime_id) for document in documents.values(): node.database.register_document(document) @@ -1046,17 +1588,6 @@ class BrokkrBlenderTarget: self._documents = documents return node, documents - def _import_debug_command_files(self, node: Any, command_document: Any, debug_mirror_root: str) -> None: - commands_root = Path(self.resolve_debug_mirror_root(debug_mirror_root)) / "blender" / "commands" - for command_path in sorted(commands_root.glob("*.json")): - with command_path.open("r", encoding="utf-8") as handle: - command = json.load(handle) - command_id = command.get("commandId") or command_path.stem - command["schema"] = command.get("schema") or COMMAND_INTENT_SCHEMA - command["commandId"] = command_id - node.database.put(command_document, f"blender/commands/{command_id}", command) - command_path.unlink(missing_ok=True) - def _write_debug_document(self, debug_mirror_root: str, relative_path: str, document: dict[str, Any]) -> None: path = Path(self.resolve_debug_mirror_root(debug_mirror_root)) / relative_path path.parent.mkdir(parents=True, exist_ok=True) @@ -1095,6 +1626,41 @@ class BrokkrBlenderTarget: }) +def bridge_documents(cultcache: Any) -> dict[str, Any]: + """The bridge's eight document definitions, under cultcache-py's default (MessagePack) payload codec.""" + return { + "host_snapshot": cultcache.define_document_type(HOST_SNAPSHOT_SCHEMA), + "command_intent": cultcache.define_document_type(COMMAND_INTENT_SCHEMA), + "command_receipt": cultcache.define_document_type(COMMAND_RECEIPT_SCHEMA), + "sync_session": cultcache.define_document_type(SYNC_SESSION_SCHEMA), + "sync_object_binding": cultcache.define_document_type(SYNC_OBJECT_BINDING_SCHEMA), + "sync_var": cultcache.define_document_type(SYNC_VAR_SCHEMA), + "sync_timeline_binding": cultcache.define_document_type(SYNC_TIMELINE_BINDING_SCHEMA), + "sync_receipt": cultcache.define_document_type(SYNC_RECEIPT_SCHEMA), + } + + +def convert_store(source: str, destination: str, cultlib_py_src: str = "") -> int: + """Write the records of a bridge store to a new MessagePack file and return the count converted. + JSON payloads (the old default) are converted; MessagePack payloads, such as records the new daemon already + appended to the old store, are carried through. The destination must not exist and the source is never written: + stop every writer, convert, then swap the files.""" + _cultmesh, cultcache = _load_cultmesh(cultlib_py_src) + json_codec, msgpack_codec = cultcache.JSON_PAYLOAD_CODEC, cultcache.MESSAGEPACK_PAYLOAD_CODEC + + def decode_either(payload: bytes) -> Any: + # A JSON object or array never starts like a MessagePack map or array, so a payload JSON refuses is MessagePack. + try: + return json_codec.decode(payload) + except Exception: + return msgpack_codec.decode(payload) + + either = cultcache.PayloadCodec("JSON or MessagePack", json_codec.encode, decode_either) + return cultcache.convert( + cultcache.SingleFileMessagePackBackingStore(source), destination, bridge_documents(cultcache).values(), + source_codec=either) + + def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: packages = Path(cultlib_py_src or DEFAULT_CULTLIB_PY_SRC) for name in CULTLIB_PY_PACKAGES: @@ -1107,24 +1673,208 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]: import cultmesh_py # type: ignore import cultcache_py # type: ignore except ModuleNotFoundError as exc: + own = {name.replace("-", "_") for name in CULTLIB_PY_PACKAGES} + if exc.name in own: + raise RuntimeError( + "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " + "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + ) from exc raise RuntimeError( - "Brokkr Blender target requires CultLib's Python packages. Set CultLib Python Source " - "to the CultLib packages directory or install cultcache-py, cultnet-py and cultmesh-py into Blender's Python." + f"A CultLib Python package needs the module {exc.name!r}, which Blender's Python does not have. " + "Install the add-on as an extension (it bundles msgpack) or install that module into Blender's Python." ) from exc + if not hasattr(cultcache_py, "convert"): + raise RuntimeError( + "Brokkr Blender target requires CultLib's cultcache-py with the MessagePack payload default " + "(CultLib main after the py-msgpack-default merge); the cultcache-py found here predates it. " + "Update the CultLib checkout named by CultLib Python Source.") return cultmesh_py, cultcache_py -@functools.lru_cache(maxsize=None) -def missing_gl_library() -> str | None: - """The GL runtime library this host cannot load, or None. Probed once, on Linux only: on - Windows and macOS a failed GPU render is not a headless-EGL abort.""" - if not sys.platform.startswith("linux"): - return None +GL_PROBE_SCRIPT = Path(__file__).with_name("gl_probe.py") # runs inside the child Blender + + +def _try_lock(fd: int) -> bool: + """Take an exclusive lock on the file, without waiting; the OS drops it when the holder dies.""" try: - ctypes.CDLL(GL_RUNTIME_LIBRARY) + if os.name == "nt": + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) + else: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: - return GL_RUNTIME_LIBRARY - return None + return False + return True + + +def _stage_lock_path(stage: Path) -> Path: + return stage.with_name(stage.name + STAGE_LOCK_SUFFIX) + + +def _open_stage(parent: Path) -> tuple[Path, int]: + """A fresh staging folder in parent, guarded by a lock file beside it that this export holds until it + closes the descriptor or dies. The lock file is created and locked first and the folder second, so + every stage on disk is either locked-live or sweepable: a kill at any step leaves a lock file a sweep + can take, never a folder no sweep can see.""" + while True: + stage = parent / (EXPORT_STAGE_PREFIX + uuid.uuid4().hex[:16]) + try: + fd = os.open(_stage_lock_path(stage), os.O_RDWR | os.O_CREAT | os.O_EXCL) + except FileExistsError: + continue + break + try: + for attempt in range(5): # a sweep may hold a fresh lock file for an instant + if _try_lock(fd): + break + time.sleep(0.02 * (attempt + 1)) + else: + raise OSError(f"could not lock staging folder {stage}") + stage.mkdir() + except BaseException: + os.close(fd) + _unlink_quietly(_stage_lock_path(stage)) + raise + return stage, fd + + +def _close_stage(stage: Path, fd: int) -> None: + """End a finished stage: remove the folder while the lock is held, then the lock file.""" + shutil.rmtree(stage, ignore_errors=True) + os.close(fd) + _unlink_quietly(_stage_lock_path(stage)) + + +def _unlink_quietly(path: Path) -> None: + """Remove a lock file; where the OS refuses (Windows, a sweeper holds it) the next sweep removes it.""" + try: + path.unlink(missing_ok=True) + except OSError: + pass + + +def _sweep_stale_stages(top: Path) -> None: + """Remove every staging folder under top whose lock can be taken: its export is over or its Blender + died. A held lock (an export running now, in any process) leaves the stage alone. A lock file with + no folder is a stage killed before its folder existed. A folder with no sibling lock file is the + older layout, locked by a file inside it, or never locked at all.""" + for root, dirs, files in os.walk(top): + for name in [d for d in dirs if d.startswith(EXPORT_STAGE_PREFIX)]: + dirs.remove(name) + stage = Path(root) / name + if not _stage_lock_path(stage).exists(): + _sweep_stage(stage, stage / LEGACY_STAGE_LOCK) + for name in files: + if name.startswith(EXPORT_STAGE_PREFIX) and name.endswith(STAGE_LOCK_SUFFIX): + stage = Path(root) / name[:-len(STAGE_LOCK_SUFFIX)] + _sweep_stage(stage, Path(root) / name) + + +def _sweep_stage(stage: Path, lock_path: Path) -> None: + try: + fd = os.open(lock_path, os.O_RDWR) + except FileNotFoundError: + fd = None # no lock was ever made for this folder: nothing can hold it + except OSError: + return + try: + if fd is not None and not _try_lock(fd): + return + journal = stage / STAGE_JOURNAL + if journal.is_file(): # a failed rollback's leftovers in the target + for line in journal.read_text(encoding="utf-8").splitlines(): + relative = Path(line) + if not line or relative.is_absolute() or ".." in relative.parts: + continue + target = stage.parent / relative + if target.is_file() and not target.is_symlink(): + target.unlink(missing_ok=True) + for folder in target.parents: + if folder == stage.parent: + break + try: + folder.rmdir() + except OSError: + break + finally: + if fd is not None: + os.close(fd) + shutil.rmtree(stage, ignore_errors=True) + if lock_path.parent != stage: + _unlink_quietly(lock_path) + + +def _kill_tree(process: "subprocess.Popen[str]") -> None: + """Kill process and everything it started, so none keeps its output pipe open.""" + if os.name == "nt": + subprocess.run(["taskkill", "/F", "/T", "/PID", str(process.pid)], capture_output=True, check=False) + else: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + pass + process.kill() + + +_GL_PROBES: dict[tuple[str, str], str | None] = {} + + +def gl_render_failure(binary: str, engine: str) -> str | None: + """Why a headless render with this engine would not survive on this host, or None when it does. + + Renders one pixel in a child process of the same Blender binary: the render aborts the process + it runs in, so only a child can find out. A definite outcome (it rendered, or it exited without + finishing) is cached per binary and engine for the life of the process; a hang, an unstartable + binary or an unknown binary is reported but not cached, so the next render probes again.""" + if not binary or not os.path.isfile(binary): + return "the Blender binary is unknown, so rendering could not be probed" + if (binary, engine) in _GL_PROBES: + return _GL_PROBES[(binary, engine)] + command = [binary, "--background", "--factory-startup", "--python-exit-code", "1", + "--python", str(GL_PROBE_SCRIPT), "--", engine] + group = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {"start_new_session": True} + try: + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **group) + except OSError as exc: + return f"the one-pixel test render could not start: {exc}" + try: + stdout, _ = process.communicate(timeout=GL_PROBE_TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + _kill_tree(process) + try: + process.communicate(timeout=10) + except subprocess.TimeoutExpired: + pass + return f"a one-pixel test render did not finish in {GL_PROBE_TIMEOUT_SECONDS} s" + if process.returncode == 0 and "BROKKR_GL_PROBE_OK" in stdout: + outcome = None + else: + outcome = f"a one-pixel test render exited with status {process.returncode}" + _GL_PROBES[(binary, engine)] = outcome + return outcome + + +gl_render_failure.cache_clear = _GL_PROBES.clear + + +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 _png_bytes(width: int, height: int, rgba: bytes) -> bytes: + """An 8-bit RGBA PNG of bottom-row-first pixels, written top row first.""" + stride = width * 4 + rows = b"".join(b"\x00" + rgba[y * stride:(y + 1) * stride] for y in range(height - 1, -1, -1)) + + def chunk(kind: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(rows, 1)) + chunk(b"IEND", b"")) def _now() -> str: @@ -1135,13 +1885,8 @@ def _to_list(value: Any) -> list[float]: return [float(item) for item in value] -def _vector(value: Any, size: int, fallback: Any) -> tuple[float, ...]: - if value is None: - return tuple(float(item) for item in fallback) - result = [float(item) for item in value[:size]] - while len(result) < size: - result.append(0.0) - return tuple(result) +def _valid_command_id(value: Any) -> bool: + return isinstance(value, str) and COMMAND_ID_SHAPE.fullmatch(value) is not None def _jsonable(value: Any) -> Any: diff --git a/surfaces/blender/brokkr_bridge/gl_probe.py b/surfaces/blender/brokkr_bridge/gl_probe.py new file mode 100644 index 0000000..6331daa --- /dev/null +++ b/surfaces/blender/brokkr_bridge/gl_probe.py @@ -0,0 +1,15 @@ +"""Run inside a child Blender by blender_target.gl_render_failure: render one pixel with the engine named +after `--`, and print the completion marker only if the render returned.""" +import sys + +import bpy + +bpy.ops.wm.read_factory_settings(use_empty=True) +scene = bpy.context.scene +scene.render.engine = sys.argv[-1] +scene.render.resolution_x = scene.render.resolution_y = 1 +camera = bpy.data.objects.new("probe", bpy.data.cameras.new("probe")) +scene.collection.objects.link(camera) +scene.camera = camera +bpy.ops.render.render(write_still=False) +print("BROKKR_GL_PROBE_OK") diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py index 5210b86..3d856bc 100644 --- a/surfaces/blender/brokkr_bridge/node_actions.py +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -1,33 +1,23 @@ """Geometry node graph command actions: createNodeGroup, addNode, linkSockets, addModifier, setModifierInput. Owner of how an intent becomes a node group, a node, a link or a modifier input on Blender 5.2. -Validation is plain Python and runs before bpy is touched; apply steps that can still fail after +Field shape is action_table's and arrives validated; apply steps that can still fail after Blender has been asked (an unknown node type, an enum that is not offered) undo what they made, so a refused intent leaves the tree as it was. Docs: docs/node-actions.md. The design is PR #3 (branch libby/blender-node-graphs-design). """ from __future__ import annotations import math -import re from typing import Any from .scene_actions import ActionRefused -ID_PATTERN = re.compile(r"[A-Za-z0-9._-]{1,63}") -KEY_PATTERN = re.compile(r"[A-Za-z0-9 ._-]{1,63}") -# A geometry tree may hold geometry, function and shader math nodes. Nodes that read or write files, -# run code, write caches, nest groups or sample images are not part of this cut. -NODE_IDNAME = re.compile(r"(GeometryNode|FunctionNode|ShaderNode)[A-Za-z0-9]+") -NODE_DENIED = ("Import", "Export", "Script", "Bake", "Group", "Simulation", "Repeat", "Foreach", "Viewer", "TexImage", "TexEnvironment", - "ImageTexture", "InputImage", "TexIES") MAX_NODES = 500 -MAX_INTERFACE = 64 MAX_MODIFIERS = 8 MAX_VALUE = 1.0e9 MAX_INT = 4096 # counts, levels and sizes multiply: a 4096 x 4096 grid is the ceiling SOCKET_TYPES = {"Geometry": "NodeSocketGeometry", "Float": "NodeSocketFloat", "Int": "NodeSocketInt", "Bool": "NodeSocketBool", "Vector": "NodeSocketVector"} -IN_OUT = {"INPUT", "OUTPUT"} # Node properties that are not node settings, or that make a node reach outside the tree. NODE_PROPERTY_DENIED = frozenset({"name", "label", "location", "width", "height", "parent", "node_tree", "select", "mute", "hide", "show_options", "show_preview", "show_texture", "use_custom_color", @@ -37,24 +27,6 @@ NODE_PROPERTY_DENIED = frozenset({"name", "label", "location", "width", "height" SETTABLE_PROPERTY_TYPES = ("ENUM", "BOOLEAN", "INT", "FLOAT") -def text(command: dict[str, Any], key: str, pattern: re.Pattern, label: str, *, required: bool = True) -> str: - value = command.get(key) - if value is None or value == "": - if required: - raise ActionRefused(f"{label} is required.") - return "" - if not isinstance(value, str) or not pattern.fullmatch(value): - raise ActionRefused(f"{label} must be 1..63 characters of letters, digits, space, '.', '_' or '-'.") - return value - - -def tree_key(command: dict[str, Any]) -> str: - kind = command.get("treeKind", "geometry") - if kind != "geometry": - raise ActionRefused(f"treeKind {kind!r} is not supported; only 'geometry'.") - return text(command, "treeKey", KEY_PATTERN, "treeKey") - - def finite(value: Any, label: str) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or abs(value) > MAX_VALUE: raise ActionRefused(f"{label} must be a finite number within +-{MAX_VALUE:g}.") @@ -82,34 +54,19 @@ def typed_value(value: Any, kind: str, label: str) -> Any: raise ActionRefused(f"{label}: socket type {kind} cannot be set by an intent.") -def check_idname(idname: Any) -> str: - if not isinstance(idname, str) or not NODE_IDNAME.fullmatch(idname): - raise ActionRefused("blIdname must be a GeometryNode*, FunctionNode* or ShaderNode* type.") - for denied in NODE_DENIED: - if denied in idname: - raise ActionRefused(f"node type {idname} is not allowed in this cut ({denied}).") - return idname - - -def check_interface(items: Any) -> list[dict[str, str]]: - if not isinstance(items, list) or not items or len(items) > MAX_INTERFACE: - raise ActionRefused(f"interface must be a list of 1..{MAX_INTERFACE} sockets.") +def check_interface(items: list[dict[str, Any]]) -> list[dict[str, Any]]: + """The interface as the table admitted it, minus what only a typed read can judge: a repeated (inOut, name) + and a default that does not fit its socket type.""" seen: set[tuple[str, str]] = set() result = [] for i, item in enumerate(items): - if not isinstance(item, dict): - raise ActionRefused(f"interface[{i}] must be an object.") - in_out = str(item.get("inOut", "")).upper() - name = item.get("name") - socket_type = item.get("type") - if in_out not in IN_OUT or not isinstance(name, str) or not name or len(name) > 63 or socket_type not in SOCKET_TYPES: - raise ActionRefused(f"interface[{i}] needs inOut INPUT|OUTPUT, a name and a type of {sorted(SOCKET_TYPES)}.") - if (in_out, name) in seen: - raise ActionRefused(f"interface[{i}] repeats {in_out} socket {name!r}.") - seen.add((in_out, name)) - entry = {"inOut": in_out, "name": name, "type": socket_type} + key = (item["inOut"], item["name"]) + if key in seen: + raise ActionRefused(f"interface[{i}] repeats {key[0]} socket {key[1]!r}.") + seen.add(key) + entry = dict(item) if "default" in item: - entry["default"] = typed_value(item["default"], socket_type, f"interface[{i}].default") + entry["default"] = typed_value(item["default"], item["type"], f"interface[{i}].default") result.append(entry) return result @@ -117,12 +74,12 @@ def check_interface(items: Any) -> list[dict[str, str]]: class NodeActions: """Applies the node-graph actions to a bpy module. Stateless: every lookup goes to bpy.data.""" - ACTIONS = ("createNodeGroup", "addNode", "removeNode", "linkSockets", "unlinkSockets", "addModifier", "removeModifier", "setModifierInput") - def __init__(self, bpy_module: Any): self.bpy = bpy_module + self.changed = False # whether the last execute wrote anything: an absent-target removal does not def execute(self, action: str, command: dict[str, Any]) -> tuple[str, str]: + self.changed = True return getattr(self, "_" + action)(command) # tree and node lookup @@ -157,8 +114,8 @@ class NodeActions: # actions def _createNodeGroup(self, command: dict[str, Any]) -> tuple[str, str]: - key = tree_key(command) - interface = check_interface(command.get("interface")) + key = command["treeKey"] + interface = check_interface(command["interface"]) existing = self.bpy.data.node_groups.get(key) if existing is not None: raise ActionRefused(f"Node group {key!r} already exists.") @@ -179,17 +136,12 @@ class NodeActions: return "Created node group; interface identifiers: " + ", ".join(made), tree.name def _addNode(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - node_id = text(command, "id", ID_PATTERN, "id") - idname = check_idname(command.get("blIdname")) - location = command.get("location", [0, 0]) - if not isinstance(location, (list, tuple)) or len(location) != 2: - raise ActionRefused("location must be two numbers.") - location = [finite(part, "location") for part in location] - properties = command.get("properties") or {} - inputs = command.get("inputs") or {} - if not isinstance(properties, dict) or not isinstance(inputs, dict): - raise ActionRefused("properties and inputs must be objects.") + tree = self._tree(command["treeKey"]) + node_id = command["id"] + idname = command["blIdname"] + location = list(command["location"]) + properties = command.get("properties", {}) + inputs = command.get("inputs", {}) if any(n.get("brokkr_id") == node_id for n in tree.nodes): raise ActionRefused(f"Node id {node_id!r} already exists in {tree.name!r}.") if len(tree.nodes) >= MAX_NODES: @@ -202,7 +154,7 @@ class NodeActions: node["brokkr_id"] = node_id node.location = location if command.get("label"): - node.label = str(command["label"])[:63] + node.label = command["label"] for name, value in properties.items(): # node settings first: they decide which sockets exist self._set_property(node, name, value) for name, value in inputs.items(): @@ -230,35 +182,39 @@ class NodeActions: raise ActionRefused(f"property {name!r} cannot be {value!r}: {error}") from None def _removeNode(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - node_id = text(command, "id", ID_PATTERN, "id") + tree = self._tree(command["treeKey"]) + node_id = command["id"] if node_id in ("gin", "gout"): raise ActionRefused(f"{node_id!r} is the group's own input/output node and stays.") node = next((n for n in tree.nodes if n.get("brokkr_id") == node_id), None) if node is None: + self.changed = False return f"Node {node_id!r} was already absent.", node_id tree.nodes.remove(node) # Blender drops the node's links with it return "Node removed.", node_id def _unlinkSockets(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode")) - into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket") + tree = self._tree(command["treeKey"]) + target = self._node(tree, command["toNode"]) + into = self._socket(target.inputs, command["toSocket"], "toSocket") source = out = None - if command.get("fromNode") or command.get("fromSocket"): - source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode")) - out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket") + if ("fromNode" in command) != ("fromSocket" in command): + raise ActionRefused("fromNode and fromSocket are given together or not at all.") + if "fromNode" in command: + source = self._node(tree, command["fromNode"]) + out = self._socket(source.outputs, command["fromSocket"], "fromSocket") doomed = [l for l in tree.links if l.to_socket == into and (out is None or l.from_socket == out)] for link in doomed: tree.links.remove(link) + self.changed = bool(doomed) # no link matched: no undo step return f"Removed {len(doomed)} link(s).", tree.name def _linkSockets(self, command: dict[str, Any]) -> tuple[str, str]: - tree = self._tree(tree_key(command)) - source = self._node(tree, text(command, "fromNode", ID_PATTERN, "fromNode")) - target = self._node(tree, text(command, "toNode", ID_PATTERN, "toNode")) - out = self._socket(source.outputs, str(command.get("fromSocket", "")), "fromSocket") - into = self._socket(target.inputs, str(command.get("toSocket", "")), "toSocket") + tree = self._tree(command["treeKey"]) + source = self._node(tree, command["fromNode"]) + target = self._node(tree, command["toNode"]) + out = self._socket(source.outputs, command["fromSocket"], "fromSocket") + into = self._socket(target.inputs, command["toSocket"], "toSocket") if reaches(tree, target, source): # includes a self link raise ActionRefused(f"Link {source.get('brokkr_id')} -> {target.get('brokkr_id')} would make a cycle.") displaced = [(l.from_socket, l.is_muted) for l in tree.links if l.to_socket == into] if not getattr(into, "is_multi_input", False) else [] @@ -271,7 +227,7 @@ class NodeActions: return f"Linked {source.get('brokkr_id')}.{out.identifier} -> {target.get('brokkr_id')}.{into.identifier}.", tree.name def _object(self, command: dict[str, Any]) -> Any: - name = command.get("objectName") or command.get("targetObjectName") + name = command["objectName"] obj = self.bpy.data.objects.get(name) if name else None if obj is None: raise ActionRefused(f"Object {name!r} was not found.") @@ -279,11 +235,8 @@ class NodeActions: def _addModifier(self, command: dict[str, Any]) -> tuple[str, str]: obj = self._object(command) - kind = command.get("modifierType", "NODES") - if kind != "NODES": - raise ActionRefused("modifierType must be NODES; other modifiers are not part of this cut.") - tree = self._tree(tree_key(command)) - name = text(command, "modifierName", KEY_PATTERN, "modifierName", required=False) or "Brokkr GeoNodes" + tree = self._tree(command["treeKey"]) + name = command["modifierName"] modifier = obj.modifiers.get(name) if modifier is not None and modifier.type != "NODES": raise ActionRefused(f"{obj.name!r} already has a non-Geometry-Nodes modifier named {name!r}.") @@ -300,11 +253,10 @@ class NodeActions: def _removeModifier(self, command: dict[str, Any]) -> tuple[str, str]: obj = self._object(command) # A lookup, not a creation: a modifier made by hand may have any name Blender allows. - name = command.get("modifierName") or "Brokkr GeoNodes" - if not isinstance(name, str) or len(name) > 255 or "\0" in name: - raise ActionRefused("modifierName must be a string of at most 255 characters.") + name = command["modifierName"] modifier = obj.modifiers.get(name) if modifier is None: + self.changed = False return f"Modifier {name!r} was already absent.", obj.name if modifier.type != "NODES": raise ActionRefused(f"{name!r} is not a Geometry Nodes modifier; only those are removed here.") @@ -314,11 +266,11 @@ class NodeActions: def _setModifierInput(self, command: dict[str, Any]) -> tuple[str, str]: obj = self._object(command) - modifier = obj.modifiers.get(str(command.get("modifierName") or "Brokkr GeoNodes")) + modifier = obj.modifiers.get(command["modifierName"]) if modifier is None or modifier.type != "NODES" or modifier.node_group is None: raise ActionRefused(f"{obj.name!r} has no Geometry Nodes modifier with a node group of that name.") - item = modifier_input(modifier.node_group, str(command.get("socket", ""))) - value = typed_value(command.get("value"), item.socket_type.replace("NodeSocket", ""), f"input {item.name!r}") + item = modifier_input(modifier.node_group, command["socket"]) + value = typed_value(command["value"], item.socket_type.replace("NodeSocket", ""), f"input {item.name!r}") # modifier.properties.inputs[id] is a raw IDPropertyGroup on 5.2.3; attribute access reaches the struct. getattr(modifier.properties.inputs, item.identifier).value = value obj.update_tag() # without it a headless re-evaluation returned the previous result diff --git a/surfaces/blender/brokkr_bridge/scene_actions.py b/surfaces/blender/brokkr_bridge/scene_actions.py index 98dcb40..c2a0b3c 100644 --- a/surfaces/blender/brokkr_bridge/scene_actions.py +++ b/surfaces/blender/brokkr_bridge/scene_actions.py @@ -1,13 +1,12 @@ -"""Validation for the Blender scene command actions. Stdlib only, no bpy. +"""Path and file safety for the Blender scene command actions. Stdlib only, no bpy. -Everything an intent can say is checked here before bpy is touched, so the rules -are testable without Blender. Failures raise ActionRefused; the target turns the -message into a failed receipt. +What an intent's fields may hold (names, types, enums, bounds) is action_table's. What a path or a glTF +may reach is checked here before bpy is touched, so the rules are testable without Blender. Failures raise +ActionRefused; the target turns the message into a failed receipt. """ from __future__ import annotations import json -import math import os import struct from pathlib import Path @@ -16,10 +15,6 @@ from urllib.parse import unquote GLTF_EXTENSIONS = (".gltf", ".glb") STILL_FORMATS = {".png": "PNG", ".jpg": "JPEG", ".jpeg": "JPEG", ".exr": "OPEN_EXR"} -CAMERA_TYPES = ("PERSP", "ORTHO", "PANO") -LIGHT_TYPES = ("POINT", "SUN", "SPOT", "AREA") -MAX_RESOLUTION = 16384 -MAX_LENS_MM = 5000.0 class ActionRefused(ValueError): @@ -166,72 +161,6 @@ def _glb_json_chunk(path: Path) -> bytes: return data -def number(command: dict[str, Any], key: str, low: float, high: float) -> float | None: - """A finite number in [low, high], or None when the key is absent.""" - if key not in command or command[key] is None: - return None - value = command[key] - if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): - raise ActionRefused(f"{key} must be a finite number.") - if not low <= value <= high: - raise ActionRefused(f"{key} must be between {low} and {high}.") - return float(value) - - -def integer(command: dict[str, Any], key: str, low: int, high: int) -> int | None: - value = number(command, key, low, high) - if value is None: - return None - if value != int(value): - raise ActionRefused(f"{key} must be a whole number.") - return int(value) - - -def unit_component(key: str, item: Any) -> float: - """One colour component: a number in [0, 1]. The range test comes first: it also refuses nan and inf, - and a huge int (10**400) never reaches math.isfinite, which would raise OverflowError instead of - naming the field.""" - if isinstance(item, bool) or not isinstance(item, (int, float)) or not 0.0 <= item <= 1.0: - raise ActionRefused(f"{key} components must be numbers between 0 and 1.") - return float(item) - - -def color(command: dict[str, Any], key: str = "color") -> tuple[float, float, float] | None: - """Linear RGB, three finite numbers in [0, 1], or None when absent.""" - if key not in command or command[key] is None: - return None - value = command[key] - if not isinstance(value, (list, tuple)) or len(value) != 3: - raise ActionRefused(f"{key} must be three numbers [r, g, b].") - parts = [] - for item in value: - parts.append(unit_component(key, item)) - return (parts[0], parts[1], parts[2]) - - -def color_rgba(command: dict[str, Any], key: str = "color") -> tuple[float, float, float, float] | None: - """Linear RGB or RGBA, finite numbers in [0, 1] (RGB gets alpha 1), or None when absent.""" - if key not in command or command[key] is None: - return None - value = command[key] - if not isinstance(value, (list, tuple)) or len(value) not in (3, 4): - raise ActionRefused(f"{key} must be [r, g, b] or [r, g, b, a].") - parts = [] - for item in value: - parts.append(unit_component(key, item)) - return (parts[0], parts[1], parts[2], parts[3] if len(parts) == 4 else 1.0) - - -def choice(command: dict[str, Any], key: str, allowed: Iterable[str]) -> str | None: - if key not in command or command[key] is None: - return None - allowed = tuple(allowed) - value = command[key] - if not isinstance(value, str) or value.upper() not in allowed: - raise ActionRefused(f"{key} must be one of {', '.join(allowed)}.") - return value.upper() - - def still_format(path: Path) -> str: try: return STILL_FORMATS[path.suffix.lower()] diff --git a/surfaces/blender/brokkr_bridge/server_guard.py b/surfaces/blender/brokkr_bridge/server_guard.py index 0e9d111..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,8 +12,7 @@ from __future__ import annotations import hmac import ipaddress import secrets -from pathlib import Path -from typing import Any +from typing import Any, Callable PUT_SCHEMA_VERSIONS = ("cultnet.document_put_raw.v0", "cultnet.document_delete.v0") TOKEN_FIELD = "sessionToken" @@ -91,17 +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, debug_mirror_root: str) -> int: - """Delete every queued command intent from the node and every command JSON under - /blender/commands. 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 - if debug_mirror_root: - for path in (Path(debug_mirror_root) / "blender" / "commands").glob("*.json"): - path.unlink(missing_ok=True) - removed += 1 - return removed + stopped += 1 + return stopped diff --git a/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl new file mode 100644 index 0000000..641dbcd Binary files /dev/null and b/surfaces/blender/brokkr_bridge/wheels/msgpack-1.2.2-py3-none-any.whl differ diff --git a/surfaces/blender/docs/install.md b/surfaces/blender/docs/install.md index f27093b..9ef449e 100644 --- a/surfaces/blender/docs/install.md +++ b/surfaces/blender/docs/install.md @@ -16,6 +16,53 @@ directory; the add-on puts each package's `src` on `sys.path`: F:/Projects/CultLib/packages ``` +That CultLib checkout must carry cultcache-py's MessagePack payload default +(CultLib main after the py-msgpack-default merge); the add-on refuses an older +one. A `.brokkr/blender-editor.ccmp` written under the JSON default is +converted into a new file, never in place: close Blender, stop the daemon, +convert, check the new file opens, then swap it in for the original: + +```text +py -3 -c "import sys; sys.path.insert(0, r'/surfaces/blender/brokkr_bridge'); import blender_target as t; print(t.convert_store(r'/blender-editor.ccmp', r'/blender-editor.mp.ccmp'))" +``` + +The command prints the record count and leaves the source unwritten. Records a new daemon already appended (MessagePack) are carried into the new file. + +### msgpack for a stock Blender + +CultLib's `cultnet-py` and `cultcache-py` import `msgpack`, and Blender's Python does +not ship it. Install Brokkr as an extension so Blender installs it for you: +`surfaces/blender/brokkr_bridge/blender_manifest.toml` lists the bundled wheel +`wheels/msgpack-1.2.2-py3-none-any.whl`, which Blender unpacks into the extension's own +site-packages when the extension is enabled. Build and install it: + +```text +blender --command extension build --source-dir surfaces/blender/brokkr_bridge --output-dir +blender --command extension install-file --repo user_default --enable /brokkr_bridge-0.2.0.zip +``` + +To try a build without touching your own Blender, run both commands (and any live test) with private +`BLENDER_USER_CONFIG`, `BLENDER_USER_EXTENSIONS` and `BLENDER_USER_SCRIPTS` directories set. Blender 5.3 ignores +`BLENDER_USER_RESOURCE_PATH`, so `install-file` under it replaces the `user_default` copy in your own extensions +folder. The live tests refuse to start without the three variables. + +The wheel is one pure-Python msgpack, so the extension carries no platform restriction (Blender 5.3 or +newer, any OS). msgpack then runs its pure-Python fallback, which CultLib `9fc4bdda` (PR #180) decodes. + +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 (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 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 +yourself. A CultLib package missing a module is reported by that module's name, not as a missing +CultLib package. + The default node cache is: ```text @@ -27,14 +74,30 @@ at `0` to bind a free local port, or set a fixed port when another runtime needs a stable endpoint. The panel reports the active `cultnet://host:port` endpoint after `Start Server`. +## Stop and the Agents panel + +`Stop agents` sits at the top of the Brokkr panel. It turns `Auto Drain Commands` (the command sink) off, then gives +every pending intent a `stopped` receipt without running it: the same path as `Start Server` and `Stop Server`. +Only the operator turns the sink on; no intent writes add-on preferences. The timer runs one intent per tick, so +Stop lands between two intents; an action already running finishes as one undo step, and `Ctrl+Z` takes it back. +A stopped intent's id is spent. While the sink is off the add-on answers every intent that arrives with a +`stopped` receipt ("agent commands are off") at once, so `brokkr-ctl wait` exits 3 and nothing queues to fire when +the operator turns the sink back on. The answer needs a node the add-on has opened (a running server or a published +snapshot). + +The `Agents` section sits directly under Stop agents and lists the agents active in the last five minutes (distinct `requestedBy` among receipts), +the number of pending intents, and the last eight receipts as ` ` with their note and +undo label. It is a display cache of the node's receipts, rebuilt from the node on first draw. The host snapshot +carries `agentCommandsEnabled`, which `brokkr-ctl blender status` prints. + ## Server Safety Always on: -- `Start Server` and `Stop Server` purge queued command intents: every - `brokkr.blender.command_intent.v0` record in the node and every - `blender/commands/*.json` under `Debug Export Root`. 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 @@ -63,9 +126,11 @@ Run the tests (no Blender needed; `CULTLIB_PACKAGES` adds the real-server tests) CULTLIB_PACKAGES=F:/Projects/CultLib/packages python -m unittest discover -s surfaces/blender/tests -v ``` -`Debug Export Root` may still emit readable JSON probe files under -`.brokkr/blender-editor-debug`, but those files are debug/import glue. CultMesh -owns the mirror state. +`Debug Export Root` may still emit readable JSON snapshot and receipt files under +`.brokkr/blender-editor-debug`. They are export only: nothing reads them back, and +a JSON file placed there is never an intent. CultMesh owns the mirror state, and +intents enter only through the node (`brokkr-ctl blender send`, a served peer, the +sync organ). ## Local Smoke @@ -73,11 +138,13 @@ owns the mirror state. 2. Open `View3D > Sidebar > Brokkr`. 3. Click `Capture Snapshot`. 4. Inspect `.brokkr/blender-editor.ccmp`. -5. Drop a command intent JSON file into - `.brokkr/blender-editor-debug/blender/commands/{commandId}.json`. +5. Send an intent into the node: + `brokkr-ctl blender send createObject --set objectType='"EMPTY"' --agent --no-wait` + (needs `EUREKA_INSTANCE` and `--store `). 6. Click `Drain Commands`, or enable `Auto Drain Commands` to poll command intents once per second while the add-on is loaded. -7. Inspect `.brokkr/blender-editor.ccmp` or the optional debug export +7. Read the receipt with `brokkr-ctl blender wait --store `, or + inspect `.brokkr/blender-editor.ccmp` or the optional debug export at `.brokkr/blender-editor-debug/blender/receipts/{commandId}.json`. 8. Click `Start Server`. 9. Use the reported `cultnet://host:port` endpoint from a CultMesh/CultNet @@ -97,78 +164,144 @@ owns the mirror state. 13. To publish an ad hoc sync variable, fill the `Ad Hoc Sync Var` fields in the sidebar or add-on preferences and click `Publish Sync Var`. -Admitted command actions: +Command actions and their fields are one table, `brokkr_bridge/actions.json` (schema +`brokkr.blender.actions.v0`): each action's fields with their types, enums, bounds, defaults and which +are required, and whether the action changes the scene (one undo step) and is safe in Edit Mode. +`brokkr-ctl blender send --help` prints it. The add-on admits every intent through that table and +nothing else: an unknown action, an unknown field (a name no action declares), a wrong type, an enum +that is not matched exactly (Blender's identifiers, case included), a number outside its bounds or a +missing required field is refused with a `denied` receipt that names the field and the rule; nothing +ran and no undo step was pushed. `null` counts as absent. `brokkr-ctl send` applies the same table +first and writes nothing for an intent it refuses. What only the scene can judge stays with the action +and answers `failed` (the object is not found or not the right type, a path escapes its directory, the +engine is not available in this Blender); a `failed` action that wrote part of its work is one labelled +undo step. Targets are named `targetObjectName` for the scene actions and `objectName` for the node +actions; there are no other spellings. -- `createObject` -- `deleteObject` -- `setObjectTransform` -- `setObjectVisibility` -- `setObjectParent` -- `setObjectCustomProperty` -- `selectObject` -- `assignMaterial` -- `importGltf` -- `exportGltf` -- `setCamera` -- `setLight` -- `setWorld` -- `renderStill` +Behaviour the table does not say, per action: -Scene action fields (all other keys are ignored; a refused intent changes nothing and -gets a `failed` receipt whose message names the rule): - -- `createObject`: optional `objectType` (`MESH`, `LIGHT`, `CAMERA`, `EMPTY`; default `EMPTY`), - `name`, `location`. Any other `objectType` (for example `TEXT` or `CURVE`) is refused with - the allowed set named. A `MESH` is a cube (`size`); a `meshType` other than `CUBE` - (case-insensitive, no surrounding whitespace) is refused rather than ignored. - `meshType` is checked only when `objectType` is `MESH`; an explicit `objectType: null` is refused. +- `createObject`: a `MESH` is a cube of `size`. `lightType`, `emptyDisplayType` and `meshType` apply + only to their own `objectType`. +- `setObjectParent`: an empty or absent `parentObjectName` clears the parent. - `importGltf`: `filepath`, `.gltf` or `.glb`, relative to the add-on preference `Import Directory` (absolute paths, `..` and symlinks that resolve outside it are refused). Empty `Import Directory` disables the action. Needs Blender's glTF add-on. - `exportGltf`: `filepath`, `.glb` (binary) or `.gltf` (separate `.bin`), relative to the add-on preference `Render Output Directory` (the renderStill rules: no `..`, no links, and an - existing name, or an existing `.bin` beside a `.gltf`, is refused; there is no overwrite). - Optional `extras` (custom properties become node `extras`), `yUp`, `applyModifiers` - (each true by default, must be a boolean) and `selection` (a non-empty list of object - names; any name not found, or not in the active view layer, refuses the export; the - selection is touched only when one is given, and restored afterwards). Not checked: texture - files a `.gltf` export writes beside it (only the `.bin` is), and a link or swap made between the - check and the write (the same residual as renderStill). + existing name is refused; there is no overwrite). + `extras` makes custom properties node `extras`; a `selection` names objects, any name not found, + or not in the active view layer, refuses the export; the + selection is touched only when one is given, and restored afterwards. The exporter writes into a + staging folder beside the target and Brokkr then moves each file into place (the `.glb`, or the `.gltf` + with its `.bin` and texture files), refusing the whole export, naming the file, if any of those names is + taken: nothing existing is overwritten. A refused or failed export leaves no file and no new folder, so + the same name can be retried. Each export holds an OS lock on its staging folder; the next export removes any `.brokkr-export-*` folder under the output directory whose lock is free (its Blender died), and a rollback that itself fails is refused naming the files left, which that same sweep removes. Not checked: a link or swap made between the check and the move (the + same residual as renderStill). The receipt message carries the written path and byte size. Needs Blender's glTF add-on. -- `setCamera`: `targetObjectName` (a camera object); optional `lens` (mm), - `cameraType` (`PERSP`, `ORTHO`, `PANO`), `panoramaType` (for example - `EQUIRECTANGULAR`; read from the camera, or from `camera.cycles` before Blender 4.2), - `orthoScale`, `clipStart`, `clipEnd`, `active` (true makes it the scene camera). - Panoramic cameras render in Cycles. -- `setLight`: `targetObjectName` (a light object); optional `energy` (>= 0), - `color` (linear `[r, g, b]`, each 0 to 1), `lightType` (`POINT`, `SUN`, `SPOT`, `AREA`). -- `setWorld`: optional `worldName` (default: the scene's world, created if there is - none), `color` (`[r, g, b]`), `strength`. Edits the world's Background node. -- `assignMaterial`: `targetObjectName` (an object with material slots, such as a mesh); - optional `materialName` (default `Brokkr Material`; an existing material of that name - is reused) and `color` (linear `[r, g, b]` or `[r, g, b, a]`, each a finite number 0 - to 1; alpha defaults to 1). `color` sets the Principled BSDF Base Color (the node tree - is created if the material has none) and `diffuse_color`; a malformed `color` is - refused naming the field and nothing is created or changed (`"color": null` counts as absent). Without `color` an +- `setCamera`: `targetObjectName` must be a camera object. `panoramaType` is a property of the camera + (Blender 4.2 and newer). Panoramic cameras render in Cycles. `cameraType` leaves out `CUSTOM`: it runs a script. +- `setLight`: `targetObjectName` must be a light object. `color` is linear. +- `setWorld`: without `worldName`, the scene's world, created if there is none. Edits the world's Background node. +- `assignMaterial`: `targetObjectName` must be an object with material slots, such as a mesh. An existing + material of that name is reused. `color` is linear `[r, g, b]` or `[r, g, b, a]`, alpha 1 when absent; it + sets the Principled BSDF Base Color (the node tree is created if the material has none) and + `diffuse_color`; a malformed `color` is refused and nothing is created or changed. Without `color` an existing material's colour is left as it is. Idempotent per (object, material): if the - object already has a slot with that material no second slot is added. Other keys are - ignored, as for every action. + object already has a slot with that material no second slot is added. - `renderStill`: `outputPath` relative to the preference `Render Output Directory`, - ending `.png`, `.jpg` or `.exr` (same containment rules as import); optional - `engine` (any engine of the running Blender, case-insensitive), `resolutionX`, - `resolutionY` (whole numbers, 1 to 16384), `cameraName`. Engine, resolution, + ending `.png`, `.jpg` or `.exr` (same containment rules as import). `engine` is an engine identifier of + the running Blender, matched exactly (Blender is asked by assignment; one it does not have is a `failed` + receipt). Resolutions are whole numbers of 4 or more: Blender stores 1 to 3 as 4 without a word, so + they are refused. Engine, resolution, camera, file path and format are restored after the render. The render blocks Blender's UI until it finishes. In a background (`-b`) Blender on Linux, the GL engines `BLENDER_WORKBENCH`, `BLENDER_EEVEE` and `BLENDER_EEVEE_NEXT` are refused - with a `failed` receipt when `libEGL.so.1` cannot be loaded (probed once and cached for the life of the process), because - rendering would abort the whole process with no receipt; `CYCLES` renders on the - CPU. The check applies to the scene's engine when `engine` is omitted. No such - check runs on Windows or macOS. + with a `failed` receipt when a one-pixel test render of that engine does not finish in a child + process of the same Blender binary (it aborts, hangs past 120 s, or the binary is unknown). The + probe runs once per engine and is cached for the life of the process, so the first GL render + after startup waits for it. Rendering would otherwise abort the whole process with no receipt; + `CYCLES` renders on the CPU. The check applies to the scene's engine when `engine` is omitted. + A foreground Blender is not probed. + +- `look`: no fields. Captures the 3D view she is looking at (the largest 3D view across the windows, its + main region) to `/look/.png` and puts the absolute path in the receipt's + `lookPath`; refused when the output directory is unset or no 3D view is open. It reads Blender's own + framebuffer for that one region, so her desktop and other applications are never in the picture; a menu, + popup or the splash Blender draws over the view is, as she sees it. It is a read: no undo step, and it runs in + Edit Mode. The capture blocks her UI for about 70 ms. `captureSource` says how it was taken: `region`, or + `offscreen` when every Blender window is minimised (Windows only; a minimised window stops redrawing, so its + framebuffer is a stale frame) and the view's own viewpoint is drawn offscreen at the region's size instead, with + her popups and menus not drawn; an offscreen failure is a refusal, never a stale picture. `sceneUpdateSeq` is the + count of depsgraph updates, hers and the agent's, that the picture reflects. The look directory keeps the newest 20 PNGs (scratch, + never read back). The receipt also carries `sessionId`, `humanEditSeq`, `humanEditsSinceLook` and + `editedSinceLook` (object names), counted for the sending `requestedBy` since its previous look in this + session, and `editSelection`: for each object in Edit Mode its selected vertex, edge and face indices (each + list capped at 4096, the true count beside it as `verticesTotal` and so on; non-mesh objects say + `unsupported`). The host snapshot carries the same `sessionId`, `humanEditSeq`, `editSelection` and each + object's `lastHumanEditSeq`. The sequences come from depsgraph updates outside an agent turn, counted per + flagged object (transform, geometry or shading) and from undo and redo; opening a file starts a new session. An + update also flags objects that only depend on what she changed (a constrained follower), and adding or + linking an object flags all of them, so `editedSinceLook` can name more than she touched; the receipt then + says so: `editedSinceLookCoarse` is true, with the reason in `editedSinceLookNote` (an update that flagged every + object, or an undo or redo). Selection totals are the mesh's own counts and the index scan stops at the cap. They are + observations: no intent is refused because of them. + +### Host add-on actions + +A host add-on (Aetheria's `aetheria_ships`, say) lets agents run some of its own operators by putting a file +`brokkr_actions.json` beside its `__init__.py`: `{"schema": "brokkr.blender.host_actions.v0", "actions": [row]}`. +The add-on imports nothing from Brokkr and registers nothing; the file is the whole contract. +`surfaces/blender/tests/fixtures/brokkr_host_fixture/` is a worked example. + +A row is a built-in row (`name`, `doc`, `changesScene`, `editModeSafe`, `fields`) plus an optional `result`. +`name` is the `bl_idname` of an operator the same add-on registers (`addon.operator`, lower case, one dot, so +it never equals a built-in name). Fields are scalar only: `string` (with `enum`, `minLength`, `maxLength`, +`chars`, `prefixes`, `forbid`), `number` or `integer` (both with `minimum` and `maximum`) and `boolean`, +with `required` and `default` as for built-ins; no arrays, objects or free JSON, and no `envelope` or +`charsets` keys. The messages are the built-in ones. + +Brokkr admits a file whole or not at all, and reads it only when a human asks: once shortly after Brokkr +registers, and whenever she presses `Reload Host Actions` in the Brokkr panel. No intent, snapshot or agent +turn re-reads a file (the operator refuses inside a turn), so rewriting `brokkr_actions.json` to list +another operator admits nothing until she reloads; press it after enabling a host add-on or editing its +file. A file is checked when it is read, and the live checks below run at every intent and snapshot, so a +disabled add-on's actions are unknown at its next intent. A field may not be named like an envelope key +(`schema`, `commandId`, `action`, `requestedBy`, `note`): Brokkr writes those itself, so the operator would +never receive the agent's value. The live checks: each named operator exists and is a Python class defined by +that add-on's module (the module itself or under it: `aetheria_ships` is not `aetheria`'s), every field is a +property of the operator of the matching type (a string with an `enum` is an enum property with the same +identifiers), the operator's RNA hard limits contain the row's bounds, a row with `changesScene` false names +no operator whose `bl_options` has `UNDO`, and `result` names a writable `StringProperty` on +`bpy.types.WindowManager`. A refused file is reported in the host snapshot as `hostActionErrors` +(`brokkr-ctl blender status` prints each) and none of its rows runs. + +`changesScene` and `editModeSafe` are the host's word: Brokkr cannot see what an operator writes. A row that +claims to change nothing but writes gets no undo step and no Edit Mode refusal, so keep the flags honest. An +operator that calls `bpy.ops.ed.undo_push` itself adds that step to Brokkr's own (two for one action), or +one with `changesScene` false; that is a documented limit, not checked. A `poll` that fails, or a result +property that cannot be cleared, refuses before anything runs and pushes no undo step. + +An admitted action goes through the same agent turn as a built-in: Edit Mode refusal for rows that are not +`editModeSafe`, one labelled undo step when `changesScene`, a receipt. The operator is called with +`'EXEC_DEFAULT'` and exactly the declared fields. It runs on Blender's main thread, so a long operator +blocks the interface for as long as her own button would. `FINISHED` is `accepted`; `CANCELLED` is `failed` +with nothing pushed; an argument Blender will not convert, or an `ERROR` report or exception, is `failed` +(with the first line of the error). `result` is how an operator returns text (a dry-run's change lines): the +agent turn clears that WindowManager property before the call and copies it, up to 16000 characters and then +`[truncated]`, into the receipt's `hostResult` (empty for every other action). + +The admitted rows are published in the host snapshot as `hostActions` (each with its `host` module). +`brokkr-ctl blender send --help --store ` lists them after the built-ins, `send` refuses an intent +they refuse before writing anything, and the add-on still decides. Human-only is absence: an operator only a +person may run (one that applies a change to a game's data) is left out of the file, so an intent naming it +is `Unsupported Blender command action`, as `runPython` is; the person still presses her own button. The scene actions were run against Blender 5.2.3 LTS headless with `surfaces/blender/tests/live/headless_smoke.py` (usage in its docstring). One real failure it found: Blender's `engine` enum is dynamic, so `bl_rna` lists only -`BLENDER_EEVEE`; `renderStill` now asks Blender by assignment instead. +`BLENDER_EEVEE`; `renderStill` now asks Blender by assignment instead. `tests/live/export_gltf.py` and +`tests/live/refusals.py` (Blender 5.3.0 headless, usage in their docstrings) run `exportGltf` against the +real exporter and the render probe and `meshType` refusal against real bpy. ### Path rules and the residual race diff --git a/surfaces/blender/docs/node-actions.md b/surfaces/blender/docs/node-actions.md index cdbb556..b481c21 100644 --- a/surfaces/blender/docs/node-actions.md +++ b/surfaces/blender/docs/node-actions.md @@ -1,20 +1,23 @@ # Geometry node graph actions Command intents (`brokkr.blender.command_intent.v0`) that build and drive a Geometry Nodes graph. -Owner: `brokkr_bridge/node_actions.py`; the target only dispatches. Every field is validated before -`bpy` is touched; a refused intent is a `failed` receipt naming the rule and leaves the tree as it was. +Owner of how an intent becomes a graph: `brokkr_bridge/node_actions.py`; the target only dispatches. The +actions' fields, types and bounds are `brokkr_bridge/actions.json` (printed by `brokkr-ctl blender send --help`): +a field the table refuses is a `denied` receipt naming the rule, before `bpy` is touched. What only the scene +can judge (an absent group, a node type Blender does not offer, a socket that does not exist, a cycle) is a +`failed` receipt that leaves the tree as it was. Node actions name their object `objectName`. Design and the parts not built yet: the design lives at tag `parked/blender-node-graphs-design` (branch `libby/blender-node-graphs-design`, PR #3, closed unmerged), not in this tree. -| action | fields | rule | -|---|---|---| -| `createNodeGroup` | `treeKey`, `interface` `[{inOut, name, type, default?}]` | New geometry node group with `gin` and `gout` nodes. Types: Geometry, Float, Int, Bool, Vector. Refuses an existing group. The receipt lists the interface identifiers (`Socket_N`). | -| `addNode` | `treeKey`, `id`, `blIdname`, `location?`, `label?`, `properties?`, `inputs?` | `id` is Brokkr's key (stored as the node's `brokkr_id`). Type must be a `GeometryNode*`, `FunctionNode*` or `ShaderNode*` name that is not an importer, exporter, script, bake, group, zone, viewer or image-texture node. Properties are enum/bool/int/float node settings (set first, they decide which sockets exist); inputs are unlinked defaults (float, int, bool, vector, colour). At most 500 nodes per group. | -| `removeNode` | `treeKey`, `id` | Removes the node and its links. Absent id: accepted. `gin` and `gout` stay. | -| `linkSockets` | `treeKey`, `fromNode`, `fromSocket`, `toNode`, `toSocket` | Sockets by identifier, or by display name when exactly one available socket has it (Group Input/Output sockets are addressed by interface name). A link Blender calls invalid (field into a single value, type mismatch) is removed and refused, and the single link it displaced is put back. A valid link into a single-link input replaces the old one (Blender's behaviour); a link that would close a cycle, or link a node to itself, is refused before Blender is asked. | -| `unlinkSockets` | `treeKey`, `toNode`, `toSocket`, `fromNode?`, `fromSocket?` | Removes the links into an input, or only the one from the given source. None to remove: accepted. | -| `addModifier` | `objectName`, `treeKey`, `modifierName?` (default `Brokkr GeoNodes`) | `NODES` only. Reuses a modifier of that name; at most 8 per object. | -| `removeModifier` | `objectName`, `modifierName?` | Geometry Nodes modifiers only (a Subdivision or other modifier is refused). Absent: accepted. | -| `setModifierInput` | `objectName`, `modifierName?`, `socket` (identifier or unique interface name), `value` | Float, Int, Bool, Vector inputs. Written as `getattr(modifier.properties.inputs, id).value = v` (indexing `inputs[id]` yields a raw ID property group without `.value` on 5.2.3), then `object.update_tag()`. | +| action | rule | +|---|---| +| `createNodeGroup` | New geometry node group with `gin` and `gout` nodes. Types: Geometry, Float, Int, Bool, Vector. Refuses an existing group. The receipt lists the interface identifiers (`Socket_N`). | +| `addNode` | `id` is Brokkr's key (stored as the node's `brokkr_id`). Type must be a `GeometryNode*`, `FunctionNode*` or `ShaderNode*` name that is not an importer, exporter, script, bake, group, zone, viewer or image-texture node. Properties are enum/bool/int/float node settings (set first, they decide which sockets exist); inputs are unlinked defaults (float, int, bool, vector, colour). At most 500 nodes per group. | +| `removeNode` | Removes the node and its links. Absent id: accepted. `gin` and `gout` stay. | +| `linkSockets` | Sockets by identifier, or by display name when exactly one available socket has it (Group Input/Output sockets are addressed by interface name). A link Blender calls invalid (field into a single value, type mismatch) is removed and refused, and the single link it displaced is put back. A valid link into a single-link input replaces the old one (Blender's behaviour); a link that would close a cycle, or link a node to itself, is refused before Blender is asked. | +| `unlinkSockets` | Removes the links into an input, or only the one from the given source. None to remove: accepted. | +| `addModifier` | `NODES` only. Reuses a modifier of that name; at most 8 per object. | +| `removeModifier` | Geometry Nodes modifiers only (a Subdivision or other modifier is refused). Absent: accepted. | +| `setModifierInput` | Float, Int, Bool, Vector inputs. Written as `getattr(modifier.properties.inputs, id).value = v` (indexing `inputs[id]` yields a raw ID property group without `.value` on 5.2.3), then `object.update_tag()`. | `setObjectCustomProperty` refuses a property whose name is the identifier (`Socket_N`) of an input of a Geometry Nodes modifier on that object; a custom property never drives a modifier input. A name that only equals an diff --git a/surfaces/blender/tests/action_cases.json b/surfaces/blender/tests/action_cases.json new file mode 100644 index 0000000..2c082f1 --- /dev/null +++ b/surfaces/blender/tests/action_cases.json @@ -0,0 +1,238 @@ +[ + {"action": "createObject", "fields": {}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "MESH", "name": "N", "location": [0, 0, 1], "size": 2, "meshType": "CUBE"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": null, "name": null, "location": null}, "expect": "ok"}, + {"action": "createObject", "fields": {"note": "n", "requestedBy": "a/b", "commandId": "x", "schema": "s"}, "expect": "ok"}, + {"action": "look", "fields": {}, "expect": "ok"}, + {"action": "deleteObject", "fields": {"targetObjectName": "Cube"}, "expect": "ok"}, + {"action": "deleteObject", "fields": {}, "expect": "targetObjectName is required."}, + {"action": "deleteObject", "fields": {"targetObjectName": null}, "expect": "targetObjectName is required."}, + {"action": "createObject", "fields": {"bogus": 1}, "expect": "createObject has no field 'bogus'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType."}, + {"action": "createObject", "fields": {"zeta": 1, "alpha": 2}, "expect": "createObject has no field 'alpha'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType."}, + {"action": "setObjectTransform", "fields": {"objectName": "x"}, "expect": "setObjectTransform has no field 'objectName'; its fields: targetObjectName, location, rotationEuler, scale."}, + {"action": "addModifier", "fields": {"targetObjectName": "x"}, "expect": "addModifier has no field 'targetObjectName'; its fields: objectName, modifierType, treeKind, treeKey, modifierName."}, + {"action": "setObjectParent", "fields": {"targetObjectName": "x", "parentName": "p"}, "expect": "setObjectParent has no field 'parentName'; its fields: targetObjectName, parentObjectName."}, + {"action": "look", "fields": {"x": 1}, "expect": "look has no field 'x'; its fields: none."}, + {"action": "runPython", "fields": {}, "expect": "Unsupported Blender command action: runPython"}, + {"action": "createobject", "fields": {}, "expect": "Unsupported Blender command action: createobject"}, + {"action": "createObject", "fields": {"name": 5}, "expect": "name must be a string."}, + {"action": "createObject", "fields": {"size": "x"}, "expect": "size must be a finite number."}, + {"action": "createObject", "fields": {"size": true}, "expect": "size must be a finite number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1.5}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": true}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": "64"}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 640.0}, "expect": "ok"}, + {"action": "setObjectVisibility", "fields": {"targetObjectName": "c", "visible": 1}, "expect": "visible must be true or false."}, + {"action": "setObjectVisibility", "fields": {"targetObjectName": "c", "visible": false}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": "x"}, "expect": "location must be an array."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": []}, "expect": "properties must be an object."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": {"x": null, "y": 1}, "inputs": {"a": [1, 2]}}, "expect": "ok"}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": null}, "expect": "value is required."}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": {"a": [1]}}, "expect": "ok"}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": false}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "mesh"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."}, + {"action": "createObject", "fields": {"objectType": " MESH"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."}, + {"action": "createObject", "fields": {"objectType": 3}, "expect": "objectType must be a string."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "CUSTOM"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "ortho"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIDISTANT"}, "expect": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "CENTRAL_CYLINDRICAL", "cameraType": "PANO", "active": true}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "SUBSURF"}, "expect": "modifierType must be one of NODES."}, + {"action": "addNode", "fields": {"treeKind": "shader", "treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath"}, "expect": "treeKind must be one of geometry."}, + {"action": "createObject", "fields": {"objectType": "MESH", "lightType": "POINT"}, "expect": "lightType applies only when objectType is one of LIGHT."}, + {"action": "createObject", "fields": {"lightType": "POINT"}, "expect": "lightType applies only when objectType is one of LIGHT."}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "emptyDisplayType": "CUBE"}, "expect": "emptyDisplayType applies only when objectType is one of EMPTY."}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "meshType": "CUBE"}, "expect": "meshType applies only when objectType is one of MESH."}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "lightType": "SPOT"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "EMPTY", "emptyDisplayType": "IMAGE"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "LIGHT", "lightType": "LASER"}, "expect": "lightType must be one of POINT, SUN, SPOT, AREA."}, + {"action": "createObject", "fields": {"objectType": "EMPTY", "emptyDisplayType": "BOX"}, "expect": "emptyDisplayType must be one of PLAIN_AXES, ARROWS, SINGLE_ARROW, CIRCLE, CUBE, SPHERE, CONE, IMAGE."}, + {"action": "createNodeGroup", "fields": {"treeKey": "", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey must have at least 1 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey must have at most 63 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "my group.1-x_y", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "a/b", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "treeKey may contain only letters, digits, space, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a b"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a\n"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "\u00e9"}, "expect": "id may contain only letters, digits, '.', '_' or '-'."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "gin"}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "Math"}, "expect": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "GeometryNode"}, "expect": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "Geometry Node"}, "expect": "blIdname may contain only letters and digits."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "GeometryNodeGroup"}, "expect": "blIdname may not contain 'Group'."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeTexImage"}, "expect": "blIdname may not contain 'TexImage'."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "FunctionNodeCompare"}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "label": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "label must have at most 63 characters."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "label": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "ok"}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "a\u0000b"}, "expect": "modifierName may not contain '\u0000'."}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "modifierName must have at most 255 characters."}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "ok"}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": ""}, "expect": "modifierName must have at least 1 characters."}, + {"action": "removeModifier", "fields": {"objectName": "o", "modifierName": "G\u00e9 x/y"}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "engine": ""}, "expect": "engine must have at least 1 characters."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "engine": "CYCLES"}, "expect": "ok"}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": []}, "expect": "selection must have at least 1 items."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": [3]}, "expect": "selection[0] must be a string."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a", ""]}, "expect": "selection[1] must have at least 1 characters."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a", null]}, "expect": "selection[1] must be a string."}, + {"action": "exportGltf", "fields": {"filepath": "a.glb", "selection": ["a"], "extras": "yes"}, "expect": "extras must be true or false."}, + {"action": "createObject", "fields": {"location": [1, 2]}, "expect": "location must have at least 3 items."}, + {"action": "createObject", "fields": {"location": [1, 2, 3, 4]}, "expect": "location must have at most 3 items."}, + {"action": "createObject", "fields": {"location": [1, "x", 3]}, "expect": "location[1] must be a finite number."}, + {"action": "createObject", "fields": {"location": [1, null, 3]}, "expect": "location[1] must be a finite number."}, + {"action": "createObject", "fields": {"location": [1, 2, true]}, "expect": "location[2] must be a finite number."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0]}, "expect": "color must have at least 3 items."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 0, 0]}, "expect": "color must have at most 4 items."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 0.5]}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [1, 0, 0, 1]}, "expect": "color must have at most 3 items."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [1]}, "expect": "location must have at least 2 items."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G"}, "expect": "interface is required."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": []}, "expect": "interface must have at least 1 items."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "interface must have at most 64 items."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [1]}, "expect": "interface[0] must be an object."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "type": "Int"}]}, "expect": "interface[0].name is required."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}, {"inOut": "INPUT", "name": null, "type": "Int"}]}, "expect": "interface[1].name is required."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "input", "name": "a", "type": "Int"}]}, "expect": "interface[0].inOut must be one of INPUT, OUTPUT."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Mat"}]}, "expect": "interface[0].type must be one of Geometry, Float, Int, Bool, Vector."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "", "type": "Int"}]}, "expect": "interface[0].name must have at least 1 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "type": "Int"}]}, "expect": "interface[0].name must have at most 63 characters."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "extra": 1}]}, "expect": "interface[0] has no field 'extra'; its fields: inOut, name, type, default."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "default": "anything"}]}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int", "default": null}]}, "expect": "ok"}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b"}, "expect": "toSocket is required."}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "fromNode": "a"}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "createObject", "fields": {"location": [-1000000000, -1000000000, 1000000001]}, "expect": "location[2] must be between -1000000000 and 1000000000."}, + {"action": "createObject", "fields": {"location": [-1000000001, -1000000000, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."}, + {"action": "createObject", "fields": {"size": 0.001}, "expect": "ok"}, + {"action": "createObject", "fields": {"size": 1000000}, "expect": "ok"}, + {"action": "createObject", "fields": {"size": 1000001}, "expect": "size must be between 0.001 and 1000000."}, + {"action": "createObject", "fields": {"size": -0.999}, "expect": "size must be between 0.001 and 1000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000000, -1000000000, 1000000001]}, "expect": "location[2] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "location": [-1000000001, -1000000000, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000000, -1000000000, 1000000001]}, "expect": "rotationEuler[2] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "rotationEuler": [-1000000001, -1000000000, -1000000000]}, "expect": "rotationEuler[0] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000000, -1000000000, -1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [1000000000, 1000000000, 1000000000]}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000000, -1000000000, 1000000001]}, "expect": "scale[2] must be between -1000000000 and 1000000000."}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c", "scale": [-1000000001, -1000000000, -1000000000]}, "expect": "scale[0] must be between -1000000000 and 1000000000."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [0, 0, 0]}, "expect": "ok"}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [1, 1, 1]}, "expect": "ok"}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c", "color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 1}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 5000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 5001}, "expect": "lens must be between 1 and 5000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "lens": 0}, "expect": "lens must be between 1 and 5000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 0.001}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 100000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": 100001}, "expect": "orthoScale must be between 0.001 and 100000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "orthoScale": -0.999}, "expect": "orthoScale must be between 0.001 and 100000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 0.0001}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 1000000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": 1000001}, "expect": "clipStart must be between 0.0001 and 1000000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipStart": -0.9999}, "expect": "clipStart must be between 0.0001 and 1000000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 0.001}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 10000000}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": 10000001}, "expect": "clipEnd must be between 0.001 and 10000000."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "clipEnd": -0.999}, "expect": "clipEnd must be between 0.001 and 10000000."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": 0}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": 10000000}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": 10000001}, "expect": "energy must be between 0 and 10000000."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "energy": -1}, "expect": "energy must be between 0 and 10000000."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [0, 0, 0]}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [1, 1, 1]}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."}, + {"action": "setWorld", "fields": {"color": [0, 0, 0]}, "expect": "ok"}, + {"action": "setWorld", "fields": {"color": [1, 1, 1]}, "expect": "ok"}, + {"action": "setWorld", "fields": {"color": [0, 0, 2]}, "expect": "color[2] must be between 0 and 1."}, + {"action": "setWorld", "fields": {"color": [-1, 0, 0]}, "expect": "color[0] must be between 0 and 1."}, + {"action": "setWorld", "fields": {"strength": 0}, "expect": "ok"}, + {"action": "setWorld", "fields": {"strength": 1000000}, "expect": "ok"}, + {"action": "setWorld", "fields": {"strength": 1000001}, "expect": "strength must be between 0 and 1000000."}, + {"action": "setWorld", "fields": {"strength": -1}, "expect": "strength must be between 0 and 1000000."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 4}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 16384}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 16385}, "expect": "resolutionX must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 3}, "expect": "resolutionX must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 4}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16384}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16385}, "expect": "resolutionY must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 3}, "expect": "resolutionY must be between 4 and 16384."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000000, -1000000000]}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [1000000000, 1000000000]}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000000, 1000000001]}, "expect": "location[1] must be between -1000000000 and 1000000000."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "location": [-1000000001, -1000000000]}, "expect": "location[0] must be between -1000000000 and 1000000000."}, + {"action": "createObject", "fields": {"objectType": "MESH"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "LIGHT"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "CAMERA"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "EMPTY"}, "expect": "ok"}, + {"action": "createObject", "fields": {"objectType": "mesh_"}, "expect": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "PERSP"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "ORTHO"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "PANO"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "cameraType": "persp_"}, "expect": "cameraType must be one of PERSP, ORTHO, PANO."}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIRECTANGULAR"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "EQUIANGULAR_CUBEMAP_FACE"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "MIRRORBALL"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_EQUIDISTANT"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_EQUISOLID"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "FISHEYE_LENS_POLYNOMIAL"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "CENTRAL_CYLINDRICAL"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c", "panoramaType": "equirectangular_"}, "expect": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL."}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "POINT"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "SUN"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "SPOT"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "AREA"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c", "lightType": "point_"}, "expect": "lightType must be one of POINT, SUN, SPOT, AREA."}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}], "treeKind": "geometry"}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}], "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "NODES"}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "modifierType": "nodes_"}, "expect": "modifierType must be one of NODES."}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "treeKind": "geometry"}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G", "treeKind": "geometry_"}, "expect": "treeKind must be one of geometry."}, + {"action": "createObject", "fields": {}, "expect": "ok"}, + {"action": "deleteObject", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectTransform", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectVisibility", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectParent", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setObjectCustomProperty", "fields": {"targetObjectName": "c", "value": 1}, "expect": "ok"}, + {"action": "selectObject", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "assignMaterial", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "importGltf", "fields": {"filepath": "a.glb"}, "expect": "ok"}, + {"action": "exportGltf", "fields": {"filepath": "a.glb"}, "expect": "ok"}, + {"action": "setCamera", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setLight", "fields": {"targetObjectName": "c"}, "expect": "ok"}, + {"action": "setWorld", "fields": {}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png"}, "expect": "ok"}, + {"action": "look", "fields": {}, "expect": "ok"}, + {"action": "createNodeGroup", "fields": {"treeKey": "G", "interface": [{"inOut": "INPUT", "name": "a", "type": "Int"}]}, "expect": "ok"}, + {"action": "addNode", "fields": {"treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath"}, "expect": "ok"}, + {"action": "removeNode", "fields": {"treeKey": "G", "id": "a"}, "expect": "ok"}, + {"action": "linkSockets", "fields": {"treeKey": "G", "fromNode": "a", "fromSocket": "o", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, + {"action": "unlinkSockets", "fields": {"treeKey": "G", "toNode": "b", "toSocket": "i"}, "expect": "ok"}, + {"action": "addModifier", "fields": {"objectName": "o", "treeKey": "G"}, "expect": "ok"}, + {"action": "removeModifier", "fields": {"objectName": "o"}, "expect": "ok"}, + {"action": "setModifierInput", "fields": {"objectName": "o", "socket": "s", "value": 1}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1920.0, "resolutionY": 1080.0}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 4.0}, "expect": "ok"}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 3.0}, "expect": "resolutionX must be between 4 and 16384."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionX": 1920.5}, "expect": "resolutionX must be a whole number."}, + {"action": "renderStill", "fields": {"outputPath": "a.png", "resolutionY": 16384.0}, "expect": "ok"} +] diff --git a/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py b/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py new file mode 100644 index 0000000..671d78c --- /dev/null +++ b/surfaces/blender/tests/fixtures/brokkr_host_fixture/__init__.py @@ -0,0 +1,72 @@ +"""A legacy host add-on for Brokkr's host-action tests. It knows nothing of Brokkr: its brokkr_actions.json is +the whole contract. apply is registered but left out of that file, the shape of an operator only a human runs.""" +bl_info = {"name": "Brokkr host fixture", "blender": (4, 2, 0), "category": "Development"} + +import bpy + + +class BROKKR_HOST_FIXTURE_OT_add_empty(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.add_empty" + bl_label = "Fixture add empty" + bl_options = {"REGISTER", "UNDO"} + name: bpy.props.StringProperty(default="Fixture") + size: bpy.props.FloatProperty(default=1.0, min=0.0, max=100.0) + + def execute(self, context): + empty = bpy.data.objects.new(self.name, None) + empty.empty_display_size = self.size + context.scene.collection.objects.link(empty) + return {"FINISHED"} + + +class BROKKR_HOST_FIXTURE_OT_report(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.report" + bl_label = "Fixture report" + bl_options = {"REGISTER"} + + def execute(self, context): + context.window_manager.brokkr_host_fixture_result = f"objects: {len(bpy.data.objects)}\nscenes: {len(bpy.data.scenes)}" + return {"FINISHED"} + + +class BROKKR_HOST_FIXTURE_OT_refuse(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.refuse" + bl_label = "Fixture refuse" + + def execute(self, context): + self.report({"ERROR"}, "the fixture refuses") + return {"CANCELLED"} + + +class BROKKR_HOST_FIXTURE_OT_cancel(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.cancel" + bl_label = "Fixture cancel" + + def execute(self, context): + return {"CANCELLED"} + + +class BROKKR_HOST_FIXTURE_OT_apply(bpy.types.Operator): + bl_idname = "brokkr_host_fixture.apply" + bl_label = "Fixture apply" + bl_options = {"REGISTER", "UNDO"} + + def execute(self, context): + bpy.data.objects.new("Applied", None) + return {"FINISHED"} + + +classes = (BROKKR_HOST_FIXTURE_OT_add_empty, BROKKR_HOST_FIXTURE_OT_report, BROKKR_HOST_FIXTURE_OT_refuse, + BROKKR_HOST_FIXTURE_OT_cancel, BROKKR_HOST_FIXTURE_OT_apply) + + +def register(): + bpy.types.WindowManager.brokkr_host_fixture_result = bpy.props.StringProperty() + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) + del bpy.types.WindowManager.brokkr_host_fixture_result diff --git a/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json b/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json new file mode 100644 index 0000000..160f67a --- /dev/null +++ b/surfaces/blender/tests/fixtures/brokkr_host_fixture/brokkr_actions.json @@ -0,0 +1,37 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_host_fixture.add_empty", + "doc": "Add an empty named for the agent.", + "changesScene": true, + "editModeSafe": false, + "fields": [ + {"name": "name", "type": "string", "required": true, "minLength": 1, "maxLength": 63, "doc": "the empty's name"}, + {"name": "size", "type": "number", "minimum": 0.1, "maximum": 10, "default": 1, "doc": "display size"} + ] + }, + { + "name": "brokkr_host_fixture.report", + "doc": "Write a report of the scene without changing it.", + "changesScene": false, + "editModeSafe": true, + "result": "brokkr_host_fixture_result", + "fields": [] + }, + { + "name": "brokkr_host_fixture.refuse", + "doc": "Report an error and cancel.", + "changesScene": false, + "editModeSafe": true, + "fields": [] + }, + { + "name": "brokkr_host_fixture.cancel", + "doc": "Cancel without a report.", + "changesScene": false, + "editModeSafe": true, + "fields": [] + } + ] +} diff --git a/surfaces/blender/tests/host_action_cases.json b/surfaces/blender/tests/host_action_cases.json new file mode 100644 index 0000000..91836a9 --- /dev/null +++ b/surfaces/blender/tests/host_action_cases.json @@ -0,0 +1,21 @@ +[ + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E"}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 0.1}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 10}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": null, "note": "n", "requestedBy": "a/b", "commandId": "x"}, "expect": "ok"}, + {"action": "brokkr_host_fixture.add_empty", "fields": {}, "expect": "name is required."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": ""}, "expect": "name must have at least 1 characters."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}, "expect": "name must have at most 63 characters."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": 5}, "expect": "name must be a string."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 0.05}, "expect": "size must be between 0.1 and 10."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": 10.5}, "expect": "size must be between 0.1 and 10."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "size": true}, "expect": "size must be a finite number."}, + {"action": "brokkr_host_fixture.add_empty", "fields": {"name": "E", "bogus": 1}, "expect": "brokkr_host_fixture.add_empty has no field 'bogus'; its fields: name, size."}, + {"action": "brokkr_host_fixture.report", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.report", "fields": {"name": "E"}, "expect": "brokkr_host_fixture.report has no field 'name'; its fields: none."}, + {"action": "brokkr_host_fixture.refuse", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.cancel", "fields": {}, "expect": "ok"}, + {"action": "brokkr_host_fixture.apply", "fields": {}, "expect": "Unsupported Blender command action: brokkr_host_fixture.apply"}, + {"action": "wm.save_mainfile", "fields": {}, "expect": "Unsupported Blender command action: wm.save_mainfile"}, + {"action": "createObject", "fields": {}, "expect": "ok"} +] diff --git a/surfaces/blender/tests/live/action_table.py b/surfaces/blender/tests/live/action_table.py new file mode 100644 index 0000000..24db485 --- /dev/null +++ b/surfaces/blender/tests/live/action_table.py @@ -0,0 +1,398 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, that the action table is the one admission. + + BROKKR_SCRATCH= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python action_table.py -- + +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. Every intent is put into the node +database as brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). For every action in actions.json: + + * malformed intents generated from its table entry (an unknown field, a wrong type, an enum miss, a bound miss, + a missing required field, a string or array rule broken, an 'only' broken) are each 'denied', add no undo step + and leave the scene unchanged: one undo after them reverts the canary step that preceded them; + * one valid intent is accepted and, when the entry's changesScene is true, is exactly one undo step (undo restores the + scene, redo brings it back); when false it pushes none. + +A final check holds a receipt write back once and proves the intent still ran exactly once (the drain claims first). +Undo and redo are read only here, by this driver. Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import sys +import traceback +from pathlib import Path + +import bpy + +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "actions": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +at = importlib.import_module(MODULE + ".action_table") +prefs = bpy.context.preferences.addons[MODULE].preferences +bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "live.blend")) +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" +prefs.output_dir = str(SCRATCH / "out") +prefs.import_dir = str(SCRATCH / "out") # importGltf reads what exportGltf wrote +prefs.auto_drain_commands = True # the sink +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +(SCRATCH / "out").mkdir(exist_ok=True) +adapter = addon.target() +R["table_actions"] = [a["name"] for a in at.table()["actions"]] + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def redo(): + with win(): + bpy.ops.ed.redo() + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +N = [0] + + +def queue(**cmd): + N[0] += 1 + cid = "live-%04d" % N[0] + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA, requestedBy="nibu/hands") + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + return cid + + +def receipt(cid): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{cid}") + + +def pending(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +def r3(values): + return [round(float(v), 4) for v in values] + + +def sig(): + """What an agent intent can change, as one comparable value.""" + scene = bpy.context.scene + world = scene.world + background = world.node_tree.nodes.get("Background") if world and world.node_tree else None + return json.dumps({ + "objects": [[o.name, o.type, r3(o.location), r3(o.rotation_euler), r3(o.scale), o.hide_viewport, o.hide_render, + o.parent.name if o.parent else "", sorted(k for k in o.keys() if not k.startswith("_")), + [[m.name, m.type] for m in o.modifiers], o.select_get()] for o in bpy.data.objects], + "active": bpy.context.view_layer.objects.active.name if bpy.context.view_layer.objects.active else "", + "materials": [[m.name, r3(m.diffuse_color)] for m in bpy.data.materials], + "groups": [[g.name, len(g.nodes), len(g.links)] for g in bpy.data.node_groups], + "cameras": [[c.name, c.lens, c.type, c.panorama_type] for c in bpy.data.cameras], + "lights": [[l.name, l.energy, r3(l.color), l.type] for l in bpy.data.lights], + "world": [world.name, r3(background.inputs["Color"].default_value), round(background.inputs["Strength"].default_value, 4)] if background else None, + "camera": scene.camera.name if scene.camera else "", + "render": [scene.render.engine, scene.render.resolution_x, scene.render.resolution_y], + "counts": [len(bpy.data.objects), len(bpy.data.meshes), len(bpy.data.images)], + }, sort_keys=True) + + +# ---- table-generated intents ------------------------------------------------------------------------------------- + +SAMPLES = [ # (action, prep intents queued and run unmeasured first, the valid sample) + ("createObject", [], {"objectType": "MESH", "name": "LiveCube", "location": [2, 0, 0], "size": 2}), + ("deleteObject", [{"action": "createObject", "objectType": "EMPTY", "name": "LiveDoomed"}], {"targetObjectName": "LiveDoomed"}), + ("setObjectTransform", [], {"targetObjectName": "LiveCube", "location": [2, 3, 0], "rotationEuler": [0, 0, 0.5], "scale": [1, 2, 1]}), + ("setObjectVisibility", [], {"targetObjectName": "LiveCube", "visible": False}), + ("setObjectParent", [], {"targetObjectName": "LiveCube", "parentObjectName": "Cube"}), + ("setObjectCustomProperty", [], {"targetObjectName": "LiveCube", "propertyName": "liveProp", "value": 3}), + ("selectObject", [], {"targetObjectName": "Camera"}), + ("assignMaterial", [], {"targetObjectName": "LiveCube", "materialName": "LiveMat", "color": [0.1, 0.2, 0.3]}), + ("exportGltf", [], {"filepath": "live.glb"}), + ("importGltf", [], {"filepath": "live.glb"}), + ("setCamera", [], {"targetObjectName": "Camera", "lens": 35, "cameraType": "PANO", "panoramaType": "FISHEYE_EQUIDISTANT", "active": True}), + ("setLight", [], {"targetObjectName": "Light", "energy": 500, "color": [1, 0.5, 0], "lightType": "SUN"}), + ("setWorld", [], {"color": [0.1, 0.1, 0.2], "strength": 1.5}), + ("renderStill", [], {"outputPath": "live.png", "engine": "CYCLES", "resolutionX": 8.0, "resolutionY": 8}), # a whole float: the table hands Blender an int + ("look", [], {}), + ("createNodeGroup", [], {"treeKey": "LiveG", "interface": [{"inOut": "INPUT", "name": "Geometry", "type": "Geometry"}, + {"inOut": "OUTPUT", "name": "Geometry", "type": "Geometry"}, + {"inOut": "INPUT", "name": "Count", "type": "Int", "default": 8}]}), + ("addNode", [], {"treeKey": "LiveG", "id": "m1", "blIdname": "ShaderNodeMath", "location": [100, 0], "label": "live"}), + ("linkSockets", [], {"treeKey": "LiveG", "fromNode": "gin", "fromSocket": "Geometry", "toNode": "gout", "toSocket": "Geometry"}), + ("unlinkSockets", [], {"treeKey": "LiveG", "toNode": "gout", "toSocket": "Geometry"}), + ("removeNode", [], {"treeKey": "LiveG", "id": "m1"}), + ("addModifier", [], {"objectName": "LiveCube", "treeKey": "LiveG", "modifierName": "LiveMod"}), + ("setModifierInput", [], {"objectName": "LiveCube", "modifierName": "LiveMod", "socket": "Count", "value": 4}), + ("removeModifier", [], {"objectName": "LiveCube", "modifierName": "LiveMod"}), +] +WRONG = {"string": 5, "number": "x", "integer": "x", "boolean": "x", "array": "x", "object": []} + + +def malformed(action, sample): + """Intents the table refuses, each derived from one rule of the action's entry. [(label, fields)]""" + row = at.entry(action) + out = [("unknown field", {**sample, "zzUnknown": 1})] + specs = {f["name"]: f for f in row["fields"]} + for name, spec in specs.items(): + def vary(label, value): + out.append((f"{name}: {label}", {**sample, name: value})) + kind = spec["type"] + if kind in WRONG: + vary("wrong type", WRONG[kind]) + if spec.get("required") and name in sample: + out.append((f"{name}: required missing", {k: v for k, v in sample.items() if k != name})) + if "enum" in spec: + vary("enum miss", "nope_") + if kind in ("number", "integer"): + vary("above maximum", spec["maximum"] + 1) + vary("below minimum", spec["minimum"] - 1) + if kind == "string" and "enum" not in spec: + if spec.get("minLength", 0) >= 1: + vary("below minLength", "") + if "maxLength" in spec: + vary("above maxLength", "x" * (spec["maxLength"] + 1)) + if "chars" in spec: + vary("outside charset", "a\n") + if "prefixes" in spec: + vary("no prefix", "Q") + if "forbid" in spec and isinstance(sample.get(name), str): + vary("forbidden part", sample[name] + spec["forbid"][0]) + if kind == "array": + item = spec["items"] + if spec.get("minItems", 0) >= 1: + vary("below minItems", [None][:0] if spec["minItems"] == 1 else [0] * (spec["minItems"] - 1)) + if "maxItems" in spec and item["type"] == "number": + vary("above maxItems", [0] * (spec["maxItems"] + 1)) + if item["type"] == "number": + low = [item["minimum"]] * spec.get("minItems", 1) + vary("item above maximum", [item["maximum"] + 1] + low[1:]) + vary("item below minimum", [item["minimum"] - 1] + low[1:]) + vary("item wrong type", [WRONG.get(item["type"], 5)] + [0] * (spec.get("minItems", 1) - 1)) + if item["type"] == "object": + vary("item missing a property", [{"inOut": "INPUT", "type": "Int"}]) + vary("item unknown property", [{"inOut": "INPUT", "name": "a", "type": "Int", "zzUnknown": 1}]) + if "only" in spec: + sibling = specs[spec["only"]["field"]] + other = next(v for v in sibling["enum"] if v not in spec["only"]["in"]) + out.append((f"{name}: only applies to {spec['only']['field']} in {spec['only']['in']}", + {**{k: v for k, v in sample.items() if k != name}, spec["only"]["field"]: other, name: spec["enum"][0]})) + return out + + +# ---- steps ------------------------------------------------------------------------------------------------------- + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=40): + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("the drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def drained(key): + return lambda: all(receipt(c) for c in S[key]) + + +def run_all(key, intents): + S[key] = [queue(**fields) for fields in intents] + + +def per_action(action, prep, sample): + row = at.entry(action) + key = action + info = R["actions"][action] = {"changesScene": row["changesScene"]} + scene_changing = row["changesScene"] + + def baseline(): + S[key + ":sig0"] = sig() + S[key + ":names0"] = names() + + def malformed_queue(): + bad = malformed(action, sample) + S[key + ":labels"] = [label for label, _ in bad] + run_all(key + ":bad", [{"action": action, **fields} for _, fields in bad]) + + def malformed_check(): + got = [receipt(c) for c in S[key + ":bad"]] + labels = S[key + ":labels"] + not_denied = [(l, r["status"], r["message"]) for l, r in zip(labels, got) if r["status"] != "denied"] + info["malformed"] = len(got) + info["messages"] = {l: r["message"] for l, r in zip(labels, got)} + steps_added = [l for l, r in zip(labels, got) if r["undoLabel"]] + check(f"{action}: {len(got)} table-generated malformed intents are each denied", got and not not_denied, not_denied[:5]) + check(f"{action}: a denied intent carries no undoLabel", not steps_added, steps_added[:5]) + check(f"{action}: the scene is unchanged by the malformed intents", sig() == S[key + ":sig1"], None) + undo() # one undo: if a malformed intent had pushed a step, the canary would survive + check(f"{action}: no malformed intent added an undo step (one undo reverts the canary before them)", + sig() == S[key + ":sig0"], {"names": names(), "was": S[key + ":names0"]}) + + def canary_queue(tag): + run_all(key + ":canary" + tag, [{"action": "createObject", "objectType": "MESH", "name": "Canary" + tag, "location": [0, 0, 9]}]) + + def canary_check(): + r = receipt(S[key + ":canary1"][0]) + S[key + ":sig1"] = sig() + check(f"{action}: the canary is accepted with one undoLabel", r["status"] == "accepted" and r["undoLabel"], r) + + def valid_queue(): + S[key + ":sigv0"] = sig() + run_all(key + ":valid", [{"action": action, **sample}]) + + def valid_check(): + r = receipt(S[key + ":valid"][0]) + info["valid"] = {"status": r["status"], "message": r["message"], "undoLabel": r["undoLabel"]} + after = sig() + S[key + ":sigv1"] = after + check(f"{action}: the valid intent is accepted", r["status"] == "accepted", r) + if scene_changing: + check(f"{action}: changesScene is true, so the receipt carries an undoLabel", r["undoLabel"].startswith(f"Brokkr nibu/hands: {action} "), r["undoLabel"]) + if after != S[key + ":sigv0"]: + undo() + check(f"{action}: one undo restores the scene to before the intent", sig() == S[key + ":sigv0"], None) + redo() + check(f"{action}: redo brings the intent's result back", sig() == after, None) + else: + info["note"] = "the intent changed nothing the signature reads (checked by label only)" + else: + check(f"{action}: changesScene is false, so no undoLabel", r["undoLabel"] == "", r["undoLabel"]) + + def noscene_check(): + # a canary, then the valid intent, then one undo: the canary goes, so the intent pushed no step + undo() + check(f"{action}: it pushed no undo step (one undo reverts the canary before it)", sig() == S[key + ":sigc0"], None) + + out = [] + for p in prep: + out += [once(lambda p=p: run_all(key + ":prep", [p])), until(drained(key + ":prep"))] + out += [once(baseline), once(lambda: canary_queue("1")), until(drained(key + ":canary1")), once(canary_check), + once(malformed_queue), until(drained(key + ":bad")), once(malformed_check)] + if scene_changing: + out += [once(valid_queue), until(drained(key + ":valid")), once(valid_check)] + else: + out += [once(lambda: S.__setitem__(key + ":sigc0", sig())), once(lambda: canary_queue("2")), until(drained(key + ":canary2")), + once(valid_queue), until(drained(key + ":valid")), once(valid_check), once(noscene_check)] + return out + + +def covered(): + missing = [a for a in R["table_actions"] if a not in {s[0] for s in SAMPLES}] + extra = [s[0] for s in SAMPLES if s[0] not in R["table_actions"]] + check("every action of actions.json has a live sample and no sample names an action the table lacks", not missing and not extra, [missing, extra]) + + +def flaky_setup(): + """Hold one receipt write back: the intent must still have run exactly once, and its receipt arrive next drain.""" + S["flaky:objects"] = len([o for o in bpy.data.objects if o.name.startswith("FlakyCube")]) + original = adapter.publish_receipt + state = {"raised": 0} + S["flaky:id"] = None + + def flaky(*args, **kwargs): + receipt_doc = args[2] if len(args) > 2 else kwargs.get("receipt") + if receipt_doc and receipt_doc.get("commandId") == S["flaky:id"] and not state["raised"]: + state["raised"] += 1 + raise OSError("injected receipt write failure") + return original(*args, **kwargs) + + adapter.publish_receipt = flaky + S["flaky:restore"] = lambda: setattr(adapter, "publish_receipt", original) + S["flaky:state"] = state + cid = queue(action="createObject", objectType="MESH", name="FlakyCube", location=[0, 0, 12]) + S["flaky:id"] = cid + S["flaky:ids"] = [cid] + + +def flaky_check(): + S["flaky:restore"]() + r = receipt(S["flaky:id"]) + flakies = [o.name for o in bpy.data.objects if o.name.startswith("FlakyCube")] + check("claim-first: with one receipt write failing, the intent ran exactly once and its receipt was written by the next drain", + S["flaky:state"]["raised"] == 1 and len(flakies) == 1 and r and r["status"] == "accepted" + and f"blender/receipts/{S['flaky:id']}.denied" not in node()[0].database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}) + and S["flaky:id"] not in str(pending()), {"raised": S["flaky:state"]["raised"], "objects": flakies, "receipt": r and r["status"]}) + check("the queue is empty and the add-on's drain reports no error", not pending() and adapter.last_auto_drain_error == "", + [list(pending()), adapter.last_auto_drain_error]) + + +steps = [once(covered)] +for action, prep, sample in SAMPLES: + steps += per_action(action, prep, sample) +steps += [once(flaky_setup), until(lambda: receipt(S["flaky:id"]) is not None), once(flaky_check)] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/action_table.result.json b/surfaces/blender/tests/live/action_table.result.json new file mode 100644 index 0000000..981a3a6 --- /dev/null +++ b/surfaces/blender/tests/live/action_table.result.json @@ -0,0 +1,2543 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "every action of actions.json has a live sample and no sample names an action the table lacks", + "ok": true, + "detail": [ + [], + [] + ] + }, + { + "name": "createObject: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0001", + "lookPath": "", + "observedAt": "2026-11-28T02:36:27.076161+00:00" + } + }, + { + "name": "createObject: 22 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "createObject: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "createObject: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "createObject: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light" + ], + "was": [ + "Camera", + "Cube", + "Light" + ] + } + }, + { + "name": "createObject: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0024", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0024", + "lookPath": "", + "observedAt": "2026-11-28T02:36:32.724431+00:00" + } + }, + { + "name": "createObject: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createObject ive-0024" + }, + { + "name": "createObject: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "createObject: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "deleteObject: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0026", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0026", + "lookPath": "", + "observedAt": "2026-11-28T02:36:36.860973+00:00" + } + }, + { + "name": "deleteObject: 3 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "deleteObject: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "deleteObject: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "deleteObject: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube", + "LiveDoomed" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube", + "LiveDoomed" + ] + } + }, + { + "name": "deleteObject: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0030", + "action": "deleteObject", + "status": "accepted", + "message": "Blender object deleted.", + "objectName": "LiveDoomed", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: deleteObject ive-0030", + "lookPath": "", + "observedAt": "2026-11-28T02:36:41.174327+00:00" + } + }, + { + "name": "deleteObject: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: deleteObject ive-0030" + }, + { + "name": "deleteObject: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "deleteObject: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0031", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0031", + "lookPath": "", + "observedAt": "2026-11-28T02:36:43.258961+00:00" + } + }, + { + "name": "setObjectTransform: 21 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectTransform: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectTransform: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectTransform: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0053", + "action": "setObjectTransform", + "status": "accepted", + "message": "Blender object transform updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectTransform ive-0053", + "lookPath": "", + "observedAt": "2026-11-28T02:36:49.152690+00:00" + } + }, + { + "name": "setObjectTransform: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectTransform ive-0053" + }, + { + "name": "setObjectTransform: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectTransform: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectVisibility: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0054", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0054", + "lookPath": "", + "observedAt": "2026-11-28T02:36:51.255025+00:00" + } + }, + { + "name": "setObjectVisibility: 4 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectVisibility: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectVisibility: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectVisibility: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectVisibility: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0059", + "action": "setObjectVisibility", + "status": "accepted", + "message": "Blender object visibility updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectVisibility ive-0059", + "lookPath": "", + "observedAt": "2026-11-28T02:36:55.787695+00:00" + } + }, + { + "name": "setObjectVisibility: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectVisibility ive-0059" + }, + { + "name": "setObjectVisibility: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectVisibility: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0060", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0060", + "lookPath": "", + "observedAt": "2026-11-28T02:36:57.891977+00:00" + } + }, + { + "name": "setObjectParent: 4 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectParent: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectParent: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectParent: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0065", + "action": "setObjectParent", + "status": "accepted", + "message": "Blender object parent updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectParent ive-0065", + "lookPath": "", + "observedAt": "2026-11-28T02:37:02.443984+00:00" + } + }, + { + "name": "setObjectParent: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectParent ive-0065" + }, + { + "name": "setObjectParent: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectParent: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setObjectCustomProperty: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0066", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0066", + "lookPath": "", + "observedAt": "2026-11-28T02:37:04.556676+00:00" + } + }, + { + "name": "setObjectCustomProperty: 5 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setObjectCustomProperty: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setObjectCustomProperty: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setObjectCustomProperty: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "setObjectCustomProperty: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0072", + "action": "setObjectCustomProperty", + "status": "accepted", + "message": "Blender custom property updated.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setObjectCustomProperty ive-0072", + "lookPath": "", + "observedAt": "2026-11-28T02:37:09.259197+00:00" + } + }, + { + "name": "setObjectCustomProperty: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setObjectCustomProperty ive-0072" + }, + { + "name": "setObjectCustomProperty: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setObjectCustomProperty: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "selectObject: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0073", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0073", + "lookPath": "", + "observedAt": "2026-11-28T02:37:11.382979+00:00" + } + }, + { + "name": "selectObject: 4 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "selectObject: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "selectObject: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "selectObject: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "selectObject: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0078", + "action": "selectObject", + "status": "accepted", + "message": "Blender object selected.", + "objectName": "Camera", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: selectObject ive-0078", + "lookPath": "", + "observedAt": "2026-11-28T02:37:16.017922+00:00" + } + }, + { + "name": "selectObject: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: selectObject ive-0078" + }, + { + "name": "selectObject: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "selectObject: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "assignMaterial: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0079", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0079", + "lookPath": "", + "observedAt": "2026-11-28T02:37:18.151455+00:00" + } + }, + { + "name": "assignMaterial: 10 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "assignMaterial: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "assignMaterial: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "assignMaterial: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "assignMaterial: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0090", + "action": "assignMaterial", + "status": "accepted", + "message": "Blender material assigned.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: assignMaterial ive-0090", + "lookPath": "", + "observedAt": "2026-11-28T02:37:23.926592+00:00" + } + }, + { + "name": "assignMaterial: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: assignMaterial ive-0090" + }, + { + "name": "assignMaterial: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "assignMaterial: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "exportGltf: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0091", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0091", + "lookPath": "", + "observedAt": "2026-11-28T02:37:26.063118+00:00" + } + }, + { + "name": "exportGltf: 9 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "exportGltf: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "exportGltf: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "exportGltf: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "exportGltf: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0102", + "action": "exportGltf", + "status": "accepted", + "message": "Exported glTF to F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\live.glb (5028 bytes).", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:37:33.358972+00:00" + } + }, + { + "name": "exportGltf: changesScene is false, so no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "exportGltf: it pushed no undo step (one undo reverts the canary before it)", + "ok": true, + "detail": null + }, + { + "name": "importGltf: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0103", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0103", + "lookPath": "", + "observedAt": "2026-11-28T02:37:35.528127+00:00" + } + }, + { + "name": "importGltf: 3 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "importGltf: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "importGltf: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "importGltf: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ], + "was": [ + "Camera", + "Cube", + "Light", + "LiveCube" + ] + } + }, + { + "name": "importGltf: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0107", + "action": "importGltf", + "status": "accepted", + "message": "Imported 3 object(s) from live.glb.", + "objectName": "Canary2", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: importGltf ive-0107", + "lookPath": "", + "observedAt": "2026-11-28T02:37:40.218377+00:00" + } + }, + { + "name": "importGltf: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: importGltf ive-0107" + }, + { + "name": "importGltf: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "importGltf: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setCamera: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0108", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0108", + "lookPath": "", + "observedAt": "2026-11-28T02:37:42.369543+00:00" + } + }, + { + "name": "setCamera: 20 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setCamera: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setCamera: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setCamera: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setCamera: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0129", + "action": "setCamera", + "status": "accepted", + "message": "Blender camera updated.", + "objectName": "Camera", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setCamera ive-0129", + "lookPath": "", + "observedAt": "2026-11-28T02:37:54.650323+00:00" + } + }, + { + "name": "setCamera: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setCamera ive-0129" + }, + { + "name": "setCamera: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setCamera: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setLight: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0130", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0130", + "lookPath": "", + "observedAt": "2026-11-28T02:37:56.820173+00:00" + } + }, + { + "name": "setLight: 14 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setLight: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setLight: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setLight: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setLight: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0145", + "action": "setLight", + "status": "accepted", + "message": "Blender light updated.", + "objectName": "Light", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setLight ive-0145", + "lookPath": "", + "observedAt": "2026-11-28T02:38:05.386213+00:00" + } + }, + { + "name": "setLight: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setLight ive-0145" + }, + { + "name": "setLight: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setLight: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setWorld: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0146", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0146", + "lookPath": "", + "observedAt": "2026-11-28T02:38:07.578985+00:00" + } + }, + { + "name": "setWorld: 11 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setWorld: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setWorld: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setWorld: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setWorld: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0158", + "action": "setWorld", + "status": "accepted", + "message": "Blender world updated.", + "objectName": "World", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setWorld ive-0158", + "lookPath": "", + "observedAt": "2026-11-28T02:38:14.740238+00:00" + } + }, + { + "name": "setWorld: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setWorld ive-0158" + }, + { + "name": "setWorld: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "setWorld: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "renderStill: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0159", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0159", + "lookPath": "", + "observedAt": "2026-11-28T02:38:16.953350+00:00" + } + }, + { + "name": "renderStill: 12 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "renderStill: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "renderStill: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "renderStill: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "renderStill: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0173", + "action": "renderStill", + "status": "accepted", + "message": "Rendered still to live.png.", + "objectName": "Scene", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:38:28.064380+00:00" + } + }, + { + "name": "renderStill: changesScene is false, so no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "renderStill: it pushed no undo step (one undo reverts the canary before it)", + "ok": true, + "detail": null + }, + { + "name": "look: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0174", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0174", + "lookPath": "", + "observedAt": "2026-11-28T02:38:31.281935+00:00" + } + }, + { + "name": "look: 1 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "look: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "look: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "look: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "look: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0177", + "action": "look", + "status": "accepted", + "message": "Captured the 3D view to look/live-0177.png.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\look\\live-0177.png", + "observedAt": "2026-11-28T02:38:37.045877+00:00", + "captureSource": "region", + "sceneUpdateSeq": 95, + "sessionId": "0cc3e9cdaf454a249a30cc24e617581c", + "humanEditSeq": 83, + "humanEditsSinceLook": 83, + "editedSinceLook": [ + "Camera", + "Canary2", + "Canary2.001", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001", + "LiveDoomed" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: undo or redo flags all objects; editedSinceLook may name objects she did not touch.", + "editSelection": [] + } + }, + { + "name": "look: changesScene is false, so no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "look: it pushed no undo step (one undo reverts the canary before it)", + "ok": true, + "detail": null + }, + { + "name": "createNodeGroup: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0178", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0178", + "lookPath": "", + "observedAt": "2026-11-28T02:38:39.309535+00:00" + } + }, + { + "name": "createNodeGroup: 14 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "createNodeGroup: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "createNodeGroup: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "createNodeGroup: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "createNodeGroup: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0193", + "action": "createNodeGroup", + "status": "accepted", + "message": "Created node group; interface identifiers: input Geometry=Socket_0, output Geometry=Socket_1, input Count=Socket_2", + "objectName": "LiveG", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createNodeGroup ive-0193", + "lookPath": "", + "observedAt": "2026-11-28T02:38:51.073058+00:00" + } + }, + { + "name": "createNodeGroup: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createNodeGroup ive-0193" + }, + { + "name": "createNodeGroup: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "createNodeGroup: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "addNode: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0194", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0194", + "lookPath": "", + "observedAt": "2026-11-28T02:38:53.324909+00:00" + } + }, + { + "name": "addNode: 28 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "addNode: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "addNode: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "addNode: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "addNode: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0223", + "action": "addNode", + "status": "accepted", + "message": "Node added.", + "objectName": "m1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: addNode ive-0223", + "lookPath": "", + "observedAt": "2026-11-28T02:39:29.096510+00:00" + } + }, + { + "name": "addNode: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: addNode ive-0223" + }, + { + "name": "addNode: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "addNode: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "linkSockets: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0224", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0224", + "lookPath": "", + "observedAt": "2026-11-28T02:39:31.428197+00:00" + } + }, + { + "name": "linkSockets: 22 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "linkSockets: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "linkSockets: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "linkSockets: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "linkSockets: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0247", + "action": "linkSockets", + "status": "accepted", + "message": "Linked gin.Socket_0 -> gout.Socket_1.", + "objectName": "LiveG", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: linkSockets ive-0247", + "lookPath": "", + "observedAt": "2026-11-28T02:39:59.079008+00:00" + } + }, + { + "name": "linkSockets: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: linkSockets ive-0247" + }, + { + "name": "linkSockets: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "linkSockets: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0248", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0248", + "lookPath": "", + "observedAt": "2026-11-28T02:40:01.374248+00:00" + } + }, + { + "name": "unlinkSockets: 20 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "unlinkSockets: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "unlinkSockets: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "unlinkSockets: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0269", + "action": "unlinkSockets", + "status": "accepted", + "message": "Removed 1 link(s).", + "objectName": "LiveG", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: unlinkSockets ive-0269", + "lookPath": "", + "observedAt": "2026-11-28T02:40:29.839429+00:00" + } + }, + { + "name": "unlinkSockets: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: unlinkSockets ive-0269" + }, + { + "name": "unlinkSockets: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "unlinkSockets: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "removeNode: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0270", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0270", + "lookPath": "", + "observedAt": "2026-11-28T02:40:32.156639+00:00" + } + }, + { + "name": "removeNode: 13 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "removeNode: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "removeNode: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "removeNode: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "removeNode: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0284", + "action": "removeNode", + "status": "accepted", + "message": "Node removed.", + "objectName": "m1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: removeNode ive-0284", + "lookPath": "", + "observedAt": "2026-11-28T02:40:48.986174+00:00" + } + }, + { + "name": "removeNode: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: removeNode ive-0284" + }, + { + "name": "removeNode: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "removeNode: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "addModifier: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0285", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0285", + "lookPath": "", + "observedAt": "2026-11-28T02:40:51.316429+00:00" + } + }, + { + "name": "addModifier: 16 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "addModifier: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "addModifier: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "addModifier: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "addModifier: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0302", + "action": "addModifier", + "status": "accepted", + "message": "Geometry Nodes modifier set.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: addModifier ive-0302", + "lookPath": "", + "observedAt": "2026-11-28T02:41:12.934572+00:00" + } + }, + { + "name": "addModifier: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: addModifier ive-0302" + }, + { + "name": "addModifier: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "addModifier: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "setModifierInput: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0303", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0303", + "lookPath": "", + "observedAt": "2026-11-28T02:41:15.376364+00:00" + } + }, + { + "name": "setModifierInput: 7 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "setModifierInput: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "setModifierInput: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "setModifierInput: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "setModifierInput: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0311", + "action": "setModifierInput", + "status": "accepted", + "message": "Modifier input Count set.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: setModifierInput ive-0311", + "lookPath": "", + "observedAt": "2026-11-28T02:41:23.279634+00:00" + } + }, + { + "name": "setModifierInput: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: setModifierInput ive-0311" + }, + { + "name": "removeModifier: the canary is accepted with one undoLabel", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0312", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "Canary1", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: createObject ive-0312", + "lookPath": "", + "observedAt": "2026-11-28T02:41:25.653006+00:00" + } + }, + { + "name": "removeModifier: 7 table-generated malformed intents are each denied", + "ok": true, + "detail": [] + }, + { + "name": "removeModifier: a denied intent carries no undoLabel", + "ok": true, + "detail": [] + }, + { + "name": "removeModifier: the scene is unchanged by the malformed intents", + "ok": true, + "detail": null + }, + { + "name": "removeModifier: no malformed intent added an undo step (one undo reverts the canary before them)", + "ok": true, + "detail": { + "names": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ], + "was": [ + "Camera", + "Canary2", + "Cube", + "Cube.001", + "Light", + "LiveCube", + "LiveCube.001" + ] + } + }, + { + "name": "removeModifier: the valid intent is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "live-0320", + "action": "removeModifier", + "status": "accepted", + "message": "Modifier removed.", + "objectName": "LiveCube", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: removeModifier ive-0320", + "lookPath": "", + "observedAt": "2026-11-28T02:41:34.791771+00:00" + } + }, + { + "name": "removeModifier: changesScene is true, so the receipt carries an undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: removeModifier ive-0320" + }, + { + "name": "removeModifier: one undo restores the scene to before the intent", + "ok": true, + "detail": null + }, + { + "name": "removeModifier: redo brings the intent's result back", + "ok": true, + "detail": null + }, + { + "name": "claim-first: with one receipt write failing, the intent ran exactly once and its receipt was written by the next drain", + "ok": true, + "detail": { + "raised": 1, + "objects": [ + "FlakyCube" + ], + "receipt": "accepted" + } + }, + { + "name": "the queue is empty and the add-on's drain reports no error", + "ok": true, + "detail": [ + [], + "" + ] + } + ], + "actions": { + "createObject": { + "changesScene": true, + "malformed": 22, + "messages": { + "unknown field": "createObject has no field 'zzUnknown'; its fields: objectType, name, location, size, meshType, lightType, emptyDisplayType.", + "objectType: wrong type": "objectType must be a string.", + "objectType: enum miss": "objectType must be one of MESH, LIGHT, CAMERA, EMPTY.", + "name: wrong type": "name must be a string.", + "location: wrong type": "location must be an array.", + "location: below minItems": "location must have at least 3 items.", + "location: above maxItems": "location must have at most 3 items.", + "location: item above maximum": "location[0] must be between -1000000000 and 1000000000.", + "location: item below minimum": "location[0] must be between -1000000000 and 1000000000.", + "location: item wrong type": "location[0] must be a finite number.", + "size: wrong type": "size must be a finite number.", + "size: above maximum": "size must be between 0.001 and 1000000.", + "size: below minimum": "size must be between 0.001 and 1000000.", + "meshType: wrong type": "meshType must be a string.", + "meshType: enum miss": "meshType must be one of CUBE.", + "meshType: only applies to objectType in ['MESH']": "meshType applies only when objectType is one of MESH.", + "lightType: wrong type": "lightType applies only when objectType is one of LIGHT.", + "lightType: enum miss": "lightType applies only when objectType is one of LIGHT.", + "lightType: only applies to objectType in ['LIGHT']": "lightType applies only when objectType is one of LIGHT.", + "emptyDisplayType: wrong type": "emptyDisplayType applies only when objectType is one of EMPTY.", + "emptyDisplayType: enum miss": "emptyDisplayType applies only when objectType is one of EMPTY.", + "emptyDisplayType: only applies to objectType in ['EMPTY']": "emptyDisplayType applies only when objectType is one of EMPTY." + }, + "valid": { + "status": "accepted", + "message": "Blender object created.", + "undoLabel": "Brokkr nibu/hands: createObject ive-0024" + } + }, + "deleteObject": { + "changesScene": true, + "malformed": 3, + "messages": { + "unknown field": "deleteObject has no field 'zzUnknown'; its fields: targetObjectName.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required." + }, + "valid": { + "status": "accepted", + "message": "Blender object deleted.", + "undoLabel": "Brokkr nibu/hands: deleteObject ive-0030" + } + }, + "setObjectTransform": { + "changesScene": true, + "malformed": 21, + "messages": { + "unknown field": "setObjectTransform has no field 'zzUnknown'; its fields: targetObjectName, location, rotationEuler, scale.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "location: wrong type": "location must be an array.", + "location: below minItems": "location must have at least 3 items.", + "location: above maxItems": "location must have at most 3 items.", + "location: item above maximum": "location[0] must be between -1000000000 and 1000000000.", + "location: item below minimum": "location[0] must be between -1000000000 and 1000000000.", + "location: item wrong type": "location[0] must be a finite number.", + "rotationEuler: wrong type": "rotationEuler must be an array.", + "rotationEuler: below minItems": "rotationEuler must have at least 3 items.", + "rotationEuler: above maxItems": "rotationEuler must have at most 3 items.", + "rotationEuler: item above maximum": "rotationEuler[0] must be between -1000000000 and 1000000000.", + "rotationEuler: item below minimum": "rotationEuler[0] must be between -1000000000 and 1000000000.", + "rotationEuler: item wrong type": "rotationEuler[0] must be a finite number.", + "scale: wrong type": "scale must be an array.", + "scale: below minItems": "scale must have at least 3 items.", + "scale: above maxItems": "scale must have at most 3 items.", + "scale: item above maximum": "scale[0] must be between -1000000000 and 1000000000.", + "scale: item below minimum": "scale[0] must be between -1000000000 and 1000000000.", + "scale: item wrong type": "scale[0] must be a finite number." + }, + "valid": { + "status": "accepted", + "message": "Blender object transform updated.", + "undoLabel": "Brokkr nibu/hands: setObjectTransform ive-0053" + } + }, + "setObjectVisibility": { + "changesScene": true, + "malformed": 4, + "messages": { + "unknown field": "setObjectVisibility has no field 'zzUnknown'; its fields: targetObjectName, visible.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "visible: wrong type": "visible must be true or false." + }, + "valid": { + "status": "accepted", + "message": "Blender object visibility updated.", + "undoLabel": "Brokkr nibu/hands: setObjectVisibility ive-0059" + } + }, + "setObjectParent": { + "changesScene": true, + "malformed": 4, + "messages": { + "unknown field": "setObjectParent has no field 'zzUnknown'; its fields: targetObjectName, parentObjectName.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "parentObjectName: wrong type": "parentObjectName must be a string." + }, + "valid": { + "status": "accepted", + "message": "Blender object parent updated.", + "undoLabel": "Brokkr nibu/hands: setObjectParent ive-0065" + } + }, + "setObjectCustomProperty": { + "changesScene": true, + "malformed": 5, + "messages": { + "unknown field": "setObjectCustomProperty has no field 'zzUnknown'; its fields: targetObjectName, propertyName, value.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "propertyName: wrong type": "propertyName must be a string.", + "value: required missing": "value is required." + }, + "valid": { + "status": "accepted", + "message": "Blender custom property updated.", + "undoLabel": "Brokkr nibu/hands: setObjectCustomProperty ive-0072" + } + }, + "selectObject": { + "changesScene": true, + "malformed": 4, + "messages": { + "unknown field": "selectObject has no field 'zzUnknown'; its fields: targetObjectName, clearSelection.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "clearSelection: wrong type": "clearSelection must be true or false." + }, + "valid": { + "status": "accepted", + "message": "Blender object selected.", + "undoLabel": "Brokkr nibu/hands: selectObject ive-0078" + } + }, + "assignMaterial": { + "changesScene": true, + "malformed": 10, + "messages": { + "unknown field": "assignMaterial has no field 'zzUnknown'; its fields: targetObjectName, materialName, color.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "materialName: wrong type": "materialName must be a string.", + "color: wrong type": "color must be an array.", + "color: below minItems": "color must have at least 3 items.", + "color: above maxItems": "color must have at most 4 items.", + "color: item above maximum": "color[0] must be between 0 and 1.", + "color: item below minimum": "color[0] must be between 0 and 1.", + "color: item wrong type": "color[0] must be a finite number." + }, + "valid": { + "status": "accepted", + "message": "Blender material assigned.", + "undoLabel": "Brokkr nibu/hands: assignMaterial ive-0090" + } + }, + "exportGltf": { + "changesScene": false, + "malformed": 9, + "messages": { + "unknown field": "exportGltf has no field 'zzUnknown'; its fields: filepath, extras, yUp, applyModifiers, selection.", + "filepath: wrong type": "filepath must be a string.", + "filepath: required missing": "filepath is required.", + "extras: wrong type": "extras must be true or false.", + "yUp: wrong type": "yUp must be true or false.", + "applyModifiers: wrong type": "applyModifiers must be true or false.", + "selection: wrong type": "selection must be an array.", + "selection: below minItems": "selection must have at least 1 items.", + "selection: item wrong type": "selection[0] must be a string." + }, + "valid": { + "status": "accepted", + "message": "Exported glTF to F:\\aeth-wt\\brokkr-action-table-live\\scratch\\out\\live.glb (5028 bytes).", + "undoLabel": "" + } + }, + "importGltf": { + "changesScene": true, + "malformed": 3, + "messages": { + "unknown field": "importGltf has no field 'zzUnknown'; its fields: filepath.", + "filepath: wrong type": "filepath must be a string.", + "filepath: required missing": "filepath is required." + }, + "valid": { + "status": "accepted", + "message": "Imported 3 object(s) from live.glb.", + "undoLabel": "Brokkr nibu/hands: importGltf ive-0107" + } + }, + "setCamera": { + "changesScene": true, + "malformed": 20, + "messages": { + "unknown field": "setCamera has no field 'zzUnknown'; its fields: targetObjectName, lens, cameraType, orthoScale, clipStart, clipEnd, panoramaType, active.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "lens: wrong type": "lens must be a finite number.", + "lens: above maximum": "lens must be between 1 and 5000.", + "lens: below minimum": "lens must be between 1 and 5000.", + "cameraType: wrong type": "cameraType must be a string.", + "cameraType: enum miss": "cameraType must be one of PERSP, ORTHO, PANO.", + "orthoScale: wrong type": "orthoScale must be a finite number.", + "orthoScale: above maximum": "orthoScale must be between 0.001 and 100000.", + "orthoScale: below minimum": "orthoScale must be between 0.001 and 100000.", + "clipStart: wrong type": "clipStart must be a finite number.", + "clipStart: above maximum": "clipStart must be between 0.0001 and 1000000.", + "clipStart: below minimum": "clipStart must be between 0.0001 and 1000000.", + "clipEnd: wrong type": "clipEnd must be a finite number.", + "clipEnd: above maximum": "clipEnd must be between 0.001 and 10000000.", + "clipEnd: below minimum": "clipEnd must be between 0.001 and 10000000.", + "panoramaType: wrong type": "panoramaType must be a string.", + "panoramaType: enum miss": "panoramaType must be one of EQUIRECTANGULAR, EQUIANGULAR_CUBEMAP_FACE, MIRRORBALL, FISHEYE_EQUIDISTANT, FISHEYE_EQUISOLID, FISHEYE_LENS_POLYNOMIAL, CENTRAL_CYLINDRICAL.", + "active: wrong type": "active must be true or false." + }, + "valid": { + "status": "accepted", + "message": "Blender camera updated.", + "undoLabel": "Brokkr nibu/hands: setCamera ive-0129" + } + }, + "setLight": { + "changesScene": true, + "malformed": 14, + "messages": { + "unknown field": "setLight has no field 'zzUnknown'; its fields: targetObjectName, energy, color, lightType.", + "targetObjectName: wrong type": "targetObjectName must be a string.", + "targetObjectName: required missing": "targetObjectName is required.", + "energy: wrong type": "energy must be a finite number.", + "energy: above maximum": "energy must be between 0 and 10000000.", + "energy: below minimum": "energy must be between 0 and 10000000.", + "color: wrong type": "color must be an array.", + "color: below minItems": "color must have at least 3 items.", + "color: above maxItems": "color must have at most 3 items.", + "color: item above maximum": "color[0] must be between 0 and 1.", + "color: item below minimum": "color[0] must be between 0 and 1.", + "color: item wrong type": "color[0] must be a finite number.", + "lightType: wrong type": "lightType must be a string.", + "lightType: enum miss": "lightType must be one of POINT, SUN, SPOT, AREA." + }, + "valid": { + "status": "accepted", + "message": "Blender light updated.", + "undoLabel": "Brokkr nibu/hands: setLight ive-0145" + } + }, + "setWorld": { + "changesScene": true, + "malformed": 11, + "messages": { + "unknown field": "setWorld has no field 'zzUnknown'; its fields: worldName, color, strength.", + "worldName: wrong type": "worldName must be a string.", + "color: wrong type": "color must be an array.", + "color: below minItems": "color must have at least 3 items.", + "color: above maxItems": "color must have at most 3 items.", + "color: item above maximum": "color[0] must be between 0 and 1.", + "color: item below minimum": "color[0] must be between 0 and 1.", + "color: item wrong type": "color[0] must be a finite number.", + "strength: wrong type": "strength must be a finite number.", + "strength: above maximum": "strength must be between 0 and 1000000.", + "strength: below minimum": "strength must be between 0 and 1000000." + }, + "valid": { + "status": "accepted", + "message": "Blender world updated.", + "undoLabel": "Brokkr nibu/hands: setWorld ive-0158" + } + }, + "renderStill": { + "changesScene": false, + "malformed": 12, + "messages": { + "unknown field": "renderStill has no field 'zzUnknown'; its fields: outputPath, engine, resolutionX, resolutionY, cameraName.", + "outputPath: wrong type": "outputPath must be a string.", + "outputPath: required missing": "outputPath is required.", + "engine: wrong type": "engine must be a string.", + "engine: below minLength": "engine must have at least 1 characters.", + "resolutionX: wrong type": "resolutionX must be a whole number.", + "resolutionX: above maximum": "resolutionX must be between 4 and 16384.", + "resolutionX: below minimum": "resolutionX must be between 4 and 16384.", + "resolutionY: wrong type": "resolutionY must be a whole number.", + "resolutionY: above maximum": "resolutionY must be between 4 and 16384.", + "resolutionY: below minimum": "resolutionY must be between 4 and 16384.", + "cameraName: wrong type": "cameraName must be a string." + }, + "valid": { + "status": "accepted", + "message": "Rendered still to live.png.", + "undoLabel": "" + } + }, + "look": { + "changesScene": false, + "malformed": 1, + "messages": { + "unknown field": "look has no field 'zzUnknown'; its fields: none." + }, + "valid": { + "status": "accepted", + "message": "Captured the 3D view to look/live-0177.png.", + "undoLabel": "" + } + }, + "createNodeGroup": { + "changesScene": true, + "malformed": 14, + "messages": { + "unknown field": "createNodeGroup has no field 'zzUnknown'; its fields: treeKind, treeKey, interface.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "interface: wrong type": "interface must be an array.", + "interface: required missing": "interface is required.", + "interface: below minItems": "interface must have at least 1 items.", + "interface: item wrong type": "interface[0] must be an object.", + "interface: item missing a property": "interface[0].name is required.", + "interface: item unknown property": "interface[0] has no field 'zzUnknown'; its fields: inOut, name, type, default." + }, + "valid": { + "status": "accepted", + "message": "Created node group; interface identifiers: input Geometry=Socket_0, output Geometry=Socket_1, input Count=Socket_2", + "undoLabel": "Brokkr nibu/hands: createNodeGroup ive-0193" + } + }, + "addNode": { + "changesScene": true, + "malformed": 28, + "messages": { + "unknown field": "addNode has no field 'zzUnknown'; its fields: treeKind, treeKey, id, blIdname, location, label, properties, inputs.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "id: wrong type": "id must be a string.", + "id: required missing": "id is required.", + "id: below minLength": "id must have at least 1 characters.", + "id: above maxLength": "id must have at most 63 characters.", + "id: outside charset": "id may contain only letters, digits, '.', '_' or '-'.", + "blIdname: wrong type": "blIdname must be a string.", + "blIdname: required missing": "blIdname is required.", + "blIdname: outside charset": "blIdname may contain only letters and digits.", + "blIdname: no prefix": "blIdname must start with one of GeometryNode, FunctionNode, ShaderNode and have at least one more character.", + "blIdname: forbidden part": "blIdname may not contain 'Import'.", + "location: wrong type": "location must be an array.", + "location: below minItems": "location must have at least 2 items.", + "location: above maxItems": "location must have at most 2 items.", + "location: item above maximum": "location[0] must be between -1000000000 and 1000000000.", + "location: item below minimum": "location[0] must be between -1000000000 and 1000000000.", + "location: item wrong type": "location[0] must be a finite number.", + "label: wrong type": "label must be a string.", + "label: above maxLength": "label must have at most 63 characters.", + "properties: wrong type": "properties must be an object.", + "inputs: wrong type": "inputs must be an object." + }, + "valid": { + "status": "accepted", + "message": "Node added.", + "undoLabel": "Brokkr nibu/hands: addNode ive-0223" + } + }, + "linkSockets": { + "changesScene": true, + "malformed": 22, + "messages": { + "unknown field": "linkSockets has no field 'zzUnknown'; its fields: treeKind, treeKey, fromNode, fromSocket, toNode, toSocket.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "fromNode: wrong type": "fromNode must be a string.", + "fromNode: required missing": "fromNode is required.", + "fromNode: below minLength": "fromNode must have at least 1 characters.", + "fromNode: above maxLength": "fromNode must have at most 63 characters.", + "fromNode: outside charset": "fromNode may contain only letters, digits, '.', '_' or '-'.", + "fromSocket: wrong type": "fromSocket must be a string.", + "fromSocket: required missing": "fromSocket is required.", + "toNode: wrong type": "toNode must be a string.", + "toNode: required missing": "toNode is required.", + "toNode: below minLength": "toNode must have at least 1 characters.", + "toNode: above maxLength": "toNode must have at most 63 characters.", + "toNode: outside charset": "toNode may contain only letters, digits, '.', '_' or '-'.", + "toSocket: wrong type": "toSocket must be a string.", + "toSocket: required missing": "toSocket is required." + }, + "valid": { + "status": "accepted", + "message": "Linked gin.Socket_0 -> gout.Socket_1.", + "undoLabel": "Brokkr nibu/hands: linkSockets ive-0247" + } + }, + "unlinkSockets": { + "changesScene": true, + "malformed": 20, + "messages": { + "unknown field": "unlinkSockets has no field 'zzUnknown'; its fields: treeKind, treeKey, toNode, toSocket, fromNode, fromSocket.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "toNode: wrong type": "toNode must be a string.", + "toNode: required missing": "toNode is required.", + "toNode: below minLength": "toNode must have at least 1 characters.", + "toNode: above maxLength": "toNode must have at most 63 characters.", + "toNode: outside charset": "toNode may contain only letters, digits, '.', '_' or '-'.", + "toSocket: wrong type": "toSocket must be a string.", + "toSocket: required missing": "toSocket is required.", + "fromNode: wrong type": "fromNode must be a string.", + "fromNode: below minLength": "fromNode must have at least 1 characters.", + "fromNode: above maxLength": "fromNode must have at most 63 characters.", + "fromNode: outside charset": "fromNode may contain only letters, digits, '.', '_' or '-'.", + "fromSocket: wrong type": "fromSocket must be a string." + }, + "valid": { + "status": "accepted", + "message": "Removed 1 link(s).", + "undoLabel": "Brokkr nibu/hands: unlinkSockets ive-0269" + } + }, + "removeNode": { + "changesScene": true, + "malformed": 13, + "messages": { + "unknown field": "removeNode has no field 'zzUnknown'; its fields: treeKind, treeKey, id.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "id: wrong type": "id must be a string.", + "id: required missing": "id is required.", + "id: below minLength": "id must have at least 1 characters.", + "id: above maxLength": "id must have at most 63 characters.", + "id: outside charset": "id may contain only letters, digits, '.', '_' or '-'." + }, + "valid": { + "status": "accepted", + "message": "Node removed.", + "undoLabel": "Brokkr nibu/hands: removeNode ive-0284" + } + }, + "addModifier": { + "changesScene": true, + "malformed": 16, + "messages": { + "unknown field": "addModifier has no field 'zzUnknown'; its fields: objectName, modifierType, treeKind, treeKey, modifierName.", + "objectName: wrong type": "objectName must be a string.", + "objectName: required missing": "objectName is required.", + "modifierType: wrong type": "modifierType must be a string.", + "modifierType: enum miss": "modifierType must be one of NODES.", + "treeKind: wrong type": "treeKind must be a string.", + "treeKind: enum miss": "treeKind must be one of geometry.", + "treeKey: wrong type": "treeKey must be a string.", + "treeKey: required missing": "treeKey is required.", + "treeKey: below minLength": "treeKey must have at least 1 characters.", + "treeKey: above maxLength": "treeKey must have at most 63 characters.", + "treeKey: outside charset": "treeKey may contain only letters, digits, space, '.', '_' or '-'.", + "modifierName: wrong type": "modifierName must be a string.", + "modifierName: below minLength": "modifierName must have at least 1 characters.", + "modifierName: above maxLength": "modifierName must have at most 63 characters.", + "modifierName: outside charset": "modifierName may contain only letters, digits, space, '.', '_' or '-'." + }, + "valid": { + "status": "accepted", + "message": "Geometry Nodes modifier set.", + "undoLabel": "Brokkr nibu/hands: addModifier ive-0302" + } + }, + "setModifierInput": { + "changesScene": true, + "malformed": 7, + "messages": { + "unknown field": "setModifierInput has no field 'zzUnknown'; its fields: objectName, modifierName, socket, value.", + "objectName: wrong type": "objectName must be a string.", + "objectName: required missing": "objectName is required.", + "modifierName: wrong type": "modifierName must be a string.", + "socket: wrong type": "socket must be a string.", + "socket: required missing": "socket is required.", + "value: required missing": "value is required." + }, + "valid": { + "status": "accepted", + "message": "Modifier input Count set.", + "undoLabel": "Brokkr nibu/hands: setModifierInput ive-0311" + }, + "note": "the intent changed nothing the signature reads (checked by label only)" + }, + "removeModifier": { + "changesScene": true, + "malformed": 7, + "messages": { + "unknown field": "removeModifier has no field 'zzUnknown'; its fields: objectName, modifierName.", + "objectName: wrong type": "objectName must be a string.", + "objectName: required missing": "objectName is required.", + "modifierName: wrong type": "modifierName must be a string.", + "modifierName: below minLength": "modifierName must have at least 1 characters.", + "modifierName: above maxLength": "modifierName must have at most 255 characters.", + "modifierName: forbidden part": "modifierName may not contain '\u0000'." + }, + "valid": { + "status": "accepted", + "message": "Modifier removed.", + "undoLabel": "Brokkr nibu/hands: removeModifier ive-0320" + } + } + }, + "table_actions": [ + "createObject", + "deleteObject", + "setObjectTransform", + "setObjectVisibility", + "setObjectParent", + "setObjectCustomProperty", + "selectObject", + "assignMaterial", + "importGltf", + "exportGltf", + "setCamera", + "setLight", + "setWorld", + "renderStill", + "look", + "createNodeGroup", + "addNode", + "removeNode", + "linkSockets", + "unlinkSockets", + "addModifier", + "removeModifier", + "setModifierInput" + ], + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/agent_turn_queue.py b/surfaces/blender/tests/live/agent_turn_queue.py new file mode 100644 index 0000000..aa0204b --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_queue.py @@ -0,0 +1,285 @@ +"""Live proof, in GUI Blender with the add-on enabled, that intents arriving through the node queue +are drained by the add-on's own 1 s timer as one undo step each, with write-once receipts. + + BROKKR_USER_SCRIPTS= (also BLENDER_USER_SCRIPTS) + BROKKR_SCRATCH= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + BROKKR_PYLIBS= + Private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are required (refused otherwise). + blender --factory-startup --python agent_turn_queue.py -- + +Intents are put into the node database as brokkr-ctl does; a command JSON dropped under the debug +root is never an intent. Writes +.result.json, then quits Blender. Undo is read only here, by this driver. +""" +import importlib +import json +import os +import sys +import traceback +from pathlib import Path + +import bpy + +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + +if os.environ.get("BROKKR_PYLIBS"): + sys.path.insert(0, os.environ["BROKKR_PYLIBS"]) +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +R = {"blender": bpy.app.version_string, "module": os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge"), + "pylibs": bool(os.environ.get("BROKKR_PYLIBS")), "checks": [], "receipts": {}} + +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "brokkr_bridge") +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") + +try: + import msgpack + R["msgpack"] = msgpack.__file__ + R["msgpack_packer"] = msgpack.Packer.__module__ # msgpack.fallback: the pure-Python codec, no C extension + R["msgpack_purepython_env"] = os.environ.get("MSGPACK_PUREPYTHON", "") +except ImportError: + R["msgpack"] = None +prefs = bpy.context.preferences.addons[MODULE].preferences +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = str(SCRATCH / "debug") # export only: q1 drops a command file there and it must stay inert +prefs.output_dir = str(SCRATCH / "out") +prefs.import_dir = "" +prefs.auto_drain_commands = True +if os.environ.get("BROKKR_CULTLIB"): + prefs.cultlib_py_src = os.environ["BROKKR_CULTLIB"] +(SCRATCH / "out").mkdir(exist_ok=True) +adapter = addon.target() + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def push(msg): + with win(): + bpy.ops.ed.undo_push(message=msg) + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +def queue(cid, **cmd): + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA) + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + + +def receipt(key): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{key}") + + +def all_receipts(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}) + + +def pending(): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {}) + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=24): + """A step that repeats each tick until pred() holds (the add-on's timer drains meanwhile).""" + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def drained(*ids): + return lambda: all(receipt(i) for i in ids) + + +def q1(): + push("driver baseline") + door = SCRATCH / "debug" / "blender" / "commands" + door.mkdir(parents=True, exist_ok=True) + (door / "door-0001.json").write_text(json.dumps( + {"commandId": "door-0001", "requestedBy": "nibu/hands", "action": "createObject", "objectType": "MESH", "name": "QDoor"})) + queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QCube", location=[4, 0, 0], + requestedBy="nibu/hands", note="queue test") + + +def q1_check(): + r = receipt("aaaaaaaa-0001") + R["receipts"]["q1"] = r + S["q1_label"] = r and r.get("undoLabel") + check("queue: createObject drained by the add-on timer, accepted, labelled, attributed", + r and r["status"] == "accepted" and r["undoLabel"] == "Brokkr nibu/hands: createObject aaa-0001" # the id's last 8 characters + and r["requestedBy"] == "nibu/hands" and r["note"] == "queue test" and "QCube" in names(), r) + check("queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", + (SCRATCH / "debug" / "blender" / "commands" / "door-0001.json").exists() and "QDoor" not in names() + and receipt("door-0001") is None and (SCRATCH / "debug" / "blender" / "receipts" / "aaaaaaaa-0001.json").exists(), + names()) + check("queue: intent removed from the queue after the drain", "blender/commands/aaaaaaaa-0001" not in pending(), list(pending())) + + +def q2(): + queue("aaaaaaaa-0001", action="createObject", objectType="MESH", name="QReuse", requestedBy="nibu/hands") + + +def q2_check(): + orig = receipt("aaaaaaaa-0001") + denial = receipt("aaaaaaaa-0001.denied") + R["receipts"]["q2_original"], R["receipts"]["q2_denial"] = orig, denial + check("queue: reused id leaves the original receipt untouched (write-once)", + orig["status"] == "accepted" and orig["undoLabel"] == S["q1_label"], orig) + check("queue: reused id reported under .denied, nothing created", + denial and denial["status"] == "denied" and "QReuse" not in names(), denial) + + +def q3(): + queue("aaaaaaaa-0003", action="createObject", objectType="MESH", name="QNoOwner") + + +def q3_check(): + r = receipt("aaaaaaaa-0003") + R["receipts"]["q3"] = r + check("queue: intent without requestedBy denied, scene unchanged", r["status"] == "denied" and "QNoOwner" not in names(), r) + + +def q4(): + queue("aaaaaaaa-0004", action="createObject", objectType="MESH", name="QOne", location=[0, 6, 0], requestedBy="nibu/hands") + queue("aaaaaaaa-0005", action="createObject", objectType="MESH", name="QTwo", location=[0, 8, 0], requestedBy="nibu/imagination") + + +def q4_undo_two(): + undo() + after_one = names() + undo() + after_two = names() + check("queue: two intents drained together are two undo steps, last first", + "QTwo" not in after_one and "QOne" in after_one and "QOne" not in after_two, [after_one, after_two]) + + +def q5_edit(): + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube + cube.select_set(True) + with win(): + bpy.ops.object.mode_set(mode="EDIT") + push("driver edit baseline") + queue("aaaaaaaa-0006", action="setWorld", color=[1, 0, 0], requestedBy="nibu/hands") + queue("aaaaaaaa-0007", action="exportGltf", filepath="edit.glb", requestedBy="nibu/hands") + queue("aaaaaaaa-0008", action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands") + + +def q5_check(): + rs = [receipt(k) for k in ("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")] + R["receipts"]["q5"] = rs + check("queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", + all(r["status"] == "denied" and r["undoLabel"] == "" for r in rs) and bpy.context.mode == "EDIT_MESH" + and not (SCRATCH / "out" / "edit.glb").exists(), [r["message"] for r in rs]) + + +def q5_exit(): + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + check("queue: add-on drain reports no error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +def q6(): + queue("bad-list", action="createObject", objectType="MESH", name="QBadList", requestedBy="nibu/hands") + queue("bad-int", action="createObject", objectType="MESH", name="QBadInt", requestedBy="nibu/hands") + n, docs = node() + for key in ("bad-list", "bad-int"): # overwrite the id with a non-string, as a hand-written put could + doc = dict(n.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{key}"]) + doc["commandId"] = ["x"] if key == "bad-list" else 7 + n.database.put(docs["command_intent"], f"blender/commands/{key}", doc) + queue("zzzzzzzz-good", action="createObject", objectType="MESH", name="QAfterBad", requestedBy="nibu/hands") + + +def q6_check(): + denials = [r for k, r in all_receipts().items() if "queue key blender/commands/bad-" in r.get("message", "")] + R["receipts"]["q6"] = denials + check("queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + len(denials) == 2 and all(r["status"] == "denied" and isinstance(r["commandId"], str) for r in denials) + and not pending() and "QBadList" not in names() and "QBadInt" not in names() + and receipt("zzzzzzzz-good")["status"] == "accepted" and "QAfterBad" in names() + and adapter.last_auto_drain_error == "", [adapter.last_auto_drain_error, list(pending())]) + + +steps = [ + once(q1), until(drained("aaaaaaaa-0001")), once(q1_check), + once(q2), until(lambda: receipt("aaaaaaaa-0001.denied")), once(q2_check), + once(q3), until(drained("aaaaaaaa-0003")), once(q3_check), + once(q4), until(drained("aaaaaaaa-0004", "aaaaaaaa-0005")), once(q4_undo_two), + once(q6), until(drained("zzzzzzzz-good")), once(q6_check), + once(q5_edit), until(drained("aaaaaaaa-0006", "aaaaaaaa-0007", "aaaaaaaa-0008")), once(q5_check), once(q5_exit), +] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/agent_turn_queue.result.json b/surfaces/blender/tests/live/agent_turn_queue.result.json new file mode 100644 index 0000000..ac8d776 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_queue.result.json @@ -0,0 +1,258 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "pylibs": false, + "checks": [ + { + "name": "queue: createObject drained by the add-on timer, accepted, labelled, attributed", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" + } + }, + { + "name": "queue: a command JSON under the debug root is inert (kept, never run, never receipted); the receipt export still lands", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "QCube" + ] + }, + { + "name": "queue: intent removed from the queue after the drain", + "ok": true, + "detail": [] + }, + { + "name": "queue: reused id leaves the original receipt untouched (write-once)", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" + } + }, + { + "name": "queue: reused id reported under .denied, nothing created", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "denied", + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:03:54.875032+00:00" + } + }, + { + "name": "queue: intent without requestedBy denied, scene unchanged", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0003", + "action": "createObject", + "status": "denied", + "message": "Intent has no requestedBy of the form '/'.", + "objectName": "", + "requestedBy": "", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:03:55.934781+00:00" + } + }, + { + "name": "queue: two intents drained together are two undo steps, last first", + "ok": true, + "detail": [ + [ + "Camera", + "Cube", + "Light", + "QCube", + "QOne" + ], + [ + "Camera", + "Cube", + "Light", + "QCube" + ] + ] + }, + { + "name": "queue: a list id and an int id are denied under fresh keys, removed from the queue, drain not wedged", + "ok": true, + "detail": [ + "", + [] + ] + }, + { + "name": "queue: in Edit Mode setWorld, exportGltf and an object write are all denied, her mode kept", + "ok": true, + "detail": [ + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + ] + }, + { + "name": "queue: add-on drain reports no error", + "ok": true, + "detail": "" + } + ], + "receipts": { + "q1": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" + }, + "q2_original": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "accepted", + "message": "Blender object created.", + "objectName": "QCube", + "requestedBy": "nibu/hands", + "note": "queue test", + "undoLabel": "Brokkr nibu/hands: createObject aaa-0001", + "lookPath": "", + "observedAt": "2026-11-28T02:03:52.780549+00:00" + }, + "q2_denial": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0001", + "action": "createObject", + "status": "denied", + "message": "commandId 'aaaaaaaa-0001' was already receipted; ids are single-use.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:03:54.875032+00:00" + }, + "q3": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0003", + "action": "createObject", + "status": "denied", + "message": "Intent has no requestedBy of the form '/'.", + "objectName": "", + "requestedBy": "", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:03:55.934781+00:00" + }, + "q6": [ + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "01683c810bbd449484c96d5984efccd7", + "action": "createObject", + "status": "denied", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:04:00.170853+00:00" + }, + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "bea34b7535da46188b741f55b3592707", + "action": "createObject", + "status": "denied", + "message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:04:00.225976+00:00" + } + ], + "q5": [ + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0006", + "action": "setWorld", + "status": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:04:02.331449+00:00" + }, + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0007", + "action": "exportGltf", + "status": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:04:02.387296+00:00" + }, + { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "aaaaaaaa-0008", + "action": "setObjectTransform", + "status": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "observedAt": "2026-11-28T02:04:02.439331+00:00" + } + ] + }, + "msgpack": "F:\\aeth-wt\\brokkr-action-table-live\\ext\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py", + "msgpack_packer": "msgpack.fallback", + "msgpack_purepython_env": "", + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/agent_turn_undo.py b/surfaces/blender/tests/live/agent_turn_undo.py new file mode 100644 index 0000000..8347907 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.py @@ -0,0 +1,213 @@ +"""Live proof, in GUI Blender, that every agent intent is one undo step. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. + + BROKKR_ADDON= \ + blender --factory-startup --python agent_turn_undo.py -- + +Writes .result.json beside , then quits Blender. Each step is its own timer tick so the +event loop runs between steps, as it does for Brokkr's 1 s drain (probe_timer_undo.py pattern). +Undo is read only here, by this driver; the add-on never calls ed.undo or ed.redo. +Exit status is not meaningful in a GUI session: read the "ok" fields of the result. +""" +import json +import os +import sys +import tempfile +import traceback +import types +from pathlib import Path + +import bmesh +import bpy + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +OUT = sys.argv[sys.argv.index("--") + 1] +R = {"blender": bpy.app.version_string, "background": bpy.app.background, "checks": [], "steps": []} +target = bt.BrokkrBlenderTarget(bpy) +N = [0] +OUTDIR = tempfile.mkdtemp(prefix="brokkr-live2-") +target.configure_action_dirs("", OUTDIR) + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + w = bpy.context.window_manager.windows[0] + return bpy.context.temp_override(window=w) + + +def intent(**cmd): + N[0] += 1 + cmd.setdefault("commandId", "%08d-live-agent-turn" % N[0]) + cmd.setdefault("requestedBy", "nibu/hands") + r = target.run_intent(bpy.context, cmd) + R["steps"].append({"intent": cmd["action"], "status": r["status"], "undoLabel": r["undoLabel"], "message": r["message"]}) + return r + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def push(msg): + with win(): + bpy.ops.ed.undo_push(message=msg) + + +def loc(name): + o = bpy.data.objects.get(name) + return None if o is None else [round(v, 3) for v in o.location] + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} + + +def vz(): + bm = bmesh.from_edit_mesh(bpy.data.objects["Cube"].data); bm.verts.ensure_lookup_table() + return round(bm.verts[0].co.z, 3) + + +def s_baseline(): + push("driver baseline") + S["objects0"] = names() + + +def s_create(): + r = intent(action="createObject", objectType="MESH", name="AgentCube", location=[3, 0, 0]) + check("createObject accepted with undoLabel", r["status"] == "accepted" and r["undoLabel"].startswith("Brokkr nibu/hands: createObject "), r["undoLabel"]) + + +def s_transform(): + intent(action="setObjectTransform", targetObjectName="AgentCube", location=[3, 2, 0]) + check("transform applied", loc("AgentCube") == [3.0, 2.0, 0.0], loc("AgentCube")) + + +def s_undo_transform(): + undo() + check("one undo reverts only the transform step", "AgentCube" in names() and loc("AgentCube") == [3.0, 0.0, 0.0], + {"objects": names(), "loc": loc("AgentCube")}) + + +def s_undo_create(): + undo() + check("one undo reverts createObject (cube_add, rename, location) together", names() == S["objects0"], names()) + + +def s_denied_setup(): + intent(action="createObject", objectType="MESH", name="AgentCube2", location=[0, 5, 0]) + r = intent(action="createObject", objectType="MESH", requestedBy="", name="Intruder") + check("denied intent: status denied, scene unchanged", r["status"] == "denied" and "Intruder" not in names(), r["status"]) + check("denied intent: no undoLabel", r["undoLabel"] == "", r["undoLabel"]) + + +def s_denied_undo(): + undo() + check("denied intent pushed nothing: one undo removes the preceding accepted intent", names() == S["objects0"], names()) + + +def s_edit_enter(): + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube + cube.select_set(True) + with win(): + bpy.ops.object.mode_set(mode="EDIT") + S["loc0"] = loc("Cube") + push("driver edit-mode baseline") + S["z0"] = vz() + bm = bmesh.from_edit_mesh(cube.data); bm.verts.ensure_lookup_table(); bm.verts[0].co.z += 5.0 + bmesh.update_edit_mesh(cube.data) + push("her edit-mesh edit") + R["editMode"] = {"mode_before": bpy.context.mode, "loc_before": S["loc0"]} + + +def s_edit_agent(): + r = intent(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5]) + R["editMode"].update(mode_after_intent=bpy.context.mode, loc_after_intent=loc("Cube"), receipt=r["status"], + message=r["message"], undoLabel=r["undoLabel"]) + check("edit mode: object-level intent refused, scene and her mode unchanged", + r["status"] == "denied" and "Edit Mode" in r["message"] and r["undoLabel"] == "" + and loc("Cube") == S["loc0"] and bpy.context.mode == "EDIT_MESH", R["editMode"]) + + +def s_edit_others(): + """Anything that writes scene state or changes her mode is refused in Edit Mode; renderStill does neither.""" + world0 = bpy.context.scene.world + rw = intent(action="setWorld", color=[1, 0, 0], strength=2.0) + rx = intent(action="exportGltf", filepath="edit.glb") + rr = intent(action="renderStill", outputPath="edit.png", engine="CYCLES", resolutionX=8, resolutionY=8) + R["editMode"].update(setWorld=rw["status"], exportGltf=rx["status"], renderStill=rr["status"], + mode_after_others=bpy.context.mode) + check("edit mode: setWorld and exportGltf denied, world untouched, no file written", + rw["status"] == "denied" and rx["status"] == "denied" and bpy.context.scene.world == world0 + and "edit.glb" not in os.listdir(OUTDIR), R["editMode"]) + check("edit mode: renderStill accepted, pushes nothing, her mode kept", + rr["status"] == "accepted" and rr["undoLabel"] == "" and bpy.context.mode == "EDIT_MESH", R["editMode"]) + + +def s_edit_undo(): + """One undo must revert her edit-mesh step: a step pushed by the refused intent would have taken it.""" + undo() + R["editMode"].update(mode_after_undo=bpy.context.mode, loc_after_undo=loc("Cube"), z_before=S["z0"] + 5.0, z_after_undo=vz()) + check("edit mode: undo stack unchanged by the refused intent (one undo reverts her edit-mesh step)", + vz() == S["z0"] and loc("Cube") == S["loc0"], R["editMode"]) + + +def s_exit(): + if bpy.context.mode != "OBJECT": + with win(): + bpy.ops.object.mode_set(mode="OBJECT") + + +def s_noop_setup(): + intent(action="createObject", objectType="MESH", name="AgentCube3", location=[0, -5, 0]) + rx = intent(action="exportGltf", filepath="object.glb") + rr = intent(action="renderStill", outputPath="object.png", engine="CYCLES", resolutionX=8, resolutionY=8) + check("exportGltf and renderStill accepted with no undoLabel", + rx["status"] == "accepted" and rr["status"] == "accepted" and rx["undoLabel"] == "" and rr["undoLabel"] == "", + [rx["message"], rr["message"]]) + + +def s_noop_undo(): + undo() + check("no-op actions pushed no step: one undo removes the preceding createObject", "AgentCube3" not in names(), names()) + + +steps = [s_baseline, s_create, s_transform, s_undo_transform, s_undo_create, s_denied_setup, s_denied_undo, + s_edit_enter, s_edit_agent, s_edit_others, s_edit_undo, s_exit, s_noop_setup, s_noop_undo] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not any("error" in s for s in R["steps"]) + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1) + + +def tick(): + global i + if i < len(steps): + try: + steps[i]() + except Exception: + R["steps"].append({"step": steps[i].__name__, "error": traceback.format_exc()}) + i += 1 + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=2.0) diff --git a/surfaces/blender/tests/live/agent_turn_undo.result.json b/surfaces/blender/tests/live/agent_turn_undo.result.json new file mode 100644 index 0000000..1f3ef58 --- /dev/null +++ b/surfaces/blender/tests/live/agent_turn_undo.result.json @@ -0,0 +1,312 @@ +{ + "blender": "5.3.0", + "background": false, + "checks": [ + { + "name": "createObject accepted with undoLabel", + "ok": true, + "detail": "Brokkr nibu/hands: createObject ent-turn" + }, + { + "name": "transform applied", + "ok": true, + "detail": [ + 3.0, + 2.0, + 0.0 + ] + }, + { + "name": "one undo reverts only the transform step", + "ok": true, + "detail": { + "objects": [ + "AgentCube", + "Camera", + "Cube", + "Light" + ], + "loc": [ + 3.0, + 0.0, + 0.0 + ] + } + }, + { + "name": "one undo reverts createObject (cube_add, rename, location) together", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "denied intent: status denied, scene unchanged", + "ok": true, + "detail": "denied" + }, + { + "name": "denied intent: no undoLabel", + "ok": true, + "detail": "" + }, + { + "name": "denied intent pushed nothing: one undo removes the preceding accepted intent", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "edit mode: object-level intent refused, scene and her mode unchanged", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: setWorld and exportGltf denied, world untouched, no file written", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: renderStill accepted, pushes nothing, her mode kept", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "edit mode: undo stack unchanged by the refused intent (one undo reverts her edit-mesh step)", + "ok": true, + "detail": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } + }, + { + "name": "exportGltf and renderStill accepted with no undoLabel", + "ok": true, + "detail": [ + "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-lmbbnbpa\\object.glb (3484 bytes).", + "Rendered still to object.png." + ] + }, + { + "name": "no-op actions pushed no step: one undo removes the preceding createObject", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + } + ], + "steps": [ + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject ent-turn", + "message": "Blender object created." + }, + { + "intent": "setObjectTransform", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform ent-turn", + "message": "Blender object transform updated." + }, + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject ent-turn", + "message": "Blender object created." + }, + { + "intent": "createObject", + "status": "denied", + "undoLabel": "", + "message": "Intent has no requestedBy of the form '/'." + }, + { + "intent": "setObjectTransform", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "setWorld", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "exportGltf", + "status": "denied", + "undoLabel": "", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "intent": "renderStill", + "status": "accepted", + "undoLabel": "", + "message": "Rendered still to edit.png." + }, + { + "intent": "createObject", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: createObject ent-turn", + "message": "Blender object created." + }, + { + "intent": "exportGltf", + "status": "accepted", + "undoLabel": "", + "message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-lmbbnbpa\\object.glb (3484 bytes)." + }, + { + "intent": "renderStill", + "status": "accepted", + "undoLabel": "", + "message": "Rendered still to object.png." + } + ], + "ok": true, + "editMode": { + "mode_before": "EDIT_MESH", + "loc_before": [ + 0.0, + 0.0, + 0.0 + ], + "mode_after_intent": "EDIT_MESH", + "loc_after_intent": [ + 0.0, + 0.0, + 0.0 + ], + "receipt": "denied", + "message": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed.", + "undoLabel": "", + "setWorld": "denied", + "exportGltf": "denied", + "renderStill": "accepted", + "mode_after_others": "EDIT_MESH", + "mode_after_undo": "EDIT_MESH", + "loc_after_undo": [ + 0.0, + 0.0, + 0.0 + ], + "z_before": 6.0, + "z_after_undo": 1.0 + } +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/export_gltf.py b/surfaces/blender/tests/live/export_gltf.py new file mode 100644 index 0000000..e133e7a --- /dev/null +++ b/surfaces/blender/tests/live/export_gltf.py @@ -0,0 +1,104 @@ +"""Live proof of exportGltf on real bpy: the option names exist on the real exporter, extras reach the +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. +file, selection filters, .gltf writes its .bin and textures without overwriting, a refused or failed +export leaves nothing behind. + + BROKKR_ADDON= \ + blender -b --factory-startup --python export_gltf.py -- result.json + +Exit status is non-zero if any check fails. +""" +import bpy, sys, os, json, types, tempfile +from pathlib import Path + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "export_gltf_result.json" +R = {"blender": bpy.app.version_string, "checks": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True) + + +# Every exporter keyword the add-on passes must be a property of the real operator. +props = {p.identifier for p in bpy.ops.export_scene.gltf.get_rna_type().properties} +passed = {"filepath", "export_format", "use_selection", "export_extras", "export_yup", "export_apply"} +check("exporter has every option the add-on passes", passed <= props, sorted(passed - props)) +work = Path(tempfile.mkdtemp(prefix="brokkr-export-live-")) +bpy.ops.wm.read_factory_settings(use_empty=True) +t = bt.BrokkrBlenderTarget(bpy) +t.configure_action_dirs("", str(work)) +bpy.ops.mesh.primitive_cube_add(); cube = bpy.context.active_object; cube.name = "Cube"; cube["brokkr_tag"] = "hello" +bpy.ops.mesh.primitive_uv_sphere_add(location=(3, 0, 0)); sphere = bpy.context.active_object; sphere.name = "Sphere" +image = bpy.data.images.new("brokkr_tex", 4, 4) +scratch = Path(tempfile.mkdtemp(prefix="brokkr-export-src-")) +image.filepath_raw = str(scratch / "brokkr_tex_src.png"); image.file_format = "PNG"; image.save() +mat = bpy.data.materials.new("Textured"); mat.use_nodes = True +node = mat.node_tree.nodes.new("ShaderNodeTexImage"); node.image = image +mat.node_tree.links.new(node.outputs["Color"], mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"]) +cube.data.materials.append(mat) +N = [0] + + +def act(**cmd): + N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = "exportGltf" + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) + + +def listing(): + return sorted(str(p.relative_to(work)).replace("\\", "/") for p in work.rglob("*")) + + +r = act(filepath="all.glb") +check("glb accepted", r["status"] == "accepted", r["message"]) +check("glb written, no staging folder", listing() == ["all.glb"], listing()) +glb = (work / "all.glb").read_bytes() +check("glb carries extras", b"brokkr_tag" in glb and b"hello" in glb) +r = act(filepath="noextras.glb", extras=False) +check("extras=false leaves them out", b"brokkr_tag" not in (work / "noextras.glb").read_bytes(), r["message"]) +cube.select_set(True); sphere.select_set(False) +r = act(filepath="only.glb", selection=["Sphere"]) +data = (work / "only.glb").read_bytes() +check("selection exports only the sphere", b"Sphere" in data and b"Cube" not in data, r["message"]) +check("selection restored", cube.select_get() and not sphere.select_get(), (cube.select_get(), sphere.select_get())) + +r = act(filepath="sep/s.gltf") +check("gltf accepted", r["status"] == "accepted", r["message"]) +files = listing() +check("gltf writes its bin and the texture beside it", "sep/s.gltf" in files and "sep/s.bin" in files and any(f.startswith("sep/brokkr_tex") for f in files), files) +before = {f: (work / f).read_bytes() for f in listing() if (work / f).is_file()} +texture = next(f for f in files if f.startswith("sep/brokkr_tex")) +(work / texture).write_bytes(b"precious") +r = act(filepath="sep/s2.gltf") +check("a taken texture name refuses", r["status"] == "failed" and Path(texture).name in r["message"], r["message"]) +check("the taken texture is untouched", (work / texture).read_bytes() == b"precious") +check("the refused export leaves nothing", not any(f.startswith("sep/s2") for f in listing()) and not any(".brokkr-export" in f for f in listing()), listing()) + +r = act(filepath="fresh/deep/x.glb", selection=["Nope"]) +check("refused selection makes no folder", r["status"] == "failed" and not (work / "fresh").exists(), r["message"]) +orig = bpy.ops.export_scene.gltf +bt_target = t +class Boom: + def __call__(self, *a, **k): + Path(k["filepath"]).write_bytes(b"partial"); raise RuntimeError("died midway") + def get_rna_type(self): return orig.get_rna_type() +import types as _t +t.bpy = _t.SimpleNamespace(**{k: getattr(bpy, k) for k in ("data", "app", "path", "context")}) +t.bpy.ops = _t.SimpleNamespace(export_scene=_t.SimpleNamespace(gltf=Boom()), import_scene=bpy.ops.import_scene, render=bpy.ops.render) +r = act(filepath="fresh/deep/x.glb") +check("a failing exporter is a failed receipt", r["status"] == "failed", r["message"]) +check("and leaves no partial file or new folder", not (work / "fresh").exists(), listing()) +t.bpy = bpy +r = act(filepath="fresh/deep/x.glb") +check("the same name then exports", r["status"] == "accepted" and (work / "fresh" / "deep" / "x.glb").is_file(), r["message"]) + +import shutil +shutil.rmtree(work, ignore_errors=True); shutil.rmtree(scratch, ignore_errors=True) +json.dump(R, open(out, "w"), indent=1) +sys.exit(0 if all(c["ok"] for c in R["checks"]) else 1) diff --git a/surfaces/blender/tests/live/export_gltf.result.json b/surfaces/blender/tests/live/export_gltf.result.json new file mode 100644 index 0000000..5a154ee --- /dev/null +++ b/surfaces/blender/tests/live/export_gltf.result.json @@ -0,0 +1,114 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "exporter has every option the add-on passes", + "ok": true, + "detail": [] + }, + { + "name": "glb accepted", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\all.glb (72752 bytes)." + }, + { + "name": "glb written, no staging folder", + "ok": true, + "detail": [ + "all.glb" + ] + }, + { + "name": "glb carries extras", + "ok": true, + "detail": null + }, + { + "name": "extras=false leaves them out", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\noextras.glb (72720 bytes)." + }, + { + "name": "selection exports only the sphere", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\only.glb (70240 bytes)." + }, + { + "name": "selection restored", + "ok": true, + "detail": [ + true, + false + ] + }, + { + "name": "gltf accepted", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\sep\\s.gltf (2840 bytes)." + }, + { + "name": "gltf writes its bin and the texture beside it", + "ok": true, + "detail": [ + "all.glb", + "noextras.glb", + "only.glb", + "sep", + "sep/brokkr_tex_src.png", + "sep/s.bin", + "sep/s.gltf" + ] + }, + { + "name": "a taken texture name refuses", + "ok": true, + "detail": "output path already exists; output actions never overwrite: brokkr_tex_src.png" + }, + { + "name": "the taken texture is untouched", + "ok": true, + "detail": null + }, + { + "name": "the refused export leaves nothing", + "ok": true, + "detail": [ + "all.glb", + "noextras.glb", + "only.glb", + "sep", + "sep/brokkr_tex_src.png", + "sep/s.bin", + "sep/s.gltf" + ] + }, + { + "name": "refused selection makes no folder", + "ok": true, + "detail": "Selection object was not found: Nope" + }, + { + "name": "a failing exporter is a failed receipt", + "ok": true, + "detail": "died midway" + }, + { + "name": "and leaves no partial file or new folder", + "ok": true, + "detail": [ + "all.glb", + "noextras.glb", + "only.glb", + "sep", + "sep/brokkr_tex_src.png", + "sep/s.bin", + "sep/s.gltf" + ] + }, + { + "name": "the same name then exports", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\fresh\\deep\\x.glb (72752 bytes)." + } + ] +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/gn_actions.py b/surfaces/blender/tests/live/gn_actions.py index 1d9e329..87eda23 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -1,10 +1,12 @@ """Live proof of the node-graph actions: rebuild three geometry-node setups through Brokkr actions only. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python gn_actions.py -- result.json Each native tree is built with bpy as the reference and evaluated with the depsgraph. The Brokkr side -uses BrokkrBlenderTarget.execute_command for every build step and capture_snapshot().objects[].evaluated +uses BrokkrBlenderTarget.run_intent for every build step and capture_snapshot().objects[].evaluated for every read: no bpy call touches the Brokkr-built scene except the harness's own reference trees. Exit status is non-zero if any check fails. """ @@ -29,7 +31,7 @@ def fresh(): N = [0] def act(t, **cmd): N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]) - r = t.execute_command(bpy.context, cmd) + r = t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) if r["status"] != "accepted": print("REFUSED", cmd["action"], r["message"], flush=True) return r @@ -37,7 +39,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): @@ -152,7 +154,7 @@ check("unwired exposed input leaves result", srt(evaluated(t, "ScatterHost")["in r = act(t, action="addNode", treeKey="Scatter", id="bad", blIdname="GeometryNodeMeshCube", inputs={"Nope": 1}); check("unknown input refused", r["status"] == "failed", r["message"]) check("refused addNode left no node", not any(n.get("brokkr_id") == "bad" for n in bpy.data.node_groups["Scatter"].nodes)) r = act(t, action="addNode", treeKey="Scatter", id="bad2", blIdname="GeometryNodeMeshCube", properties={"nope": 1}); check("unknown property refused", r["status"] == "failed", r["message"]) -r = act(t, action="addNode", treeKey="Scatter", id="bad3", blIdname="GeometryNodeImportOBJ"); check("file-reading node refused", r["status"] == "failed", r["message"]) +r = act(t, action="addNode", treeKey="Scatter", id="bad3", blIdname="GeometryNodeImportOBJ"); check("file-reading node refused", r["status"] == "denied", r["message"]) r = act(t, action="addNode", treeKey="Scatter", id="bad4", blIdname="GeometryNodeNoSuchThing"); check("unknown node type refused", r["status"] == "failed", r["message"]) r = act(t, action="linkSockets", treeKey="Scatter", fromNode="cone", fromSocket="Mesh", toNode="dist", toSocket="Density"); check("invalid link refused and removed", r["status"] == "failed" and not any(l.to_socket.name == "Density" for l in bpy.data.node_groups["Scatter"].links), r["message"]) r = act(t, action="setModifierInput", objectName="ScatterHost", modifierName="GN", socket="Seed", value="x"); check("wrong value type refused", r["status"] == "failed", r["message"]) @@ -167,7 +169,7 @@ after = [(l.from_node.get("brokkr_id"), l.to_socket.identifier) for l in bpy.dat check("refused link keeps the link it would have replaced", r["status"] == "failed" and before == after == [("cube", "Points")], (r["message"], before, after)) ok(t2, action="createObject", objectType="CAMERA", name="Cam") r = act(t2, action="addModifier", objectName="Cam", treeKey="L"); check("modifier on a camera refused clearly", r["status"] == "failed" and "CAMERA" in r["message"], r["message"]) -r = act(t2, action="addNode", treeKey="L", id="n\n", blIdname="ShaderNodeMath"); check("trailing newline in an id refused", r["status"] == "failed", r["message"]) +r = act(t2, action="addNode", treeKey="L", id="n\n", blIdname="ShaderNodeMath"); check("trailing newline in an id refused", r["status"] == "denied", r["message"]) # off-origin host: vertices are local, instances world, bounds kept apart t3 = fresh() graph(t3, "Off", GEO_OUT, [dict(id="circle", blIdname="GeometryNodeMeshCircle", inputs={"Vertices": 4, "Radius": 1.0}), dict(id="cube", blIdname="GeometryNodeMeshCube"), dict(id="iop", blIdname="GeometryNodeInstanceOnPoints"), dict(id="join", blIdname="GeometryNodeJoinGeometry")], @@ -254,7 +256,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_actions.result.json b/surfaces/blender/tests/live/gn_actions.result.json index cdcc1f5..3253af1 100644 --- a/surfaces/blender/tests/live/gn_actions.result.json +++ b/surfaces/blender/tests/live/gn_actions.result.json @@ -1,5 +1,5 @@ { - "blender": "5.2.3 LTS", + "blender": "5.3.0", "checks": [ { "name": "createNodeGroup Ring", @@ -435,7 +435,7 @@ { "name": "file-reading node refused", "ok": true, - "detail": "node type GeometryNodeImportOBJ is not allowed in this cut (Import)." + "detail": "blIdname may not contain 'Import'." }, { "name": "unknown node type refused", @@ -514,7 +514,7 @@ { "name": "trailing newline in an id refused", "ok": true, - "detail": "id must be 1..63 characters of letters, digits, space, '.', '_' or '-'." + "detail": "id may contain only letters, digits, '.', '_' or '-'." }, { "name": "createNodeGroup Off", @@ -955,7 +955,7 @@ "detail": [ 59, 59, - 0.008 + 0.013 ] }, { @@ -1052,7 +1052,7 @@ "name": "2000x2000 instanced grid: capture is bounded", "ok": true, "detail": [ - 1.2, + 2.17, 99999, false ] @@ -1086,12 +1086,12 @@ "name": "2000x2000 mesh grid: counts only, bounded", "ok": true, "detail": [ - 0.05, + 0.0, 4000000 ] } ], - "cycle_probe_seconds": 0.008, - "capture_2000_grid_instanced_seconds": 1.198, - "capture_2000_grid_mesh_seconds": 0.045 + "cycle_probe_seconds": 0.013, + "capture_2000_grid_instanced_seconds": 2.173, + "capture_2000_grid_mesh_seconds": 0.002 } \ No newline at end of file diff --git a/surfaces/blender/tests/live/gn_recreation.py b/surfaces/blender/tests/live/gn_recreation.py index 6ef8036..2281812 100644 --- a/surfaces/blender/tests/live/gn_recreation.py +++ b/surfaces/blender/tests/live/gn_recreation.py @@ -1,10 +1,12 @@ """Recreate geometry-node setups through the Brokkr scene/object actions and compare with the native result. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python gn_recreation.py -- result.json Each setup is built twice: natively (geometry-nodes tree via bpy, evaluated) and through -BrokkrBlenderTarget.execute_command using only the actions that exist. Prints GAP lines where an +BrokkrBlenderTarget.run_intent using only the actions that exist. Prints GAP lines where an action that would be needed is refused or has no effect. Not part of the unittest run (needs Blender). """ import bpy, sys, os, json, types, math, random @@ -25,7 +27,7 @@ def reset(): def act(t, **cmd): cmd.setdefault("commandId", "c%d" % act.n); act.n += 1 - return t.execute_command(bpy.context, cmd) + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) act.n = 0 def gap(key, **detail): @@ -104,7 +106,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 +155,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/headless_smoke.py b/surfaces/blender/tests/live/headless_smoke.py index 085df0c..40e6fff 100644 --- a/surfaces/blender/tests/live/headless_smoke.py +++ b/surfaces/blender/tests/live/headless_smoke.py @@ -1,4 +1,6 @@ """Live Blender smoke for the scene actions. Not part of the unittest run: it needs Blender. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_RUN= BROKKR_ADDON= \ blender --background --factory-startup --python surfaces/blender/tests/live/headless_smoke.py @@ -43,7 +45,7 @@ results = [] def run(label, **cmd): cmd.setdefault("commandId", label) try: - r = target.execute_command(bpy.context, cmd) + r = target.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) except Exception: r = {"status": "EXCEPTION", "message": traceback.format_exc()} print("RESULT", label, r["status"], r.get("message", "").replace("\n", " | ")[:400], flush=True) diff --git a/surfaces/blender/tests/live/host_action.py b/surfaces/blender/tests/live/host_action.py new file mode 100644 index 0000000..930a51a --- /dev/null +++ b/surfaces/blender/tests/live/host_action.py @@ -0,0 +1,286 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, that a host add-on's brokkr_actions.json adds +rows the agent turn admits, runs and undoes like a built-in, and that an operator left out of the file stays human-only. + + BROKKR_SCRATCH= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python host_action.py -- + +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. It copies tests/fixtures/brokkr_host_fixture into BLENDER_USER_SCRIPTS/addons and +enables it there; it writes nothing else outside BROKKR_SCRATCH. Every intent is put into the node database as +brokkr-ctl does and answered by the add-on's own 1 s drain (the sink is on). Proves, with wm.undo_stack as the counter: + + * the snapshot lists the fixture's four rows (host, no apply) and no hostActionErrors; + * add_empty is accepted as exactly one new undo step, undo removes the empty, redo brings it back; + * report is accepted with hostResult equal to what the operator wrote, no new step, humanEditSeq unchanged; + * refuse is failed with the operator's text and cancel is failed, each with no new step; + * apply (registered, left out of the file) and wm.save_mainfile are denied Unsupported with no step, the scene + unchanged and no 'Applied' object; + * the file is then rewritten to list apply: apply and the reload operator sent as intents are still denied (no + re-read on an intent), the operator refuses inside an agent turn, and only the human's reload (this driver + calling bpy.ops.brokkr.reload_host_actions outside a turn) admits apply, as one undo step. + +Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import shutil +import sys +import traceback +from pathlib import Path + +import bpy + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own folders are used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if os.path.normcase(os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != os.path.normcase(os.path.abspath(os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") +if os.path.normcase(os.path.abspath(bpy.utils.user_resource("SCRIPTS"))) != os.path.normcase(os.path.abspath(os.environ["BLENDER_USER_SCRIPTS"])): + raise SystemExit("Blender's scripts folder is not BLENDER_USER_SCRIPTS; refusing to touch it") + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +HOST = "brokkr_host_fixture" +FIXTURE = Path(__file__).resolve().parents[1] / "fixtures" / HOST +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": []} + +addons_dir = Path(os.environ["BLENDER_USER_SCRIPTS"]) / "addons" +addons_dir.mkdir(parents=True, exist_ok=True) +if (addons_dir / HOST).exists(): + shutil.rmtree(addons_dir / HOST) +shutil.copytree(FIXTURE, addons_dir / HOST, ignore=shutil.ignore_patterns("__pycache__")) +bpy.utils.refresh_script_paths() + +bpy.ops.preferences.addon_enable(module=MODULE) +bpy.ops.preferences.addon_enable(module=HOST) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +prefs = bpy.context.preferences.addons[MODULE].preferences +bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "live.blend")) +CACHE = str(SCRATCH / "queue.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.debug_mirror_root = "" +prefs.auto_drain_commands = True # the sink +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +bpy.ops.brokkr.reload_host_actions() # the human's button: the host files are read here + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +def steps_now(): + return [s.name for s in bpy.context.window_manager.undo_stack.steps] + + +def undo(): + with win(): + bpy.ops.ed.undo() + + +def redo(): + with win(): + bpy.ops.ed.redo() + + +def node(): + return adapter._open_node(CACHE, prefs.cultlib_py_src) + + +N = [0] + + +def queue(**cmd): + N[0] += 1 + cid = "host-%04d" % N[0] + n, docs = node() + cmd.update(commandId=cid, schema=bt.COMMAND_INTENT_SCHEMA, requestedBy="nibu/hands") + n.database.put(docs["command_intent"], f"blender/commands/{cid}", cmd) + return cid + + +def receipt(cid): + n, _ = node() + return n.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).get(f"blender/receipts/{cid}") + + +def names(): + return sorted(o.name for o in bpy.data.objects) + + +S = {} +WAIT = {"ticks": 0} + + +def until(pred, limit=40): + def step(): + WAIT["ticks"] += 1 + if pred(): + WAIT["ticks"] = 0 + return True + if WAIT["ticks"] > limit: + raise TimeoutError("the drain did not receipt in time") + return False + return step + + +def once(fn): + def step(): + fn() + return True + return step + + +def send(key, **fields): + S[key + ":before"] = {"steps": steps_now(), "names": names(), "seq": adapter.human_edit_seq} + S[key] = queue(**fields) + + +def done(key): + return lambda: receipt(S[key]) is not None + + +def same_world(key): + before = S[key + ":before"] + return (steps_now() == before["steps"] and names() == before["names"] and adapter.human_edit_seq == before["seq"]) + + +def snapshot_check(): + snapshot = adapter.capture_snapshot(bpy.context, True) + rows = snapshot["hostActions"] + expect = [f"{HOST}.{n}" for n in ("add_empty", "report", "refuse", "cancel")] + check("the snapshot lists the fixture's four rows with their host and none other (apply is left out)", + sorted(r["name"] for r in rows) == sorted(expect) and {r["host"] for r in rows} == {HOST}, [r["name"] for r in rows]) + check("the snapshot carries no hostActionErrors", snapshot["hostActionErrors"] == [], snapshot["hostActionErrors"]) + check("the operators are registered by the legacy add-on, apply included", + all(hasattr(getattr(bpy.ops, HOST), n) for n in ("add_empty", "report", "refuse", "cancel", "apply"))) + + +def add_check(): + r = receipt(S["add"]) + before = S["add:before"] + after = steps_now() + check("add_empty is accepted", r["status"] == "accepted", r) + check("add_empty is exactly one new undo step carrying the receipt's label", + len(after) == len(before["steps"]) + 1 and after[-1] == r["undoLabel"] and r["undoLabel"].startswith(f"Brokkr nibu/hands: {HOST}.add_empty "), + {"before": before["steps"][-2:], "after": after[-2:], "label": r["undoLabel"]}) + check("add_empty made the empty with the declared name and size", + "LiveEmpty" in bpy.data.objects and abs(bpy.data.objects["LiveEmpty"].empty_display_size - 2.0) < 1e-6, names()) + check("add_empty is the agent's write: humanEditSeq did not move", adapter.human_edit_seq == before["seq"]) + S["add:names"] = names() + undo() + check("one undo removes the empty", "LiveEmpty" not in bpy.data.objects, names()) + redo() + check("redo brings it back", names() == S["add:names"], names()) + + +def report_check(): + r = receipt(S["report"]) + expect = f"objects: {len(bpy.data.objects)}\nscenes: {len(bpy.data.scenes)}" + check("report is accepted with hostResult equal to what the operator wrote", r["status"] == "accepted" and r["hostResult"] == expect, [r["status"], r["hostResult"], expect]) + check("report pushed no undo step, added no object and left humanEditSeq alone", same_world("report"), [steps_now()[-2:], S["report:before"]["steps"][-2:]]) + + +def failure_check(key, text): + def run(): + r = receipt(S[key]) + check(f"{key} is failed{' with ' + repr(text) if text else ''}", r["status"] == "failed" and text in r["message"], r) + check(f"{key} pushed no undo step and changed nothing", same_world(key) and r["undoLabel"] == "", r["undoLabel"]) + return run + + +def denied_check(key, action): + def run(): + r = receipt(S[key]) + check(f"{action} is denied Unsupported", r["status"] == "denied" and "Unsupported Blender command action" in r["message"], r) + check(f"{action} ran nothing: no step, no new object, no 'Applied'", same_world(key) and "Applied" not in bpy.data.objects, names()) + return run + + +def rewrite_listing_apply(): + path = addons_dir / HOST / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"].append({"name": f"{HOST}.apply", "doc": "applies", "changesScene": True, "editModeSafe": False, "fields": []}) + path.write_text(json.dumps(document), encoding="utf-8") + + +def reload_refused_in_a_turn(): + adapter.agent_turn = True + try: + try: + bpy.ops.brokkr.reload_host_actions() + refused = False + except RuntimeError as error: + refused = "human only" in str(error) + finally: + adapter.agent_turn = False + check("the Reload Host Actions operator refuses inside an agent turn", refused) + names_now = [r["name"] for r in adapter.host_actions()[0]] + check("and re-read nothing: the edited file's apply row is still not admitted", f"{HOST}.apply" not in names_now, names_now) + + +def human_reload_check(): + bpy.ops.brokkr.reload_host_actions() + names_now = [r["name"] for r in adapter.host_actions()[0]] + check("the human's reload admits the edited file's apply row", f"{HOST}.apply" in names_now, names_now) + + +def applied_check(): + r = receipt(S["apply2"]) + after = steps_now() + before = S["apply2:before"] + check("apply is accepted after the human's reload as one labelled undo step", + r["status"] == "accepted" and len(after) == len(before["steps"]) + 1 and after[-1] == r["undoLabel"] and "Applied" in bpy.data.objects, r) + + +steps = [ + once(snapshot_check), + once(lambda: send("add", action=f"{HOST}.add_empty", name="LiveEmpty", size=2)), until(done("add")), once(add_check), + once(lambda: send("report", action=f"{HOST}.report")), until(done("report")), once(report_check), + once(lambda: send("refuse", action=f"{HOST}.refuse")), until(done("refuse")), once(failure_check("refuse", "the fixture refuses")), + once(lambda: send("cancel", action=f"{HOST}.cancel")), until(done("cancel")), once(failure_check("cancel", "cancelled; nothing changed")), + once(lambda: send("apply", action=f"{HOST}.apply")), until(done("apply")), once(denied_check("apply", f"{HOST}.apply")), + once(lambda: send("save", action="wm.save_mainfile")), until(done("save")), once(denied_check("save", "wm.save_mainfile")), + once(rewrite_listing_apply), + once(lambda: send("apply1", action=f"{HOST}.apply")), until(done("apply1")), once(denied_check("apply1", f"{HOST}.apply after the file was edited")), + once(lambda: send("reload", action="brokkr.reload_host_actions")), until(done("reload")), once(denied_check("reload", "brokkr.reload_host_actions")), + once(reload_refused_in_a_turn), once(human_reload_check), + once(lambda: send("apply2", action=f"{HOST}.apply")), until(done("apply2")), once(applied_check), +] +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def tick(): + global i + if i < len(steps): + try: + if steps[i](): + i += 1 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + i = len(steps) + write() + return 0.5 + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(tick, first_interval=3.0) diff --git a/surfaces/blender/tests/live/host_action.result.json b/surfaces/blender/tests/live/host_action.result.json new file mode 100644 index 0000000..5ef9544 --- /dev/null +++ b/surfaces/blender/tests/live/host_action.result.json @@ -0,0 +1,318 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "the snapshot lists the fixture's four rows with their host and none other (apply is left out)", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel" + ] + }, + { + "name": "the snapshot carries no hostActionErrors", + "ok": true, + "detail": [] + }, + { + "name": "the operators are registered by the legacy add-on, apply included", + "ok": true, + "detail": null + }, + { + "name": "add_empty is accepted", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0001", + "action": "brokkr_host_fixture.add_empty", + "status": "accepted", + "message": "Operator brokkr_host_fixture.add_empty finished.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:04.276267+00:00" + } + }, + { + "name": "add_empty is exactly one new undo step carrying the receipt's label", + "ok": true, + "detail": { + "before": [ + "Original" + ], + "after": [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ], + "label": "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + } + }, + { + "name": "add_empty made the empty with the declared name and size", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "add_empty is the agent's write: humanEditSeq did not move", + "ok": true, + "detail": null + }, + { + "name": "one undo removes the empty", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light" + ] + }, + { + "name": "redo brings it back", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "report is accepted with hostResult equal to what the operator wrote", + "ok": true, + "detail": [ + "accepted", + "objects: 4\nscenes: 1", + "objects: 4\nscenes: 1" + ] + }, + { + "name": "report pushed no undo step, added no object and left humanEditSeq alone", + "ok": true, + "detail": [ + [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ], + [ + "Original", + "Brokkr nibu/hands: brokkr_host_fixture.add_empty ost-0001" + ] + ] + }, + { + "name": "refuse is failed with 'the fixture refuses'", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0003", + "action": "brokkr_host_fixture.refuse", + "status": "failed", + "message": "Error: the fixture refuses", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:08.396168+00:00" + } + }, + { + "name": "refuse pushed no undo step and changed nothing", + "ok": true, + "detail": "" + }, + { + "name": "cancel is failed with 'cancelled; nothing changed'", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0004", + "action": "brokkr_host_fixture.cancel", + "status": "failed", + "message": "Operator brokkr_host_fixture.cancel cancelled; nothing changed.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:10.456189+00:00" + } + }, + { + "name": "cancel pushed no undo step and changed nothing", + "ok": true, + "detail": "" + }, + { + "name": "brokkr_host_fixture.apply is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0005", + "action": "brokkr_host_fixture.apply", + "status": "denied", + "message": "Unsupported Blender command action: brokkr_host_fixture.apply", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:12.513224+00:00" + } + }, + { + "name": "brokkr_host_fixture.apply ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "wm.save_mainfile is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0006", + "action": "wm.save_mainfile", + "status": "denied", + "message": "Unsupported Blender command action: wm.save_mainfile", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:14.572017+00:00" + } + }, + { + "name": "wm.save_mainfile ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "brokkr_host_fixture.apply after the file was edited is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0007", + "action": "brokkr_host_fixture.apply", + "status": "denied", + "message": "Unsupported Blender command action: brokkr_host_fixture.apply", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:16.631534+00:00" + } + }, + { + "name": "brokkr_host_fixture.apply after the file was edited ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "brokkr.reload_host_actions is denied Unsupported", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0008", + "action": "brokkr.reload_host_actions", + "status": "denied", + "message": "Unsupported Blender command action: brokkr.reload_host_actions", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:18.693145+00:00" + } + }, + { + "name": "brokkr.reload_host_actions ran nothing: no step, no new object, no 'Applied'", + "ok": true, + "detail": [ + "Camera", + "Cube", + "Light", + "LiveEmpty" + ] + }, + { + "name": "the Reload Host Actions operator refuses inside an agent turn", + "ok": true, + "detail": null + }, + { + "name": "and re-read nothing: the edited file's apply row is still not admitted", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel" + ] + }, + { + "name": "the human's reload admits the edited file's apply row", + "ok": true, + "detail": [ + "brokkr_host_fixture.add_empty", + "brokkr_host_fixture.report", + "brokkr_host_fixture.refuse", + "brokkr_host_fixture.cancel", + "brokkr_host_fixture.apply" + ] + }, + { + "name": "apply is accepted after the human's reload as one labelled undo step", + "ok": true, + "detail": { + "schema": "brokkr.blender.command_receipt.v0", + "commandId": "host-0009", + "action": "brokkr_host_fixture.apply", + "status": "accepted", + "message": "Operator brokkr_host_fixture.apply finished.", + "objectName": "", + "requestedBy": "nibu/hands", + "note": "", + "undoLabel": "Brokkr nibu/hands: brokkr_host_fixture.apply ost-0009", + "lookPath": "", + "hostResult": "", + "observedAt": "2026-11-28T06:03:21.755767+00:00" + } + } + ], + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/material_colour.py b/surfaces/blender/tests/live/material_colour.py index 4b43135..d31533d 100644 --- a/surfaces/blender/tests/live/material_colour.py +++ b/surfaces/blender/tests/live/material_colour.py @@ -1,4 +1,6 @@ """Live proof of assignMaterial colour and idempotence on real bpy. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. BROKKR_ADDON= \ blender -b --factory-startup --python material_colour.py -- result.json @@ -26,7 +28,7 @@ cube = bpy.context.active_object N = [0] def act(**cmd): N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = "assignMaterial"; cmd["targetObjectName"] = cube.name - return t.execute_command(bpy.context, cmd) + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) def base(): return tuple(round(c, 6) for c in bpy.data.materials["oxide red"].node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value) diff --git a/surfaces/blender/tests/live/perception.py b/surfaces/blender/tests/live/perception.py new file mode 100644 index 0000000..7523763 --- /dev/null +++ b/surfaces/blender/tests/live/perception.py @@ -0,0 +1,285 @@ +"""Live proof, in GUI Blender with the add-on installed as an extension, of perception, with real brokkr-ctl sends. + + BROKKR_SCRATCH= + BROKKR_CTL= + BROKKR_ADDON_MODULE= + BROKKR_CULTLIB= + blender --python perception.py -- + +Run it in Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH; without them the operator's own extensions folder is used). The script +refuses to run when they are unset. The add-on's preferences are then the +defaults. The driver stands in for the operator's hands only: it saves the blend, ticks the sink and sets the render +output directory (the two preferences an operator sets), enters Edit Mode, selects, moves objects and presses undo. +Every intent is sent by brokkr-ctl and answered by the add-on's own timer. Writes .result.json, then quits. +""" +import importlib +import json +import os +import shutil +import struct +import subprocess +import sys +import time +import traceback +from pathlib import Path + +import bmesh +import bpy + +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + +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) +prefs = bpy.context.preferences.addons[MODULE].preferences +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +STORE = SCRATCH / ".brokkr" / "blender-editor.ccmp" # what the default blend-relative preference resolves to +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=str(STORE), BROKKR_AGENT="hands") + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def fields(text): + out = {} + for line in text.splitlines(): + key, _, value = line.partition(": ") + try: + out[key] = json.loads(value) if value[:1] in "[{0123456789" else value + except ValueError: + out[key] = value + return out + + +def ctl(*args): + """A brokkr-ctl run beside Blender's timers (it blocks until the receipt, and the add-on's timer answers it).""" + proc = subprocess.Popen([CTL, "blender", *args], env=ENV, stdout=subprocess.PIPE, text=True) + began = time.perf_counter() + while proc.poll() is None: + yield + out = proc.stdout.read() + return proc.returncode, fields(out), round((time.perf_counter() - began) * 1000) + + +def png_size(path): + data = Path(path).read_bytes() + assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG" + return struct.unpack(">II", data[16:24]) + + +def view3d(): + for window in bpy.context.window_manager.windows: + for area in window.screen.areas: + if area.type == "VIEW_3D": + return window, area, next(r for r in area.regions if r.type == "WINDOW") + + +def snapshot(): + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.brokkr.capture_snapshot() + return adapter.last_snapshot + + +def objects_named(prefix): + return sorted(o.name for o in bpy.data.objects if o.name.startswith(prefix)) + + +def mode_edit(on): + window, area, region = view3d() + cube = bpy.data.objects["Cube"] + bpy.context.view_layer.objects.active = cube # she clicks it first + cube.select_set(True) + with bpy.context.temp_override(window=window, area=area, region=region, active_object=cube, object=cube): + bpy.ops.object.mode_set(mode="EDIT" if on else "OBJECT") + + +def flow(): + cube = bpy.data.objects["Cube"] + window, area, region = view3d() + R["notes"]["window_px"] = [window.width, window.height] + R["notes"]["region_px"] = [region.width, region.height] + R["notes"]["area_px"] = [area.width, area.height] + + # ---- a default install: the preferences are untouched except what the operator sets ---- + check("default install: the store preference is the blend-relative default", + prefs.cultmesh_cache_path == "//.brokkr/blender-editor.ccmp", prefs.cultmesh_cache_path) + bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "perception.blend")) + prefs.output_dir = str(SCRATCH / "out") + prefs.auto_drain_commands = True # the operator ticks the sink + yield 1.0 + snap = snapshot() + check("the default blend-relative store was created beside the saved blend", STORE.is_file(), str(STORE)) + check("the snapshot carries sessionId, humanEditSeq 0, editSelection [] and per-object lastHumanEditSeq", + snap["sessionId"] == adapter.session_id and snap["humanEditSeq"] == 0 and snap["editSelection"] == [] + and all(o["lastHumanEditSeq"] == 0 for o in snap["objects"]), [snap["sessionId"], snap["humanEditSeq"]]) + session = snap["sessionId"] + + # ---- look: her 3D view, scoped to the viewport ---- + code, r, ms = yield from ctl("look", "--note", "first look") + R["notes"]["first_look"] = r + R["notes"]["first_look_round_trip_ms"] = ms + path = r.get("lookPath", "") + size = png_size(path) if path and Path(path).is_file() else None + check("look: exit 0, accepted, a lookPath PNG under /look/.png", + code == 0 and r.get("status") == "accepted" and size is not None + and Path(path).parent == (SCRATCH / "out" / "look") and Path(path).name == r["commandId"] + ".png", [code, r]) + check("look: the PNG is the 3D view's WINDOW region, not the Blender window and not the desktop", + list(size) == R["notes"]["region_px"] and list(size) != R["notes"]["window_px"], [size, R["notes"]]) + check("look: no undo step, receipt names the session, edits so far 0, none edited since", + r.get("undoLabel", "") == "" and r.get("sessionId") == session and r.get("humanEditSeq") == 0 + and r.get("humanEditsSinceLook") == 0 and r.get("editedSinceLook") == [], r) + + # ---- the agent's own edits are not hers ---- + seq_before = adapter.human_edit_seq + code, r, _ = yield from ctl("send", "createObject", "--set", 'objectType="EMPTY"', "--set", 'name="AgentEmpty"') + code2, r2, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[0,0,0.5]") + for _ in range(12): # a deferred depsgraph update, if the turn left one behind, arrives within a few ticks + yield 0.1 + check("agent turns (createObject, setObjectTransform) leave humanEditSeq unmoved, also after idle ticks", + code == 0 and code2 == 0 and adapter.human_edit_seq == seq_before == 0 + and adapter.last_human_edit_seq("AgentEmpty") == 0 and adapter.last_human_edit_seq("Cube") == 0, + [code, code2, adapter.human_edit_seq, adapter._last_human_edit]) + + # ---- Edit Mode selection, read live, without leaving Edit Mode ---- + mode_edit(True) + yield 0.3 + bm = bmesh.from_edit_mesh(cube.data) + for v in bm.verts: + v.select = False + bm.verts.ensure_lookup_table() + bm.verts[0].select = True + bm.verts[3].select = True + bm.select_flush_mode() + bmesh.update_edit_mesh(cube.data) + yield 0.3 + code, r, _ = yield from ctl("look") + if r.get("lookPath"): + shutil.copy(r["lookPath"], SCRATCH / "edit-look.png") + sel = (r.get("editSelection") or [{}])[0] + check("edit selection: look reads her two selected vertices live; the mode stays Edit Mode", + code == 0 and sel.get("name") == "Cube" and sel.get("vertices") == [0, 3] and sel.get("verticesTotal") == 2 + and bpy.context.mode == "EDIT_MESH", [r.get("editSelection"), bpy.context.mode]) + code, r2, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[0,0,3]") + check("an object intent is refused while she is in Edit Mode (ruling in force); look was not", code == 2 and r2.get("status") == "denied", + r2.get("message")) + snap = snapshot() + check("the snapshot's editSelection matches", snap["editSelection"][0]["vertices"] == [0, 3], snap["editSelection"]) + mode_edit(False) + yield 0.3 + + # ---- her edits: counters, and a follower that moves with its target ---- + follower = bpy.data.objects.new("Follower", bpy.data.meshes.new("FollowerMesh")) + bpy.context.scene.collection.objects.link(follower) + constraint = follower.constraints.new("COPY_LOCATION") + constraint.target = cube + constraint.use_y = False + yield 0.5 + # Linking an object rebuilds the depsgraph relations and Blender flags other objects in that update: collateral + # of her adding an object, recorded, not attributed to a move. + R["notes"]["after_adding_follower"] = dict(adapter._last_human_edit) + code, r, _ = yield from ctl("look") # the marker: what she does next is "since this look" + marker = r["humanEditSeq"] + cube.location.x = 2.0 # her move + yield 0.5 + cube.location.x = 4.0 + yield 0.5 + snap = snapshot() + by = {o["name"]: o["lastHumanEditSeq"] for o in snap["objects"]} + R["notes"]["after_moving_cube"] = {"marker": marker, "humanEditSeq": snap["humanEditSeq"], "last": by} + check("her moves bump humanEditSeq; Cube and its constrained Follower carry the same last sequence, the untouched Light and Camera do not", + snap["humanEditSeq"] > marker and by["Cube"] == by["Follower"] == snap["humanEditSeq"] + and by["Light"] <= marker and by["Camera"] <= marker, [marker, snap["humanEditSeq"], by]) + code, r, _ = yield from ctl("look") + check("the next look says what changed since the last one: exactly the moved Cube and its Follower", + r["humanEditsSinceLook"] >= 2 and r["editedSinceLook"] == ["Cube", "Follower"], r) + code, r, _ = yield from ctl("look") + check("and a look right after it says nothing changed since", r["humanEditsSinceLook"] == 0 and r["editedSinceLook"] == [], r) + + # ---- scene-last-writer-wins and act-then-undo ---- + seq = adapter.human_edit_seq + code, r, _ = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[9,9,9]") + check("after her edit, the agent's action on the same object is accepted (last writer wins)", code == 0 and r.get("status") == "accepted" + and tuple(round(c, 3) for c in bpy.data.objects["Cube"].location) == (9.0, 9.0, 9.0), r) + check("and still did not count as hers", adapter.human_edit_seq == seq, [seq, adapter.human_edit_seq]) + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.ed.undo() # her Ctrl+Z + yield 0.5 + check("her Ctrl+Z takes the agent's step back and counts as hers", + bpy.data.objects["Cube"].location.x != 9.0 and adapter.human_edit_seq > seq, + [bpy.data.objects["Cube"].location.x, seq, adapter.human_edit_seq]) + + # ---- a popup open over the view is in the picture, as she sees it ---- + window, area, region = view3d() + with bpy.context.temp_override(window=window, area=area, region=region): + bpy.ops.wm.call_menu("INVOKE_DEFAULT", name="VIEW3D_MT_add") + yield 0.8 + code, r, _ = yield from ctl("look", "--note", "with the Add menu open") + R["notes"]["popup_look"] = r.get("lookPath") + if r.get("lookPath"): + shutil.copy(r["lookPath"], SCRATCH / "popup-look.png") # the look directory is pruned; this copy is for a human to see + check("look with a popup open: accepted, a PNG of the same region size", code == 0 and r.get("lookPath") + and list(png_size(r["lookPath"])) == R["notes"]["region_px"], r) + + # ---- prune to twenty ---- + for _ in range(24): + yield from ctl("look") + kept = sorted((SCRATCH / "out" / "look").glob("*.png")) + check("after 30 looks the look directory holds exactly the newest 20 PNGs", len(kept) == 20, len(kept)) + + # ---- refusals ---- + area.type = "OUTLINER" + yield 0.3 + code, r, _ = yield from ctl("look") + area.type = "VIEW_3D" + check("no 3D view open: look is refused naming why, with no path", code == 2 and "3D" in r.get("message", "") and r.get("lookPath", "") == "", r) + prefs.output_dir = "" + code, r, _ = yield from ctl("look") + prefs.output_dir = str(SCRATCH / "out") + check("no output directory set: look is refused naming why", code == 2 and "output" in r.get("message", ""), r) + code, r, _ = yield from ctl("look") + check("the next look works again", code == 0, r) + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +gen = flow() +wait_until = 0.0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def runner(): + global wait_until + try: + delay = next(gen) + return delay if isinstance(delay, (int, float)) and delay else 0.05 + except StopIteration: + write() + bpy.ops.wm.quit_blender() + return None + except Exception: + R.setdefault("errors", []).append(traceback.format_exc()) + write() + bpy.ops.wm.quit_blender() + return None + + +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/perception.result.json b/surfaces/blender/tests/live/perception.result.json new file mode 100644 index 0000000..ac8afdb --- /dev/null +++ b/surfaces/blender/tests/live/perception.result.json @@ -0,0 +1,437 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "default install: the store preference is the blend-relative default", + "ok": true, + "detail": "//.brokkr/blender-editor.ccmp" + }, + { + "name": "the default blend-relative store was created beside the saved blend", + "ok": true, + "detail": "F:\\aeth-wt\\brokkr-live-5.scratch\\.brokkr\\blender-editor.ccmp" + }, + { + "name": "the snapshot carries sessionId, humanEditSeq 0, editSelection [] and per-object lastHumanEditSeq", + "ok": true, + "detail": [ + "3e3712b94e944cb9ad4a74aafdc699bd", + 0 + ] + }, + { + "name": "look: exit 0, accepted, a lookPath PNG under /look/.png", + "ok": true, + "detail": [ + 0, + { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + ] + }, + { + "name": "look: the PNG is the 3D view's WINDOW region, not the Blender window and not the desktop", + "ok": true, + "detail": [ + [ + 1574, + 888 + ], + { + "window_px": [ + 1920, + 1009 + ], + "region_px": [ + 1574, + 888 + ], + "area_px": [ + 1574, + 888 + ], + "first_look": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + }, + "first_look_round_trip_ms": 456, + "after_adding_follower": { + "Cube": 4, + "Light": 4, + "Camera": 4, + "AgentEmpty": 4, + "Follower": 4 + }, + "after_moving_cube": { + "marker": 4, + "humanEditSeq": 6, + "last": { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + }, + "popup_look": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png" + } + ] + }, + { + "name": "look: no undo step, receipt names the session, edits so far 0, none edited since", + "ok": true, + "detail": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "agent turns (createObject, setObjectTransform) leave humanEditSeq unmoved, also after idle ticks", + "ok": true, + "detail": [ + 0, + 0, + 0, + { + "Cube": 8, + "Light": 8, + "Camera": 8, + "AgentEmpty": 8, + "Follower": 6 + } + ] + }, + { + "name": "edit selection: look reads her two selected vertices live; the mode stays Edit Mode", + "ok": true, + "detail": [ + [ + { + "edges": [], + "edgesTotal": 0, + "faces": [], + "facesTotal": 0, + "name": "Cube", + "type": "MESH", + "vertices": [ + 0, + 3 + ], + "verticesTotal": 2 + } + ], + "EDIT_MESH" + ] + }, + { + "name": "an object intent is refused while she is in Edit Mode (ruling in force); look was not", + "ok": true, + "detail": "Object 'Cube' is in Edit Mode: object-level intents are refused until she leaves it; nothing was changed." + }, + { + "name": "the snapshot's editSelection matches", + "ok": true, + "detail": [ + { + "name": "Cube", + "type": "MESH", + "vertices": [ + 0, + 3 + ], + "verticesTotal": 2, + "edges": [], + "edgesTotal": 0, + "faces": [], + "facesTotal": 0 + } + ] + }, + { + "name": "her moves bump humanEditSeq; Cube and its constrained Follower carry the same last sequence, the untouched Light and Camera do not", + "ok": true, + "detail": [ + 4, + 6, + { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + ] + }, + { + "name": "the next look says what changed since the last one: exactly the moved Cube and its Follower", + "ok": true, + "detail": { + "commandId": "01a21ee56f787012b0f2312b77c478b4", + "action": "look", + "editSelection": [], + "editedSinceLook": [ + "Cube", + "Follower" + ], + "humanEditSeq": 6, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee56f787012b0f2312b77c478b4.png", + "message": "Captured the 3D view to look/01a21ee56f787012b0f2312b77c478b4.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:24:43.509761+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "and a look right after it says nothing changed since", + "ok": true, + "detail": { + "commandId": "01a21ee574627220a1ed3e104667b73c", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 6, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee574627220a1ed3e104667b73c.png", + "message": "Captured the 3D view to look/01a21ee574627220a1ed3e104667b73c.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:24:44.677117+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after her edit, the agent's action on the same object is accepted (last writer wins)", + "ok": true, + "detail": { + "commandId": "01a21ee5788978c1b7f353ca2e2147be", + "action": "setObjectTransform", + "lookPath": "", + "message": "Blender object transform updated.", + "note": "", + "objectName": "Cube", + "observedAt": "2026-11-27T21:24:45.745214+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "accepted", + "undoLabel": "Brokkr nibu/hands: setObjectTransform 2e2147be" + } + }, + { + "name": "and still did not count as hers", + "ok": true, + "detail": [ + 6, + 6 + ] + }, + { + "name": "her Ctrl+Z takes the agent's step back and counts as hers", + "ok": true, + "detail": [ + 0.0, + 6, + 8 + ] + }, + { + "name": "look with a popup open: accepted, a PNG of the same region size", + "ok": true, + "detail": { + "commandId": "01a21ee581c771d2b3b688dfce3996f3", + "action": "look", + "editSelection": [], + "editedSinceLook": [ + "AgentEmpty", + "Camera", + "Cube", + "Light" + ], + "humanEditSeq": 8, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png", + "message": "Captured the 3D view to look/01a21ee581c771d2b3b688dfce3996f3.png.", + "note": "with the Add menu open", + "objectName": "", + "observedAt": "2026-11-27T21:24:47.877250+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after 30 looks the look directory holds exactly the newest 20 PNGs", + "ok": true, + "detail": 20 + }, + { + "name": "no 3D view open: look is refused naming why, with no path", + "ok": true, + "detail": { + "commandId": "01a21ee5f6b27cc2ae9dd61ee3a5bdef", + "action": "look", + "lookPath": "", + "message": "No 3D viewport is open to look at.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:17.807716+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "failed", + "undoLabel": "" + } + }, + { + "name": "no output directory set: look is refused naming why", + "ok": true, + "detail": { + "commandId": "01a21ee5fa117271abc6c3536e2194d3", + "action": "look", + "lookPath": "", + "message": "output directory is not configured in the add-on preferences.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:18.920883+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "status": "failed", + "undoLabel": "" + } + }, + { + "name": "the next look works again", + "ok": true, + "detail": { + "commandId": "01a21ee5fe627fc3ad7ae77850c6e812", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 8, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5fe627fc3ad7ae77850c6e812.png", + "message": "Captured the 3D view to look/01a21ee5fe627fc3ad7ae77850c6e812.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-27T21:25:20.088455+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "window_px": [ + 1920, + 1009 + ], + "region_px": [ + 1574, + 888 + ], + "area_px": [ + 1574, + 888 + ], + "first_look": { + "commandId": "01a21ee5507774d293ea4186f58a4689", + "action": "look", + "editSelection": [], + "editedSinceLook": [], + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee5507774d293ea4186f58a4689.png", + "message": "Captured the 3D view to look/01a21ee5507774d293ea4186f58a4689.png.", + "note": "first look", + "objectName": "", + "observedAt": "2026-11-27T21:24:34.894575+00:00", + "requestedBy": "nibu/hands", + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "3e3712b94e944cb9ad4a74aafdc699bd", + "status": "accepted", + "undoLabel": "" + }, + "first_look_round_trip_ms": 456, + "after_adding_follower": { + "Cube": 4, + "Light": 4, + "Camera": 4, + "AgentEmpty": 4, + "Follower": 4 + }, + "after_moving_cube": { + "marker": 4, + "humanEditSeq": 6, + "last": { + "AgentEmpty": 4, + "Camera": 4, + "Cube": 6, + "Follower": 6, + "Light": 4 + } + }, + "popup_look": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21ee581c771d2b3b688dfce3996f3.png" + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/perception_fixes.py b/surfaces/blender/tests/live/perception_fixes.py new file mode 100644 index 0000000..d535a51 --- /dev/null +++ b/surfaces/blender/tests/live/perception_fixes.py @@ -0,0 +1,251 @@ +"""Live proof of the live-5 fix batch, in GUI Blender with the add-on installed as an extension, real brokkr-ctl looks. + +Same environment as perception.py (BROKKR_SCRATCH, BROKKR_CTL, BROKKR_CULTLIB; private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS; the script refuses to run without them). + blender --python perception_fixes.py -- +The driver stands in for the operator: it saves the blend, ticks the sink, sets the output directory, minimises and +restores the Blender window (Windows ShowWindow on this process's own window), moves objects, enters Edit Mode. +""" +import ctypes +import importlib +import json +import os +import statistics +import subprocess +import sys +import time +import traceback +from ctypes import wintypes +from pathlib import Path + +import bmesh +import bpy + +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") +import numpy + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +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, "checks": [], "notes": {}} +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +prefs = bpy.context.preferences.addons[MODULE].preferences +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +adapter = addon.target() +STORE = SCRATCH / ".brokkr" / "blender-editor.ccmp" +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=str(STORE), BROKKR_AGENT="hands") +user32 = ctypes.windll.user32 + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def fields(text): + out = {} + for line in text.splitlines(): + key, _, value = line.partition(": ") + try: + out[key] = json.loads(value) if value[:1] in "[{0123456789tf" else value + except ValueError: + out[key] = value + return out + + +def ctl(*args): + proc = subprocess.Popen([CTL, "blender", *args], env=ENV, stdout=subprocess.PIPE, text=True) + while proc.poll() is None: + yield + return proc.returncode, fields(proc.stdout.read()) + + +def blender_windows(): + found = [] + + @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) + def visit(hwnd, _): + owner = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) + name = ctypes.create_unicode_buffer(64) + user32.GetClassNameW(hwnd, name, 64) + if owner.value == os.getpid() and name.value == "GHOST_WindowClass" and user32.IsWindowVisible(hwnd): + found.append(hwnd) + return True + + user32.EnumWindows(visit, 0) + return found + + +def show(cmd): # 6 minimise, 9 restore + for hwnd in blender_windows(): + user32.ShowWindow(hwnd, cmd) + + +def pixels(path): + image = bpy.data.images.load(str(path)) + try: + return numpy.array(image.pixels[:], dtype=numpy.float32).reshape(image.size[1], image.size[0], 4) + finally: + bpy.data.images.remove(image) + + +def diff_box(a, b): + mask = numpy.abs(a - b).max(axis=2) > 0.02 + if not mask.any(): + return None + ys, xs = numpy.where(mask) + return [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())] + + +def old_scan(obj): + """The scan this fix replaces: every vertex, edge and face walked in Python.""" + mesh = bmesh.from_edit_mesh(obj.data) + out = [] + for elements in (mesh.verts, mesh.edges, mesh.faces): + chosen = [i for i, e in enumerate(elements) if e.select] + out.append((chosen[:4096], len(chosen))) + return out + + +def flow(): + bpy.ops.wm.save_as_mainfile(filepath=str(SCRATCH / "fixes.blend")) + prefs.output_dir = str(SCRATCH / "out") + prefs.auto_drain_commands = True + yield 1.0 + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.brokkr.capture_snapshot() + cube = bpy.data.objects["Cube"] + # ---- minimised window: look must show the current scene ---- + code, a0 = yield from ctl("look") + check("window up: the region capture, source named", code == 0 and a0["captureSource"] == "region", a0) + show(6) + yield 1.0 + iconic = [bool(user32.IsIconic(h)) for h in blender_windows()] + R["notes"]["iconic_after_minimise"] = iconic + check("the Blender window is minimised (IsIconic)", iconic and all(iconic), iconic) + code, a = yield from ctl("look") + cube.location.x = 3.0 # her edit, while minimised + yield 0.5 + code, b = yield from ctl("look") + pa = pixels(a["lookPath"]) if a.get("lookPath") else None + pb = pixels(b["lookPath"]) if b.get("lookPath") else None + box = diff_box(pa, pb) if pa is not None and pb is not None else None + R["notes"]["minimised"] = {"a": a, "b": b, "diff_box": box} + check("minimised: both looks are accepted and say they were rendered offscreen", + code == 0 and a.get("captureSource") == "offscreen" and b.get("captureSource") == "offscreen", [a.get("captureSource"), b.get("captureSource")]) + check("minimised: the Cube moved by her shows in the next look (the pictures differ, in a box)", box is not None, box) + check("minimised: sceneUpdateSeq advanced between the two looks", b["sceneUpdateSeq"] > a["sceneUpdateSeq"], [a["sceneUpdateSeq"], b["sceneUpdateSeq"]]) + check("minimised: size equals the 3D region", [pb.shape[1], pb.shape[0]] == [1574, 888] if pb is not None else False, + None if pb is None else [pb.shape[1], pb.shape[0]]) + # the agent's own move while minimised, then look + code, m = yield from ctl("send", "setObjectTransform", "--set", 'targetObjectName="Cube"', "--set", "location=[-3,0,0]") + code, c = yield from ctl("look") + pc = pixels(c["lookPath"]) + check("minimised: the agent's own move is in its next look", diff_box(pb, pc) is not None and c["sceneUpdateSeq"] > b["sceneUpdateSeq"], diff_box(pb, pc)) + show(9) + yield 1.5 + code, d = yield from ctl("look") + check("restored: back to the region capture", code == 0 and d.get("captureSource") == "region", d.get("captureSource")) + + # ---- coarse attribution ---- + code, e0 = yield from ctl("look") + follower = bpy.data.objects.new("Follower", bpy.data.meshes.new("FM")) + bpy.context.scene.collection.objects.link(follower) + yield 0.5 + code, e1 = yield from ctl("look") + check("after her link of an object: the receipt says the attribution is coarse", + e1.get("editedSinceLookCoarse") is True and "all objects flagged" in e1.get("editedSinceLookNote", ""), e1) + code, e2 = yield from ctl("look") + cube.location.y = 1.0 + yield 0.5 + code, e3 = yield from ctl("look") + check("after a plain move: not coarse, only the Cube named", e3.get("editedSinceLookCoarse") is False and e3.get("editedSinceLook") == ["Cube"], e3) + with bpy.context.temp_override(window=bpy.context.window_manager.windows[0]): + bpy.ops.ed.undo() + yield 0.5 + code, e4 = yield from ctl("look") + check("after her undo: coarse", e4.get("editedSinceLookCoarse") is True, e4) + + # ---- one million vertices in Edit Mode ---- + mesh = bpy.data.meshes.new("Big") + bm = bmesh.new() + bmesh.ops.create_grid(bm, x_segments=1000, y_segments=1000, size=1.0) + bm.to_mesh(mesh) + bm.free() + big = bpy.data.objects.new("Big", mesh) + bpy.context.scene.collection.objects.link(big) + bpy.context.view_layer.objects.active = big + for o in bpy.context.view_layer.objects: + o.select_set(o is big) + yield 0.5 + window = bpy.context.window_manager.windows[0] + area = next(a for a in window.screen.areas if a.type == "VIEW_3D") + region = next(r for r in area.regions if r.type == "WINDOW") + with bpy.context.temp_override(window=window, area=area, region=region, active_object=big, object=big): + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="SELECT") + yield 0.5 + R["notes"]["verts"] = len(mesh.vertices) + new_ms, old_ms = [], [] + for _ in range(5): # paired, interleaved + t = time.perf_counter() + new = adapter.edit_selection() + new_ms.append((time.perf_counter() - t) * 1000) + t = time.perf_counter() + old = old_scan(big) + old_ms.append((time.perf_counter() - t) * 1000) + entry = new[0] + parts = {} + t = time.perf_counter(); bm2 = bmesh.from_edit_mesh(big.data); parts["from_edit_mesh"] = (time.perf_counter() - t) * 1000 + t = time.perf_counter(); totals = (big.data.total_vert_sel, big.data.total_edge_sel, big.data.total_face_sel); parts["totals"] = (time.perf_counter() - t) * 1000 + for name, seq in (("verts", bm2.verts), ("edges", bm2.edges), ("faces", bm2.faces)): + t = time.perf_counter(); n = 0 + for i, e in enumerate(seq): + if e.select: + n += 1 + if n == 4096: + break + parts[name] = (time.perf_counter() - t) * 1000 + R["notes"]["edit_selection_parts_ms"] = {k: round(v, 1) for k, v in parts.items()} + R["notes"]["edit_selection_ms"] = {"new": [round(x) for x in new_ms], "old": [round(x) for x in old_ms], + "new_median": round(statistics.median(new_ms)), "old_median": round(statistics.median(old_ms))} + check("1M vertices: the totals are the mesh's own and the lists are capped at 4096", + entry["verticesTotal"] == 1_002_001 and len(entry["vertices"]) == 4096 and entry["vertices"] == old[0][0] + and entry["edgesTotal"] == old[1][1] and entry["facesTotal"] == old[2][1], [entry["verticesTotal"], entry["edgesTotal"], entry["facesTotal"]]) + check("1M vertices: the read is several times faster than the full scan (medians in notes)", + statistics.median(old_ms) > 3 * statistics.median(new_ms), R["notes"]["edit_selection_ms"]) + with bpy.context.temp_override(window=window, area=area, region=region, active_object=big, object=big): + bpy.ops.object.mode_set(mode="OBJECT") + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + + +gen = flow() + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +def runner(): + try: + delay = next(gen) + return delay if isinstance(delay, (int, float)) and delay else 0.05 + except StopIteration: + write() + bpy.ops.wm.quit_blender() + except Exception: + R.setdefault("errors", []).append(traceback.format_exc()) + write() + bpy.ops.wm.quit_blender() + + +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/perception_fixes.result.json b/surfaces/blender/tests/live/perception_fixes.result.json new file mode 100644 index 0000000..11ca160 --- /dev/null +++ b/surfaces/blender/tests/live/perception_fixes.result.json @@ -0,0 +1,298 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "window up: the region capture, source named", + "ok": true, + "detail": { + "commandId": "01a21fe56d007f03a2355733ee33a416", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe56d007f03a2355733ee33a416.png", + "message": "Captured the 3D view to look/01a21fe56d007f03a2355733ee33a416.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-28T02:04:19.958143+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 0, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "the Blender window is minimised (IsIconic)", + "ok": true, + "detail": [ + true + ] + }, + { + "name": "minimised: both looks are accepted and say they were rendered offscreen", + "ok": true, + "detail": [ + "offscreen", + "offscreen" + ] + }, + { + "name": "minimised: the Cube moved by her shows in the next look (the pictures differ, in a box)", + "ok": true, + "detail": [ + 711, + 248, + 975, + 529 + ] + }, + { + "name": "minimised: sceneUpdateSeq advanced between the two looks", + "ok": true, + "detail": [ + 0, + 1 + ] + }, + { + "name": "minimised: size equals the 3D region", + "ok": true, + "detail": [ + 1574, + 888 + ] + }, + { + "name": "minimised: the agent's own move is in its next look", + "ok": true, + "detail": [ + 656, + 248, + 975, + 581 + ] + }, + { + "name": "restored: back to the region capture", + "ok": true, + "detail": "region" + }, + { + "name": "after her link of an object: the receipt says the attribution is coarse", + "ok": true, + "detail": { + "commandId": "01a21fe5a09b70728ba3f974ad47eecc", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Camera", + "Cube", + "Follower", + "Light" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", + "humanEditSeq": 4, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe5a09b70728ba3f974ad47eecc.png", + "message": "Captured the 3D view to look/01a21fe5a09b70728ba3f974ad47eecc.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-28T02:04:32.629832+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 5, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after a plain move: not coarse, only the Cube named", + "ok": true, + "detail": { + "commandId": "01a21fe5a8a677439cb3f76df5eed508", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Cube" + ], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 5, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe5a8a677439cb3f76df5eed508.png", + "message": "Captured the 3D view to look/01a21fe5a8a677439cb3f76df5eed508.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-28T02:04:34.918968+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 6, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "after her undo: coarse", + "ok": true, + "detail": { + "commandId": "01a21fe5ad537f33846b930d41821f0e", + "action": "look", + "captureSource": "region", + "editSelection": [], + "editedSinceLook": [ + "Camera", + "Cube", + "Light" + ], + "editedSinceLookCoarse": true, + "editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.", + "humanEditSeq": 7, + "humanEditsSinceLook": 2, + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe5ad537f33846b930d41821f0e.png", + "message": "Captured the 3D view to look/01a21fe5ad537f33846b930d41821f0e.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-28T02:04:36.080195+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 7, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", + "status": "accepted", + "undoLabel": "" + } + }, + { + "name": "1M vertices: the totals are the mesh's own and the lists are capped at 4096", + "ok": true, + "detail": [ + 1002001, + 2002000, + 1000000 + ] + }, + { + "name": "1M vertices: the read is several times faster than the full scan (medians in notes)", + "ok": true, + "detail": { + "new": [ + 262, + 192, + 187, + 188, + 187 + ], + "old": [ + 1044, + 1060, + 1010, + 1044, + 1313 + ], + "new_median": 188, + "old_median": 1044 + } + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "iconic_after_minimise": [ + true + ], + "minimised": { + "a": { + "commandId": "01a21fe575527fa0b4a36ecdbdd38ae6", + "action": "look", + "captureSource": "offscreen", + "editSelection": [], + "editedSinceLook": [], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 0, + "humanEditsSinceLook": 0, + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe575527fa0b4a36ecdbdd38ae6.png", + "message": "Captured the 3D view to look/01a21fe575527fa0b4a36ecdbdd38ae6.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-28T02:04:22.160175+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 0, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", + "status": "accepted", + "undoLabel": "" + }, + "b": { + "commandId": "01a21fe57bb173238bf0f2419a61ec46", + "action": "look", + "captureSource": "offscreen", + "editSelection": [], + "editedSinceLook": [ + "Cube" + ], + "editedSinceLookCoarse": false, + "editedSinceLookNote": "", + "humanEditSeq": 1, + "humanEditsSinceLook": 1, + "lookPath": "F:\\aeth-wt\\brokkr-action-table-live\\scratch3\\out\\look\\01a21fe57bb173238bf0f2419a61ec46.png", + "message": "Captured the 3D view to look/01a21fe57bb173238bf0f2419a61ec46.png.", + "note": "", + "objectName": "", + "observedAt": "2026-11-28T02:04:23.398210+00:00", + "requestedBy": "nibu/hands", + "sceneUpdateSeq": 1, + "schema": "brokkr.blender.command_receipt.v0", + "sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162", + "status": "accepted", + "undoLabel": "" + }, + "diff_box": [ + 711, + 248, + 975, + 529 + ] + }, + "verts": 1002001, + "edit_selection_parts_ms": { + "from_edit_mesh": 0.0, + "totals": 0.0, + "verts": 27.4, + "edges": 70.9, + "faces": 27.4 + }, + "edit_selection_ms": { + "new": [ + 262, + 192, + 187, + 188, + 187 + ], + "old": [ + 1044, + 1060, + 1010, + 1044, + 1313 + ], + "new_median": 188, + "old_median": 1044 + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/refusals.py b/surfaces/blender/tests/live/refusals.py new file mode 100644 index 0000000..a7292ad --- /dev/null +++ b/surfaces/blender/tests/live/refusals.py @@ -0,0 +1,76 @@ +"""Live proof of the renderStill GL refusal and the createObject meshType refusal on real bpy. +Launch Blender with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories +(Blender 5.3 ignores BLENDER_USER_RESOURCE_PATH); see docs/install.md. + + BROKKR_ADDON= \ + blender -b --factory-startup --python refusals.py -- result.json + +The pass outcome runs a real child Blender (a one-pixel Workbench and EEVEE render) and then a real +renderStill. The abort outcome needs a host whose headless GL fails (a container with libEGL and no +GPU), which this script cannot make: it runs the real probe against a stand-in binary that aborts, and +on such a host the first two checks fail instead of passing. Exit status is non-zero if any check fails. +""" +import bpy, sys, os, json, types, tempfile, stat, shutil +from pathlib import Path + +ADDON = Path(os.environ["BROKKR_ADDON"]).resolve() +pkg = types.ModuleType("brokkr_bridge"); pkg.__path__ = [str(ADDON)] +sys.modules["brokkr_bridge"] = pkg +from brokkr_bridge import blender_target as bt + +out = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "refusals_result.json" +R = {"blender": bpy.app.version_string, "background": bpy.app.background, "platform": sys.platform, "checks": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + print("CHECK", "ok " if ok else "FAIL", name, detail if not ok else "", flush=True) + + +work = Path(tempfile.mkdtemp(prefix="brokkr-refusals-live-")) +bpy.ops.wm.read_factory_settings(use_empty=True) +t = bt.BrokkrBlenderTarget(bpy) +t.configure_action_dirs("", str(work)) +N = [0] + + +def act(action, **cmd): + N[0] += 1; cmd.setdefault("commandId", "c%d" % N[0]); cmd["action"] = action + return t.run_intent(bpy.context, dict(cmd, requestedBy="test/driver")) + + +for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE_NEXT", "BLENDER_EEVEE"): + try: # the engine enum is dynamic: ask by assignment + bpy.context.scene.render.engine = engine + except TypeError: + continue + if True: + failure = bt.gl_render_failure(bpy.app.binary_path, engine) + check("real one-pixel %s render survives in a child Blender" % engine, failure is None, failure) + +bpy.ops.object.camera_add(); bpy.context.scene.camera = bpy.context.active_object +r = act("renderStill", outputPath="shot.png", engine="BLENDER_WORKBENCH", resolutionX=8, resolutionY=8) +check("renderStill Workbench headless renders after the probe", r["status"] == "accepted" and (work / "shot.png").is_file(), r["message"]) + +stand_in = work / ("abort.cmd" if os.name == "nt" else "abort.sh") +stand_in.write_text("@echo off\r\nexit /b 3\r\n" if os.name == "nt" else "#!/bin/sh\nkill -ABRT $$\n") +stand_in.chmod(stand_in.stat().st_mode | stat.S_IEXEC) +failure = bt.gl_render_failure(str(stand_in), "BLENDER_WORKBENCH") +check("a child that aborts is a refusal reason", failure is not None and "exited with status" in failure, failure) +t.bpy = types.SimpleNamespace(data=bpy.data, path=bpy.path, context=bpy.context, ops=bpy.ops, + app=types.SimpleNamespace(background=True, binary_path=str(stand_in))) +bpy.context.scene.render.engine = "BLENDER_WORKBENCH" +r = act("renderStill", outputPath="no.png", engine="BLENDER_WORKBENCH") +check("renderStill refuses and renders nothing", r["status"] == "failed" and "cannot render" in r["message"] and not (work / "no.png").exists(), r["message"]) +t.bpy = bpy + +for kind in ("LIGHT", "EMPTY", "CAMERA"): + r = act("createObject", objectType=kind, meshType="CYLINDER") + check("meshType on %s is refused" % kind, r["status"] == "denied" and "MESH" in r["message"], r["message"]) +check("and nothing was created for them", len([o for o in bpy.data.objects if o.type in ("LIGHT", "EMPTY")]) == 0) +r = act("createObject", objectType="MESH", meshType="CUBE") +check("meshType CUBE on a MESH still works", r["status"] == "accepted", r["message"]) + +shutil.rmtree(work, ignore_errors=True) +json.dump(R, open(out, "w"), indent=1) +sys.exit(0 if all(c["ok"] for c in R["checks"]) else 1) diff --git a/surfaces/blender/tests/live/refusals.result.json b/surfaces/blender/tests/live/refusals.result.json new file mode 100644 index 0000000..9c06d28 --- /dev/null +++ b/surfaces/blender/tests/live/refusals.result.json @@ -0,0 +1,57 @@ +{ + "blender": "5.3.0", + "background": true, + "platform": "win32", + "checks": [ + { + "name": "real one-pixel BLENDER_WORKBENCH render survives in a child Blender", + "ok": true, + "detail": null + }, + { + "name": "real one-pixel BLENDER_EEVEE render survives in a child Blender", + "ok": true, + "detail": null + }, + { + "name": "renderStill Workbench headless renders after the probe", + "ok": true, + "detail": "Rendered still to shot.png." + }, + { + "name": "a child that aborts is a refusal reason", + "ok": true, + "detail": "a one-pixel test render exited with status 3" + }, + { + "name": "renderStill refuses and renders nothing", + "ok": true, + "detail": "engine BLENDER_WORKBENCH cannot render in this headless Blender (a one-pixel test render exited with status 3); rendering would abort the process; use engine CYCLES." + }, + { + "name": "meshType on LIGHT is refused", + "ok": true, + "detail": "meshType applies only when objectType is one of MESH." + }, + { + "name": "meshType on EMPTY is refused", + "ok": true, + "detail": "meshType applies only when objectType is one of MESH." + }, + { + "name": "meshType on CAMERA is refused", + "ok": true, + "detail": "meshType applies only when objectType is one of MESH." + }, + { + "name": "and nothing was created for them", + "ok": true, + "detail": null + }, + { + "name": "meshType CUBE on a MESH still works", + "ok": true, + "detail": "Blender object created." + } + ] +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/stop_presence.closed.result.json b/surfaces/blender/tests/live/stop_presence.closed.result.json new file mode 100644 index 0000000..2fa8684 --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.closed.result.json @@ -0,0 +1,28 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "phase two: a store on disk from phase one, sink off, no snapshot published this session", + "ok": true, + "detail": null + }, + { + "name": "phase two: a send to a sink-off Blender with a closed node is answered stopped at once (exit 3)", + "ok": true, + "detail": [ + 3, + 1.2883892059326172, + "commandId: 01a21ed2b9747d53bc380f32f2057a09\naction: createObject\ncommandId: 01a21ed2b9747d53bc380f32f2057a09\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: closed\nobjectName: \nobservedAt: 2026-11-27T21:04:17.259806+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + ] + } + ], + "notes": { + "closed": { + "exit": 3, + "seconds": 1.29, + "out": "commandId: 01a21ed2b9747d53bc380f32f2057a09\naction: createObject\ncommandId: 01a21ed2b9747d53bc380f32f2057a09\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: closed\nobjectName: \nobservedAt: 2026-11-27T21:04:17.259806+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + } + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/live/stop_presence.py b/surfaces/blender/tests/live/stop_presence.py new file mode 100644 index 0000000..9e0c8a3 --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.py @@ -0,0 +1,346 @@ +"""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= + Private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are required (refused otherwise). + blender --factory-startup --python stop_presence.py -- + Run a second Blender on the same store with BROKKR_PHASE=closed for the sink-off, node-closed answer. + +The driver stands in for the operator's hands only: it ticks the sink preference on and runs the add-on's own +"Stop agents" operator. Every intent is sent by brokkr-ctl; the add-on's timer drains them. Undo is read only here. +Writes .result.json, then quits Blender. +""" +import importlib +import json +import os +import re +import subprocess +import sys +import time +import traceback +from pathlib import Path + +import bpy + +import os as _os + +for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): + if not _os.environ.get(_name): # this Blender ignores BLENDER_USER_RESOURCE_PATH: without these, her own extensions folder is used + raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +if _os.path.normcase(_os.path.abspath(bpy.utils.user_resource("EXTENSIONS"))) != _os.path.normcase(_os.path.abspath(_os.environ["BLENDER_USER_EXTENSIONS"])): + raise SystemExit("Blender's extensions folder is not BLENDER_USER_EXTENSIONS; refusing to touch it") + +SCRATCH = Path(os.environ["BROKKR_SCRATCH"]).resolve() +SCRATCH.mkdir(parents=True, exist_ok=True) +CTL = os.environ["BROKKR_CTL"] +OUT = sys.argv[sys.argv.index("--") + 1] +MODULE = os.environ.get("BROKKR_ADDON_MODULE", "bl_ext.user_default.brokkr_bridge") +R = {"blender": bpy.app.version_string, "module": MODULE, "checks": [], "notes": {}} + +bpy.ops.preferences.addon_enable(module=MODULE) +addon = importlib.import_module(MODULE) +bt = importlib.import_module(MODULE + ".blender_target") +prefs = bpy.context.preferences.addons[MODULE].preferences +CACHE = str(SCRATCH / "stop.ccmp") +prefs.cultmesh_cache_path = CACHE +prefs.cultlib_py_src = os.environ.get("BROKKR_CULTLIB", prefs.cultlib_py_src) +prefs.auto_drain_commands = False +adapter = addon.target() +ENV = dict(os.environ, EUREKA_INSTANCE="nibu", BROKKR_BLENDER_STORE=CACHE, BROKKR_AGENT="hands") +S = {"ids": []} + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def ctl(*args): + done = subprocess.run([CTL, "blender", *args], env=ENV, capture_output=True, text=True, timeout=30) + return done.returncode, done.stdout + + +SEND = ["send", "createObject", "--set", 'objectType="EMPTY"'] + + +def send(name, note): + code, out = ctl(*SEND, "--set", f'name="{name}"', "--note", note, "--no-wait") + match = re.search(r"commandId:\s*(\S+)", out) + assert code == 0 and match, (code, out) + return match.group(1) + + +def spawn(name, note): + """A brokkr-ctl send that runs beside Blender's timers: the sender is another process, as an agent is.""" + return subprocess.Popen([CTL, "blender", *SEND, "--set", f'name="{name}"', "--note", note, "--no-wait"], + env=ENV, stdout=subprocess.PIPE, text=True) + + +def receipts(): + node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) + return {r["commandId"]: r for r in node.database.snapshot().get(bt.COMMAND_RECEIPT_SCHEMA, {}).values()} + + +def pending(): + node, _ = adapter._open_node(CACHE, prefs.cultlib_py_src) + return list(node.database.snapshot().get(bt.COMMAND_INTENT_SCHEMA, {})) + + +def empties(prefix): + return sorted(o.name for o in bpy.data.objects if o.name.startswith(prefix)) + + +def win(): + return bpy.context.temp_override(window=bpy.context.window_manager.windows[0]) + + +class Recorder: + """A layout that records the panel's labels and operators; the real BROKKR_PT_status.draw runs against it.""" + def __init__(self): + self.labels, self.operators = [], [] + + def __getattr__(self, name): + if name == "label": + return lambda text="", **kw: self.labels.append(text) + if name == "operator": + return lambda idname, **kw: self.operators.append(idname) + return lambda *a, **kw: self + + +def panel(): + layout = Recorder() + addon.BROKKR_PT_status.draw(type("Drawn", (), {"layout": layout})(), bpy.context) + return layout + + +# ---- steps ------------------------------------------------------------------------------------------------- +BURST = 20 + + +def s_setup(): + """A default install: no server, no snapshot, Auto Capture off, sink off. An idle session makes no store.""" + check("setup: default install, no node open and no store file", not adapter.node_open and not Path(CACHE).exists(), + [adapter.node_open, Path(CACHE).exists()]) + + +def s_idle_check(): + check("idle: with the sink off and no store, the timer has still opened no node and made no store", + not adapter.node_open and not Path(CACHE).exists(), [adapter.node_open, Path(CACHE).exists()]) + prefs.auto_drain_commands = True # the operator ticks the sink + + +def node_opened(): + return adapter.node_open + + +def s_open(): + check("sink on with the node closed: the timer opened the node itself (an empty node writes no file until something is put)", adapter.node_open, None) + with win(): + bpy.ops.brokkr.capture_snapshot() # she presses Capture, so brokkr-ctl status has a snapshot to read + code, out = ctl("status") + check("the stored snapshot says agentCommandsEnabled: true", code == 0 and "agentCommandsEnabled: true" in out, out) + + +def s_burst(): + S["procs"] = [spawn(f"B{n:02d}", "burst") for n in range(BURST)] + + +def started(): + return len(receipts()) >= 2 + + +def s_stop(): + S["at_stop"] = sorted(receipts()) + S["panel_before"] = panel().labels # what she sees the moment before she presses Stop, mid-burst + with win(): + S["stop_result"] = bpy.ops.brokkr.stop_agents() + S["pending_after_stop"] = adapter.pending_count + + +def finished(): + return all(p.poll() is not None for p in S["procs"]) and pending() == [] + + +def s_after_stop(): + ids = [] + for proc in S["procs"]: + match = re.search(r"commandId:\s*(\S+)", proc.stdout.read()) + ids.append(match.group(1)) + S["ids"] = ids + rs = receipts() + states = {i: (rs.get(i) or {}).get("status") for i in ids} + accepted = [i for i, st in states.items() if st == "accepted"] + stopped = [i for i, st in states.items() if st == "stopped"] + R["notes"]["states"] = states + check("stop: every one of the 20 intents has a receipt, each accepted or stopped, none missing", + len(accepted) + len(stopped) == BURST and len(stopped) >= 1 and len(accepted) >= 2, states) + check("stop: the queue is empty, the sink is off, Pending read 0 the moment Stop returned", + pending() == [] and prefs.auto_drain_commands is False and S["stop_result"] == {"FINISHED"} + and S["pending_after_stop"] == 0, [pending(), S["stop_result"], S["pending_after_stop"]]) + check("stop: exactly the accepted intents ran and the stopped ones left no object", + len(empties("B")) == len(accepted), [len(empties("B")), len(accepted)]) + check("stop: each accepted intent is one labelled undo step the receipt names", + all(rs[i]["undoLabel"].startswith("Brokkr nibu/hands: createObject ") for i in accepted), + [rs[i]["undoLabel"] for i in accepted][:3]) + check("stop: stopped receipts say who, what and why, and never carry an undo label", + all(rs[i]["requestedBy"] == "nibu/hands" and rs[i]["action"] == "createObject" and rs[i]["undoLabel"] == "" + and ("stopped by the operator" in rs[i]["message"] or "agent commands are off" in rs[i]["message"]) + for i in stopped), sorted({rs[i]["message"][:50] for i in stopped})) + R["notes"]["stop_reasons"] = sorted({rs[i]["message"][:48] for i in stopped}) + exits = {i: (states[i], ctl("wait", i, "--timeout", "5")[0]) for i in ids} + R["notes"]["wait_exits"] = exits + check("stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", + all(code == (0 if st == "accepted" else 3) for st, code in exits.values()), sorted(set(exits.values()))) + code, out = ctl("status") + check("stop: brokkr-ctl status now reads agentCommandsEnabled: false", "agentCommandsEnabled: false" in out, out) + + +def s_late(): + """An agent that never saw Stop sends again and waits: the add-on's timer answers at once, nothing queues.""" + S["late_began"] = time.time() + S["late"] = subprocess.Popen([CTL, "blender", *SEND, "--set", 'name="Late"', "--note", "late", "--timeout", "10"], + env=ENV, stdout=subprocess.PIPE, text=True) + + +def late_done(): + return S["late"].poll() is not None + + +def s_late_check(): + took = time.time() - S["late_began"] + out = S["late"].stdout.read() + code = S["late"].returncode + R["notes"]["late"] = {"exit": code, "seconds": round(took, 2), "out": out} + check("sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", + code == 3 and took < 5 and "agent commands are off" in out and pending() == [] and not empties("Late"), + [code, took, out]) + S["receipt_count"] = len(receipts()) + prefs.auto_drain_commands = True # she turns the sink back on + + +def s_reenabled(): + check("re-enable: nothing queued fires; the late intent never runs", + pending() == [] and not empties("Late") and len(receipts()) == S["receipt_count"], + [pending(), empties("Late"), len(receipts()) - S["receipt_count"]]) + before = len(empties("B")) + with win(): + bpy.ops.ed.undo() + check("stop + Ctrl+Z: one undo takes back the last agent step, nothing else", before - len(empties("B")) == 1, + [before, len(empties("B"))]) + + +def s_panel(): + before = "\n".join(S["panel_before"]) + R["notes"]["panel_before_stop"] = S["panel_before"] + check("panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", + S["panel_before"].index("Agents") < S["panel_before"].index("Provider: brokkr.blender_editor") + and "Active: nibu/hands" in before and "Agent commands: on" in before + and "nibu/hands createObject accepted" in before and "burst" in before + and "Brokkr nibu/hands: createObject" in before + and before.count("createObject accepted") == len(S["at_stop"]), before) + prefs.auto_drain_commands = False + layout = panel() + text = "\n".join(layout.labels) + R["notes"]["panel_labels"] = layout.labels + check("panel after Stop: Stop agents is the first operator drawn", layout.operators[:1] == ["brokkr.stop_agents"], layout.operators[:3]) + check("panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", + "Agent commands: off" in text and "Pending: 0" in text and "nibu/hands createObject stopped" in text, text) + prefs.auto_drain_commands = True + + +def s_server_up(): + with win(): + bpy.ops.brokkr.start_server() + + +def s_server_stop(): + S["ids2"] = [send(f"S{n}", "server-stop") for n in range(3)] # the sender blocks Blender's thread: they cannot drain yet + check("server stop: three intents queued behind a running server, sink on", len(pending()) == 3, len(pending())) + with win(): + bpy.ops.brokkr.stop_server() + rs = receipts() + check("server stop: the same path gives each a stopped receipt naming 'server stopped'", + pending() == [] and all(rs[i]["status"] == "stopped" and "server stopped" in rs[i]["message"] for i in S["ids2"]) + and not empties("S"), [rs[i]["message"] for i in S["ids2"]][:1]) + + +def s_server_start(): + S["ids3"] = [send(f"T{n}", "server-start") for n in range(2)] + with win(): + bpy.ops.brokkr.start_server() + rs = receipts() + exits = [ctl("wait", i, "--timeout", "5")[0] for i in S["ids3"]] + check("server start: intents queued while stopped get stopped receipts naming 'server started', wait exits 3", + pending() == [] and all(rs[i]["status"] == "stopped" and "server started" in rs[i]["message"] for i in S["ids3"]) + and exits == [3, 3] and not empties("T"), [exits, [rs[i]["message"] for i in S["ids3"]][:1]]) + + +def s_final(): + check("no add-on drain error", adapter.last_auto_drain_error == "", adapter.last_auto_drain_error) + with win(): + bpy.ops.brokkr.stop_server() + + +i = 0 + + +def write(): + R["ok"] = bool(R["checks"]) and all(c["ok"] for c in R["checks"]) and not R.get("errors") + with open(OUT + ".result.json", "w") as f: + json.dump(R, f, indent=1, default=str) + + +# The add-on's own timer drains between our ticks. Stop is pressed as soon as two receipts exist, so the burst +# is cut in the middle; sends that arrive after it meet a sink that is off. +def runner(): + global i + try: + if i >= len(steps): + write() + bpy.ops.wm.quit_blender() + return None + step = steps[i] + if step == "wait-two": + if started(): + s_stop() + i += 1 + return 0.005 + if step in ("wait-done", "wait-late", "wait-store", "wait-idle"): + if step == "wait-idle": + S["idle"] = S.get("idle", 0) + 1 + if {"wait-done": finished, "wait-late": late_done, "wait-store": node_opened, + "wait-idle": lambda: S.get("idle", 0) >= 15}[step](): + i += 1 + return 0.1 + step() + i += 1 + write() + return 0.005 if step is s_burst else 0.5 + except Exception: + R.setdefault("errors", []).append({"step": i, "error": traceback.format_exc()}) + write() + bpy.ops.wm.quit_blender() + return None + + +if os.environ.get("BROKKR_PHASE") == "closed": + # Phase two, a fresh Blender on the phase-one store: sink off, no node opened, a store on disk. A send must + # be answered stopped within a tick. + def s_closed(): + check("phase two: a store on disk from phase one, sink off, no snapshot published this session", + Path(CACHE).exists() and not prefs.auto_drain_commands and adapter.last_snapshot is None, None) + S["late_began"] = time.time() + S["late"] = subprocess.Popen([CTL, "blender", *SEND, "--set", 'name="Closed"', "--note", "closed", "--timeout", "10"], + env=ENV, stdout=subprocess.PIPE, text=True) + + def s_closed_check(): + out, code, took = S["late"].stdout.read(), S["late"].returncode, time.time() - S["late_began"] + R["notes"]["closed"] = {"exit": code, "seconds": round(took, 2), "out": out} + check("phase two: a send to a sink-off Blender with a closed node is answered stopped at once (exit 3)", + code == 3 and took < 5 and "agent commands are off" in out and not empties("Closed"), [code, took, out]) + steps = [s_closed, "wait-late", s_closed_check] +else: + steps = [s_setup, "wait-idle", s_idle_check, "wait-store", s_open, s_burst, "wait-two", "wait-done", s_after_stop, s_late, "wait-late", s_late_check, s_reenabled, s_panel, + s_server_up, s_server_stop, s_server_start, s_final] +bpy.app.timers.register(runner, first_interval=3.0) diff --git a/surfaces/blender/tests/live/stop_presence.result.json b/surfaces/blender/tests/live/stop_presence.result.json new file mode 100644 index 0000000..ab9f8ee --- /dev/null +++ b/surfaces/blender/tests/live/stop_presence.result.json @@ -0,0 +1,355 @@ +{ + "blender": "5.3.0", + "module": "bl_ext.user_default.brokkr_bridge", + "checks": [ + { + "name": "setup: default install, no node open and no store file", + "ok": true, + "detail": [ + false, + false + ] + }, + { + "name": "idle: with the sink off and no store, the timer has still opened no node and made no store", + "ok": true, + "detail": [ + false, + false + ] + }, + { + "name": "sink on with the node closed: the timer opened the node itself (an empty node writes no file until something is put)", + "ok": true, + "detail": null + }, + { + "name": "the stored snapshot says agentCommandsEnabled: true", + "ok": true, + "detail": "observedAt: 2026-11-27T21:04:00.546944+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: Cube\nselectedObjectNames: [\"Cube\"]\nobjectCount: 3\nagentCommandsEnabled: true\n" + }, + { + "name": "stop: every one of the 20 intents has a receipt, each accepted or stopped, none missing", + "ok": true, + "detail": { + "01a21ed27e2e74e1b8e725800116e4e8": "accepted", + "01a21ed27e347fc1a9335eece58a845e": "accepted", + "01a21ed27e51773392985e0e1859abec": "stopped", + "01a21ed27e6d7b53a39ad7e8d7316c8b": "stopped", + "01a21ed27e6f78c1a05ed37723e2b309": "stopped", + "01a21ed27e6d76f1bb533bed0a748a13": "stopped", + "01a21ed27e6d7c1092c429ea773c8fc1": "stopped", + "01a21ed27e6f7d33a2055b67edc92f18": "stopped", + "01a21ed27e8272e195d68ac7f7fdf699": "stopped", + "01a21ed27e897ba19eba4c3b3093126d": "stopped", + "01a21ed27e9379e3831640c51caf5f7a": "stopped", + "01a21ed27ea270008ef42324ca91b333": "stopped", + "01a21ed27e9472d3930a123edde8b2fd": "stopped", + "01a21ed27ed57222bce4b3537264e29c": "stopped", + "01a21ed27ea674d1bb4f93ccf3f84df2": "stopped", + "01a21ed27ed07ea180078e4a1d81fc24": "stopped", + "01a21ed27eb37ea3ac2277d337e6fad9": "stopped", + "01a21ed27ed07f63aa4a193a340243bd": "stopped", + "01a21ed27ed070408f8bd458009ab441": "stopped", + "01a21ed27ed27ba1ae1e97b2320d6264": "stopped" + } + }, + { + "name": "stop: the queue is empty, the sink is off, Pending read 0 the moment Stop returned", + "ok": true, + "detail": [ + [], + "{'FINISHED'}", + 0 + ] + }, + { + "name": "stop: exactly the accepted intents ran and the stopped ones left no object", + "ok": true, + "detail": [ + 2, + 2 + ] + }, + { + "name": "stop: each accepted intent is one labelled undo step the receipt names", + "ok": true, + "detail": [ + "Brokkr nibu/hands: createObject 0116e4e8", + "Brokkr nibu/hands: createObject e58a845e" + ] + }, + { + "name": "stop: stopped receipts say who, what and why, and never carry an undo label", + "ok": true, + "detail": [ + "Stopped (stopped by the operator); the intent was " + ] + }, + { + "name": "stop: brokkr-ctl wait exits 0 for accepted and the distinct 3 for stopped", + "ok": true, + "detail": [ + [ + "accepted", + 0 + ], + [ + "stopped", + 3 + ] + ] + }, + { + "name": "stop: brokkr-ctl status now reads agentCommandsEnabled: false", + "ok": true, + "detail": "observedAt: 2026-11-27T21:04:01.582528+00:00\nblenderVersion: 5.3.0\nprojectPath: \nmode: OBJECT\nactiveScene: Scene\nactiveObjectName: B01\nselectedObjectNames: [\"B01\"]\nobjectCount: 5\nagentCommandsEnabled: false\n" + }, + { + "name": "sink off: a send after Stop is answered stopped at once (wait exit 3, 'agent commands are off'), nothing queued", + "ok": true, + "detail": [ + 3, + 0.6054728031158447, + "commandId: 01a21ed2867e7733982b0eaf93547dcc\naction: createObject\ncommandId: 01a21ed2867e7733982b0eaf93547dcc\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T21:04:03.327292+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + ] + }, + { + "name": "re-enable: nothing queued fires; the late intent never runs", + "ok": true, + "detail": [ + [], + [], + 0 + ] + }, + { + "name": "stop + Ctrl+Z: one undo takes back the last agent step, nothing else", + "ok": true, + "detail": [ + 2, + 1 + ] + }, + { + "name": "panel mid-burst: Agents is first under Stop, the agent is active, accepted receipts show note and undo label, each once", + "ok": true, + "detail": "Agents\nAgent commands: on\nActive: nibu/hands\nPending: 18\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject e58a845e\nnibu/hands createObject accepted\n burst\n Brokkr nibu/hands: createObject 0116e4e8\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: stopped\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 3\nMaterials: 2\nSelected: 1" + }, + { + "name": "panel after Stop: Stop agents is the first operator drawn", + "ok": true, + "detail": [ + "brokkr.stop_agents", + "brokkr.capture_snapshot", + "brokkr.drain_commands" + ] + }, + { + "name": "panel after Stop: commands off, pending 0, the stopped receipts listed with who and what", + "ok": true, + "detail": "Agents\nAgent commands: off\nActive: nibu/hands\nPending: 0\nnibu/hands createObject stopped\n late\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nnibu/hands createObject stopped\n burst\nProvider: brokkr.blender_editor\nTool: blender-editor\nBroker: cultmesh://brokkr\nNode: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp\nServer: stopped\nObject Sync\nTimeline / Cinemachine\nAd Hoc Sync Var\nObjects: 4\nMaterials: 2\nSelected: 1" + }, + { + "name": "server stop: three intents queued behind a running server, sink on", + "ok": true, + "detail": 3 + }, + { + "name": "server stop: the same path gives each a stopped receipt naming 'server stopped'", + "ok": true, + "detail": [ + "Stopped (server stopped); the intent was not run and nothing was changed." + ] + }, + { + "name": "server start: intents queued while stopped get stopped receipts naming 'server started', wait exits 3", + "ok": true, + "detail": [ + [ + 3, + 3 + ], + [ + "Stopped (server started); the intent was not run and nothing was changed." + ] + ] + }, + { + "name": "no add-on drain error", + "ok": true, + "detail": "" + } + ], + "notes": { + "states": { + "01a21ed27e2e74e1b8e725800116e4e8": "accepted", + "01a21ed27e347fc1a9335eece58a845e": "accepted", + "01a21ed27e51773392985e0e1859abec": "stopped", + "01a21ed27e6d7b53a39ad7e8d7316c8b": "stopped", + "01a21ed27e6f78c1a05ed37723e2b309": "stopped", + "01a21ed27e6d76f1bb533bed0a748a13": "stopped", + "01a21ed27e6d7c1092c429ea773c8fc1": "stopped", + "01a21ed27e6f7d33a2055b67edc92f18": "stopped", + "01a21ed27e8272e195d68ac7f7fdf699": "stopped", + "01a21ed27e897ba19eba4c3b3093126d": "stopped", + "01a21ed27e9379e3831640c51caf5f7a": "stopped", + "01a21ed27ea270008ef42324ca91b333": "stopped", + "01a21ed27e9472d3930a123edde8b2fd": "stopped", + "01a21ed27ed57222bce4b3537264e29c": "stopped", + "01a21ed27ea674d1bb4f93ccf3f84df2": "stopped", + "01a21ed27ed07ea180078e4a1d81fc24": "stopped", + "01a21ed27eb37ea3ac2277d337e6fad9": "stopped", + "01a21ed27ed07f63aa4a193a340243bd": "stopped", + "01a21ed27ed070408f8bd458009ab441": "stopped", + "01a21ed27ed27ba1ae1e97b2320d6264": "stopped" + }, + "stop_reasons": [ + "Stopped (stopped by the operator); the intent wa" + ], + "wait_exits": { + "01a21ed27e2e74e1b8e725800116e4e8": [ + "accepted", + 0 + ], + "01a21ed27e347fc1a9335eece58a845e": [ + "accepted", + 0 + ], + "01a21ed27e51773392985e0e1859abec": [ + "stopped", + 3 + ], + "01a21ed27e6d7b53a39ad7e8d7316c8b": [ + "stopped", + 3 + ], + "01a21ed27e6f78c1a05ed37723e2b309": [ + "stopped", + 3 + ], + "01a21ed27e6d76f1bb533bed0a748a13": [ + "stopped", + 3 + ], + "01a21ed27e6d7c1092c429ea773c8fc1": [ + "stopped", + 3 + ], + "01a21ed27e6f7d33a2055b67edc92f18": [ + "stopped", + 3 + ], + "01a21ed27e8272e195d68ac7f7fdf699": [ + "stopped", + 3 + ], + "01a21ed27e897ba19eba4c3b3093126d": [ + "stopped", + 3 + ], + "01a21ed27e9379e3831640c51caf5f7a": [ + "stopped", + 3 + ], + "01a21ed27ea270008ef42324ca91b333": [ + "stopped", + 3 + ], + "01a21ed27e9472d3930a123edde8b2fd": [ + "stopped", + 3 + ], + "01a21ed27ed57222bce4b3537264e29c": [ + "stopped", + 3 + ], + "01a21ed27ea674d1bb4f93ccf3f84df2": [ + "stopped", + 3 + ], + "01a21ed27ed07ea180078e4a1d81fc24": [ + "stopped", + 3 + ], + "01a21ed27eb37ea3ac2277d337e6fad9": [ + "stopped", + 3 + ], + "01a21ed27ed07f63aa4a193a340243bd": [ + "stopped", + 3 + ], + "01a21ed27ed070408f8bd458009ab441": [ + "stopped", + 3 + ], + "01a21ed27ed27ba1ae1e97b2320d6264": [ + "stopped", + 3 + ] + }, + "late": { + "exit": 3, + "seconds": 0.61, + "out": "commandId: 01a21ed2867e7733982b0eaf93547dcc\naction: createObject\ncommandId: 01a21ed2867e7733982b0eaf93547dcc\nmessage: Stopped (agent commands are off); the intent was not run and nothing was changed.\nnote: late\nobjectName: \nobservedAt: 2026-11-27T21:04:03.327292+00:00\nrequestedBy: nibu/hands\nschema: brokkr.blender.command_receipt.v0\nstatus: stopped\nundoLabel: \n" + }, + "panel_before_stop": [ + "Agents", + "Agent commands: on", + "Active: nibu/hands", + "Pending: 18", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject e58a845e", + "nibu/hands createObject accepted", + " burst", + " Brokkr nibu/hands: createObject 0116e4e8", + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: stopped", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 3", + "Materials: 2", + "Selected: 1" + ], + "panel_labels": [ + "Agents", + "Agent commands: off", + "Active: nibu/hands", + "Pending: 0", + "nibu/hands createObject stopped", + " late", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "nibu/hands createObject stopped", + " burst", + "Provider: brokkr.blender_editor", + "Tool: blender-editor", + "Broker: cultmesh://brokkr", + "Node: F:\\aeth-wt\\live3-proof\\scratch\\stop.ccmp", + "Server: stopped", + "Object Sync", + "Timeline / Cinemachine", + "Ad Hoc Sync Var", + "Objects: 4", + "Materials: 2", + "Selected: 1" + ] + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_action_table.py b/surfaces/blender/tests/test_action_table.py new file mode 100644 index 0000000..af2938b --- /dev/null +++ b/surfaces/blender/tests/test_action_table.py @@ -0,0 +1,287 @@ +"""The action table: the parity fixture, handler coverage, and the table's own load checks. No Blender.""" +from __future__ import annotations + +import copy +import json +import re +import unittest +from pathlib import Path +from unittest import mock + +import test_scene_actions as ts + +at = ts.at +bt = ts.bt +na = ts.bt.na +CASES = json.loads((Path(__file__).with_name("action_cases.json")).read_text(encoding="utf-8")) +HOST_FILE = json.loads((Path(__file__).parent / "fixtures" / "brokkr_host_fixture" / "brokkr_actions.json").read_text(encoding="utf-8")) +HOST_CASES = json.loads((Path(__file__).with_name("host_action_cases.json")).read_text(encoding="utf-8")) + + +def validate(action, fields): + try: + at.validate({"action": action, **fields}) + except at.IntentInvalid as error: + return str(error) + return "ok" + + +class HostTableTests(unittest.TestCase): + """A host add-on's brokkr_actions.json adds rows; the same messages as for built-ins.""" + + def charsets(self): + return at.table()["charsets"] + + def host_file(self, **row): + base = copy.deepcopy(HOST_FILE) + base["actions"][0].update(row) + return base + + def test_the_fixture_file_is_admitted(self): + at.check_host(HOST_FILE, self.charsets()) + + def wrong_cases(self): + wrong = [] + for case in HOST_CASES: + try: + at.validate({"action": case["action"], **case["fields"]}, HOST_FILE["actions"]) + got = "ok" + except at.IntentInvalid as error: + got = str(error) + if got != case["expect"]: + wrong.append((case["action"], case["fields"], case["expect"], got)) + return wrong + + def test_every_host_case_yields_exactly_its_expected_message_or_ok(self): + self.assertEqual(self.wrong_cases(), []) + + def test_a_mutant_that_skips_host_rows_or_lets_an_undeclared_field_through_fails_a_case(self): + original = at.entry + with mock.patch.object(at, "entry", lambda action, host=(): original(action)): + self.assertTrue(self.wrong_cases()) + with mock.patch.object(at, "_fields", lambda *args: None): + self.assertTrue(self.wrong_cases()) + + def test_check_host_refuses_non_scalar_fields_bad_names_and_foreign_keys(self): + field = {"name": "f", "type": "array", "items": {"type": "number", "minimum": 0, "maximum": 1}} + for bad, why in ( + (self.host_file(fields=[field]), "array"), + (self.host_file(fields=[{"name": "f", "type": "object"}]), "object"), + (self.host_file(fields=[{"name": "f", "type": "any"}]), "any"), + (self.host_file(name="undotted"), "undotted"), + (self.host_file(name="Upper.case"), "uppercase"), + (self.host_file(fields=[{"name": "f", "type": "string", "chars": "nope"}]), "charset"), + (self.host_file(result="not an identifier"), "result"), + (self.host_file(fields=[{"name": "f", "type": "number"}]), "unbounded"), + ({**HOST_FILE, "envelope": []}, "envelope key"), + ({**HOST_FILE, "charsets": {}}, "charsets key"), + ({**HOST_FILE, "schema": at.SCHEMA}, "schema"), + ): + with self.assertRaises(at.TableInvalid, msg=why): + at.check_host(bad, self.charsets()) + for key in ("note", "action", "commandId", "requestedBy", "schema"): # Brokkr writes these: the operator would never receive the agent's value + with self.assertRaises(at.TableInvalid, msg=key): + at.check_host(self.host_file(fields=[{"name": key, "type": "string"}]), self.charsets()) + with self.assertRaises(at.TableInvalid): + at.check_host(self.host_file(unknown=1), self.charsets()) + with self.assertRaises(at.TableInvalid): + at.check_host(self.host_file(fields=[{"name": "a", "type": "string"}, {"name": "b", "type": "string", "only": {"field": "a", "in": ["x"]}}]), self.charsets()) + twice = copy.deepcopy(HOST_FILE) + twice["actions"].append(copy.deepcopy(twice["actions"][0])) + with self.assertRaises(at.TableInvalid): + at.check_host(twice, self.charsets()) + + def test_a_host_row_never_shadows_a_built_in(self): + shadow = [{"name": "createObject", "doc": "", "changesScene": True, "editModeSafe": True, "fields": []}] + self.assertIs(at.entry("createObject", shadow), at.entry("createObject")) + self.assertEqual(at.entry("brokkr_host_fixture.report", HOST_FILE["actions"])["name"], "brokkr_host_fixture.report") + self.assertIsNone(at.entry("brokkr_host_fixture.report")) + self.assertTrue(all("." not in a["name"] for a in at.table()["actions"])) + + +class ParityFixtureTests(unittest.TestCase): + """action_cases.json is also run by brokkr-ctl's actions.rs: one table, two interpreters, one set of messages.""" + + def test_every_case_yields_exactly_its_expected_message_or_ok(self): + wrong = [(c["action"], c["fields"], c["expect"], validate(c["action"], c["fields"])) + for c in CASES if validate(c["action"], c["fields"]) != c["expect"]] + self.assertEqual(wrong, []) + + def test_the_fixture_covers_every_rule_kind_and_every_number_field(self): + text = json.dumps(CASES) + for needle in ("is required.", "has no field", "must be one of", "must be between", "must have at least", "must have at most", + "may contain only", "must start with one of", "may not contain", "applies only when", "Unsupported Blender"): + self.assertIn(needle, text) + for action in at.table()["actions"]: + for field in action["fields"]: + if field["type"] in ("number", "integer") or field.get("items", {}).get("type") == "number": + pins = [c for c in CASES if c["action"] == action["name"] and field["name"] in c["fields"] + and c["expect"].startswith(f"{field['name']}") and "must be between" in c["expect"]] + self.assertGreaterEqual(len(pins), 2, f"{action['name']}.{field['name']}: both bounds") + self.assertTrue(any(c["action"] == action["name"] and c["expect"] == "ok" for c in CASES), action["name"]) + + def test_validate_normalizes_null_to_absent_and_fills_defaults(self): + normal = at.validate({"action": "createObject", "objectType": None, "location": None, "note": "n"}) + self.assertEqual(normal["objectType"], "EMPTY") + self.assertEqual((normal["size"], normal["lightType"], normal["emptyDisplayType"]), (1, "POINT", "PLAIN_AXES")) + self.assertNotIn("location", normal) + self.assertEqual(normal["note"], "n") + self.assertEqual(at.validate({"action": "setLight", "targetObjectName": "L"}).get("lightType"), None) # no default: absent stays absent + + def test_a_mutant_validator_fails_the_fixture(self): + """The fixture pins the rules: casefolding enums, widening a bound or letting bool pass as a number each break cases.""" + original = at._value + + def casefolded(spec, value, path): + if "enum" in spec and isinstance(value, str): + value = next((e for e in spec["enum"] if e.lower() == value.lower()), value) + return original(spec, value, path) + + for mutant in (casefolded,): + with mock.patch.object(at, "_value", mutant): + self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], []) + number = at._number + + def widened(spec, value, path): + return number({**spec, "maximum": spec["maximum"] * 10 + 10}, value, path) + + def boolish(spec, value, path): + return number(spec, int(value) if isinstance(value, bool) else value, path) + + for mutant in (widened, boolish): + with mock.patch.object(at, "_number", mutant): + self.assertNotEqual([c for c in CASES if validate(c["action"], c["fields"]) != c["expect"]], [], mutant.__name__) + + +class NormalizationTests(unittest.TestCase): + def test_a_whole_float_for_an_integer_field_reaches_the_handler_as_an_int(self): + normal = at.validate({"action": "renderStill", "outputPath": "a.png", "resolutionX": 1920.0, "resolutionY": 4.0}) + self.assertEqual((normal["resolutionX"], normal["resolutionY"]), (1920, 4)) + self.assertIs(type(normal["resolutionX"]), int) + + def test_validate_never_raises_whatever_the_document_holds(self): + """A store writer outside brokkr-ctl can put anything in an intent; the drain has already claimed it, so a raise + here would lose the intent without a receipt. Every hostile shape ends as ok or IntentInvalid.""" + hostile = [ + {"action": "createObject", 1: "a", "zz": "b"}, + {"action": "createObject", (1, 2): 1, None: 2, "zz": 3}, + {"action": "createNodeGroup", "treeKey": "G", "interface": [{1: "a", "name": "x", "inOut": "INPUT", "type": "Int"}]}, + {"action": "createNodeGroup", "treeKey": "G", "interface": [{"inOut": "INPUT", "name": "x", "type": "Int", 5: 6, None: 7}]}, + {"action": ["createObject"]}, {"action": {"a": 1}}, {"action": None}, {"action": 7}, {}, + {"action": "createObject", "location": [10 ** 400, float("nan"), float("inf")]}, + {"action": "renderStill", "outputPath": b"bytes", "resolutionX": 10 ** 400}, + {"action": "renderStill", "outputPath": "a.png", "resolutionX": float("inf")}, + {"action": "addNode", "treeKey": "G", "id": "a", "blIdname": "ShaderNodeMath", "properties": {1: 2, (3,): 4}}, + {"action": "createObject", "objectType": ["MESH"]}, {"action": "createObject", "objectType": {"a": 1}}, + {"action": "setObjectCustomProperty", "targetObjectName": "c", "value": object()}, + ] + for command in hostile: + try: + at.validate(command) + except at.IntentInvalid: + pass + except Exception as error: # noqa: BLE001 + self.fail(f"{command!r} raised {error!r}") + + +class HandlerCoverageTests(unittest.TestCase): + def test_each_table_action_resolves_to_exactly_one_handler_and_each_handler_has_an_entry(self): + names = [a["name"] for a in at.table()["actions"]] + self.assertEqual(len(names), len(set(names))) + target = bt.BrokkrBlenderTarget + for name in names: + owners = [owner for owner in (target, na.NodeActions) if hasattr(owner, "_" + name)] + self.assertEqual(len(owners), 1, f"{name}: handlers {owners}") + camel = re.compile(r"_[a-z]+[A-Z][A-Za-z0-9]*") # every other private name of both classes is snake_case + handlers = {n[1:] for owner in (target, na.NodeActions) for n in vars(owner) if camel.fullmatch(n)} | {"look"} + self.assertEqual(sorted(handlers - set(names)), [], "a handler without a table entry") + self.assertEqual(sorted(set(names) - handlers), [], "a table entry without a handler") + + def test_node_socket_types_are_the_tables(self): + spec = next(a for a in at.table()["actions"] if a["name"] == "createNodeGroup") + interface = next(f for f in spec["fields"] if f["name"] == "interface") + kinds = next(p for p in interface["items"]["properties"] if p["name"] == "type")["enum"] + self.assertEqual(sorted(kinds), sorted(na.SOCKET_TYPES)) + + def test_removing_an_entry_makes_the_action_unsupported(self): + trimmed = copy.deepcopy(at.table()) + trimmed["actions"] = [a for a in trimmed["actions"] if a["name"] != "deleteObject"] + with mock.patch.object(at, "table", return_value=trimmed), mock.patch.object(at, "_by_name", return_value={a["name"]: a for a in trimmed["actions"]}): + self.assertEqual(validate("deleteObject", {"targetObjectName": "c"}), "Unsupported Blender command action: deleteObject") + + def test_undo_and_edit_mode_classes_are_the_tables(self): + rows = {a["name"]: a for a in at.table()["actions"]} + self.assertEqual(sorted(n for n, a in rows.items() if not a["changesScene"]), ["exportGltf", "look", "renderStill"]) + self.assertEqual(sorted(n for n, a in rows.items() if a["editModeSafe"]), ["look", "renderStill"]) + + +class TableCheckTests(unittest.TestCase): + def table(self): + return copy.deepcopy(at.table()) + + def test_an_unbounded_number_field_is_refused_at_load(self): + broken = self.table() + del next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "lens")["maximum"] + with self.assertRaisesRegex(at.TableInvalid, "lens.*maximum"): + at.check_table(broken) + broken = self.table() + del next(f for a in broken["actions"] if a["name"] == "createObject" for f in a["fields"] if f["name"] == "location")["items"]["minimum"] + with self.assertRaisesRegex(at.TableInvalid, "minimum"): + at.check_table(broken) + + def test_an_only_naming_a_missing_field_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "lightType" and "only" in f)["only"]["field"] = "nope" + with self.assertRaisesRegex(at.TableInvalid, "only"): + at.check_table(broken) + + def test_an_unknown_charset_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f.get("chars") == "key")["chars"] = "nope" + with self.assertRaisesRegex(at.TableInvalid, "charset"): + at.check_table(broken) + + def test_a_default_that_breaks_its_own_field_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "objectType")["default"] = "TEXT" + with self.assertRaisesRegex(at.TableInvalid, "default"): + at.check_table(broken) + + def test_a_bound_that_prints_differently_in_python_and_rust_is_refused(self): + broken = self.table() + next(f for a in broken["actions"] for f in a["fields"] if f["name"] == "clipStart")["minimum"] = 1e-7 + with self.assertRaisesRegex(at.TableInvalid, "plain digits"): + at.check_table(broken) + + +class AdmissionTests(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def test_a_table_refusal_is_denied_pushes_no_undo_step_and_calls_no_operator(self): + for fields in ({"action": "createObject", "bogus": 1}, {"action": "createObject", "objectType": "mesh"}, + {"action": "renderStill", "outputPath": "a.png", "resolutionX": 2}, + {"action": "setObjectTransform", "objectName": "Cube", "location": [0, 0, 1]}): + receipt = self.run_action(**fields) + self.assertEqual(receipt["status"], "denied", fields) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual((self.bpy.created, self.bpy.undo.pushes, self.bpy.rendered), ([], [], [])) + self.assertEqual(self.bpy.mesh.__dict__.get("location"), None) + + def test_the_unknown_action_message_and_the_order_of_admission(self): + self.assertEqual(self.run_action(action="runPython")["message"], "Unsupported Blender command action: runPython") + self.bpy.mesh.mode = "EDIT" + receipt = self.run_action(action="createObject", objectType="mesh") # invalid fields are named before the mode + self.assertNotIn("Edit Mode", receipt["message"]) + receipt = self.run_action(action="createObject", objectType="EMPTY") + self.assertIn("Edit Mode", receipt["message"]) + + def test_defaults_reach_the_handler(self): + self.assertEqual(self.run_action(action="createObject", objectType="MESH")["status"], "accepted") + self.assertEqual(self.bpy.created[-1][1]["size"], 1.0) + self.assertEqual(self.run_action(action="createObject", objectType="LIGHT")["status"], "accepted") + self.assertEqual(self.bpy.created[-1][1]["type"], "POINT") + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_addon_ui.py b/surfaces/blender/tests/test_addon_ui.py index 04e97d3..2240371 100644 --- a/surfaces/blender/tests/test_addon_ui.py +++ b/surfaces/blender/tests/test_addon_ui.py @@ -32,7 +32,7 @@ def load_addon(): fake = types.ModuleType("bpy") fake.types = NS(AddonPreferences=Base, Panel=Base, Operator=Base) fake.props = props - fake.app = NS(handlers=NS(depsgraph_update_post=[]), timers=NS(is_registered=lambda f: False)) + fake.app = NS(handlers=NS(depsgraph_update_post=[], persistent=lambda f: setattr(f, "persistent", True) or f), timers=NS(is_registered=lambda f: False)) fake.utils = NS() previous = sys.modules.get("bpy") sys.modules["bpy"] = fake @@ -113,6 +113,37 @@ class CopyOperatorTests(unittest.TestCase): self.assertIn(addon.BROKKR_OT_copy_session_token, addon.classes) +class ReloadHostActionsTests(unittest.TestCase): + """The panel's Reload Host Actions button is the human's: it reads the files; it refuses inside an agent turn.""" + + def press(self, target): + operator = addon.BROKKR_OT_reload_host_actions() + operator.reported = None + with mock.patch.object(addon, "_target", target): + return operator.execute(None), operator.reported + + def test_pressed_it_reloads_and_reports_the_counts(self): + target = bt.BrokkrBlenderTarget(NS()) + target.reload_host_actions = mock.Mock(return_value=2) + target.host_actions = mock.Mock(return_value=([{"name": "a.b"}], [])) + result, reported = self.press(target) + self.assertEqual(result, {"FINISHED"}) + target.reload_host_actions.assert_called_once_with() + self.assertIn("2 host file(s) read; 1 host action(s) admitted", reported[1]) + + def test_inside_an_agent_turn_it_refuses_and_reads_nothing(self): + target = bt.BrokkrBlenderTarget(NS()) + target.agent_turn = True + target._host_docs = {"kept": {}} + result, reported = self.press(target) + self.assertEqual((result, reported[0]), ({"CANCELLED"}, {"ERROR"})) + self.assertEqual(target._host_docs, {"kept": {}}) + + def test_it_is_registered_and_drawn_in_the_panel(self): + self.assertIn(addon.BROKKR_OT_reload_host_actions, addon.classes) + self.assertIn("brokkr.reload_host_actions", (ADDON / "__init__.py").read_text(encoding="utf-8")) + + class PanelTests(unittest.TestCase): def test_the_panel_never_draws_the_token(self): target = running_target() diff --git a/surfaces/blender/tests/test_agent_turn.py b/surfaces/blender/tests/test_agent_turn.py new file mode 100644 index 0000000..17b80e3 --- /dev/null +++ b/surfaces/blender/tests/test_agent_turn.py @@ -0,0 +1,748 @@ +"""run_intent: admission, one labelled undo step, receipts. A fake bpy records ops calls.""" +from __future__ import annotations + +import json +import re +import sys +import tempfile +import unittest +import unittest.mock +from pathlib import Path + +import test_scene_actions as ts + +bt = ts.bt +at = ts.at +SOURCE = Path(bt.__file__) + + +class AgentTurnTests(unittest.TestCase): + """Reuses the scene fixture (fake bpy, temp import/output dirs).""" + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def test_intent_without_requested_by_is_denied(self): + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.undo.pushes, []) + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="nibu") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_object_intent_is_refused_while_an_object_is_in_edit_mode(self): + self.bpy.mesh.mode = "EDIT" + receipt = self.run_action(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5]) + self.assertEqual(receipt["status"], "denied") + self.assertIn("Edit Mode", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.mesh.mode, "EDIT") # the agent never changes her mode + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + self.bpy.mesh.mode = "OBJECT" + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + + def test_unknown_action_is_denied(self): + self.assertEqual(self.run_action(action="runPython")["status"], "denied") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_reused_command_id_is_denied(self): + first = self.run_action(action="createObject", objectType="EMPTY", commandId="same-id-1") + self.assertEqual(first["status"], "accepted") + second = self.run_action(action="createObject", objectType="EMPTY", commandId="same-id-1") + self.assertEqual(second["status"], "denied") + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(len(self.bpy.undo.pushes), 1) + + def test_accepted_receipt_carries_undo_label(self): + receipt = self.run_action(action="createObject", objectType="EMPTY", + commandId="abcdef0123456789", requestedBy="nibu/hands", note="x" * 300) + label = "Brokkr nibu/hands: createObject 23456789" # the id's tail: uuid v7 ids lead with a timestamp + self.assertEqual(self.bpy.undo.pushes, [label]) + self.assertEqual(receipt["undoLabel"], label) + self.assertEqual(receipt["requestedBy"], "nibu/hands") + self.assertEqual(len(receipt["note"]), 200) + + def test_two_sends_a_minute_apart_get_distinct_labels(self): + # brokkr-ctl ids are uuid v7: the first 8 hex are one value per 65 seconds, the tail is random + self.run_action(action="createObject", objectType="EMPTY", commandId="01a21e88" + "0" * 16 + "aaaa1111") + self.run_action(action="createObject", objectType="EMPTY", commandId="01a21e88" + "0" * 16 + "bbbb2222") + self.assertEqual(len(set(self.bpy.undo.pushes)), 2, self.bpy.undo.pushes) + + def test_architecture_page_does_not_call_the_debug_json_an_import_path(self): + page = (SOURCE.parents[3] / "docs" / "architecture.md").read_text(encoding="utf-8") + for line in page.splitlines(): + if "debug" in line.lower() and "json" in line.lower(): + self.assertNotRegex(line.lower(), r"import", line) + + def test_refusal_pushes_nothing(self): + receipt = self.run_action(action="createObject", objectType="BOGUS") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + receipt = self.run_action(action="deleteObject", targetObjectName="Nope") # a scene refusal: ran, failed, no step + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_read_action_pushes_nothing(self): + self.assertNotEqual(self.run_action(action="look")["status"], "denied") # admitted; the fake has no 3D view to capture + self.assertEqual(self.bpy.undo.pushes, []) + + def test_raise_after_admission_pushes_failed_step(self): + def boom(*a, **kw): + raise RuntimeError("half done") + self.bpy.ops.object.empty_add = boom + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="deadbeef99") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, ["Brokkr nibu/hands: createObject adbeef99 (failed)"]) + + def test_agent_turn_flag_is_scoped(self): + seen = [] + original = self.bpy.ops.object.empty_add + self.bpy.ops.object.empty_add = lambda *a, **kw: (seen.append(self.target.agent_turn), original(*a, **kw))[1] + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(seen, [True]) + self.assertFalse(self.target.agent_turn) + + def test_operators_called_with_undo_false(self): + self.assertEqual(self.run_action(action="exportGltf", filepath="o.glb")["status"], "accepted") + self.assertEqual(self.run_action(action="importGltf", filepath="model.glb")["status"], "accepted") + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + for kind in ("MESH", "LIGHT", "CAMERA", "EMPTY"): + self.assertEqual(self.run_action(action="createObject", objectType=kind)["status"], "accepted") + # the fake ops assert ("EXEC_DEFAULT", False); the source pattern pins the spelling too + bad = re.findall(r'bpy\.ops\.(?:mesh|object|import_scene|export_scene|render)\.[a-z_]+\((?!"EXEC_DEFAULT", False)', + SOURCE.read_text(encoding="utf-8")) + self.assertEqual(bad, []) + + # fix batch s1 + def test_world_and_export_are_refused_in_edit_mode_render_is_not(self): + self.bpy.mesh.mode = "EDIT" + for action, fields in (("setWorld", {}), ("exportGltf", {"filepath": "o.glb"})): + receipt = self.run_action(action=action, **fields) + self.assertEqual(receipt["status"], "denied", action) + self.assertIn("Edit Mode", receipt["message"]) + self.assertEqual(self.bpy.exported, []) + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES")["status"], "accepted") + + def test_export_and_render_push_no_undo_step(self): + self.assertEqual(self.run_action(action="exportGltf", filepath="o.glb")["status"], "accepted") + receipt = self.run_action(action="renderStill", outputPath="r.png", engine="CYCLES") + self.assertEqual(receipt["status"], "accepted") + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_returned_failed_receipt_pushes_nothing(self): + receipt = self.run_action(action="setObjectTransform", targetObjectName="NoSuchObject", location=[1, 2, 3]) + self.assertEqual(receipt["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_denied_id_is_recorded_as_receipted(self): + self.bpy.mesh.mode = "EDIT" + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY", commandId="denied-1")["status"], "denied") + self.bpy.mesh.mode = "OBJECT" + again = self.run_action(action="createObject", objectType="EMPTY", commandId="denied-1") + self.assertEqual(again["status"], "denied") + self.assertIn("single-use", again["message"]) + self.assertEqual(self.bpy.created, []) + + def test_undo_push_runs_under_the_first_window(self): + self.run_action(action="createObject", objectType="EMPTY") + self.assertEqual(self.bpy.undo.overrides, [{"window": self.bpy.undo.window}]) + + def test_push_failure_is_a_failed_receipt_and_never_reruns(self): + def broken(message): + raise RuntimeError("no undo stack") + self.bpy.ops.ed.undo_push = broken + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="push-fail-1") + self.assertEqual(receipt["status"], "failed") + self.assertIn("no undo stack", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + again = self.run_action(action="createObject", objectType="EMPTY", commandId="push-fail-1") + self.assertEqual(again["status"], "denied") + self.assertEqual(len(self.bpy.created), 1) + + # fix batch s2 + def test_no_scene_change_set_is_exactly_export_and_render(self): + self.assertEqual([a["name"] for a in at.table()["actions"] if not a["changesScene"]], ["exportGltf", "renderStill", "look"]) + receipt = self.run_action(action="setWorld", color=[0.1, 0.2, 0.3]) + self.assertEqual(receipt["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 1) + + def test_malformed_command_ids_are_denied_without_raising(self): + for bad in (["x"], 7, 1.5, {"a": 1}, "", "a/b", "x.denied", "has space", "a" * 200, None, True): + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId=bad) + self.assertEqual(receipt["status"], "denied", repr(bad)) + self.assertIsInstance(receipt["commandId"], str) + self.assertRegex(receipt["commandId"], bt.COMMAND_ID_SHAPE.pattern, repr(bad)) + self.assertEqual(self.bpy.created, []) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_trailing_newline_does_not_pass_the_id_shapes(self): + self.assertFalse(bt._valid_command_id("okid\n")) + receipt = self.run_action(action="createObject", objectType="EMPTY", commandId="okid\n") + self.assertEqual(receipt["status"], "denied") + receipt = self.run_action(action="createObject", objectType="EMPTY", requestedBy="nibu/hands\n") + self.assertEqual(receipt["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_load_cultmesh_pins_its_own_package_set(self): + # an unrelated module named like a CultLib package is a missing dependency, not "CultLib is absent" + self.assertEqual(bt.CULTLIB_PY_PACKAGES, ("cultcache-py", "cultnet-py", "cultmesh-py")) + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) + src = root / "cultmesh-py" / "src" / "cultmesh_py" + src.mkdir(parents=True) + (src / "__init__.py").write_text("import cultnet_py") # an own package that is absent here + saved = {k: sys.modules.pop(k) for k in ("cultmesh_py", "cultcache_py", "cultnet_py") if k in sys.modules} + saved_path = list(sys.path) + self.addCleanup(lambda: (sys.modules.update(saved), sys.path.__setitem__(slice(None), saved_path))) + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh(str(root)) + self.assertIn("requires CultLib's Python packages", str(caught.exception)) + + def test_debug_command_file_is_not_executed(self): + with tempfile.TemporaryDirectory() as tmp: + commands = Path(tmp) / "blender" / "commands" + commands.mkdir(parents=True) + door = commands / "door-1.json" + door.write_text('{"commandId": "door-1", "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY"}') + node = FakeNode({}) + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, docs)): + receipts = self.target.drain_commands(self.context, "cache", "src", tmp) + self.assertEqual(receipts, []) + self.assertEqual(node.puts, []) + self.assertEqual(self.bpy.created, []) + self.assertTrue(door.exists()) + + def test_load_cultmesh_names_the_missing_module(self): + root = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(root, ignore_errors=True)) + src = root / "cultmesh-py" / "src" / "cultmesh_py" + src.mkdir(parents=True) + (src / "__init__.py").write_text("import brokkr_no_such_dependency_xyz") + saved = {k: sys.modules.pop(k) for k in ("cultmesh_py", "cultcache_py") if k in sys.modules} + saved_path = list(sys.path) + self.addCleanup(lambda: (sys.modules.update(saved), sys.path[:] == saved_path or sys.path.__setitem__(slice(None), saved_path))) + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh(str(root)) + self.assertIn("brokkr_no_such_dependency_xyz", str(caught.exception)) + self.assertNotIn("requires CultLib's Python packages", str(caught.exception)) + + +FIXTURE = Path(__file__).parent / "fixtures" / "brokkr_host_fixture" +HOST = "brokkr_host_fixture" +NS = ts.NS + + +def types_module(name, file): + import types + module = types.ModuleType(name) + module.__file__ = str(file) + return module + + +class HostOp: + """bpy.ops..: callable with idname() and get_rna_type(), recording its calls.""" + + def __init__(self, name, props, behave): + self.cls = type(f"BROKKR_HOST_FIXTURE_OT_{name}", (), {"__module__": HOST}) + self.props = props + self.behave = behave + self.calls = [] + self.pollable = True + + def poll(self): + return self.pollable + + def idname(self): + return self.cls.__name__ + + def get_rna_type(self): + return NS(properties=self.props) + + def __call__(self, mode, undo, **kwargs): + assert (mode, undo) == ("EXEC_DEFAULT", False) + self.calls.append(kwargs) + return self.behave(self, kwargs) + + +def prop(identifier, kind, lo=0.0, hi=1e30, enum=()): + return NS(identifier=identifier, type=kind, hard_min=lo, hard_max=hi, enum_items=[NS(identifier=e) for e in enum], is_readonly=False) + + +def raising(error): + def behave(op, kwargs): + raise error + return behave + + +class HostActionTests(unittest.TestCase): + """Host rows from a host add-on's brokkr_actions.json, discovered through a fake bpy, run by run_intent.""" + + def setUp(self): + ts.ActionTests.setUp(self) + self.dir = Path(self.tmp.name) / HOST + self.dir.mkdir() + (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + patch = unittest.mock.patch.dict(sys.modules, {HOST: types_module(HOST, self.dir / "__init__.py")}) + patch.start() + self.addCleanup(patch.stop) + bpy = self.bpy + self.ops = { + "add_empty": HostOp("add_empty", [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 100.0)], self.finish), + "report": HostOp("report", [], self.write_report), + "refuse": HostOp("refuse", [], raising(RuntimeError("Error: the fixture refuses"))), + "cancel": HostOp("cancel", [], lambda op, kw: {"CANCELLED"}), + "apply": HostOp("apply", [], self.finish), + } + bpy.ops.brokkr_host_fixture = NS(**self.ops) + bpy.types = NS(WindowManager=NS(bl_rna=NS(properties={"brokkr_host_fixture_result": NS(type="STRING", is_readonly=False)})), + **{op.idname(): op.cls for op in self.ops.values()}) + bpy.context.preferences.addons = {HOST: object(), "brokkr_bridge": object()} + bpy.context.window_manager.brokkr_host_fixture_result = "stale" + self.report_text = "objects: 3" + self.target.reload_host_actions() # the human's act: the files are read here and nowhere else + + def finish(self, op, kwargs): + return {"FINISHED"} + + def write_report(self, op, kwargs): + self.bpy.context.window_manager.brokkr_host_fixture_result = self.report_text + return {"FINISHED"} + + run_action = ts.ActionTests.run_action + + def send(self, operator, **fields): + return self.run_action(action=f"{HOST}.{operator}", **fields) + + def test_a_changing_host_operator_runs_with_exactly_its_declared_fields_and_is_one_undo_step(self): + receipt = self.send("add_empty", name="E", size=2) + self.assertEqual(receipt["status"], "accepted", receipt) + self.assertEqual(receipt["message"], f"Operator {HOST}.add_empty finished.") + self.assertEqual(receipt["hostResult"], "") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 2}]) + self.assertEqual(len(self.bpy.undo.pushes), 1) + self.assertTrue(self.bpy.undo.pushes[0].startswith("Brokkr nibu/hands: brokkr_host_fixture.add_empty ")) + self.assertEqual(receipt["undoLabel"], self.bpy.undo.pushes[0]) + + def test_the_default_is_filled_and_an_undeclared_field_never_reaches_the_operator(self): + self.assertEqual(self.send("add_empty", name="E")["status"], "accepted") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) + self.ops["add_empty"].calls.clear() + self.assertEqual(self.send("add_empty", name="E", note="why")["status"], "accepted") + self.assertEqual(self.ops["add_empty"].calls, [{"name": "E", "size": 1}]) # the envelope never reaches the operator + self.ops["add_empty"].calls.clear() + self.ops["add_empty"].calls.append({}) + denied = self.send("add_empty", name="E", location=[1, 2, 3]) + self.assertEqual(denied["status"], "denied") + self.assertEqual(len(self.ops["add_empty"].calls), 1) # only the seeded marker: the denied intent ran nothing + + def test_a_non_changing_operator_pushes_no_undo_step_and_returns_its_result(self): + receipt = self.send("report") + self.assertEqual((receipt["status"], receipt["hostResult"]), ("accepted", "objects: 3")) + self.assertEqual(self.bpy.undo.pushes, []) + self.assertEqual(self.run_action(action="createObject")["hostResult"], "") # a built-in's receipt carries the field empty + + def test_the_result_is_cleared_before_the_call_and_capped_after(self): + seen = [] + self.ops["report"].behave = lambda op, kw: (seen.append(self.bpy.context.window_manager.brokkr_host_fixture_result), {"CANCELLED"})[1] + self.assertEqual(self.send("report")["hostResult"], "") + self.assertEqual(seen, [""]) # 'stale' was cleared first + self.ops["report"].behave = self.write_report + self.report_text = "x" * (bt.HOST_RESULT_LIMIT + 50) + text = self.send("report")["hostResult"] + self.assertEqual(text, "x" * bt.HOST_RESULT_LIMIT + " [truncated]") + self.report_text = "y" * bt.HOST_RESULT_LIMIT + self.assertEqual(self.send("report")["hostResult"], "y" * bt.HOST_RESULT_LIMIT) + + def test_cancelled_is_failed_with_no_push(self): + receipt = self.send("cancel") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", f"Operator {HOST}.cancel cancelled; nothing changed.")) + self.ops["add_empty"].behave = lambda op, kw: {"CANCELLED"} + self.assertEqual(self.send("add_empty", name="E")["status"], "failed") + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_conversion_error_is_failed_and_pushes_nothing(self): + self.ops["add_empty"].behave = raising(TypeError('keyword "size" could not be converted')) + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("refused its arguments", receipt["message"]) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_runtime_error_is_failed_with_its_first_line_and_pushes_failed_only_for_a_changing_row(self): + receipt = self.send("refuse") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "Error: the fixture refuses")) + self.assertEqual(self.bpy.undo.pushes, []) + self.ops["add_empty"].behave = raising(RuntimeError("Traceback...\nboom")) + receipt = self.send("add_empty", name="E") + self.assertEqual((receipt["status"], receipt["message"]), ("failed", "boom")) + self.assertEqual(len(self.bpy.undo.pushes), 1) + self.assertTrue(self.bpy.undo.pushes[0].endswith("(failed)")) + + def test_an_operator_left_out_of_the_file_and_a_c_operator_are_unsupported_and_leave_no_trace(self): + for action in (f"{HOST}.apply", "wm.save_mainfile", "brokkr.stop_agents"): + receipt = self.run_action(action=action) + self.assertEqual(receipt["status"], "denied", action) + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertEqual(self.ops["apply"].calls, []) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_a_host_row_is_refused_in_edit_mode_unless_it_is_edit_mode_safe(self): + self.bpy.mesh.mode = "EDIT" + self.assertEqual(self.send("add_empty", name="E")["status"], "denied") + self.assertEqual(self.send("report")["status"], "accepted") + + def test_the_snapshot_lists_the_admitted_rows_with_their_host_and_no_left_out_row(self): + self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0), background=False) + context = NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT") + snapshot = self.target.capture_snapshot(context, True) + names = [row["name"] for row in snapshot["hostActions"]] + self.assertEqual(names, [f"{HOST}.{n}" for n in ("add_empty", "report", "refuse", "cancel")]) + self.assertEqual({row["host"] for row in snapshot["hostActions"]}, {HOST}) + self.assertEqual(snapshot["hostActionErrors"], []) + + def refused(self): + rows, errors = self.target.host_actions() + self.assertEqual(rows, []) + self.assertEqual([e["host"] for e in errors], [HOST]) + self.assertIn("brokkr_actions.json", errors[0]["error"]) + self.assertEqual(self.send("report")["status"], "denied") # none of its rows is admitted + return errors[0]["error"] + + def test_a_row_naming_another_add_ons_operator_refuses_the_whole_file(self): + self.ops["report"].cls.__module__ = "other_addon" + self.assertIn("not an operator defined by", self.refused()) + self.ops["report"].cls.__module__ = HOST + ".sub" + self.assertEqual(len(self.target.host_actions()[0]), 4) # a submodule is its own + + def test_a_c_operator_refuses_the_whole_file(self): + self.bpy.types = NS(**{**vars(self.bpy.types), self.ops["cancel"].idname(): None}) + self.refused() + + def test_rna_disagreement_refuses_the_whole_file(self): + self.ops["add_empty"].props = [prop("name", "STRING")] # size missing + self.assertIn("size is not a property", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "INT", 0, 100)] + self.assertIn("is INT in the operator", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.5, 100.0)] # hard min above the row's 0.1 + self.assertIn("bounds exceed", self.refused()) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 5.0)] # hard max below the row's 10 + self.assertIn("bounds exceed", self.refused()) + + def test_a_result_that_is_not_a_window_manager_string_refuses_the_whole_file(self): + self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"] = NS(type="INT") + self.assertIn("not a writable string property", self.refused()) + self.bpy.types.WindowManager.bl_rna.properties.clear() + self.refused() + + def test_a_malformed_file_refuses_itself_and_a_reload_reads_the_changed_file(self): + path = self.dir / "brokkr_actions.json" + good = path.read_text(encoding="utf-8") + path.write_text(good.replace("host_actions.v0", "host_actions.v9"), encoding="utf-8") + self.target.reload_host_actions() + self.assertIn("schema", self.refused()) + path.write_text(good, encoding="utf-8") + self.target.reload_host_actions() + self.assertEqual(len(self.target.host_actions()[0]), 4) + path.write_text("not json", encoding="utf-8") + self.target.reload_host_actions() + self.refused() + + def listing_apply(self): + path = self.dir / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"].append({"name": f"{HOST}.apply", "doc": "applies", "changesScene": True, "editModeSafe": False, "fields": []}) + path.write_text(json.dumps(document), encoding="utf-8") + + def test_an_edited_file_admits_nothing_until_a_human_reload(self): + self.assertEqual(self.send("apply")["status"], "denied") + self.listing_apply() + for _ in range(3): # the file changed; intents and snapshots come and go + receipt = self.send("apply") + self.assertEqual(receipt["status"], "denied", receipt) + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertNotIn(f"{HOST}.apply", [r["name"] for r in self.target.host_actions()[0]]) + self.assertEqual(self.ops["apply"].calls, []) + self.assertEqual(self.bpy.undo.pushes, []) + self.target.reload_host_actions() # she presses the button + self.assertEqual(self.send("apply")["status"], "accepted") + self.assertEqual(len(self.ops["apply"].calls), 1) + + def test_a_reload_inside_an_agent_turn_is_refused_whatever_asks_for_it(self): + self.target.agent_turn = True + try: + with self.assertRaises(PermissionError): + self.target.reload_host_actions() + finally: + self.target.agent_turn = False + self.assertEqual(self.send("reload_host_actions")["status"], "denied") # not an action at all + self.assertEqual(self.run_action(action="brokkr.reload_host_actions")["status"], "denied") + self.listing_apply() + self.ops["add_empty"].behave = lambda op, kw: self.target.reload_host_actions() # a host operator that tries + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("human only", receipt["message"]) + self.assertEqual(self.send("apply")["status"], "denied") # the attempt re-read nothing + + def test_a_reload_drops_what_the_files_no_longer_say(self): + (self.dir / "brokkr_actions.json").unlink() + self.assertEqual(len(self.target.host_actions()[0]), 4) # until she reloads + self.assertEqual(self.target.reload_host_actions(), 0) + self.assertEqual(self.target.host_actions(), ([], [])) + + def test_disabling_the_add_on_makes_its_action_unsupported_at_the_next_intent(self): + self.assertEqual(self.send("report")["status"], "accepted") + self.bpy.context.preferences.addons.pop(HOST) + receipt = self.send("report") + self.assertEqual(receipt["status"], "denied") + self.assertIn("Unsupported Blender command action", receipt["message"]) + self.assertEqual(self.target.host_actions(), ([], [])) + + def test_an_add_on_without_the_file_is_not_a_host_and_this_add_on_is_never_read(self): + (self.dir / "brokkr_actions.json").unlink() + self.target.reload_host_actions() + self.assertEqual(self.target.host_actions(), ([], [])) + self.bpy.context.preferences.addons["brokkr_bridge"] = object() + self.target.reload_host_actions() + self.assertEqual(self.target.host_actions(), ([], [])) + (self.dir / "brokkr_actions.json").write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + with unittest.mock.patch.object(sys.modules["brokkr_bridge"], "__file__", str(self.dir / "__init__.py"), create=True): + self.bpy.context.preferences.addons.pop(HOST) # a file sits beside this add-on itself: still not read as a host's + self.assertEqual(self.target.reload_host_actions(), 0) + self.assertEqual(self.target.host_actions(), ([], [])) + + def test_a_sibling_add_on_whose_name_starts_with_the_hosts_is_not_the_host(self): + # aetheria_ships' operator is not aetheria's: the ownership guard is module equality or module + '.', never a bare prefix + self.ops["report"].cls.__module__ = HOST + "_ships" + self.assertIn("not an operator defined by", self.refused()) + self.ops["report"].cls.__module__ = HOST + "x.sub" + self.refused() + self.ops["report"].cls.__module__ = HOST + self.assertEqual(len(self.target.host_actions()[0]), 4) + + def rewrite_row(self, **changes): + path = self.dir / "brokkr_actions.json" + document = json.loads(path.read_text(encoding="utf-8")) + document["actions"][0].update(changes) + path.write_text(json.dumps(document), encoding="utf-8") + self.target.reload_host_actions() + + def test_a_file_with_an_unknown_row_key_or_an_only_is_refused_whole(self): + self.rewrite_row(unknown=1) + self.assertIn("no key", self.refused()) + self.rewrite_row(unknown=None) # restore: a null is still a key + path = self.dir / "brokkr_actions.json" + path.write_bytes((FIXTURE / "brokkr_actions.json").read_bytes()) + self.rewrite_row(fields=[{"name": "name", "type": "string"}, {"name": "size", "type": "number", "minimum": 0.1, "maximum": 10, + "only": {"field": "name", "in": ["a"]}}]) + self.assertIn("no 'only'", self.refused()) + + def test_an_enum_field_must_list_the_operators_identifiers(self): + field = {"name": "kind", "type": "string", "enum": ["A", "B"]} + self.ops["add_empty"].props = [prop("name", "STRING"), prop("size", "FLOAT", 0.0, 100.0), prop("kind", "ENUM", enum=("A", "B"))] + self.rewrite_row(fields=[{"name": "name", "type": "string"}, field]) + self.assertEqual(len(self.target.host_actions()[0]), 4) + self.ops["add_empty"].props = [prop("name", "STRING"), prop("kind", "ENUM", enum=("A", "C"))] + self.assertIn("enum differs", self.refused()) + + def test_a_refused_file_is_reported_in_the_snapshot(self): + self.ops["report"].cls.__module__ = "other_addon" + self.bpy.data = NS(objects=[], scenes=[], collections=[], materials=[], images=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0), background=False) + snapshot = self.target.capture_snapshot(NS(selected_objects=[], active_object=None, scene=None, mode="OBJECT"), True) + self.assertEqual(snapshot["hostActions"], []) + self.assertEqual([e["host"] for e in snapshot["hostActionErrors"]], [HOST]) + self.assertIn("not an operator defined by", snapshot["hostActionErrors"][0]["error"]) + + def test_a_poll_that_fails_refuses_before_the_operator_and_before_any_undo_step(self): + self.ops["add_empty"].pollable = False + receipt = self.send("add_empty", name="E") + self.assertEqual(receipt["status"], "failed") + self.assertIn("poll failed", receipt["message"]) + self.assertEqual((self.ops["add_empty"].calls, self.bpy.undo.pushes), ([], [])) + + def test_a_poll_that_raises_refuses_too(self): + self.ops["add_empty"].poll = raising(RuntimeError("Operator bpy.ops.x.poll() failed, context is incorrect")) + receipt = self.send("add_empty", name="E") + self.assertEqual((receipt["status"], self.ops["add_empty"].calls, self.bpy.undo.pushes), ("failed", [], [])) + + def test_a_read_only_result_property_refuses_the_whole_file_at_load(self): + self.bpy.types.WindowManager.bl_rna.properties["brokkr_host_fixture_result"].is_readonly = True + self.assertIn("writable string property", self.refused()) + + def test_an_operator_that_pushes_undo_itself_may_not_be_a_row_that_changes_nothing(self): + self.ops["report"].cls.bl_options = {"REGISTER", "UNDO"} # report says changesScene false + self.assertIn("bl_options UNDO", self.refused()) + self.ops["report"].cls.bl_options = {"REGISTER"} + self.ops["add_empty"].cls.bl_options = {"REGISTER", "UNDO"} # a changing row may + self.assertEqual(len(self.target.host_actions()[0]), 4) + + def test_a_runtime_error_names_its_cause_not_the_traceback_header(self): + self.ops["add_empty"].behave = raising(RuntimeError("Error: Python: Traceback (most recent call last):" + chr(10) + " File x.py, line 1" + chr(10) + "ValueError: boom")) + self.assertEqual(self.send("add_empty", name="E")["message"], "ValueError: boom") + + +class FakeNode: + """The node database drain_commands reads: intents, receipts, and what it puts and deletes.""" + def __init__(self, intents, receipts=()): + self.docs = {bt.COMMAND_INTENT_SCHEMA: dict(intents), bt.COMMAND_RECEIPT_SCHEMA: dict(receipts)} + self.initial = sorted(intents) + self.puts = [] + self.deleted = [] + self.put_failures = 0 # the next n puts raise + self.delete_failures = 0 # the next n deletes raise + 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()} + + def put(self, document, key, value): + if self.put_failures: + self.put_failures -= 1 + raise OSError("store write failed") + self.puts.append((key, value)) + if key.startswith("blender/receipts/"): + self.docs[bt.COMMAND_RECEIPT_SCHEMA][key] = value + + def delete(self, document, key): + if self.delete_failures: + self.delete_failures -= 1 + raise OSError("store delete failed") + self.deleted.append(key) + self.docs[bt.COMMAND_INTENT_SCHEMA].pop(key, None) + + +class DrainTests(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + + def drain(self, node): + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, docs)): + return self.target.drain_commands(self.context, "cache", "src") + + def intent(self, cid, **fields): + return {"commandId": cid, "requestedBy": "nibu/hands", "action": "createObject", "objectType": "EMPTY", **fields} + + def test_malformed_ids_in_the_queue_never_wedge_the_drain(self): + node = FakeNode({ + "blender/commands/a-list": self.intent(["x"]), + "blender/commands/b-int": self.intent(7), + "blender/commands/c-good": self.intent("good-1"), + }) + receipts = self.drain(node) # must not raise + self.assertEqual(sorted(node.deleted), node.initial) + self.assertEqual([r["status"] for r in receipts], ["denied", "denied", "accepted"]) + keys = [k for k, _ in node.puts] + self.assertTrue(all(isinstance(k, str) and "[" not in k for k in keys), keys) + self.assertIn("blender/receipts/good-1", keys) + bad = [v for k, v in node.puts if k != "blender/receipts/good-1"] + self.assertTrue(all("blender/commands/" in v["message"] for v in bad), [v["message"] for v in bad]) + + def test_drain_seeds_receipted_from_persisted_receipts(self): + old = {"blender/receipts/old-1": {"commandId": "old-1", "status": "accepted"}} + node = FakeNode({"blender/commands/old-1": self.intent("old-1")}, old) + receipts = self.drain(node) + self.assertEqual(receipts[0]["status"], "denied") + self.assertEqual(self.bpy.created, []) + + def test_reused_id_never_overwrites_the_original_receipt(self): + node = FakeNode({"blender/commands/a": self.intent("dup-1"), "blender/commands/b": self.intent("dup-1")}) + self.drain(node) + keys = [k for k, _ in node.puts] + self.assertEqual(keys.count("blender/receipts/dup-1"), 1) + self.assertEqual(dict(node.puts)["blender/receipts/dup-1"]["status"], "accepted") + denial = dict(node.puts)["blender/receipts/dup-1.denied"] + self.assertEqual(denial["status"], "denied") + self.assertEqual(sorted(node.deleted), ["blender/commands/a", "blender/commands/b"]) + + def test_a_mixed_key_intent_in_the_queue_ends_as_a_denied_receipt(self): + # a store writer can mix key types; the drain has claimed the intent, so validate must not raise + node = FakeNode({"blender/commands/a": {"commandId": "mixed-1", "requestedBy": "nibu/hands", "action": "createObject", 1: "a", "zz": "b"}}) + receipts = self.drain(node) + self.assertEqual([r["status"] for r in receipts], ["denied"]) + self.assertEqual(node.puts[0][0], "blender/receipts/mixed-1") + self.assertEqual(node.docs[bt.COMMAND_INTENT_SCHEMA], {}) + + def test_parenting_an_object_to_itself_or_its_own_child_is_refused_before_any_undo_step(self): + self.bpy.lamp.parent = self.bpy.mesh + for target, parent in (("Cube", "Cube"), ("Cube", "Lamp")): # Lamp is Cube's child + receipt = self.run_action(action="setObjectParent", targetObjectName=target, parentObjectName=parent) + self.assertEqual(receipt["status"], "failed", (target, parent)) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(self.bpy.undo.pushes, []) + self.bpy.lamp.parent = None + self.assertEqual(self.run_action(action="setObjectParent", targetObjectName="Lamp", parentObjectName="Cube")["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 1) + + # claim-first: an intent leaves the queue before it runs, so no failure can run it twice + def test_the_intent_is_deleted_before_its_handler_runs(self): + node = FakeNode({"blender/commands/a": self.intent("claim-1")}) + seen = [] + original = self.bpy.ops.object.empty_add + self.bpy.ops.object.empty_add = lambda *a, **kw: (seen.append(list(node.deleted)), original(*a, **kw))[1] + self.drain(node) + self.assertEqual(seen, [["blender/commands/a"]]) + self.assertEqual(node.puts[0][0], "blender/receipts/claim-1") + + def test_a_failed_receipt_write_is_held_and_written_next_drain_and_the_intent_never_reruns(self): + node = FakeNode({"blender/commands/a": self.intent("held-1")}) + node.put_failures = 1 + with self.assertRaises(OSError): + self.drain(node) + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(node.docs[bt.COMMAND_INTENT_SCHEMA], {}) + self.assertEqual(node.puts, []) + self.assertEqual(self.drain(node), []) # nothing queued: it runs nothing and writes the held receipt + self.assertEqual([k for k, _ in node.puts], ["blender/receipts/held-1"]) # not '.denied' + self.assertEqual(node.puts[0][1]["status"], "accepted") + self.assertEqual(len(self.bpy.created), 1) + self.assertEqual(self.drain(node), []) + self.assertEqual(len(node.puts), 1) # written once + + def test_a_held_receipt_survives_a_second_failed_write(self): + node = FakeNode({"blender/commands/a": self.intent("held-2")}) + node.put_failures = 2 + with self.assertRaises(OSError): + self.drain(node) + with self.assertRaises(OSError): + self.drain(node) + self.assertEqual(self.drain(node), []) + self.assertEqual([k for k, _ in node.puts], ["blender/receipts/held-2"]) + self.assertEqual(len(self.bpy.created), 1) + + def test_a_fresh_target_on_the_same_node_runs_nothing_after_a_failed_write(self): + node = FakeNode({"blender/commands/a": self.intent("fresh-1")}) + node.put_failures = 1 + with self.assertRaises(OSError): + self.drain(node) + fresh = bt.BrokkrBlenderTarget(self.bpy) + docs = {"command_intent": "i", "command_receipt": "r"} + with unittest.mock.patch.object(fresh, "_open_node", return_value=(node, docs)): + self.assertEqual(fresh.drain_commands(self.context, "cache", "src"), []) + self.assertEqual(len(self.bpy.created), 1) # the intent is gone from the queue: nothing re-ran it + + def test_a_delete_that_raises_runs_nothing_and_leaves_the_intent_queued(self): + node = FakeNode({"blender/commands/a": self.intent("keep-1")}) + node.delete_failures = 1 + with self.assertRaises(OSError): + self.drain(node) + self.assertEqual(self.bpy.created, []) + self.assertEqual(node.puts, []) + self.assertIn("blender/commands/a", node.docs[bt.COMMAND_INTENT_SCHEMA]) + receipts = self.drain(node) # the retry claims and runs it + self.assertEqual([r["status"] for r in receipts], ["accepted"]) + self.assertEqual(len(self.bpy.created), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_brokkr_ctl_interop.py b/surfaces/blender/tests/test_brokkr_ctl_interop.py new file mode 100644 index 0000000..92bef5a --- /dev/null +++ b/surfaces/blender/tests/test_brokkr_ctl_interop.py @@ -0,0 +1,73 @@ +"""brokkr-ctl writes an intent a cultmesh-py node pulls as the same dict, and reads a node's receipt. + +No Blender. Needs CultLib's Python packages (CULTLIB_PACKAGES, the packages directory) and the built +binary (BROKKR_CTL, the path to brokkr-ctl or brokkr-ctl.exe); skipped when either is missing. +""" +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import types +import unittest +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(ADDON)] +sys.modules.setdefault("brokkr_bridge", package) + +from brokkr_bridge import blender_target as bt # noqa: E402 + +PACKAGES = os.environ.get("CULTLIB_PACKAGES", "") +CTL = os.environ.get("BROKKR_CTL", "") + + +@unittest.skipUnless(PACKAGES and Path(PACKAGES).is_dir(), "set CULTLIB_PACKAGES to CultLib's packages directory") +@unittest.skipUnless(CTL and Path(CTL).is_file(), "set BROKKR_CTL to the built brokkr-ctl binary") +class BrokkrCtlInterop(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.store = str(Path(self.tmp.name) / "blender-editor.ccmp") + self.cultmesh, self.cultcache = bt._load_cultmesh(PACKAGES) + self.node = self.cultmesh.CultMesh.start_node(self.store, runtime_id="addon") + self.intent = self.cultcache.define_document_type(bt.COMMAND_INTENT_SCHEMA) + self.receipt = self.cultcache.define_document_type(bt.COMMAND_RECEIPT_SCHEMA) + self.node.database.register_document(self.intent) + self.node.database.register_document(self.receipt) + # The add-on's own first write is what creates its store file. + self.node.database.put(self.receipt, "blender/receipts/seed", { + "schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "seed", "status": "accepted"}) + + def ctl(self, *args): + env = dict(os.environ, EUREKA_INSTANCE="nibu") + env.pop("BROKKR_AGENT", None) + return subprocess.run([CTL, "blender", *args, "--store", self.store], env=env, + capture_output=True, text=True, timeout=60) + + def test_a_node_pulls_the_intent_as_the_dict_ctl_wrote(self): + sent = self.ctl("send", "createObject", "--set", 'objectType="MESH"', "--set", "location=[0,0,1]", + "--note", "a cube", "--agent", "hands", "--no-wait") + self.assertEqual(sent.returncode, 0, sent.stderr) + command_id = sent.stdout.split("commandId:")[1].split()[0] + self.node.database.pull() + got = self.node.database.snapshot()[bt.COMMAND_INTENT_SCHEMA][f"blender/commands/{command_id}"] + self.assertEqual(got, { + "schema": bt.COMMAND_INTENT_SCHEMA, "commandId": command_id, "action": "createObject", + "requestedBy": "nibu/hands", "note": "a cube", "objectType": "MESH", "location": [0, 0, 1]}) + # The node's own earlier record is still there after the Rust whole-store write. + self.assertIn("blender/receipts/seed", self.node.database.snapshot()[bt.COMMAND_RECEIPT_SCHEMA]) + + def test_ctl_reads_a_receipt_the_node_wrote(self): + self.node.database.put(self.receipt, "blender/receipts/r1", { + "schema": bt.COMMAND_RECEIPT_SCHEMA, "commandId": "r1", "action": "createObject", + "status": "failed", "message": "refused"}) + waited = self.ctl("wait", "r1", "--timeout", "5") + self.assertEqual(waited.returncode, 2, waited.stderr) + self.assertIn("message: refused", waited.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_extension_wheel.py b/surfaces/blender/tests/test_extension_wheel.py new file mode 100644 index 0000000..362e32f --- /dev/null +++ b/surfaces/blender/tests/test_extension_wheel.py @@ -0,0 +1,59 @@ +"""The extension's one bundled wheel is pure Python, matches its recorded hash, and the manifest does not pin a platform.""" +from __future__ import annotations + +import base64 +import hashlib +import importlib.metadata +import re +import tomllib +import unittest +import zipfile +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +INSTALL = Path(__file__).resolve().parents[1] / "docs" / "install.md" + + +class ExtensionWheelTests(unittest.TestCase): + def setUp(self): + self.manifest = tomllib.loads((ADDON / "blender_manifest.toml").read_text(encoding="utf-8")) + + def test_one_pure_python_wheel_and_no_platform_restriction(self): + self.assertEqual(len(self.manifest["wheels"]), 1) + wheel = ADDON / self.manifest["wheels"][0] + self.assertTrue(wheel.name.endswith("-py3-none-any.whl"), wheel.name) + self.assertNotIn("platforms", self.manifest) + with zipfile.ZipFile(wheel) as z: + names = z.namelist() + self.assertEqual([n for n in names if n.endswith((".pyd", ".so", ".dylib"))], []) + self.assertIn("Root-Is-Purelib: true", z.read("msgpack-1.2.2.dist-info/WHEEL").decode()) + for line in z.read("msgpack-1.2.2.dist-info/RECORD").decode().splitlines(): + name, digest, size = line.split(",") + if digest: + data = z.read(name) + 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")) + self.assertIn(hashlib.sha256(wheel.read_bytes()).hexdigest(), recorded) + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_material_actions.py b/surfaces/blender/tests/test_material_actions.py index 9ecc2ec..bf2baef 100644 --- a/surfaces/blender/tests/test_material_actions.py +++ b/surfaces/blender/tests/test_material_actions.py @@ -5,6 +5,9 @@ The real API is exercised by tests/live/material_colour.py. """ from __future__ import annotations +import contextlib +import itertools + import sys import types import unittest @@ -50,11 +53,25 @@ class Materials(dict): return self[name] +IDS = itertools.count() + + +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), preferences=NS(addons={}), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.mesh = NS(name="Cube", type="MESH", data=NS(materials=[])) self.empty = NS(name="Empty", type="EMPTY", data=None) self.data = NS(objects={"Cube": self.mesh, "Empty": self.empty}, materials=Materials()) + self.undo = FakeUndo(self) class MaterialTests(unittest.TestCase): @@ -63,7 +80,7 @@ class MaterialTests(unittest.TestCase): self.target = bt.BrokkrBlenderTarget(self.bpy) def assign(self, **fields): - return self.target.execute_command(NS(), {"commandId": "c1", "action": "assignMaterial", + return self.target.run_intent(NS(), {"commandId": f"c{next(IDS)}", "requestedBy": "nibu/hands", "action": "assignMaterial", "targetObjectName": "Cube", **fields}) def base_color(self, name="oxide red"): @@ -104,7 +121,7 @@ class MaterialTests(unittest.TestCase): [float("nan"), 0, 0], [float("inf"), 0, 0], [-0.1, 0, 0], [1.1, 0, 0], [0, 0, 0, 2], [1.0000001, 0, 0], [-1e-9, 0, 0], [0, 0, 0, 1.0000001], [10**400, 0, 0], [0, -10**400, 0]): receipt = self.assign(materialName="oxide red", color=bad) - self.assertEqual(receipt["status"], "failed", bad) + self.assertEqual(receipt["status"], "denied", bad) self.assertIn("color", receipt["message"], bad) self.assertEqual(dict(self.bpy.data.materials), {}) self.assertEqual(self.bpy.mesh.data.materials, []) @@ -126,7 +143,7 @@ class MaterialTests(unittest.TestCase): def test_refused_colour_on_an_existing_material_leaves_it_alone(self): self.assign(materialName="oxide red", color=[0.5, 0.1, 0.1]) - self.assertEqual(self.assign(materialName="oxide red", color=[2, 0, 0])["status"], "failed") + self.assertEqual(self.assign(materialName="oxide red", color=[2, 0, 0])["status"], "denied") self.assertEqual(self.base_color(), (0.5, 0.1, 0.1, 1.0)) def test_existing_tree_without_a_principled_node_gets_one(self): @@ -137,7 +154,7 @@ class MaterialTests(unittest.TestCase): self.assertEqual(self.base_color("bare"), (0.2, 0.3, 0.4, 1.0)) def test_object_without_material_slots_is_refused(self): - receipt = self.target.execute_command(NS(), {"commandId": "c", "action": "assignMaterial", + receipt = self.target.run_intent(NS(), {"commandId": f"c{next(IDS)}", "requestedBy": "nibu/hands", "action": "assignMaterial", "targetObjectName": "Empty", "color": [1, 0, 0]}) self.assertEqual(receipt["status"], "failed") self.assertEqual(dict(self.bpy.data.materials), {}) diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 4c333f1..6d4a762 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -5,6 +5,8 @@ The real API is exercised by tests/live/gn_actions.py. """ from __future__ import annotations +import contextlib + import sys import types import unittest @@ -168,9 +170,20 @@ class Obj: self.custom = (key, value) +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + bpy.context = NS(window_manager=NS(windows=[object()]), preferences=NS(addons={}), temp_override=lambda **kw: contextlib.nullcontext()) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops + + class FakeBpy: def __init__(self): self.data = NS(node_groups=Groups(), objects={"Host": Obj("Host")}) + self.undo = FakeUndo(self) class NodeActionTests(unittest.TestCase): @@ -182,7 +195,8 @@ class NodeActionTests(unittest.TestCase): def run_action(self, **command): self.n += 1 command.setdefault("commandId", f"c{self.n}") - return self.target.execute_command(None, command) + command.setdefault("requestedBy", "nibu/hands") + return self.target.run_intent(None, command) def accepted(self, **command): receipt = self.run_action(**command) @@ -190,8 +204,9 @@ class NodeActionTests(unittest.TestCase): return receipt def refused(self, **command): + """Refused either at admission by the table ('denied') or by the handler against the scene ('failed').""" receipt = self.run_action(**command) - self.assertEqual(receipt["status"], "failed", receipt["message"]) + self.assertIn(receipt["status"], ("denied", "failed"), receipt["message"]) return receipt def group(self, interface=None): @@ -530,8 +545,11 @@ class NodeActionTests(unittest.TestCase): tree = self.chain() self.accepted(action="removeNode", treeKey="G", id="b") self.assertEqual([n.get("brokkr_id") for n in tree.nodes], ["gin", "gout", "a", "c"]) + pushes = len(self.bpy.undo.pushes) again = self.accepted(action="removeNode", treeKey="G", id="b") self.assertIn("already absent", again["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) # nothing changed: no undo step + self.assertEqual(again["undoLabel"], "") for keep in ("gin", "gout"): self.refused(action="removeNode", treeKey="G", id=keep) self.refused(action="removeNode", treeKey="Nope", id="a") @@ -542,9 +560,17 @@ class NodeActionTests(unittest.TestCase): self.accepted(action="linkSockets", treeKey="G", fromNode="a", fromSocket="Out", toNode="c", toSocket="A") self.accepted(action="linkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="Size") self.refused(action="unlinkSockets", treeKey="G", fromNode="zzz", fromSocket="Out", toNode="c", toSocket="A") - self.assertIn("Removed 0", self.accepted(action="unlinkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A")["message"]) + pushes = len(self.bpy.undo.pushes) + empty = self.accepted(action="unlinkSockets", treeKey="G", fromNode="b", fromSocket="Out", toNode="c", toSocket="A") + self.assertIn("Removed 0", empty["message"]) + 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) @@ -561,7 +587,11 @@ class NodeActionTests(unittest.TestCase): self.accepted(action="removeModifier", objectName="Host", modifierName="GN") self.assertEqual([m.name for m in host.modifiers], ["Sub"]) self.assertEqual(host.tagged, tags + 1) - self.assertIn("already absent", self.accepted(action="removeModifier", objectName="Host", modifierName="GN")["message"]) + pushes = len(self.bpy.undo.pushes) + again = self.accepted(action="removeModifier", objectName="Host", modifierName="GN") + self.assertIn("already absent", again["message"]) + self.assertEqual(len(self.bpy.undo.pushes), pushes) + self.assertEqual(again["undoLabel"], "") self.refused(action="removeModifier", objectName="Nope", modifierName="GN") for bad in (["x"], "x" * 256, "a\0b", 5): self.refused(action="removeModifier", objectName="Host", modifierName=bad) diff --git a/surfaces/blender/tests/test_perception.py b/surfaces/blender/tests/test_perception.py new file mode 100644 index 0000000..e2a2017 --- /dev/null +++ b/surfaces/blender/tests/test_perception.py @@ -0,0 +1,728 @@ +"""Perception: look captures her 3D view, the snapshot carries her Edit Mode selection, a session id and +human-edit sequences. A fake bpy, a fake bmesh and fake depsgraphs; no Blender. +""" +from __future__ import annotations + +import contextlib +import inspect +import os +import re +import sys +import types +import unittest +import unittest.mock +from pathlib import Path + +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 +PNG = b"\x89PNG\r\n\x1a\n" + b"x" * 32 + + +def area(kind, width, height, name=None): + return NS(type=kind, width=width, height=height, name=name or kind, + regions=[NS(type="HEADER"), NS(type="WINDOW", width=width, height=height)]) + + +def window(*areas): + return NS(screen=NS(areas=list(areas))) + + +class Element: + def __init__(self, selected, fake): + self._select, self._fake = selected, fake + + @property + def select(self): + self._fake.touched += 1 # every look at an element's flag costs a Python call in the real thing + return self._select + + +class Elements: + """A lazy sequence: a million of them without a million objects.""" + def __init__(self, fake, flags): + self.fake, self.flags = fake, flags + + def __iter__(self): + for flag in self.flags: + yield Element(flag, self.fake) + + +class FakeBmesh: + """bmesh.from_edit_mesh(mesh) -> verts, edges, faces that carry .select. The mesh carries + total_vert_sel and friends, as Mesh does in Edit Mode; a test may set them apart from the flags.""" + def __init__(self, meshes): + self.meshes = meshes + self.reads = 0 + self.touched = 0 + self.totals = None # override: (verts, edges, faces) the mesh claims + + def from_edit_mesh(self, mesh): + self.reads += 1 + verts, edges, faces = self.meshes[id(mesh)] + counts = self.totals or tuple(sum(1 for f in kind if f) for kind in (verts, edges, faces)) + mesh.total_vert_sel, mesh.total_edge_sel, mesh.total_face_sel = counts + return NS(verts=Elements(self, verts), edges=Elements(self, edges), faces=Elements(self, faces)) + + +class PerceptionFixture(unittest.TestCase): + """The scene fixture plus a window with a 3D view, a screenshot operator and a bmesh.""" + run_action = ts.ActionTests.run_action + + def setUp(self): + ts.ActionTests.setUp(self) + self.view = area("VIEW_3D", 1574, 888) + self.windows = [window(area("PROPERTIES", 300, 900), self.view, area("TIMELINE", 1600, 100))] + self.stack, self.shots, self.shot_result, self.shot_writes = [], [], {"FINISHED"}, True + bpy = self.bpy + bpy.context.window_manager.windows = self.windows + bpy.context.temp_override = self.override + bpy.ops.screen = NS(screenshot_area=self.screenshot) + bpy.mesh_data = NS(name="CubeMesh", vertices=[], edges=[], polygons=[], uv_layers=[], shape_keys=None) + bpy.mesh.data = bpy.mesh_data + bpy.mesh.mode = "OBJECT" + self.bmesh = FakeBmesh({id(bpy.mesh_data): ([True, False, True], [False, True], [False])}) + patch = unittest.mock.patch.dict(sys.modules, {"bmesh": self.bmesh}) + patch.start() + self.addCleanup(patch.stop) + bpy.data.scenes = [bpy.scene] + + @contextlib.contextmanager + def override(self, **kw): + self.stack.append(kw) + try: + yield + finally: + self.stack.pop() + + def screenshot(self, mode, undo, filepath): + assert (mode, undo) == ("EXEC_DEFAULT", False) # operators run with undo off + self.shots.append((dict(self.stack[-1]) if self.stack else None, filepath)) + if self.shot_writes: + Path(filepath).write_bytes(PNG) + return self.shot_result + + def look(self, **command): + return self.run_action(action="look", **command) + + def look_dir(self): + return self.root / "out" / "look" + + +class LookTests(PerceptionFixture): + def test_look_is_a_read_action(self): + receipt = self.look(commandId="look-0001") + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.bpy.undo.pushes, []) # reads push no undo step + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(Path(receipt["lookPath"]), self.look_dir() / "look-0001.png") + self.assertEqual((self.look_dir() / "look-0001.png").read_bytes(), PNG) + self.assertEqual(self.bpy.created, []) + + def test_other_receipts_carry_an_empty_look_path(self): + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["lookPath"], "") + + def test_look_captures_only_the_largest_3d_view_and_its_window_region(self): + # the capture is scoped to one area's WINDOW region: that is what keeps the desktop and every + # other Blender area out of the picture + small = area("VIEW_3D", 400, 300) + big = area("VIEW_3D", 1600, 900) + second = window(area("OUTLINER", 3000, 3000), small) + self.windows.append(second) + self.windows[0].screen.areas.append(big) + self.look() + override, path = self.shots[0] + self.assertIs(override["area"], big) + self.assertIs(override["window"], self.windows[0]) + self.assertEqual((override["region"].type, override["region"].width), ("WINDOW", 1600)) + self.assertEqual(len(self.shots), 1) + + def test_look_in_a_second_window_uses_that_window(self): + only = area("VIEW_3D", 800, 600) + self.windows[0].screen.areas.remove(self.view) + self.windows.append(window(only)) + self.look() + self.assertIs(self.shots[0][0]["window"], self.windows[1]) + self.assertIs(self.shots[0][0]["area"], only) + + def test_look_without_a_3d_view_is_refused_and_captures_nothing(self): + self.windows[0].screen.areas.remove(self.view) + receipt = self.look() + self.assertEqual(receipt["status"], "failed") + self.assertIn("3D", receipt["message"]) + self.assertEqual((self.shots, receipt["lookPath"]), ([], "")) + self.assertFalse(self.look_dir().exists()) + self.assertEqual(self.bpy.undo.pushes, []) + + def test_look_without_an_output_directory_is_refused(self): + self.target.configure_action_dirs(str(self.root / "in"), "") + receipt = self.look() + self.assertEqual(receipt["status"], "failed") + self.assertIn("output", receipt["message"]) + self.assertEqual(self.shots, []) + + def test_a_cancelled_or_unwritten_capture_is_a_failed_receipt_with_no_path(self): + self.shot_result = {"CANCELLED"} + receipt = self.look(commandId="look-c1") + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + self.shot_result, self.shot_writes = {"FINISHED"}, False + receipt = self.look(commandId="look-c2") + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + + def test_look_works_in_edit_mode_and_leaves_her_mode_alone(self): + self.bpy.mesh.mode = "EDIT" + receipt = self.look() + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.bpy.mesh.mode, "EDIT") + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "denied") + + def test_look_prunes_to_twenty(self): + # look-files-are-scratch: the newest twenty files stay, the capture just taken among them + self.look_dir().mkdir(parents=True) + for n in range(30): + old = self.look_dir() / f"old-{n:02d}.png" + old.write_bytes(PNG) + os.utime(old, (1_000_000 + n, 1_000_000 + n)) + receipt = self.look(commandId="look-new") + kept = sorted(p.name for p in self.look_dir().iterdir()) + self.assertEqual(len(kept), 20, kept) + self.assertIn("look-new.png", kept) + self.assertEqual([k for k in kept if k != "look-new.png"], [f"old-{n:02d}.png" for n in range(11, 30)]) # the newest 19 of the old + self.assertTrue(Path(receipt["lookPath"]).is_file()) + + def test_the_pruning_below_the_cap_removes_nothing(self): + for n in range(19): + self.look(commandId=f"look-{n:03d}") + self.assertEqual(len(list(self.look_dir().iterdir())), 19) + self.look(commandId="look-last") + self.assertEqual(len(list(self.look_dir().iterdir())), 20) + + def test_pruning_touches_only_png_files_directly_inside_look(self): + self.look_dir().mkdir(parents=True) + (self.root / "out" / "keep.png").write_bytes(PNG) + (self.look_dir() / "notes.txt").write_text("x") + (self.look_dir() / "dir.png").mkdir() + for n in range(25): + f = self.look_dir() / f"old-{n:02d}.png" + f.write_bytes(PNG) + os.utime(f, (1_000_000 + n, 1_000_000 + n)) + self.look() + self.assertTrue((self.root / "out" / "keep.png").exists()) + self.assertTrue((self.look_dir() / "notes.txt").exists()) + self.assertTrue((self.look_dir() / "dir.png").is_dir()) + self.assertEqual(len([p for p in self.look_dir().iterdir() if p.suffix == ".png" and p.is_file()]), 20) + + def test_a_refused_look_prunes_nothing(self): + self.look_dir().mkdir(parents=True) + for n in range(30): + (self.look_dir() / f"old-{n:02d}.png").write_bytes(PNG) + self.windows[0].screen.areas.remove(self.view) + self.look() + self.assertEqual(len(list(self.look_dir().iterdir())), 30) + + def test_a_refusal_does_not_echo_the_output_path(self): + self.windows[0].screen.areas.remove(self.view) + self.assertNotIn(str(self.root), self.look()["message"]) + + +def rich(obj): + """What the real _object_snapshot reads of an object.""" + for key, value in dict(library=None, location=(0.0, 0.0, 0.0), rotation_euler=(0.0, 0.0, 0.0), scale=(1.0, 1.0, 1.0), + parent=None, users_collection=[], material_slots=[], modifiers=[], constraints=[]).items(): + setattr(obj, key, value) + obj.visible_get = lambda: True + obj.items = lambda: [] + obj.mode = getattr(obj, "mode", "OBJECT") + return obj + + +class _All: + """Endless selected flags: a scan that does not stop at the cap would never return.""" + def __iter__(self): + return iter([True] * 5_000_000) + + +class _First: + """A huge mesh whose first n elements are selected: reading past them would show in the touches.""" + def __init__(self, n): + self.n = n + + def __iter__(self): + for i in range(10_000_000): + yield i < self.n + + +class LookFreshnessTests(PerceptionFixture): + """A minimised Blender stops redrawing, so a region capture is a stale frame. Then the view is drawn offscreen.""" + + def setUp(self): + super().setUp() + self.drawn = True + self.target._windows_drawn = lambda: self.drawn + self.offscreen_calls = [] + self.pixels = bytes([10, 20, 30, 255, 40, 50, 60, 255, # bottom row first, as GL reads it + 70, 80, 90, 255, 100, 110, 120, 255]) + + def render(window, area, region): + self.offscreen_calls.append((window, area, region)) + return 2, 2, self.pixels + + self.target._render_view_offscreen = render + + def test_a_drawn_window_is_captured_from_the_region_and_says_so(self): + receipt = self.look() + self.assertEqual((receipt["captureSource"], len(self.shots), self.offscreen_calls), ("region", 1, [])) + + def test_a_window_that_is_not_drawn_is_rendered_offscreen_and_says_so(self): + self.drawn = False + receipt = self.look(commandId="look-off") + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(receipt["captureSource"], "offscreen") + self.assertEqual(self.shots, []) # the stale framebuffer is never read + window, area, region = self.offscreen_calls[0] + self.assertIs(window, self.windows[0]) + self.assertIs(area, self.view) + self.assertEqual(region.type, "WINDOW") + self.assertEqual(Path(receipt["lookPath"]), self.look_dir() / "look-off.png") + + def test_the_offscreen_file_is_a_png_of_the_pixels_top_row_first(self): + import struct + import zlib + self.drawn = False + data = Path(self.look()["lookPath"]).read_bytes() + self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n") + chunks, at = {}, 8 + while at < len(data): + size, kind = struct.unpack(">I4s", data[at:at + 8]) + chunks[kind] = data[at + 8:at + 8 + size] + at += 12 + size + self.assertEqual(struct.unpack(">IIBBBBB", chunks[b"IHDR"]), (2, 2, 8, 6, 0, 0, 0)) + raw = zlib.decompress(chunks[b"IDAT"]) + rows = [raw[i:i + 9] for i in range(0, len(raw), 9)] # a filter byte, then 2 RGBA pixels + self.assertEqual([r[0] for r in rows], [0, 0]) + self.assertEqual(rows[0][1:], self.pixels[8:]) # the top of the picture is the last row GL read + self.assertEqual(rows[1][1:], self.pixels[:8]) + + def test_an_offscreen_failure_is_a_refusal_never_a_stale_picture(self): + self.drawn = False + + def boom(*a): + raise RuntimeError("no gpu") + + self.target._render_view_offscreen = boom + receipt = self.look() + self.assertEqual((receipt["status"], receipt["lookPath"]), ("failed", "")) + self.assertEqual(self.shots, []) + self.assertEqual(list(self.look_dir().glob("*.png")) if self.look_dir().exists() else [], []) + + def test_the_receipt_names_the_scene_update_the_picture_reflects(self): + first = self.look()["sceneUpdateSeq"] + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.look()["sceneUpdateSeq"], first + 1) + + def test_agent_turn_updates_move_the_scene_update_sequence_too(self): + # it counts every update, hers or the agent's: what the capture reflects is the whole scene + before = self.target.scene_update_seq + self.target.agent_turn = True + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.target.agent_turn = False + self.assertEqual((self.target.scene_update_seq, self.target.human_edit_seq), (before + 1, 0)) + + def test_an_update_without_flags_still_counts_as_a_scene_update(self): + before = self.target.scene_update_seq + self.target.track_human_edits(depsgraph(update("Cube"))) + self.assertEqual(self.target.scene_update_seq, before + 1) + + def test_a_new_session_restarts_the_scene_update_sequence(self): + self.target.track_human_edits(depsgraph(update("Cube"))) + self.target.renew_session() + self.assertEqual(self.target.scene_update_seq, 0) + + def test_the_default_window_check_assumes_drawn_off_windows(self): + target = bt.BrokkrBlenderTarget(self.bpy) + with unittest.mock.patch.object(bt.sys, "platform", "linux"): + self.assertTrue(target._windows_drawn()) + + +class LookPathTests(PerceptionFixture): + def test_a_path_that_changes_after_the_directory_is_made_is_refused_and_nothing_is_captured(self): + # the second check is the guard for the gap between the first check and the capture + real = bt.sa.resolve_inside + calls = [] + + def swapped(root, candidate, label, **kw): + path = real(root, candidate, label, **kw) + calls.append(path) + return path if len(calls) == 1 else path.with_name("elsewhere.png") + + with unittest.mock.patch.object(bt.sa, "resolve_inside", swapped): + receipt = self.look() + self.assertEqual((receipt["status"], len(calls)), ("failed", 2)) + self.assertIn("changed", receipt["message"]) + self.assertEqual((self.shots, receipt["lookPath"]), ([], "")) + + def test_the_prune_does_not_follow_a_link_to_a_file(self): + # a link named *.png is not a plain file: it is never counted or removed through + removed = [] + + class Entry: + def __init__(self, name, mtime, link): + self.name, self.path, self._mtime, self._link = name, "dir/" + name, mtime, link + + def is_file(self, follow_symlinks=True): + return follow_symlinks or not self._link # a link is a file only when followed + + def stat(self, follow_symlinks=True): + return NS(st_mtime_ns=self._mtime) + + entries = [Entry(f"f{n:02d}.png", n, False) for n in range(21)] + [Entry("link.png", 0, True)] + + class Scan: + def __enter__(self): + return iter(entries) + + def __exit__(self, *a): + return False + + with unittest.mock.patch.object(bt.os, "scandir", lambda d: Scan()), \ + unittest.mock.patch.object(bt.os, "unlink", removed.append): + bt.BrokkrBlenderTarget._prune_looks(Path("dir")) + self.assertEqual(removed, ["dir/f00.png"]) + + +class CoarseAttributionTests(PerceptionFixture): + NOTE_WORDS = ("all objects flagged",) + + def edits(self, since_look="nibu/hands"): + return self.look(requestedBy=since_look) + + def test_a_precise_edit_is_not_marked_coarse(self): + self.edits() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + receipt = self.edits() + self.assertEqual((receipt["editedSinceLookCoarse"], receipt["editedSinceLookNote"]), (False, "")) + + def test_an_update_that_flags_every_object_is_marked_coarse_and_says_why(self): + self.edits() + self.target.track_human_edits(depsgraph(*[update(n, transform=True, geometry=True) for n in ("Cube", "Lamp", "Cam")])) + receipt = self.edits() + self.assertTrue(receipt["editedSinceLookCoarse"]) + self.assertIn("all objects flagged", receipt["editedSinceLookNote"]) + self.assertEqual(receipt["editedSinceLook"], ["Cam", "Cube", "Lamp"]) # the semantics are unchanged + + def test_an_undo_or_redo_is_coarse(self): + self.edits() + self.target.note_undo_redo() + receipt = self.edits() + self.assertTrue(receipt["editedSinceLookCoarse"]) + self.assertIn("undo", receipt["editedSinceLookNote"]) + + def test_coarse_clears_with_the_next_look_and_comes_back_only_for_a_new_coarse_edit(self): + self.edits() + self.target.note_undo_redo() + self.assertTrue(self.edits()["editedSinceLookCoarse"]) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + def test_each_agent_has_its_own_coarse_since_its_last_look(self): + self.edits("nibu/hands") + self.target.note_undo_redo() + self.edits("nibu/hands") + self.assertTrue(self.edits("nibu/soul")["editedSinceLookCoarse"]) # soul has not looked since + + def test_a_new_session_forgets_coarse(self): + self.target.note_undo_redo() + self.target.renew_session() + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + def test_one_object_in_a_scene_of_one_is_not_coarse(self): + # nothing to over-attribute when there is only one object to name + for name in ("Cam", "Lamp"): + del self.bpy.data.objects[name] + self.edits() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertFalse(self.edits()["editedSinceLookCoarse"]) + + +class EditSelectionTests(PerceptionFixture): + def snapshot(self): + for obj in self.bpy.data.objects: + rich(obj) + self.bpy.camera_data.name, self.bpy.light_data.name, self.bpy.camera_data.angle = "CamData", "LightData", 0.6 + self.bpy.app.version = (5, 3, 0) + self.bpy.data.filepath = "" + for name in ("collections", "materials", "images"): + setattr(self.bpy.data, name, []) + self.bpy.scene.frame_current = self.bpy.scene.frame_start = self.bpy.scene.frame_end = 1 + self.bpy.scene.collection = None + context = NS(selected_objects=[], active_object=None, scene=self.bpy.scene, mode="EDIT_MESH") + with unittest.mock.patch.object(self.target, "_evaluated_snapshot", return_value=None): + return self.target.capture_snapshot(context, False) + + def test_selection_is_read_from_the_edit_mesh_without_leaving_edit_mode(self): + self.bpy.mesh.mode = "EDIT" + selection = self.target.edit_selection() + self.assertEqual(selection, [{"name": "Cube", "type": "MESH", + "vertices": [0, 2], "verticesTotal": 2, + "edges": [1], "edgesTotal": 1, + "faces": [], "facesTotal": 0}]) + self.assertEqual(self.bpy.mesh.mode, "EDIT") + self.assertEqual(self.bmesh.reads, 1) + + def test_nothing_in_edit_mode_is_an_empty_list_and_reads_no_mesh(self): + self.assertEqual(self.target.edit_selection(), []) + self.assertEqual(self.bmesh.reads, 0) + + def test_each_list_is_capped_at_4096_with_the_true_total_beside_it(self): + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = ([True] * 5000, [False] * 5000 + [True], [True] * 4096) + entry = self.target.edit_selection()[0] + self.assertEqual((len(entry["vertices"]), entry["verticesTotal"]), (4096, 5000)) + self.assertEqual(entry["vertices"][:3], [0, 1, 2]) + self.assertEqual((entry["edges"], entry["edgesTotal"]), ([5000], 1)) + self.assertEqual((len(entry["faces"]), entry["facesTotal"]), (4096, 4096)) + + def test_totals_come_from_the_mesh_and_the_scan_stops_at_the_cap(self): + # a million selected of each kind: the totals are the mesh's own counts, and each kind is read only up to the cap + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = (_All(), _All(), _All()) + self.bmesh.totals = (1_000_000, 2_000_000, 3_000_000) + entry = self.target.edit_selection()[0] + self.assertEqual((entry["verticesTotal"], entry["edgesTotal"], entry["facesTotal"]), (1_000_000, 2_000_000, 3_000_000)) + self.assertEqual([len(entry[k]) for k in ("vertices", "edges", "faces")], [4096] * 3) + self.assertEqual(self.bmesh.touched, 3 * 4096) + + def test_a_small_selection_in_a_big_mesh_stops_when_every_selected_element_is_found(self): + self.bpy.mesh.mode = "EDIT" + self.bmesh.meshes[id(self.bpy.mesh_data)] = (_First(3), _First(2), _First(0)) + entry = self.target.edit_selection()[0] + self.assertEqual((entry["vertices"], entry["edges"], entry["faces"]), ([0, 1, 2], [0, 1], [])) + self.assertEqual(self.bmesh.touched, 3 + 2) # no scan past the last selected one, none at all when the total is zero + + def test_every_object_in_edit_mode_is_listed_and_a_non_mesh_says_unsupported(self): + self.bpy.mesh.mode = "EDIT" + self.bpy.cam.mode = "EDIT" + names = {e["name"]: e for e in self.target.edit_selection()} + self.assertEqual(sorted(names), ["Cam", "Cube"]) + self.assertEqual(names["Cam"], {"name": "Cam", "type": "CAMERA", "unsupported": True}) + + def test_the_snapshot_carries_selection_session_and_sequences(self): + self.bpy.mesh.mode = "EDIT" + snap = self.snapshot() + self.assertEqual(snap["editSelection"][0]["vertices"], [0, 2]) + self.assertEqual(snap["sessionId"], self.target.session_id) + self.assertEqual(snap["humanEditSeq"], 0) + self.assertTrue(all(o["lastHumanEditSeq"] == 0 for o in snap["objects"])) + self.assertEqual(self.snapshot()["sessionId"], snap["sessionId"]) + + def test_the_object_snapshot_carries_the_last_human_edit_sequence(self): + self.target._last_human_edit["Cube"] = 7 + objects = {o["name"]: o["lastHumanEditSeq"] for o in self.snapshot()["objects"]} + self.assertEqual(objects, {"Cam": 0, "Lamp": 0, "Cube": 7}) + + +def update(name, *, kind="OBJECT", transform=False, geometry=False, shading=False): + return NS(id=NS(name=name, id_type=kind), is_updated_transform=transform, is_updated_geometry=geometry, + is_updated_shading=shading) + + +def depsgraph(*updates): + return NS(updates=list(updates)) + + +class HumanEditTests(PerceptionFixture): + def test_an_update_outside_an_agent_turn_bumps_the_sequence_and_stamps_the_object(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + self.target.track_human_edits(depsgraph(update("Lamp", geometry=True))) + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Lamp")), (2, 2)) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + + def test_a_constrained_follower_moves_with_its_target(self): + # the update names both objects, the follower's carrying the transform flag only because of its constraint + self.target.track_human_edits(depsgraph(update("Cube", transform=True), update("Follower", transform=True))) + self.assertEqual(self.target.last_human_edit_seq("Follower"), self.target.last_human_edit_seq("Cube")) + self.assertEqual(self.target.human_edit_seq, 1) + + def test_geometry_and_shading_count_and_an_unflagged_presence_does_not(self): + self.target.track_human_edits(depsgraph(update("Cube", shading=True))) + self.assertEqual(self.target.last_human_edit_seq("Cube"), 1) + self.target.track_human_edits(depsgraph(update("Lamp"), update("Cam"))) # named, not changed + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Lamp")), (1, 0)) + + def test_only_objects_are_stamped(self): + self.target.track_human_edits(depsgraph(update("Mesh", kind="MESH", geometry=True))) + self.assertEqual(self.target.human_edit_seq, 0) + + def test_agent_turn_updates_do_not_count_as_human(self): + # the update arrives inside the turn (probe depsgraph-timing), so the in-turn flag attributes it + original = self.bpy.ops.object.empty_add + + def add_and_update(*a, **kw): + original(*a, **kw) + self.target.track_human_edits(depsgraph(update("Empty", transform=True, geometry=True))) + + self.bpy.ops.object.empty_add = add_and_update + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + self.assertEqual(self.target.human_edit_seq, 0) + self.assertEqual(self.target.last_human_edit_seq("Empty"), 0) + self.target.track_human_edits(depsgraph(update("Empty", transform=True))) # after the turn: hers + self.assertEqual(self.target.human_edit_seq, 1) + + def test_a_failed_turn_still_ends_the_turn_for_attribution(self): + def boom(*a, **kw): + raise RuntimeError("half done") + self.bpy.ops.object.empty_add = boom + self.run_action(action="createObject", objectType="EMPTY") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + + def test_undo_and_redo_bump_the_sequence_without_naming_an_object(self): + self.target.note_undo_redo() + self.target.note_undo_redo() + self.assertEqual(self.target.human_edit_seq, 2) + self.assertEqual(self.target._last_human_edit, {}) + + def test_human_edit_seq_never_refuses(self): + # scene-last-writer-wins: an intent after her edit is accepted, and so is one that targets what she edited + rich(self.bpy.mesh) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + receipt = self.run_action(action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 5]) + self.assertEqual(receipt["status"], "accepted", receipt["message"]) + self.assertEqual(self.run_action(action="createObject", objectType="EMPTY")["status"], "accepted") + self.assertEqual(len(self.bpy.undo.pushes), 2) + + def test_the_admission_code_never_reads_the_sequences(self): + source = inspect.getsource(bt.BrokkrBlenderTarget.run_intent) + self.assertEqual(re.findall(r"humanEditSeq|lastHumanEditSeq|human_edit", source), []) + self.assertEqual(re.findall(r"human_edit|session_id", inspect.getsource(bt.BrokkrBlenderTarget._dispatch)), []) + + def test_a_new_session_resets_the_counters_and_mints_a_new_id(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + before = self.target.session_id + self.target.renew_session() + self.assertNotEqual(self.target.session_id, before) + self.assertEqual((self.target.human_edit_seq, self.target.last_human_edit_seq("Cube")), (0, 0)) + + def test_two_targets_mint_different_session_ids(self): + self.assertNotEqual(bt.BrokkrBlenderTarget(self.bpy).session_id, self.target.session_id) + + +class LookReportsHerEditsTests(PerceptionFixture): + def test_the_receipt_carries_the_session_the_selection_and_the_edits_since_the_last_look(self): + self.bpy.mesh.mode = "EDIT" + first = self.look(requestedBy="nibu/hands") + self.assertEqual(first["sessionId"], self.target.session_id) + self.assertEqual((first["humanEditSeq"], first["humanEditsSinceLook"], first["editedSinceLook"]), (0, 0, [])) + self.assertEqual(first["editSelection"][0]["vertices"], [0, 2]) + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.target.track_human_edits(depsgraph(update("Lamp", geometry=True))) + second = self.look(requestedBy="nibu/hands") + self.assertEqual((second["humanEditSeq"], second["humanEditsSinceLook"]), (2, 2)) + self.assertEqual(second["editedSinceLook"], ["Cube", "Lamp"]) + third = self.look(requestedBy="nibu/hands") + self.assertEqual((third["humanEditsSinceLook"], third["editedSinceLook"]), (0, [])) + + def test_each_agent_has_its_own_last_look(self): + self.look(requestedBy="nibu/hands") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.assertEqual(self.look(requestedBy="nibu/hands")["humanEditsSinceLook"], 1) + self.assertEqual(self.look(requestedBy="nibu/soul")["humanEditsSinceLook"], 1) # soul's first look: all of it + + def test_a_new_session_forgets_the_last_look(self): + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.look(requestedBy="nibu/hands") # her edit number 1 is now seen + self.target.renew_session() + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) # number 1 again, in the new session + receipt = self.look(requestedBy="nibu/hands") + self.assertEqual((receipt["humanEditSeq"], receipt["humanEditsSinceLook"], receipt["editedSinceLook"]), (1, 1, ["Cube"])) + + def test_a_refused_look_does_not_move_the_last_look(self): + self.look(requestedBy="nibu/hands") + self.target.track_human_edits(depsgraph(update("Cube", transform=True))) + self.windows[0].screen.areas.remove(self.view) + self.look(requestedBy="nibu/hands") + self.windows[0].screen.areas.append(self.view) + self.assertEqual(self.look(requestedBy="nibu/hands")["humanEditsSinceLook"], 1) + + +class StorePathTests(unittest.TestCase): + def test_the_default_blend_relative_store_is_found_where_the_blend_file_is(self): + # live-3 Low: store_exists must resolve the default '//.brokkr/...' against the blend file, as the add-on does + import tempfile + with tempfile.TemporaryDirectory() as tmp: + blend = Path(tmp).resolve() + (blend / ".brokkr").mkdir() + (blend / ".brokkr" / "blender-editor.ccmp").write_bytes(b"") + + def abspath(p): + return str(blend / p[2:]) if p.startswith("//") else p + + target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=abspath))) + self.assertTrue(target.store_exists(bt.DEFAULT_CULTMESH_CACHE_PATH)) + self.assertTrue(target.store_exists("")) # an empty preference means the default + self.assertEqual(Path(target.resolve_cache_path(bt.DEFAULT_CULTMESH_CACHE_PATH)), + blend / ".brokkr" / "blender-editor.ccmp") + (blend / ".brokkr" / "blender-editor.ccmp").unlink() + self.assertFalse(target.store_exists(bt.DEFAULT_CULTMESH_CACHE_PATH)) + + def test_the_preference_default_is_the_blend_relative_path_the_target_resolves(self): + prop = addon.BrokkrPreferences.__annotations__["cultmesh_cache_path"] + self.assertEqual(prop.kwargs["default"], "//.brokkr/blender-editor.ccmp") + self.assertEqual(bt.DEFAULT_CULTMESH_CACHE_PATH, prop.kwargs["default"]) + + +class HandlerWiringTests(unittest.TestCase): + def setUp(self): + self.lists = {name: [] for name in ("depsgraph_update_post", "undo_post", "redo_post", "load_post")} + handlers = NS(persistent=lambda f: setattr(f, "persistent", True) or f, **self.lists) + self.fake = NS(app=NS(handlers=handlers, timers=NS(is_registered=lambda f: False, register=lambda *a, **k: None, + unregister=lambda f: None)), + utils=NS(register_class=lambda c: None, unregister_class=lambda c: None)) + patch = unittest.mock.patch.multiple(addon.bpy, app=self.fake.app, utils=self.fake.utils) + patch.start() + self.addCleanup(patch.stop) + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + + def test_register_adds_persistent_human_edit_handlers_and_unregister_removes_them(self): + addon.register() + for name in ("depsgraph_update_post", "undo_post", "redo_post", "load_post"): + ours = [h for h in self.lists[name] if getattr(h, "persistent", False)] + self.assertEqual(len(ours), 1, name) + self.assertIn(addon._auto_capture, self.lists["depsgraph_update_post"]) # the snapshot handler stays + self.assertEqual(len(self.lists["depsgraph_update_post"]), 2) + addon.register() # twice adds nothing + self.assertEqual(len(self.lists["depsgraph_update_post"]), 2) + addon.unregister() + self.assertEqual([len(v) for v in self.lists.values()], [0, 0, 0, 0]) + + def test_the_handlers_feed_the_target(self): + addon.register() + addon._target = self.target + track = next(h for h in self.lists["depsgraph_update_post"] if getattr(h, "persistent", False)) + track(None, depsgraph(update("Cube", transform=True))) + self.assertEqual(self.target.human_edit_seq, 1) + self.lists["undo_post"][0](None) + self.lists["redo_post"][0](None) + self.assertEqual(self.target.human_edit_seq, 3) + before = self.target.session_id + self.lists["load_post"][0](None) + self.assertNotEqual(self.target.session_id, before) + self.assertEqual(self.target.human_edit_seq, 0) + + def test_the_human_edit_tracker_does_not_depend_on_auto_capture(self): + # always on: it reads no preference at all + source = inspect.getsource(addon._track_human_edits) + self.assertNotRegex(source, r"auto_capture|preferences") + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index bb3a292..ef3ae3b 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -4,6 +4,7 @@ Run: python3 -m unittest discover -s surfaces/blender/tests -v """ from __future__ import annotations +import contextlib import json import os import struct @@ -19,6 +20,7 @@ package = types.ModuleType("brokkr_bridge") package.__path__ = [str(ADDON)] sys.modules.setdefault("brokkr_bridge", package) +from brokkr_bridge import action_table as at # noqa: E402 from brokkr_bridge import blender_target as bt # noqa: E402 from brokkr_bridge import scene_actions as sa # noqa: E402 @@ -66,7 +68,23 @@ def fake_render(): class Objects(dict): - """bpy.data.objects: a mapping with keys() and get().""" + """bpy.data.objects: a mapping with keys() and get(); like bpy_prop_collection, iterating it yields the objects.""" + + def __iter__(self): + return iter(self.values()) + + +class FakeUndo: + """What run_intent needs of bpy: a window to override and ed.undo_push, recorded.""" + def __init__(self, bpy): + self.pushes = [] + self.overrides = [] + self.window = object() + bpy.context = NS(window_manager=NS(windows=[self.window]), preferences=NS(addons={}), + temp_override=lambda **kw: (self.overrides.append(kw), contextlib.nullcontext())[1]) + ops = getattr(bpy, "ops", None) or NS() + ops.ed = NS(undo_push=lambda message: self.pushes.append(message)) + bpy.ops = ops class FakeBpy: @@ -91,18 +109,22 @@ class FakeBpy: self.exported = [] self.export_result = {"FINISHED"} self.export_writes = True + self.export_siblings = [] # extra files the exporter writes beside the target (textures) + self.export_raises_after_writing = None for o in self.data.objects.values(): o.selected = o is self.mesh o.select_get = (lambda o=o: o.selected) o.select_set = (lambda state, o=o: setattr(o, "selected", state)) - add = lambda kind: (lambda **kw: self.add_object(kind, kw)) + add = lambda kind: (lambda mode, undo, **kw: self.add_object(kind, kw, (mode, undo))) self.ops = NS(import_scene=NS(gltf=self.import_gltf), render=NS(render=self.render_still), export_scene=NS(gltf=self.export_gltf), mesh=NS(primitive_cube_add=add("MESH")), object=NS(light_add=add("LIGHT"), camera_add=add("CAMERA"), empty_add=add("EMPTY"))) self.on_add = lambda obj: None + self.undo = FakeUndo(self) - def add_object(self, kind, kwargs): + def add_object(self, kind, kwargs, call=("EXEC_DEFAULT", False)): + assert call == ("EXEC_DEFAULT", False), call # operators run with undo off self.created.append((kind, kwargs)) obj = NS(name=kind.title(), type=kind) self.data.objects[obj.name] = obj @@ -115,18 +137,28 @@ class FakeBpy: world.background = background return world - def import_gltf(self, filepath): + def import_gltf(self, mode, undo, filepath): + assert (mode, undo) == ("EXEC_DEFAULT", False) self.imported.append(filepath) self.data.objects["Imported"] = NS(name="Imported", type="MESH", data=None) - def export_gltf(self, **kwargs): + def export_gltf(self, mode, undo, **kwargs): + assert (mode, undo) == ("EXEC_DEFAULT", False) kwargs["selected_at_call"] = sorted(o.name for o in self.data.objects.values() if o.selected) self.exported.append(kwargs) + target = Path(kwargs["filepath"]) if self.export_writes: - Path(kwargs["filepath"]).write_bytes(b"x" * 10) + target.write_bytes(b"x" * 10) + if target.suffix == ".gltf": + target.with_suffix(".bin").write_bytes(b"b" * 4) + for name in self.export_siblings: + (target.parent / name).write_bytes(b"t" * 3) + if self.export_raises_after_writing: + raise RuntimeError(self.export_raises_after_writing) return self.export_result - def render_still(self, write_still): + def render_still(self, mode, undo, write_still): + assert (mode, undo) == ("EXEC_DEFAULT", False) r = self.scene.render self.rendered.append((r.engine, r.resolution_x, r.resolution_y, r.filepath, r.image_settings.file_format, self.scene.camera)) @@ -149,8 +181,10 @@ class ActionTests(unittest.TestCase): self.bpy.on_add = lambda obj: setattr(self.context, "object", obj) def run_action(self, **command): - command.setdefault("commandId", "c1") - return self.target.execute_command(self.context, command) + self.n = getattr(self, "n", 0) + 1 + command.setdefault("commandId", f"c{self.n:07d}") + command.setdefault("requestedBy", "nibu/hands") + return self.target.run_intent(self.context, command) # importGltf def test_import_inside_the_import_dir_runs(self): @@ -185,27 +219,18 @@ class ActionTests(unittest.TestCase): # setCamera def test_set_camera_sets_lens_type_panorama_and_active(self): - receipt = self.run_action(action="setCamera", targetObjectName="Cam", lens=35, cameraType="pano", + receipt = self.run_action(action="setCamera", targetObjectName="Cam", lens=35, cameraType="PANO", panoramaType="EQUIRECTANGULAR", active=True, clipEnd=500) self.assertEqual(receipt["status"], "accepted") d = self.bpy.camera_data self.assertEqual((d.lens, d.type, d.panorama_type, d.clip_end), (35.0, "PANO", "EQUIRECTANGULAR", 500.0)) self.assertIs(self.bpy.scene.camera, self.bpy.cam) - def test_set_camera_falls_back_to_the_cycles_panorama_property(self): - cycles = NS(panorama_type="FISHEYE_EQUISOLID", - bl_rna=NS(properties={"panorama_type": Enum("EQUIRECTANGULAR")})) - data = NS(lens=50.0, type="PERSP", cycles=cycles) - self.bpy.data.objects["Cam"] = NS(name="Cam", type="CAMERA", data=data) - receipt = self.run_action(action="setCamera", targetObjectName="Cam", panoramaType="EQUIRECTANGULAR") - self.assertEqual(receipt["status"], "accepted") - self.assertEqual(cycles.panorama_type, "EQUIRECTANGULAR") - def test_set_camera_refused_input_changes_nothing(self): for bad in ({"lens": -1}, {"lens": "wide"}, {"lens": float("nan")}, {"cameraType": "FISHEYE"}, {"panoramaType": "NOPE"}, {"lens": True}): receipt = self.run_action(action="setCamera", targetObjectName="Cam", clipEnd=9, **bad) - self.assertEqual(receipt["status"], "failed", bad) + self.assertEqual(receipt["status"], "denied", bad) # the table's refusal: admission, nothing ran self.assertEqual(self.bpy.camera_data.clip_end, 100.0) self.assertEqual(self.run_action(action="setCamera", targetObjectName="Lamp", lens=35)["status"], "failed") self.assertEqual(self.run_action(action="setCamera", targetObjectName="Nope", lens=35)["status"], "failed") @@ -218,7 +243,7 @@ class ActionTests(unittest.TestCase): def test_set_light_rejects_bad_values_whole(self): for bad in ({"energy": -5}, {"color": [2, 0, 0]}, {"color": [1, 0]}, {"color": "red"}, {"lightType": "LASER"}): - self.assertEqual(self.run_action(action="setLight", targetObjectName="Lamp", **bad)["status"], "failed", bad) + self.assertEqual(self.run_action(action="setLight", targetObjectName="Lamp", **bad)["status"], "denied", bad) self.assertEqual(self.bpy.light_data.energy, 1000.0) self.assertEqual(self.run_action(action="setLight", targetObjectName="Cam", energy=1)["status"], "failed") @@ -232,7 +257,7 @@ class ActionTests(unittest.TestCase): self.assertEqual(world.background.inputs["Strength"].default_value, 2.0) def test_set_world_refuses_bad_colour_before_creating_a_world(self): - self.assertEqual(self.run_action(action="setWorld", color=[9, 0, 0])["status"], "failed") + self.assertEqual(self.run_action(action="setWorld", color=[9, 0, 0])["status"], "denied") self.assertIsNone(self.bpy.scene.world) # exportGltf @@ -243,8 +268,11 @@ class ActionTests(unittest.TestCase): self.assertIn(path, receipt["message"]) self.assertIn("10 bytes", receipt["message"]) call = self.bpy.exported[0] - self.assertEqual({k: v for k, v in call.items() if k != "selected_at_call"}, - {"filepath": path, "export_format": "GLB", "export_extras": True, + staged = Path(call["filepath"]) # the exporter writes into a staging folder, then Brokkr moves the file + self.assertEqual((staged.name, staged.parent.parent, staged.parent.name.startswith(".brokkr-export-")), + ("a.glb", self.root / "out" / "ship", True)) + self.assertEqual({k: v for k, v in call.items() if k not in ("selected_at_call", "filepath")}, + {"export_format": "GLB", "export_extras": True, "export_yup": True, "export_apply": True, "use_selection": False}) def test_export_gltf_suffix_is_separate_and_options_pass_through(self): @@ -289,7 +317,7 @@ class ActionTests(unittest.TestCase): self.assertFalse((self.root / "out" / "b.glb").exists()) def test_export_selection_restored_when_the_exporter_raises(self): - def boom(**kw): + def boom(*a, **kw): raise RuntimeError("exporter blew up") self.bpy.ops.export_scene.gltf = boom receipt = self.run_action(action="exportGltf", filepath="a.glb", selection=["Cam"]) @@ -299,18 +327,16 @@ class ActionTests(unittest.TestCase): def test_export_refusals_never_reach_bpy_or_disk(self): (self.root / "out" / "taken.glb").write_bytes(b"old") + denied = [{"filepath": 5}, {"filepath": "a.glb", "selection": []}, {"filepath": "a.glb", "selection": "Cube"}, + {"filepath": "a.glb", "selection": [3]}, {"filepath": "a.glb", "extras": "yes"}, {"filepath": "a.glb", "yUp": 1}] + for case in denied: # the table refuses these at admission + self.assertEqual(self.run_action(action="exportGltf", **case)["status"], "denied", case) cases = [ - {"filepath": "a.obj"}, {"filepath": "a"}, {"filepath": ""}, {"filepath": 5}, + {"filepath": "a.obj"}, {"filepath": "a"}, {"filepath": ""}, {"filepath": "../a.glb"}, {"filepath": str(self.root / "a.glb")}, {"filepath": "taken.glb"}, {"filepath": "a.glb", "selection": ["Nope"]}, {"filepath": "a.glb", "selection": ["Cube", "Nope"]}, - {"filepath": "a.glb", "selection": []}, - {"filepath": "a.glb", "selection": "Cube"}, - {"filepath": "a.glb", "selection": [3]}, - {"filepath": "a.glb", "extras": "yes"}, - {"filepath": "a.glb", "yUp": 1}, - {"filepath": "a.glb", "applyModifiers": None}, ] for case in cases: self.assertEqual(self.run_action(action="exportGltf", **case)["status"], "failed", case) @@ -319,13 +345,237 @@ class ActionTests(unittest.TestCase): self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken.glb"]) self.assertIn("already exists", self.run_action(action="exportGltf", filepath="taken.glb")["message"]) - def test_export_gltf_refuses_an_existing_bin_sibling(self): + def test_export_gltf_writes_its_bin_and_textures_beside_it_and_nothing_else(self): + self.bpy.export_siblings = ["tex.png"] + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(receipt["status"], "accepted", receipt) + self.assertEqual(sorted(p.name for p in (self.root / "out" / "sub").iterdir()), ["a.bin", "a.gltf", "tex.png"]) + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["sub"]) # no staging folder left + + def test_export_gltf_refuses_an_existing_bin_sibling_and_keeps_it(self): (self.root / "out" / "a.bin").write_bytes(b"old") - self.assertEqual(self.run_action(action="exportGltf", filepath="a.gltf")["status"], "failed") - self.assertEqual(self.bpy.exported, []) + receipt = self.run_action(action="exportGltf", filepath="a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertIn("a.bin", receipt["message"]) + self.assertEqual((self.root / "out" / "a.bin").read_bytes(), b"old") + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["a.bin"]) + + def test_export_gltf_never_overwrites_a_texture_the_exporter_writes(self): + (self.root / "out" / "tex.png").write_bytes(b"old") + self.bpy.export_siblings = ["tex.png"] + receipt = self.run_action(action="exportGltf", filepath="a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertIn("tex.png", receipt["message"]) + self.assertEqual((self.root / "out" / "tex.png").read_bytes(), b"old") + self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["tex.png"]) # no a.gltf, no a.bin + + def test_a_failed_export_leaves_no_file_no_folder_and_the_name_can_be_retried(self): + self.bpy.export_raises_after_writing = "exporter died midway" + receipt = self.run_action(action="exportGltf", filepath="new/deep/a.glb") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(list((self.root / "out").iterdir()), []) + self.bpy.export_raises_after_writing = None + retry = self.run_action(action="exportGltf", filepath="new/deep/a.glb") + self.assertEqual(retry["status"], "accepted", retry) + self.assertTrue((self.root / "out" / "new" / "deep" / "a.glb").is_file()) + + def test_a_move_that_fails_partway_rolls_back_so_the_target_is_untouched_and_retry_works(self): + self.bpy.export_siblings = ["tex1.png", "tex2.png"] + real_rename = os.rename + calls = [] + + def fail_on_third(src, dst): + calls.append(dst) + if len(calls) == 3: + raise OSError("disk full") + return real_rename(src, dst) + + with mock.patch.object(bt.os, "rename", fail_on_third): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertGreaterEqual(len(calls), 3) + self.assertEqual(list((self.root / "out").iterdir()), []) # nothing moved stays; no staging, no new folder + retry = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(retry["status"], "accepted", retry) + self.assertEqual(sorted(p.name for p in (self.root / "out" / "sub").iterdir()), + ["a.bin", "a.gltf", "tex1.png", "tex2.png"]) + + HOLD_STAGE = ( + "import sys\n" + "sys.path.insert(0, sys.argv[1])\n" + "import types\n" + "pkg = types.ModuleType('brokkr_bridge'); pkg.__path__ = [sys.argv[1] + '/brokkr_bridge']\n" + "sys.modules['brokkr_bridge'] = pkg\n" + "from brokkr_bridge import blender_target as bt\n" + "from pathlib import Path\n" + "stage, fd = bt._open_stage(Path(sys.argv[2]))\n" + "print(stage, flush=True)\n" + "sys.stdin.read()\n") + + def start_export_holding_a_stage(self): + import subprocess + child = subprocess.Popen([sys.executable, "-c", self.HOLD_STAGE, str(ADDON.parent), str(self.root / "out")], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + self.addCleanup(child.kill) + self.addCleanup(child.wait) + self.addCleanup(child.stdout.close) + self.addCleanup(child.stdin.close) + return child, Path(child.stdout.readline().strip()) + + def test_a_sweep_spares_another_processs_live_stage_and_removes_a_killed_ones(self): + child, stage = self.start_export_holding_a_stage() + (stage / "a.glb").write_bytes(b"in flight") + os.utime(stage, (0, 0)) # old by any clock: only the lock decides + bt._sweep_stale_stages(self.root / "out") + self.assertTrue((stage / "a.glb").exists()) + self.assertEqual(self.run_action(action="exportGltf", filepath="b.glb")["status"], "accepted") + self.assertTrue((stage / "a.glb").exists()) # an export in this process swept too + child.kill() + child.wait() + bt._sweep_stale_stages(self.root / "out") + self.assertFalse(stage.exists()) + + def test_a_stage_killed_at_each_step_is_swept_by_the_next_export(self): + out = self.root / "out" + lock_only = out / ".brokkr-export-1.lock" # killed after taking the lock, before making the folder + lock_only.write_bytes(b"") + empty = out / ".brokkr-export-2" # killed after making the folder, before staging anything + empty.mkdir() + (out / ".brokkr-export-2.lock").write_bytes(b"") + mid = out / ".brokkr-export-3" # killed mid-export with files staged + mid.mkdir() + (mid / "a.glb").write_bytes(b"half") + (out / ".brokkr-export-3.lock").write_bytes(b"") + self.assertEqual(self.run_action(action="exportGltf", filepath="b.glb")["status"], "accepted") + self.assertEqual([p.name for p in out.iterdir()], ["b.glb"]) + + def test_a_stage_made_the_old_way_is_swept_with_its_journal_so_the_export_can_retry(self): + out = self.root / "out" + out.mkdir(exist_ok=True) + (out / "a.glb").write_bytes(b"left by a failed rollback") + old = out / ".brokkr-export-old" + old.mkdir() + (old / ".brokkr-lock").write_bytes(b"") + (old / ".brokkr-journal").write_text("a.glb", encoding="utf-8") + unlocked = out / ".brokkr-export-nolock" + unlocked.mkdir() + self.assertEqual(self.run_action(action="exportGltf", filepath="a.glb")["status"], "accepted") + self.assertEqual([p.name for p in out.iterdir()], ["a.glb"]) + self.assertNotEqual((out / "a.glb").read_bytes(), b"left by a failed rollback") + + def test_a_stage_whose_lock_a_sweep_briefly_holds_is_locked_after_a_short_wait(self): + calls = [] + real = bt._try_lock + + def busy_twice(fd): + calls.append(fd) + return len(calls) > 2 and real(fd) + + with mock.patch.object(bt, "_try_lock", busy_twice): + stage, fd = bt._open_stage(self.root / "out") + os.close(fd) + self.assertEqual(len(calls), 3) + + def test_a_lock_file_the_os_will_not_unlink_is_left_for_the_next_sweep(self): + stage, fd = bt._open_stage(self.root / "out") + with mock.patch.object(Path, "unlink", side_effect=PermissionError("held")): + bt._close_stage(stage, fd) # no error + self.assertTrue(bt._stage_lock_path(stage).exists()) + bt._sweep_stale_stages(self.root / "out") + self.assertEqual(list((self.root / "out").iterdir()), []) + + def test_every_stage_is_locked_before_its_folder_exists(self): + real_mkdir = Path.mkdir + seen = [] + + def watch(path, *args, **kw): + if path.name.startswith(bt.EXPORT_STAGE_PREFIX): + seen.append(bt._stage_lock_path(path).exists()) + return real_mkdir(path, *args, **kw) + + with mock.patch.object(Path, "mkdir", watch): + stage, fd = bt._open_stage(self.root / "out") + os.close(fd) + self.assertEqual(seen, [True]) + + def test_a_concurrent_sweep_during_a_failed_move_never_loses_the_journal(self): + self.bpy.export_siblings = ["tex1.png"] + real_rename = os.rename + real_write = Path.write_text + calls = [] + + def fail_forever_from_third(src, dst): + calls.append(dst) + if len(calls) >= 3: + raise OSError("disk gone") + return real_rename(src, dst) + + def sweep_then_write(path, *args, **kw): + if path.name == bt.STAGE_JOURNAL: + bt._sweep_stale_stages(self.root / "out") # another export's sweep, mid-failure + self.assertTrue(path.parent.is_dir()) + return real_write(path, *args, **kw) + + with mock.patch.object(bt.os, "rename", fail_forever_from_third), mock.patch.object(Path, "write_text", sweep_then_write): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertIn("could not be rolled back", receipt["message"]) + journals = list((self.root / "out").glob("**/" + bt.STAGE_JOURNAL)) + self.assertEqual(len(journals), 1) + self.assertIn("a.bin", journals[0].read_text(encoding="utf-8")) + + def test_a_failed_rollback_is_refused_loudly_naming_the_files_and_the_next_export_recovers(self): + self.bpy.export_siblings = ["tex1.png"] + real_rename = os.rename + calls = [] + + def fail_forever_from_third(src, dst): + calls.append(dst) + if len(calls) >= 3: + raise OSError("disk gone") + return real_rename(src, dst) + + with mock.patch.object(bt.os, "rename", fail_forever_from_third): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertIn("could not be rolled back", receipt["message"]) + self.assertIn("sub/a.bin", receipt["message"]) + self.assertIn("sub/a.gltf", receipt["message"]) + self.assertTrue((self.root / "out" / "sub" / "a.bin").exists()) + retry = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertEqual(retry["status"], "accepted", retry) + self.assertEqual(sorted(p.name for p in (self.root / "out").rglob("*") if p.is_file()), + ["a.bin", "a.gltf", "tex1.png"]) + self.assertEqual([p.name for p in (self.root / "out").iterdir()], ["sub"]) # no stage left + + def test_a_failed_texture_subfolder_move_leaves_no_empty_folder(self): + self.bpy.export_siblings = [] + real_rename = os.rename + + def fail_the_texture(src, dst): + if "textures" in str(dst): + raise OSError("no") + return real_rename(src, dst) + + orig = self.bpy.export_gltf + + def with_subfolder(mode, undo, **kw): + result = orig(mode, undo, **kw) + target = Path(kw["filepath"]) + (target.parent / "textures").mkdir() + (target.parent / "textures" / "t.png").write_bytes(b"t") + return result + + self.bpy.ops.export_scene.gltf = with_subfolder + with mock.patch.object(bt.os, "rename", fail_the_texture): + receipt = self.run_action(action="exportGltf", filepath="a.gltf") + self.assertEqual(receipt["status"], "failed") + self.assertEqual(list((self.root / "out").iterdir()), []) def test_export_refuses_a_symlinked_folder(self): - os.symlink(self.root, self.root / "out" / "link") + try: + os.symlink(self.root, self.root / "out" / "link") + except OSError: + self.skipTest("the OS denies symlink creation to this user") self.assertEqual(self.run_action(action="exportGltf", filepath="link/a.glb")["status"], "failed") self.assertEqual(self.bpy.exported, []) @@ -349,7 +599,7 @@ class ActionTests(unittest.TestCase): # renderStill def test_render_still_writes_inside_output_dir_and_restores_settings(self): - receipt = self.run_action(action="renderStill", outputPath="shots/a.png", engine="cycles", + receipt = self.run_action(action="renderStill", outputPath="shots/a.png", engine="CYCLES", resolutionX=640, resolutionY=360, cameraName="Cam") self.assertEqual(receipt["status"], "accepted") engine, x, y, filepath, fmt, camera = self.bpy.rendered[0] @@ -362,17 +612,20 @@ class ActionTests(unittest.TestCase): self.assertIsNone(self.bpy.scene.camera) def test_render_still_restores_settings_when_the_render_fails(self): - def boom(write_still): + def boom(*a, **kw): raise RuntimeError("render failed") self.bpy.ops.render.render = boom self.assertEqual(self.run_action(action="renderStill", outputPath="a.png", engine="CYCLES")["status"], "failed") self.assertEqual(self.bpy.scene.render.engine, "BLENDER_EEVEE") def test_render_still_outside_the_output_dir_or_with_bad_input_never_renders(self): + for case in ({"outputPath": "a.png", "resolutionX": 0}, {"outputPath": "a.png", "resolutionX": 3}, + {"outputPath": "a.png", "resolutionX": 99999}, {"outputPath": "a.png", "resolutionX": 10.5}, + {"outputPath": "a.png", "engine": ""}, {"outputPath": "a.png", "resolutionY": "x"}): + self.assertEqual(self.run_action(action="renderStill", **case)["status"], "denied", case) cases = [{"outputPath": "../a.png"}, {"outputPath": str(self.root / "a.png")}, {"outputPath": "a.txt"}, - {"outputPath": ""}, {"outputPath": "a.png", "engine": "NOPE"}, - {"outputPath": "a.png", "resolutionX": 0}, {"outputPath": "a.png", "resolutionX": 99999}, - {"outputPath": "a.png", "resolutionX": 10.5}, {"outputPath": "a.png", "cameraName": "Lamp"}] + {"outputPath": ""}, {"outputPath": "a.png", "engine": "NOPE"}, {"outputPath": "a.png", "engine": "cycles"}, + {"outputPath": "a.png", "cameraName": "Lamp"}] for case in cases: self.assertEqual(self.run_action(action="renderStill", **case)["status"], "failed", case) self.assertEqual(self.bpy.rendered, []) @@ -385,47 +638,57 @@ class ActionTests(unittest.TestCase): receipt = self.run_action(action="createObject", objectType=kind, name="N") self.assertEqual(receipt["status"], "accepted", kind) self.assertEqual(self.bpy.created[-1][0], kind) - self.assertEqual(self.run_action(action="createObject", objectType="MESH", meshType="cube")["status"], "accepted") + self.assertEqual(self.run_action(action="createObject", objectType="MESH", meshType="CUBE")["status"], "accepted") - def test_create_object_refuses_other_types_naming_the_type_and_the_allowed_set(self): - for kind in ("TEXT", "CURVE", "mesh", "", None, 3): + def test_create_object_refuses_other_types_naming_the_field_and_the_allowed_set(self): + for kind in ("TEXT", "CURVE", "mesh", ""): receipt = self.run_action(action="createObject", objectType=kind) - self.assertEqual(receipt["status"], "failed", kind) - for allowed in ("MESH", "LIGHT", "CAMERA", "EMPTY"): - self.assertIn(allowed, receipt["message"]) - self.assertIn(repr(kind) if not isinstance(kind, str) else kind, receipt["message"]) + self.assertEqual(receipt["status"], "denied", kind) + self.assertEqual(receipt["message"], "objectType must be one of MESH, LIGHT, CAMERA, EMPTY.") + receipt = self.run_action(action="createObject", objectType=3) + self.assertEqual((receipt["status"], receipt["message"]), ("denied", "objectType must be a string.")) self.assertEqual(self.bpy.created, []) + self.assertEqual(self.run_action(action="createObject", objectType=None)["status"], "accepted") # null is absent: EMPTY + self.assertEqual(self.bpy.created[-1][0], "EMPTY") def test_create_object_refuses_a_mesh_type_other_than_cube(self): - for mesh_type in ("CYLINDER", "", 1, " CUBE", "CUBE "): + for mesh_type in ("CYLINDER", "", 1, " CUBE", "CUBE ", "cube"): receipt = self.run_action(action="createObject", objectType="MESH", meshType=mesh_type) - self.assertEqual(receipt["status"], "failed", mesh_type) - self.assertIn("CUBE", receipt["message"]) + self.assertEqual(receipt["status"], "denied", mesh_type) + self.assertIn("meshType must be", receipt["message"]) self.assertEqual(self.bpy.created, []) - # renderStill: GPU engines without a GL runtime - def test_render_still_refuses_gpu_engines_headless_when_the_gl_library_is_missing(self): + def test_mesh_type_on_a_non_mesh_object_is_refused_not_ignored(self): + for object_type in ("LIGHT", "EMPTY", "CAMERA"): + receipt = self.run_action(action="createObject", objectType=object_type, meshType="CUBE") + self.assertEqual(receipt["status"], "denied", object_type) + self.assertEqual(receipt["message"], "meshType applies only when objectType is one of MESH.") + self.assertEqual(self.run_action(action="createObject", meshType="CUBE")["status"], "denied") # objectType absent is EMPTY + self.assertEqual(self.bpy.created, []) + + # renderStill: GPU engines that would abort a headless Blender + def test_render_still_refuses_gpu_engines_headless_when_a_test_render_fails(self): self.bpy.app.background = True - for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT", "blender_workbench"): + for engine in ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"): self.bpy.scene.render.ENGINES = FakeRender.ENGINES + ("BLENDER_EEVEE_NEXT",) - with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"): + with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"): receipt = self.run_action(action="renderStill", outputPath="a.png", engine=engine) self.assertEqual(receipt["status"], "failed", engine) - self.assertIn("libEGL.so.1", receipt["message"]) + self.assertIn("one-pixel test render", receipt["message"]) self.assertIn("CYCLES", receipt["message"]) self.assertEqual(self.bpy.rendered, []) self.assertEqual(self.bpy.scene.render.engine, "BLENDER_EEVEE") def test_render_still_refuses_the_scene_engine_too_and_leaves_no_folder(self): self.bpy.app.background = True # scene engine is BLENDER_EEVEE - with mock.patch.object(bt, "missing_gl_library", return_value="libEGL.so.1"): + with mock.patch.object(bt, "gl_render_failure", return_value="a one-pixel test render exited with status 134"): receipt = self.run_action(action="renderStill", outputPath="shots/a.png") self.assertEqual(receipt["status"], "failed") self.assertFalse((self.root / "out" / "shots").exists()) - def test_render_still_gl_check_spares_cycles_foreground_and_a_present_library(self): - probe = mock.Mock(return_value="libEGL.so.1") - with mock.patch.object(bt, "missing_gl_library", probe): + def test_render_still_gl_check_spares_cycles_foreground_and_a_working_test_render(self): + probe = mock.Mock(return_value="a one-pixel test render exited with status 134") + with mock.patch.object(bt, "gl_render_failure", probe): self.bpy.app.background = True self.assertEqual(self.run_action(action="renderStill", outputPath="a.png", engine="CYCLES")["status"], "accepted") probe.assert_not_called() @@ -436,20 +699,94 @@ class ActionTests(unittest.TestCase): probe.return_value = None self.assertEqual(self.run_action(action="renderStill", outputPath="c.png", engine="BLENDER_WORKBENCH")["status"], "accepted") - def test_missing_gl_library_probes_only_on_linux_and_only_once(self): - bt.missing_gl_library.cache_clear() - with mock.patch.object(bt.sys, "platform", "win32"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll: - self.assertIsNone(bt.missing_gl_library()) - cdll.assert_not_called() - bt.missing_gl_library.cache_clear() - with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL", side_effect=OSError) as cdll: - self.assertEqual(bt.missing_gl_library(), "libEGL.so.1") - self.assertEqual(bt.missing_gl_library(), "libEGL.so.1") - cdll.assert_called_once_with("libEGL.so.1") - bt.missing_gl_library.cache_clear() - with mock.patch.object(bt.sys, "platform", "linux"), mock.patch.object(bt.ctypes, "CDLL"): - self.assertIsNone(bt.missing_gl_library()) - bt.missing_gl_library.cache_clear() + def fake_blender(self, status, marker=True): + """A stand-in Blender binary: a script that ignores its arguments, prints the probe's completion + marker (or not) and exits with status.""" + if os.name == "nt": + path = self.root / "fake_blender.cmd" + path.write_text("@echo off\r\n" + ("echo BROKKR_GL_PROBE_OK\r\n" if marker else "") + f"exit /b {status}\r\n") + else: + path = self.root / "fake_blender.sh" + path.write_text("#!/bin/sh\n" + ("echo BROKKR_GL_PROBE_OK\n" if marker else "") + f"exit {status}\n") + path.chmod(0o755) + return str(path) + + def test_gl_probe_passes_when_the_test_render_finishes_and_says_so(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + self.assertIsNone(bt.gl_render_failure(self.fake_blender(0), "BLENDER_EEVEE")) + + def test_gl_probe_fails_on_an_abort_a_missing_marker_a_hang_and_an_unknown_binary(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + self.assertIn("status 3", bt.gl_render_failure(self.fake_blender(3), "BLENDER_EEVEE")) + self.assertIn("status 0", bt.gl_render_failure(self.fake_blender(0, marker=False), "BLENDER_WORKBENCH")) + with mock.patch.object(bt, "GL_PROBE_TIMEOUT_SECONDS", 0.001): + self.assertIn("did not finish", bt.gl_render_failure(self.fake_blender(0), "BLENDER_EEVEE_NEXT")) + self.assertIn("unknown", bt.gl_render_failure("", "BLENDER_EEVEE")) + self.assertIn("unknown", bt.gl_render_failure(str(self.root / "missing"), "BLENDER_EEVEE")) + + def slow_blender(self): + """A stand-in that starts a child which holds the output pipe for 30 s.""" + if os.name == "nt": + path = self.root / "slow_blender.cmd" + path.write_text("@echo off\r\nping -n 30 127.0.0.1 >nul\r\n") + else: + path = self.root / "slow_blender.sh" + path.write_text("#!/bin/sh\nsleep 30\necho BROKKR_GL_PROBE_OK\n") + path.chmod(0o755) + return path + + def test_gl_probe_timeout_returns_on_time_killing_the_childs_children_and_is_not_cached(self): + import time + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + slow = self.slow_blender() + with mock.patch.object(bt, "GL_PROBE_TIMEOUT_SECONDS", 1): + started = time.monotonic() + failure = bt.gl_render_failure(str(slow), "BLENDER_EEVEE") + took = time.monotonic() - started + self.assertIn("did not finish", failure) + self.assertLess(took, 10) + # the same binary and engine, now fast: a timeout was not remembered + slow.unlink() + fast = self.fake_blender(0) + os.replace(fast, str(slow.with_suffix(Path(fast).suffix))) + self.assertIsNone(bt.gl_render_failure(str(slow.with_suffix(Path(fast).suffix)), "BLENDER_EEVEE")) + + def test_gl_probe_caches_a_definite_abort_and_forgets_an_unstartable_binary(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + binary = self.fake_blender(3) + self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE")) + self.fake_blender(0) # same path, now a working binary: the abort is still the answer + self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE")) + with mock.patch.object(bt.subprocess, "Popen", side_effect=OSError("denied")): + self.assertIn("could not start", bt.gl_render_failure(binary, "BLENDER_WORKBENCH")) + self.assertIsNone(bt.gl_render_failure(binary, "BLENDER_WORKBENCH")) + + def test_gl_probe_runs_once_per_binary_and_engine(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + binary = self.fake_blender(0) + with mock.patch.object(bt.subprocess, "Popen", wraps=bt.subprocess.Popen) as run: + bt.gl_render_failure(binary, "BLENDER_EEVEE") + bt.gl_render_failure(binary, "BLENDER_EEVEE") + bt.gl_render_failure(binary, "BLENDER_WORKBENCH") + self.assertEqual(run.call_count, 2) + + def test_render_still_end_to_end_with_a_binary_that_aborts_and_one_that_renders(self): + bt.gl_render_failure.cache_clear() + self.addCleanup(bt.gl_render_failure.cache_clear) + self.bpy.app.background = True + self.bpy.app.binary_path = self.fake_blender(134) + refused = self.run_action(action="renderStill", outputPath="a.png") + self.assertEqual(refused["status"], "failed") + self.assertIn("status 134", refused["message"]) + self.assertEqual(self.bpy.rendered, []) + bt.gl_render_failure.cache_clear() + self.bpy.app.binary_path = self.fake_blender(0) + self.assertEqual(self.run_action(action="renderStill", outputPath="a.png")["status"], "accepted") # importGltf: names def test_import_refuses_drive_unc_extended_stream_and_device_names(self): @@ -585,10 +922,12 @@ class ActionTests(unittest.TestCase): def test_a_refused_render_leaves_no_folders_behind(self): (self.root / "out" / "taken").mkdir() (self.root / "out" / "taken" / "a.png").write_bytes(b"x") - for case in ({"outputPath": "new/deep/a.png", "resolutionX": 0}, {"outputPath": "new/deep/a.png", "engine": ""}, {"outputPath": "new/deep/a.png", "engine": "NOPE"}, + for case in ({"outputPath": "new/deep/a.png", "engine": "NOPE"}, {"outputPath": "new/deep/a.png", "cameraName": "Nope"}, {"outputPath": "new/deep/a.txt"}, {"outputPath": "taken/a.png"}): self.assertEqual(self.run_action(action="renderStill", **case)["status"], "failed", case) + for case in ({"outputPath": "new/deep/a.png", "resolutionX": 0}, {"outputPath": "new/deep/a.png", "engine": ""}): + self.assertEqual(self.run_action(action="renderStill", **case)["status"], "denied", case) self.assertIn("already exists", self.run_action(action="renderStill", outputPath="taken/a.png")["message"]) self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken"]) self.assertEqual(self.bpy.rendered, []) diff --git a/surfaces/blender/tests/test_server_guard.py b/surfaces/blender/tests/test_server_guard.py index 439cfe0..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,49 +146,46 @@ class FakeNode: self.database = FakeDatabase(bt.COMMAND_INTENT_SCHEMA, keys) -class PurgeTests(unittest.TestCase): - def make_debug_root(self, tmp): - commands = Path(tmp) / "blender" / "commands" - commands.mkdir(parents=True) - (commands / "a.json").write_text("{}") - (commands / "b.json").write_text("{}") - (commands / "note.txt").write_text("keep") - receipts = Path(tmp) / "blender" / "receipts" - receipts.mkdir() - (receipts / "r.json").write_text("{}") - return commands, receipts +class StopPendingTests(unittest.TestCase): + def test_stop_pending_receipts_each_intent_then_deletes_it(self): + node = FakeNode(["c1", "c2"]) + 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_removes_queued_intents_and_debug_command_files_only(self): - with tempfile.TemporaryDirectory() as tmp: - commands, receipts = self.make_debug_root(tmp) - node = FakeNode(["c1", "c2"]) - removed = sg.purge_command_intents(node, "DOC", bt.COMMAND_INTENT_SCHEMA, tmp) - self.assertEqual(removed, 4) - self.assertEqual(node.database.deleted, [("DOC", "c1"), ("DOC", "c2")]) - self.assertEqual(sorted(p.name for p in commands.iterdir()), ["note.txt"]) - self.assertTrue((receipts / "r.json").exists()) + def test_an_intent_whose_receipt_cannot_be_written_is_not_deleted(self): + node = FakeNode(["c1", "c2"]) - def test_purge_without_a_debug_root_or_node_is_quiet(self): - self.assertEqual(sg.purge_command_intents(None, "DOC", bt.COMMAND_INTENT_SCHEMA, ""), 0) + 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): - with tempfile.TemporaryDirectory() as tmp: - commands, _ = self.make_debug_root(tmp) - target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) - stopped = [] - target._server = types.SimpleNamespace(stop=lambda: stopped.append(True)) - target._guard = sg.SessionGuard() - guard = target._guard - old = guard.token - target._node = FakeNode(["c1"]) - target._documents = {"command_intent": "DOC"} - target._debug_mirror_root = tmp - target.stop_server() - self.assertEqual(stopped, [True]) - self.assertEqual(target._node.database.keys, []) - self.assertEqual(sorted(p.name for p in commands.iterdir()), ["note.txt"]) - self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) - self.assertEqual(target.session_token, "") + target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) + stopped = [] + target._server = types.SimpleNamespace(stop=lambda: stopped.append(True)) + target._guard = sg.SessionGuard() + guard = target._guard + old = guard.token + target._node = FakeNode(["c1"]) + target._documents = {"command_intent": "DOC", "command_receipt": "RDOC"} + target.stop_server() + self.assertEqual(stopped, [True]) + self.assertEqual(target._node.database.keys, []) + self.assertFalse(guard.admits({sg.TOKEN_FIELD: old})) + self.assertEqual(target.session_token, "") def test_stop_server_revokes_and_purges_even_when_the_socket_stop_raises(self): target = bt.BrokkrBlenderTarget(types.SimpleNamespace()) @@ -197,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})) @@ -214,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"]) @@ -229,24 +229,19 @@ class RealServerTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) - self.debug = str(Path(self.tmp.name) / "debug") - commands = Path(self.debug) / "blender" / "commands" - commands.mkdir(parents=True) - (commands / "stale.json").write_text("{}") self.cache = str(Path(self.tmp.name) / "node.ccmp") self.target = bt.BrokkrBlenderTarget(types.SimpleNamespace( path=types.SimpleNamespace(abspath=lambda p: p))) self.addCleanup(self.target.stop_server) def start(self, **kwargs): - return self.target.start_server(self.cache, PACKAGES, "127.0.0.1", 0, 100, 1 << 20, self.debug, **kwargs) + return self.target.start_server(self.cache, PACKAGES, "127.0.0.1", 0, 100, 1 << 20, **kwargs) - def test_default_start_has_no_token_and_purges_stale_debug_commands(self): + def test_default_start_has_no_token(self): status = self.start() self.assertTrue(status["running"]) self.assertFalse(status["tokenRequired"]) self.assertEqual(self.target.session_token, "") - self.assertEqual(list((Path(self.debug) / "blender" / "commands").glob("*.json")), []) self.assertTrue(status["cultmeshModule"].endswith("__init__.py")) self.assertIn("cultmesh_py", status["cultmeshModule"]) self.assertTrue(status["loopback"]) @@ -296,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) @@ -303,25 +314,27 @@ 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, self.debug, + status = self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=True) self.assertTrue(status["running"]) self.assertFalse(status["loopback"]) with self.assertRaises(sg.BindRefused): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=False) self.assertFalse(self.target.server_status()["running"]) def test_unticking_the_allow_stops_a_running_non_loopback_server(self): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug, + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, allow_non_loopback=True) self.target.enforce_bind_policy(False) self.assertFalse(self.target.server_status()["running"]) @@ -378,7 +391,7 @@ class RealServerTests(unittest.TestCase): def test_non_loopback_bind_is_refused_before_anything_starts(self): with self.assertRaises(sg.BindRefused): - self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20, self.debug) + self.target.start_server(self.cache, PACKAGES, "0.0.0.0", 0, 100, 1 << 20) self.assertFalse(self.target.server_status()["running"]) diff --git a/surfaces/blender/tests/test_stop_presence.py b/surfaces/blender/tests/test_stop_presence.py new file mode 100644 index 0000000..ea796b7 --- /dev/null +++ b/surfaces/blender/tests/test_stop_presence.py @@ -0,0 +1,371 @@ +"""Stop and presence: one human control turns the sink off and receipts every pending intent as stopped; +the panel's agent activity is derived from receipts. A fake bpy and a fake node database; no Blender. +""" +from __future__ import annotations + +import re +import tempfile +import types +import unittest +import unittest.mock +from collections import deque +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import test_agent_turn as tat +import test_scene_actions as ts +import test_addon_ui as ui + +bt = ts.bt +NS = types.SimpleNamespace +addon = ui.addon +BRIDGE = Path(bt.__file__).parent +DOCS = {"command_intent": "i", "command_receipt": "r"} + + +class StopFixture(unittest.TestCase): + setUp = ts.ActionTests.setUp + run_action = ts.ActionTests.run_action + intent = tat.DrainTests.intent + + def patched(self, node): + patch = unittest.mock.patch.object(self.target, "_open_node", return_value=(node, DOCS)) + patch.start() + self.addCleanup(patch.stop) + + +class StopPendingTests(StopFixture): + def queue(self): + return tat.FakeNode({f"blender/commands/{n}": self.intent(n, requestedBy=who) + for n, who in (("q-1", "nibu/hands"), ("q-2", "nibu/hands"), ("q-3", "nibu/soul"))}) + + def test_stop_receipts_every_pending_intent(self): + node = self.queue() + self.patched(node) + stopped = self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(stopped, 3) + receipts = dict(node.puts) + self.assertEqual(sorted(receipts), [f"blender/receipts/q-{n}" for n in (1, 2, 3)]) + for key, receipt in receipts.items(): + self.assertEqual(receipt["status"], "stopped", key) + self.assertIn("stopped by the operator", receipt["message"]) + self.assertEqual(receipt["undoLabel"], "") + self.assertEqual(receipt["action"], "createObject") + self.assertEqual(receipts["blender/receipts/q-3"]["requestedBy"], "nibu/soul") + self.assertEqual(sorted(node.deleted), node.initial) + self.assertEqual(self.bpy.created, []) # none dispatched + self.assertEqual(self.bpy.undo.pushes, []) + + def test_every_intent_is_receipted_before_it_is_deleted(self): + node = self.queue() + events = [] + node.put = lambda document, key, value: events.append(("put", key)) + node.delete = lambda document, key: events.append(("delete", key)) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + for n in (1, 2, 3): + self.assertLess(events.index(("put", f"blender/receipts/q-{n}")), + events.index(("delete", f"blender/commands/q-{n}"))) + + def test_a_failed_receipt_write_leaves_the_intent_queued(self): + node = self.queue() + + def put(document, key, value): + raise OSError("disk full") + node.put = put + self.patched(node) + with self.assertRaises(OSError): + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(node.deleted, []) # no silent delete + + def test_a_stopped_id_is_spent_and_a_reused_id_keeps_its_original_receipt(self): + old = {"blender/receipts/q-1": {"commandId": "q-1", "status": "accepted"}} + node = tat.FakeNode({"blender/commands/a": self.intent("q-1"), "blender/commands/b": self.intent("q-2")}, old) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + keys = [k for k, _ in node.puts] + self.assertNotIn("blender/receipts/q-1", keys) # write-once: the accepted receipt stands + self.assertIn("blender/receipts/q-1.stopped", keys) + self.assertIn("blender/receipts/q-2", keys) + later = self.run_action(action="createObject", objectType="EMPTY", commandId="q-2") + self.assertEqual(later["status"], "denied") # the sender resends under a new id + self.assertEqual(self.bpy.created, []) + + def test_a_malformed_id_is_receipted_under_a_fresh_key_naming_the_queue_key(self): + node = tat.FakeNode({"blender/commands/odd": self.intent(["x"])}) + self.patched(node) + self.target.stop_pending("stopped by the operator", "cache", "src") + ((key, receipt),) = node.puts + self.assertNotIn("[", key) + self.assertEqual(receipt["status"], "stopped") + self.assertIn("blender/commands/odd", receipt["message"]) + self.assertEqual(node.deleted, ["blender/commands/odd"]) + + def test_stop_with_nothing_pending_writes_nothing(self): + node = tat.FakeNode({}) + self.patched(node) + self.assertEqual(self.target.stop_pending("stopped by the operator", "cache", "src"), 0) + self.assertEqual((node.puts, node.deleted), ([], [])) + + def test_server_stop_and_start_receipt_with_their_own_reasons(self): + node = self.queue() + self.target._node, self.target._documents = node, DOCS + self.target._server = NS(stop=lambda: None) + self.target.stop_server() + self.assertEqual({v["status"] for _, v in node.puts}, {"stopped"}) + self.assertTrue(all("server stopped" in v["message"] for _, v in node.puts)) + self.assertEqual(len(node.deleted), 3) + + def test_start_server_receipts_stale_intents(self): + node = self.queue() + self.patched(node) + with unittest.mock.patch.object(bt, "_load_cultmesh", side_effect=RuntimeError("stop here")): + with self.assertRaises(RuntimeError): + self.target.start_server("cache", "src", "127.0.0.1", 0, 10, 1 << 20) + self.assertEqual({v["status"] for _, v in node.puts}, {"stopped"}) + self.assertTrue(all("server started" in v["message"] for _, v in node.puts)) + self.assertEqual(len(node.deleted), 3) + + +class DrainLimitTests(StopFixture): + def test_a_limited_drain_runs_that_many_and_leaves_the_rest_queued_for_stop(self): + node = tat.FakeNode({f"blender/commands/{n}": self.intent(n) for n in ("b-1", "b-2", "b-3")}) + node.delete = lambda document, key: (node.deleted.append(key), node.docs[bt.COMMAND_INTENT_SCHEMA].pop(key)) + self.patched(node) + receipts = self.target.drain_commands(self.context, "cache", "src", limit=1) + self.assertEqual([r["commandId"] for r in receipts], ["b-1"]) + self.assertEqual(node.deleted, ["blender/commands/b-1"]) + self.target.stop_pending("stopped by the operator", "cache", "src") + stopped = {v["commandId"]: v["status"] for _, v in node.puts} + self.assertEqual(stopped, {"b-1": "accepted", "b-2": "stopped", "b-3": "stopped"}) + self.assertEqual(len(self.bpy.created), 1) + + +class SnapshotTests(StopFixture): + def test_the_snapshot_carries_the_sink_toggle(self): + self.bpy.data = NS(objects=[], scenes=[], materials=[], images=[], collections=[], filepath="") + self.bpy.app = NS(version=(5, 3, 0)) + context = NS(selected_objects=[], active_object=None, scene=self.bpy.scene, mode="OBJECT") + for enabled in (True, False): + self.assertIs(self.target.capture_snapshot(context, enabled)["agentCommandsEnabled"], enabled) + + +def receipt(agent, action, status, minutes_ago=0, note="", undo="", key="k"): + when = datetime.now(timezone.utc) - timedelta(minutes=minutes_ago) + return {"commandId": key, "requestedBy": agent, "action": action, "status": status, "note": note, + "undoLabel": undo, "observedAt": when.isoformat(), "message": ""} + + +class PresenceTests(StopFixture): + def test_active_agents_are_distinct_requesters_in_the_last_five_minutes(self): + self.target.note_receipt(receipt("nibu/hands", "createObject", "accepted", 1)) + self.target.note_receipt(receipt("nibu/hands", "addNode", "accepted", 2)) + self.target.note_receipt(receipt("nibu/soul", "selectObject", "stopped", 4)) + self.target.note_receipt(receipt("nibu/eyes", "selectObject", "accepted", 6)) + self.assertEqual(self.target.active_agents(), ["nibu/hands", "nibu/soul"]) + + def test_recent_receipts_are_the_last_eight_newest_first(self): + for n in range(12): + self.target.note_receipt(receipt("nibu/hands", f"a{n}", "accepted", key=f"k{n}")) + self.assertEqual([r["action"] for r in self.target.recent_receipts()], [f"a{n}" for n in range(11, 3, -1)]) + + def test_publish_receipt_and_stop_both_fill_the_display_cache(self): + node = tat.FakeNode({"blender/commands/s-1": self.intent("s-1")}) + self.patched(node) + self.target.publish_receipt("cache", "src", receipt("nibu/hands", "createObject", "accepted", key="p-1")) + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual({r["commandId"]: r["status"] for r in self.target.recent_receipts()}, + {"p-1": "accepted", "s-1": "stopped"}) + + def test_first_load_rebuilds_the_cache_from_the_node_once(self): + stored = {f"blender/receipts/{n}": receipt("nibu/hands", "createObject", "accepted", n, key=f"n{n}") + for n in range(1, 4)} + node = tat.FakeNode({}, stored) + self.patched(node) + self.target.load_recent_receipts("cache", "src") + self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1", "n2", "n3"]) + node.docs[bt.COMMAND_RECEIPT_SCHEMA]["blender/receipts/x"] = receipt("a/b", "x", "accepted", key="x") + self.target.load_recent_receipts("cache", "src") + self.assertEqual(len(self.target.recent_receipts()), 3) # loaded once + + def test_loading_after_receipts_were_noted_lists_each_receipt_once(self): + stored = {"blender/receipts/n1": receipt("nibu/hands", "createObject", "accepted", 1, key="n1")} + node = tat.FakeNode({}, stored) + self.patched(node) + self.target.note_receipt(stored["blender/receipts/n1"]) # written by this session before the first draw + self.target.load_recent_receipts("cache", "src") + self.assertEqual([r["commandId"] for r in self.target.recent_receipts()], ["n1"]) + + def test_many_agents_inside_the_window_are_all_active_beyond_eight_receipts(self): + for n in range(20): + self.target.note_receipt(receipt(f"nibu/a{n}", "createObject", "accepted", 1, key=f"m{n}")) + self.assertEqual(len(self.target.active_agents()), 20) + + def test_a_receipt_time_without_a_zone_is_read_as_utc(self): + fresh = receipt("nibu/naive", "createObject", "accepted", 1) + fresh["observedAt"] = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + self.target.note_receipt(fresh) + self.assertEqual(self.target.active_agents(), ["nibu/naive"]) + + def test_pending_reads_zero_the_moment_stop_returns(self): + node = tat.FakeNode({"blender/commands/a": self.intent("a-1"), "blender/commands/b": self.intent("b-1")}) + self.patched(node) + self.assertEqual(self.target.count_pending("cache", "src"), 2) + self.target.stop_pending("stopped by the operator", "cache", "src") + self.assertEqual(self.target.pending_count, 0) + + def test_pending_count_comes_from_the_node(self): + node = tat.FakeNode({"blender/commands/a": self.intent("a"), "blender/commands/b": self.intent("b")}) + self.patched(node) + self.assertEqual(self.target.count_pending("cache", "src"), 2) + + +class PanelAndOperatorTests(unittest.TestCase): + def setUp(self): + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + self.prefs = unittest.mock.MagicMock(auto_drain_commands=True, cultmesh_cache_path="cache", + cultlib_py_src="src", debug_mirror_root="", broker_uri="b") + self.context = NS(preferences=NS(addons={"brokkr_addon": NS(preferences=self.prefs)})) + + def test_stop_agents_turns_the_sink_off_and_receipts_the_queue(self): + node = tat.FakeNode({"blender/commands/a": {"commandId": "a-1", "requestedBy": "x/y", "action": "createObject"}}) + with unittest.mock.patch.object(self.target, "_open_node", return_value=(node, DOCS)): + operator = addon.BROKKR_OT_stop_agents() + result = operator.execute(self.context) + self.assertEqual(result, {"FINISHED"}) + self.assertFalse(self.prefs.auto_drain_commands) + self.assertEqual([v["status"] for _, v in node.puts], ["stopped"]) + self.assertIn("stopped by the operator", node.puts[0][1]["message"]) + + def test_stop_agents_is_registered_and_first_in_the_panel(self): + self.assertIn(addon.BROKKR_OT_stop_agents, addon.classes) + layout = unittest.mock.MagicMock() + panel = addon.BROKKR_PT_status() + panel.layout = layout + panel.draw(self.context) + first = [c for c in layout.mock_calls if c[0] == "operator" or c[0].endswith(".operator")][0] + self.assertEqual(first.args[0], "brokkr.stop_agents") + + def test_the_sink_preference_defaults_off_and_says_only_the_operator_turns_it_on(self): + prop = addon.BrokkrPreferences.__annotations__["auto_drain_commands"] + self.assertIs(prop.kwargs["default"], False) + self.assertIn("operator", prop.kwargs["description"].lower()) + self.assertTrue(callable(prop.kwargs.get("update"))) # the stored snapshot follows the toggle + + def test_toggling_the_sink_republishes_the_stored_snapshot_once_a_node_is_open(self): + update = addon.BrokkrPreferences.__annotations__["auto_drain_commands"].kwargs["update"] + addon.bpy.context = NS() + with unittest.mock.patch.object(self.target, "publish_snapshot") as publish: + update(self.prefs, None) + publish.assert_not_called() # nothing has opened a node: no snapshot to correct + self.target._node = object() + self.prefs.auto_drain_commands = False + update(self.prefs, None) + self.assertEqual(publish.call_args.args[-1], False) + + def test_the_agents_section_lists_agents_pending_and_receipts(self): + self.target.note_receipt(receipt("nibu/hands", "createObject", "accepted", 1, note="a cube", + undo="Brokkr nibu/hands: createObject abcd1234")) + self.target.note_receipt(receipt("nibu/soul", "setLight", "stopped", 2)) + self.target.pending_count = 3 + self.target._receipts_loaded = True + layout = unittest.mock.MagicMock() + panel = addon.BROKKR_PT_status() + panel.layout = layout + panel.draw(self.context) + texts = [str(c.kwargs.get("text", "")) for c in layout.mock_calls if c.kwargs] + joined = "\n".join(texts) + self.assertIn("Agents", joined) + agents_at = [i for i, c in enumerate(layout.mock_calls) if c.kwargs.get("text") == "Agents"][0] + first_sync = [i for i, c in enumerate(layout.mock_calls) if c.args[:1] == ("brokkr.publish_object_sync",)][0] + first_other = [i for i, c in enumerate(layout.mock_calls) if str(c.kwargs.get("text", "")).startswith("Provider")][0] + self.assertLess(agents_at, first_other) # directly under Stop agents, above everything else + self.assertLess(agents_at, first_sync) + self.assertIn("nibu/hands", joined) + self.assertIn("nibu/soul setLight stopped", joined) + self.assertIn("nibu/hands createObject accepted", joined) + self.assertIn("a cube", joined) + self.assertIn("Brokkr nibu/hands: createObject abcd1234", joined) + self.assertRegex(joined, r"Pending: 3") + self.assertNotIn("Last receipt", joined) + + +class TimerTests(unittest.TestCase): + def setUp(self): + self.target = bt.BrokkrBlenderTarget(NS(path=NS(abspath=lambda p: p))) + addon._target = self.target + self.addCleanup(lambda: setattr(addon, "_target", None)) + self.prefs = NS(auto_drain_commands=True, cultmesh_cache_path="c", cultlib_py_src="s", debug_mirror_root="", + import_dir="", output_dir="") + patch = unittest.mock.patch.object(addon, "_redraw") + self.redraws = patch.start() + self.addCleanup(patch.stop) + addon.bpy.context = NS(preferences=NS(addons=NS(get=lambda name: NS(preferences=self.prefs)))) + self.drains, self.counts, self.stops = [], [], [] + self.ran = 0 + self.target.drain_commands = lambda *a, **k: self.drains.append(k) or [1] * self.ran + self.target.count_pending = lambda *a: self.counts.append(a) or 0 + self.target.stop_pending = lambda *a: self.stops.append(a) or 0 + self.target.configure_action_dirs = lambda *a: None + self.target._node = object() + + def test_the_timer_drains_one_intent_per_tick_so_stop_lands_between_them(self): + self.ran = 1 + interval = addon._auto_drain_commands() + self.assertEqual(self.drains[0].get("limit"), 1) + self.assertLess(interval, 0.22) # more may be queued: come back soon (bound: geometric mean of the 0.05 shipped and the 1.0 idle reading) + + def test_an_empty_tick_goes_back_to_the_idle_interval(self): + self.ran = 0 + self.assertEqual(addon._auto_drain_commands(), 1.0) + + def test_with_the_sink_on_the_timer_keeps_the_pending_count_moving(self): + addon._auto_drain_commands() + self.assertEqual(len(self.counts), 1) + + def test_with_the_sink_off_every_arriving_intent_is_answered_stopped_not_queued(self): + self.prefs.auto_drain_commands = False + self.ran = 1 + self.assertEqual(addon._auto_drain_commands(), 1.0) + self.assertEqual(self.drains, []) + self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) + + def test_with_the_sink_on_and_no_node_open_the_timer_still_drains(self): + self.target._node = None + self.ran = 1 + addon._auto_drain_commands() + self.assertEqual(len(self.drains), 1) + + def test_with_the_sink_off_and_an_existing_store_a_closed_node_still_answers_stopped(self): + self.prefs.auto_drain_commands = False + self.target._node = None + with tempfile.TemporaryDirectory() as tmp: + store = Path(tmp) / "node.ccmp" + store.write_bytes(b"") + self.prefs.cultmesh_cache_path = str(store) + addon._auto_drain_commands() + self.assertEqual([call[0] for call in self.stops], ["agent commands are off"]) + + def test_an_idle_session_creates_no_store_and_answers_nothing(self): + self.prefs.auto_drain_commands = False + self.target._node = None + with tempfile.TemporaryDirectory() as tmp: + store = Path(tmp) / "node.ccmp" + self.prefs.cultmesh_cache_path = str(store) + addon._auto_drain_commands() + self.assertFalse(store.exists()) + self.assertEqual((self.stops, self.drains, self.counts), ([], [], [])) + + +class NoPreferenceWritesTests(unittest.TestCase): + def test_no_action_writes_preferences(self): + # the sink toggle is the human's: no intent or action code reaches add-on preferences + for name in ("scene_actions.py", "node_actions.py", "blender_target.py"): + source = (BRIDGE / name).read_text(encoding="utf-8") + self.assertEqual(re.findall(r"[.]preferences\b(?![.]addons[.]keys\(\))|\bprefs\b", source), [], name) + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/blender/tests/test_store_convert.py b/surfaces/blender/tests/test_store_convert.py new file mode 100644 index 0000000..17d6506 --- /dev/null +++ b/surfaces/blender/tests/test_store_convert.py @@ -0,0 +1,129 @@ +"""convert_store and the CultLib guard. No Blender, no bpy. + +Run: CULTLIB_PACKAGES= python3 -m unittest discover -s surfaces/blender/tests -v +Needs the msgpack package and CultLib main with cultcache-py's MessagePack payload default. +""" +from __future__ import annotations + +import hashlib +import os +import sys +import tempfile +import types +import unittest +from pathlib import Path + +ADDON = Path(__file__).resolve().parents[1] / "brokkr_bridge" +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(ADDON)] +sys.modules.setdefault("brokkr_bridge", package) + +from brokkr_bridge import blender_target as bt # noqa: E402 + +PACKAGES = os.environ.get("CULTLIB_PACKAGES", "") + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +@unittest.skipUnless(PACKAGES and Path(PACKAGES).is_dir(), "set CULTLIB_PACKAGES to CultLib's packages directory") +class ConvertStoreTests(unittest.TestCase): + def setUp(self): + self.cultmesh, self.cultcache = bt._load_cultmesh(PACKAGES) + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.source = self.dir / "blender-editor.ccmp" + self.records = {} + old_definitions = [ + self.cultcache.define_document_type(d.type, payload_codec=self.cultcache.JSON_PAYLOAD_CODEC) + for d in bt.bridge_documents(self.cultcache).values() + ] + node = self.cultmesh.CultMesh.start_node(str(self.source), runtime_id="brokkr-test") + for definition in old_definitions: + node.database.register_document(definition) + key = f"test/{definition.type}" + value = {"schema": definition.type, "id": key, "n": 7, "nested": {"a": [1, 2, "é"]}} + node.database.put(definition, key, value) + self.records[(definition.type, key)] = value + # What the old daemon wrote: a raw JSON receipt envelope. + receipt = {"schema": bt.SYNC_RECEIPT_SCHEMA, "receiptId": "r1", "status": "ok"} + store = self.cultcache.SingleFileMessagePackBackingStore(self.source) + import json + store.push(self.cultcache.CultCacheEnvelope( + key="sync/receipts/r1", type=bt.SYNC_RECEIPT_SCHEMA, payload=json.dumps(receipt).encode(), + stored_at="2026-11-27T00:00:00Z", schema_id=bt.SYNC_RECEIPT_SCHEMA)) + self.records[(bt.SYNC_RECEIPT_SCHEMA, "sync/receipts/r1")] = receipt + + def test_converted_store_opens_under_default(self): + import msgpack + before = sha256(self.source) + destination = self.dir / "blender-editor.mp.ccmp" + count = bt.convert_store(str(self.source), str(destination), PACKAGES) + self.assertEqual(count, len(self.records)) + self.assertEqual(sha256(self.source), before) + + node = self.cultmesh.CultMesh.start_node(str(destination), runtime_id="brokkr-test-new") + documents = bt.bridge_documents(self.cultcache) + for document in documents.values(): + node.database.register_document(document) + node.database.pull() + snapshot = node.database.snapshot() + for (schema, key), value in self.records.items(): + self.assertEqual(snapshot[schema][key], value, (schema, key)) + for envelope in self.cultcache.SingleFileMessagePackBackingStore(destination).pull_all(): + decoded = msgpack.unpackb(envelope.payload, raw=False) # raises ExtraData on a trailing byte + self.assertIsInstance(decoded, dict, envelope.key) + + def test_mixed_store_converts_json_and_carries_messagepack(self): + import msgpack + # What the new daemon appends to an old store before the operator converts it. + appended = {"schema": bt.SYNC_RECEIPT_SCHEMA, "receiptId": "r2", "status": "ok"} + self.cultcache.SingleFileMessagePackBackingStore(self.source).push(self.cultcache.CultCacheEnvelope( + key="sync/receipts/r2", type=bt.SYNC_RECEIPT_SCHEMA, payload=msgpack.packb(appended), + stored_at="2026-11-27T01:00:00Z", schema_id=bt.SYNC_RECEIPT_SCHEMA)) + before = sha256(self.source) + destination = self.dir / "mixed.mp.ccmp" + self.assertEqual(bt.convert_store(str(self.source), str(destination), PACKAGES), len(self.records) + 1) + self.assertEqual(sha256(self.source), before) + node = self.cultmesh.CultMesh.start_node(str(destination), runtime_id="brokkr-test-mixed") + for document in bt.bridge_documents(self.cultcache).values(): + node.database.register_document(document) + node.database.pull() + snapshot = node.database.snapshot() + self.assertEqual(snapshot[bt.SYNC_RECEIPT_SCHEMA]["sync/receipts/r2"], appended) + for (schema, key), value in self.records.items(): + self.assertEqual(snapshot[schema][key], value, (schema, key)) + + def test_convert_store_writes_only_a_new_file(self): + destination = self.dir / "new.ccmp" + bt.convert_store(str(self.source), str(destination), PACKAGES) + source_bytes, destination_bytes = self.source.read_bytes(), destination.read_bytes() + with self.assertRaises(Exception) as caught: + bt.convert_store(str(self.source), str(destination), PACKAGES) + self.assertIn("destination_exists", str(caught.exception)) + self.assertEqual(self.source.read_bytes(), source_bytes) + self.assertEqual(destination.read_bytes(), destination_bytes) + + +class LoadGuardTests(unittest.TestCase): + def test_load_cultmesh_refuses_json_default_cultcache(self): + names = ("cultcache_py", "cultmesh_py") + saved = {name: sys.modules.get(name) for name in names} + try: + sys.modules["cultcache_py"] = types.ModuleType("cultcache_py") # no convert + sys.modules["cultmesh_py"] = types.ModuleType("cultmesh_py") + with self.assertRaises(RuntimeError) as caught: + bt._load_cultmesh("") + self.assertIn("MessagePack payload default", str(caught.exception)) + finally: + for name, module in saved.items(): + if module is None: + sys.modules.pop(name, None) + else: + sys.modules[name] = module + + +if __name__ == "__main__": + unittest.main() diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs index fccfe07..1c46ed7 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs @@ -77,8 +77,9 @@ namespace GameCult.Brokkr.Editor internal async Task PublishSnapshotAsync(BrokkrHostSnapshot snapshot) { RequireRunning(); + snapshot.RefuseDefaultLists(); await node.Database.PutAsync(new CultRecordKey("unity/host/current"), snapshot); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } // Command ids are single-use: a caller with no id gets a fresh one, and reusing an answered id is a defect. @@ -91,42 +92,42 @@ namespace GameCult.Brokkr.Editor } await node.Database.PutAsync(BrokkrCommandLedger.CommandKey(command.commandId), command); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishQuestRouteAsync(BrokkrQuestRoute route) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"unity/quest-routes/{route.id}"), route); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishSyncSessionAsync(BrokkrSyncSession session) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/sessions/{session.sessionId}"), session); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishSyncObjectBindingAsync(BrokkrSyncObjectBinding binding) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/bindings/objects/{binding.bindingId}"), binding); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishSyncVarAsync(BrokkrSyncVar syncVar) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/vars/{syncVar.syncVarId}"), syncVar); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal async Task PublishTimelineBindingAsync(BrokkrSyncTimelineBinding binding) { RequireRunning(); await node.Database.PutAsync(new CultRecordKey($"sync/bindings/timelines/{binding.bindingId}"), binding); - await node.FlushAsync(soft: true); + await node.FlushAsync(); } internal bool TryDequeueSyncReceipt(out BrokkrSyncReceipt receipt) diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs index 45ae610..3536a50 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Reflection; @@ -55,7 +56,7 @@ namespace GameCult.Brokkr.Editor }; } - private static BrokkrGameObjectSnapshot[] CaptureSceneObjects() + private static ImmutableArray CaptureSceneObjects() { var objects = new List(); @@ -73,7 +74,7 @@ namespace GameCult.Brokkr.Editor } } - return objects.ToArray(); + return objects.ToImmutableArray(); } private static void CaptureGameObject( @@ -109,7 +110,7 @@ namespace GameCult.Brokkr.Editor } } - private static BrokkrComponentSnapshot[] CaptureComponents(GameObject gameObject) + private static ImmutableArray CaptureComponents(GameObject gameObject) { return gameObject.GetComponents() .Where(component => component != null) @@ -121,7 +122,7 @@ namespace GameCult.Brokkr.Editor enabled = ReadEnabled(component), properties = CaptureProperties(component) }) - .ToArray(); + .ToImmutableArray(); } private static string[] CaptureMaterialNames(GameObject gameObject) @@ -135,7 +136,7 @@ namespace GameCult.Brokkr.Editor .ToArray(); } - private static BrokkrSerializedPropertySnapshot[] CaptureProperties(UnityEngine.Object target) + private static ImmutableArray CaptureProperties(UnityEngine.Object target) { var properties = new List(); using var serializedObject = new SerializedObject(target); @@ -165,10 +166,10 @@ namespace GameCult.Brokkr.Editor } } - return properties.ToArray(); + return properties.ToImmutableArray(); } - private static BrokkrAssetSnapshot[] CaptureAssets() + private static ImmutableArray CaptureAssets() { return AssetDatabase.GetAllAssetPaths() .Where(path => path.StartsWith("Assets/", StringComparison.Ordinal)) @@ -185,7 +186,7 @@ namespace GameCult.Brokkr.Editor name = System.IO.Path.GetFileNameWithoutExtension(path) }; }) - .ToArray(); + .ToImmutableArray(); } internal static string GetObjectId(UnityEngine.Object target) diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs index a33b9d2..f30466e 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Immutable; using GameCult.Caching; using MessagePack; @@ -21,14 +22,30 @@ namespace GameCult.Brokkr [Key(9)] public string[] selectedObjectNames = Array.Empty(); [Key(10)] public int assetCount; [Key(11)] public string[] capabilities = Array.Empty(); - [Key(12)] public BrokkrGameObjectSnapshot[] sceneObjects = Array.Empty(); - [Key(13)] public BrokkrAssetSnapshot[] assets = Array.Empty(); + [Key(12)] public ImmutableArray sceneObjects = ImmutableArray.Empty; + [Key(13)] public ImmutableArray assets = ImmutableArray.Empty; [Key(14)] public bool isPlaying; [Key(15)] public bool isPaused; [Key(16)] public bool isCompiling; [Key(17)] public bool isUpdating; // False means the editor executes no agent commands: the operator has not enabled the sink. [Key(18)] public bool agentCommandsEnabled; + + // The snapshot lists are whole values (ImmutableArray, no element ids): a store row from a writer that left + // one nil decodes to a default array, which this refuses instead of letting a reader throw later. + public void RefuseDefaultLists() + { + if (sceneObjects.IsDefault) throw new InvalidOperationException("Brokkr host snapshot sceneObjects is default, not a list."); + if (assets.IsDefault) throw new InvalidOperationException("Brokkr host snapshot assets is default, not a list."); + foreach (var sceneObject in sceneObjects) + { + if (sceneObject.components.IsDefault) + throw new InvalidOperationException($"Brokkr host snapshot object '{sceneObject.path}' components is default, not a list."); + foreach (var component in sceneObject.components) + if (component.properties.IsDefault) + throw new InvalidOperationException($"Brokkr host snapshot component '{component.typeName}' properties is default, not a list."); + } + } } // Written by the editor, into the store, when the operator enables the command sink. The token is also kept in @@ -73,7 +90,7 @@ namespace GameCult.Brokkr [Key(6)] public int layer; [Key(7)] public int childCount; [Key(8)] public string parentId = ""; - [Key(9)] public BrokkrComponentSnapshot[] components = Array.Empty(); + [Key(9)] public ImmutableArray components = ImmutableArray.Empty; [Key(10)] public string localPosition = ""; [Key(11)] public string localEulerAngles = ""; [Key(12)] public string localScale = ""; @@ -88,7 +105,7 @@ namespace GameCult.Brokkr [Key(1)] public string typeName = ""; [Key(2)] public string assemblyQualifiedName = ""; [Key(3)] public bool enabled; - [Key(4)] public BrokkrSerializedPropertySnapshot[] properties = Array.Empty(); + [Key(4)] public ImmutableArray properties = ImmutableArray.Empty; } [MessagePackObject] diff --git a/tools/build-msgpack-wheel.py b/tools/build-msgpack-wheel.py new file mode 100644 index 0000000..6dbf28e --- /dev/null +++ b/tools/build-msgpack-wheel.py @@ -0,0 +1,27 @@ +"""Repack the installed msgpack's pure-Python modules as one py3-none-any wheel (no download, no C extension). + +usage: python tools/build-msgpack-wheel.py +Deterministic: the same installed msgpack gives the same bytes, so the sha256 in install.md is checkable. +""" +import base64, hashlib, importlib.metadata as md, pathlib, sys, zipfile + +PURE = ("__init__.py", "exceptions.py", "ext.py", "fallback.py") # _cmsgpack is the C extension: left out +dist = md.distribution("msgpack") +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"] = (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" +digest = lambda data: "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() +files[f"{info}/RECORD"] = ("".join(f"{n},{digest(d)},{len(d)}\n" for n, d in files.items()) + f"{info}/RECORD,,\n").encode() + +out = pathlib.Path(sys.argv[1]) / f"msgpack-{version}-py3-none-any.whl" +with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z: + for name, data in files.items(): + entry = zipfile.ZipInfo(name, (1980, 1, 1, 0, 0, 0)) + entry.compress_type, entry.external_attr = zipfile.ZIP_DEFLATED, 0o644 << 16 + z.writestr(entry, data) +print(out, hashlib.sha256(out.read_bytes()).hexdigest()) diff --git a/tools/check.ps1 b/tools/check.ps1 index c5d8dbb..e0aba41 100644 --- a/tools/check.ps1 +++ b/tools/check.ps1 @@ -88,6 +88,9 @@ try { } & $pythonExe -c "import sys, tempfile; sys.path.insert(0, r'surfaces\blender\brokkr_bridge'); import blender_target; cultmesh, cultcache = blender_target._load_cultmesh(r'$cultLibPackages'); doc = cultcache.define_document_type('brokkr.check.v0'); node = cultmesh.CultMesh.start_node(tempfile.NamedTemporaryFile(suffix='.ccmp').name, runtime_id='brokkr-check'); node.database.register_document(doc); node.database.put(doc, 'check', {'ok': True}); assert node.database.snapshot()['brokkr.check.v0']['check']['ok'] is True; server = cultmesh.CultMesh.serve_node(node, host='127.0.0.1', port=0); assert server.port > 0; server.stop()" Assert-NativeSuccess "Blender adapter CultMesh import" + $env:CULTLIB_PACKAGES = $cultLibPackages + & $pythonExe -m unittest discover -s surfaceslender ests + Assert-NativeSuccess "Blender adapter unit tests" } finally { Pop-Location