One action table for every Blender intent; claim-then-run drain; private Blender dirs for live runs #19

Merged
eureka merged 6 commits from nibu/live-action-table into main 2026-11-28 02:51:37 +00:00
39 changed files with 4855 additions and 787 deletions

456
brokkr-ctl/src/actions.rs Normal file
View file

@ -0,0 +1,456 @@
//! 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.
use serde_json::{Map, Value};
use std::sync::LazyLock;
const TABLE_JSON: &str = include_str!("../../surfaces/blender/brokkr_bridge/actions.json");
static TABLE: LazyLock<Value> =
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)
}
fn entry(name: &str) -> Option<&'static Value> {
actions().iter().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::<Vec<_>>()
.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<String, Value>) -> Result<(), String> {
let action = command.get("action").and_then(Value::as_str).unwrap_or("");
let Some(row) = entry(action) else {
return Err(format!("Unsupported Blender command action: {action}"));
};
let present: Map<String, Value> = 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<String, Value>,
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<String, Value> = 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 {
let mut text = String::new();
for action in actions() {
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<Value> = 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")
);
}
#[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);
}
}
}

View file

@ -2,6 +2,7 @@
//! 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;
@ -14,7 +15,6 @@ 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 RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "note"];
const DEFAULT_TIMEOUT_SECS: u64 = 60;
const POLL: Duration = Duration::from_millis(200);
const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600);
@ -215,15 +215,12 @@ fn build_intent(
note: &str,
sets: &[String],
) -> Result<Value> {
if action.is_empty() || !action.chars().all(|c| c.is_ascii_alphanumeric()) {
bail!("action must be letters and digits, e.g. createObject");
}
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() || RESERVED.contains(&key) {
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)
@ -235,6 +232,7 @@ fn build_intent(
map.insert("action".into(), action.into());
map.insert("requestedBy".into(), requested_by.into());
map.insert("note".into(), note.into());
actions::validate(&map).map_err(|message| anyhow!(message))?;
Ok(Value::Object(map))
}
@ -280,6 +278,20 @@ fn wait_for_receipt(
}
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())
}
}
@ -414,8 +426,9 @@ brokkr-ctl blender: send typed intents to the live Blender add-on and read what
Every command needs --store <path> or $BROKKR_BLENDER_STORE (the add-on's .ccmp).
send needs $EUREKA_INSTANCE and --agent or $BROKKR_AGENT; requestedBy is '<instance>/<agent>'.
Output is 'key: value' lines. Exit: 0 accepted, 2 denied or failed, 3 stopped, 4 timeout,
1 usage or store error. brokkr-ctl validates nothing about an action: the add-on does, and
its refusal comes back in the receipt.
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()
}
@ -426,196 +439,16 @@ pub fn send_help() -> String {
brokkr-ctl blender send <action> [--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. Fields below are what the
add-on reads; it validates them and refuses in the receipt. Targets also accept objectName.
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:
",
);
for (action, fields) in ACTIONS {
text.push_str(&format!(" {action}\n"));
for (name, kind, note) in *fields {
text.push_str(&format!(" {name}: {kind} {note}\n"));
}
}
text.push_str(&actions::help());
text
}
type Field = (&'static str, &'static str, &'static str);
/// Help text only: what the add-on's `execute_command` dispatches and reads at the base commit.
const ACTIONS: &[(&str, &[Field])] = &[
(
"createObject",
&[
("objectType", "string", "MESH | LIGHT | CAMERA | EMPTY (default EMPTY)"),
("name", "string", ""),
("location", "[x,y,z]", ""),
("size", "number", "MESH"),
("meshType", "string", "CUBE"),
("lightType", "string", "LIGHT"),
("emptyDisplayType", "string", "EMPTY"),
],
),
("deleteObject", &[("targetObjectName", "string", "")]),
(
"setObjectTransform",
&[
("targetObjectName", "string", ""),
("location", "[x,y,z]", ""),
("rotationEuler", "[x,y,z]", "radians"),
("scale", "[x,y,z]", ""),
],
),
(
"setObjectVisibility",
&[("targetObjectName", "string", ""), ("visible", "bool", "")],
),
(
"setObjectParent",
&[
("targetObjectName", "string", ""),
("parentObjectName", "string", "empty clears the parent"),
],
),
(
"setObjectCustomProperty",
&[
("targetObjectName", "string", ""),
("propertyName", "string", ""),
("value", "json", ""),
],
),
(
"selectObject",
&[("targetObjectName", "string", ""), ("clearSelection", "bool", "default true")],
),
(
"assignMaterial",
&[
("targetObjectName", "string", ""),
("materialName", "string", ""),
("color", "[r,g,b] or [r,g,b,a]", "linear, 0..1"),
],
),
(
"importGltf",
&[("filepath", "string", "inside the add-on's import directory")],
),
(
"exportGltf",
&[
("filepath", "string", ".glb or .gltf inside the add-on's output directory"),
("extras", "bool", ""),
("yUp", "bool", ""),
("applyModifiers", "bool", ""),
("selection", "[string]", "object names"),
],
),
(
"setCamera",
&[
("targetObjectName", "string", ""),
("lens", "number", "mm"),
("cameraType", "string", ""),
("orthoScale", "number", ""),
("clipStart", "number", ""),
("clipEnd", "number", ""),
("panoramaType", "string", ""),
("active", "bool", "make it the scene camera"),
],
),
(
"setLight",
&[
("targetObjectName", "string", ""),
("energy", "number", ""),
("color", "[r,g,b]", "linear, 0..1"),
("lightType", "string", ""),
],
),
(
"setWorld",
&[
("worldName", "string", ""),
("color", "[r,g,b]", "linear, 0..1"),
("strength", "number", ""),
],
),
(
"renderStill",
&[
("outputPath", "string", "inside the add-on's output directory"),
("engine", "string", ""),
("resolutionX", "integer", ""),
("resolutionY", "integer", ""),
("cameraName", "string", ""),
],
),
("look", &[]),
(
"createNodeGroup",
&[
("treeKey", "string", ""),
("interface", "[{inOut,name,type,default?}]", "types: Geometry Float Int Bool Vector"),
],
),
(
"addNode",
&[
("treeKey", "string", ""),
("id", "string", "brokkr's key for the node"),
("blIdname", "string", "GeometryNode*, FunctionNode* or ShaderNode*"),
("location", "[x,y]", ""),
("label", "string", ""),
("properties", "object", "enum, bool, int or float node settings"),
("inputs", "object", "unlinked input defaults"),
],
),
("removeNode", &[("treeKey", "string", ""), ("id", "string", "")]),
(
"linkSockets",
&[
("treeKey", "string", ""),
("fromNode", "string", ""),
("fromSocket", "string", ""),
("toNode", "string", ""),
("toSocket", "string", ""),
],
),
(
"unlinkSockets",
&[
("treeKey", "string", ""),
("toNode", "string", ""),
("toSocket", "string", ""),
("fromNode", "string", "optional"),
("fromSocket", "string", "optional"),
],
),
(
"addModifier",
&[
("objectName", "string", ""),
("treeKey", "string", ""),
("modifierName", "string", "default Brokkr GeoNodes"),
],
),
(
"removeModifier",
&[("objectName", "string", ""), ("modifierName", "string", "")],
),
(
"setModifierInput",
&[
("objectName", "string", ""),
("modifierName", "string", ""),
("socket", "string", "identifier or unique interface name"),
("value", "json", "Float, Int, Bool or Vector"),
],
),
];
#[cfg(test)]
mod tests {
use super::*;

View file

@ -1,5 +1,6 @@
//! brokkr-ctl: command-line hands for Brokkr's creative-tool surfaces.
mod actions;
mod blender;
fn main() {

View file

@ -162,6 +162,27 @@ fn wait_matches_the_exact_receipt_key() {
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();
@ -383,36 +404,91 @@ fn status_prints_the_snapshot_summary() {
}
}
/// A pin, not a copy: every action the add-on dispatches is in `send --help`, and every help field
/// name is a string the add-on source mentions. The add-on has no machine-readable action table.
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<String>) {
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_dispatched_action_and_only_fields_the_addon_mentions() {
let addon = Path::new(env!("CARGO_MANIFEST_DIR")).join("../surfaces/blender/brokkr_bridge");
let source: String = ["blender_target.py", "node_actions.py", "scene_actions.py"]
.iter()
.map(|file| std::fs::read_to_string(addon.join(file)).unwrap())
.collect();
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 mut dispatched: Vec<String> = source
.lines()
.filter_map(|line| line.trim().strip_prefix("if action == \""))
.filter_map(|rest| rest.split('"').next())
.map(String::from)
.collect();
let actions_line = source.lines().find(|l| l.trim_start().starts_with("ACTIONS = (\"")).unwrap();
dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from));
assert!(dispatched.len() >= 20, "{dispatched:?}");
let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect();
for action in &dispatched {
assert!(listed.contains(&action.as_str()), "help lacks {action}");
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 action in &listed {
assert!(dispatched.iter().any(|d| d == action) || *action == "actions:", "help lists unknown {action}");
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}");
}
for field in help.lines().filter_map(|l| l.strip_prefix(" ")).filter_map(|l| l.split(':').next()) {
assert!(source.contains(&format!("\"{field}\"")), "add-on never mentions {field}");
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");
}
}

View file

@ -207,30 +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`
- `exportGltf` (writes under the add-on preference Render Output Directory, never overwriting)
- `setCamera`
- `setLight`
- `setWorld`
- `renderStill`
- `look` (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)
- `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

View file

@ -0,0 +1,216 @@
"""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) is the one owner. 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
from pathlib import Path
from typing import Any
TABLE_PATH = Path(__file__).with_name("actions.json")
SCHEMA = "brokkr.blender.actions.v0"
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) -> dict[str, Any] | None:
"""The table row for an action name, or None."""
return _by_name().get(action) if isinstance(action, str) else 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_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]) -> 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)
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'])}.")

View file

@ -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"}
]}
]
}

View file

@ -25,6 +25,7 @@ if os.name == "nt":
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, stop_pending
@ -49,8 +50,6 @@ 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 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.
@ -60,20 +59,6 @@ EXPORT_STAGE_PREFIX = ".brokkr-export-"
STAGE_LOCK = ".brokkr-lock"
STAGE_JOURNAL = ".brokkr-journal"
# Actions that only read the scene and so push no undo step.
READ_ACTIONS = ("look",)
MUTATING_ACTIONS = (
"createObject", "deleteObject", "setObjectTransform", "setObjectVisibility", "setObjectParent",
"setObjectCustomProperty", "selectObject", "assignMaterial", "importGltf", "exportGltf",
"setCamera", "setLight", "setWorld", "renderStill",
)
# Actions that change no scene state: they push no undo step (exportGltf restores its selection;
# renderStill restores its settings).
NO_SCENE_CHANGE_ACTIONS = ("exportGltf", "renderStill")
# 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).
# Anything that writes scene state or changes her mode is refused; renderStill and look do neither.
EDIT_MODE_SAFE_ACTIONS = ("renderStill", "look")
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
@ -136,6 +121,7 @@ class BrokkrBlenderTarget:
self.agent_turn = False # true only inside run_intent
self._wrote = True # run_intent: false when an accepted action changed nothing
self._receipted: set[str] = set()
self._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
@ -182,8 +168,15 @@ class BrokkrBlenderTarget:
debug_mirror_root: str = "",
limit: int | None = None,
) -> list[dict[str, Any]]:
"""Run queued intents, oldest key first: all of them, or at most `limit`, the rest staying queued."""
"""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]] = []
@ -193,6 +186,7 @@ class BrokkrBlenderTarget:
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
@ -200,10 +194,13 @@ class BrokkrBlenderTarget:
receipt["message"] += f" (queue key {command_key})"
# Receipts are write-once: a reused id's denial goes under '<id>.denied', never over the
# original. The sender learns of it by reading that key (and the drain's returned list).
self.publish_receipt(cache_path, cultlib_py_src, receipt, debug_mirror_root,
key_suffix=".denied" if reused else "")
node.database.delete(documents["command_intent"], command_key)
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
@ -636,29 +633,40 @@ class BrokkrBlenderTarget:
}
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."""
"""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. 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 '<mind>/<agent>'."
elif action not in MUTATING_ACTIONS and action not in READ_ACTIONS and action not in na.NodeActions.ACTIONS:
denial = f"Unsupported Blender command action: {action}"
elif action not in EDIT_MODE_SAFE_ACTIONS 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.")
else:
try:
command = at.validate(command)
row = at.entry(action)
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 = action not in READ_ACTIONS and action not in NO_SCENE_CHANGE_ACTIONS
push = row["changesScene"]
self.agent_turn = True
self._wrote = True
try:
@ -700,151 +708,119 @@ class BrokkrBlenderTarget:
self.bpy.ops.ed.undo_push(message=label)
def _dispatch(self, context: Any, command: dict[str, Any]) -> dict[str, Any]:
"""The action table. Only run_intent calls it; it owns refusal, failure and the undo step."""
action = command.get("action", "")
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 == "look":
return self._look(context, command)
if action in na.NodeActions.ACTIONS:
"""Only run_intent calls it, with an intent the table admitted: 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 hasattr(self.nodes, "_" + action):
message, name = self.nodes.execute(action, command)
self._wrote = self.nodes.changed
return self._receipt(command, "accepted", message, name)
return self._receipt(command, "failed", f"Unsupported Blender command action: {action}", "")
return getattr(self, "_" + action)(context, command)
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 mesh_type is not None and object_type != "MESH":
raise sa.ActionRefused(f"meshType applies only to objectType MESH, not {object_type}.")
if 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 _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("EXEC_DEFAULT", False, 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("EXEC_DEFAULT", False, 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("EXEC_DEFAULT", False, location=location)
else: # EMPTY
self.bpy.ops.object.empty_add("EXEC_DEFAULT", False, 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:
@ -858,8 +834,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
@ -877,28 +853,19 @@ class BrokkrBlenderTarget:
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]}")
@ -1002,58 +969,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:
@ -1069,22 +1018,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)
@ -1301,7 +1247,7 @@ class BrokkrBlenderTarget:
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]:
@ -1742,15 +1688,6 @@ def _valid_command_id(value: Any) -> bool:
return isinstance(value, str) and COMMAND_ID_SHAPE.fullmatch(value) is not None
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 _jsonable(value: Any) -> Any:
if value is None or isinstance(value, (str, int, float, bool)):
if isinstance(value, float) and not math.isfinite(value):

View file

@ -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,8 +74,6 @@ 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
@ -159,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.")
@ -181,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:
@ -204,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():
@ -232,8 +182,8 @@ 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)
@ -244,13 +194,15 @@ class NodeActions:
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)
@ -258,11 +210,11 @@ class NodeActions:
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 []
@ -275,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.")
@ -283,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}.")
@ -304,9 +253,7 @@ 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
@ -319,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

View file

@ -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()]

View file

@ -41,6 +41,11 @@ blender --command extension build --source-dir surfaces/blender/brokkr_bridge --
blender --command extension install-file --repo user_default --enable <dist>/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.
@ -159,70 +164,55 @@ sync organ).
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`
- `look`
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` on any other `objectType` is refused too; 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 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). The exporter writes into a
`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

View file

@ -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

View file

@ -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"}
]

View file

@ -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=<scratch dir: the blend file is saved here, so the default '//.brokkr/blender-editor.ccmp' lands here>
BROKKR_ADDON_MODULE=<default bl_ext.user_default.brokkr_bridge, the extension install>
BROKKR_CULTLIB=<CultLib packages dir>
blender --python action_table.py -- <out>
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 <out>.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)

File diff suppressed because it is too large Load diff

View file

@ -8,6 +8,7 @@ are drained by the add-on's own 1 s timer as one undo step each, with write-once
BROKKR_CULTLIB=<optional CultLib packages dir, default the add-on preference's F:/Projects/CultLib/packages>
BROKKR_PYLIBS=<optional dir holding the msgpack package, for an add-on copy without the wheel;
leave unset to prove a stock install>
Private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are required (refused otherwise).
blender --factory-startup --python agent_turn_queue.py -- <out>
Intents are put into the node database as brokkr-ctl does; a command JSON dropped under the debug
@ -23,6 +24,14 @@ 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()
@ -202,7 +211,7 @@ def q5_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", objectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands")
queue("aaaaaaaa-0008", action="setObjectTransform", targetObjectName="Cube", location=[0, 0, 9], requestedBy="nibu/hands")
def q5_check():

View file

@ -16,7 +16,8 @@
"requestedBy": "nibu/hands",
"note": "queue test",
"undoLabel": "Brokkr nibu/hands: createObject aaa-0001",
"observedAt": "2026-11-27T20:02:43.826604+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:03:52.780549+00:00"
}
},
{
@ -47,7 +48,8 @@
"requestedBy": "nibu/hands",
"note": "queue test",
"undoLabel": "Brokkr nibu/hands: createObject aaa-0001",
"observedAt": "2026-11-27T20:02:43.826604+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:03:52.780549+00:00"
}
},
{
@ -63,7 +65,8 @@
"requestedBy": "nibu/hands",
"note": "",
"undoLabel": "",
"observedAt": "2026-11-27T20:02:45.831074+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:03:54.875032+00:00"
}
},
{
@ -79,7 +82,8 @@
"requestedBy": "",
"note": "",
"undoLabel": "",
"observedAt": "2026-11-27T20:02:47.837505+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:03:55.934781+00:00"
}
},
{
@ -135,7 +139,8 @@
"requestedBy": "nibu/hands",
"note": "queue test",
"undoLabel": "Brokkr nibu/hands: createObject aaa-0001",
"observedAt": "2026-11-27T20:02:43.826604+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:03:52.780549+00:00"
},
"q2_original": {
"schema": "brokkr.blender.command_receipt.v0",
@ -147,7 +152,8 @@
"requestedBy": "nibu/hands",
"note": "queue test",
"undoLabel": "Brokkr nibu/hands: createObject aaa-0001",
"observedAt": "2026-11-27T20:02:43.826604+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:03:52.780549+00:00"
},
"q2_denial": {
"schema": "brokkr.blender.command_receipt.v0",
@ -159,7 +165,8 @@
"requestedBy": "nibu/hands",
"note": "",
"undoLabel": "",
"observedAt": "2026-11-27T20:02:45.831074+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:03:54.875032+00:00"
},
"q3": {
"schema": "brokkr.blender.command_receipt.v0",
@ -171,12 +178,13 @@
"requestedBy": "",
"note": "",
"undoLabel": "",
"observedAt": "2026-11-27T20:02:47.837505+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:03:55.934781+00:00"
},
"q6": [
{
"schema": "brokkr.blender.command_receipt.v0",
"commandId": "3414cf427aa549ea9e9a52c4cfc61908",
"commandId": "01683c810bbd449484c96d5984efccd7",
"action": "createObject",
"status": "denied",
"message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-int)",
@ -184,11 +192,12 @@
"requestedBy": "nibu/hands",
"note": "",
"undoLabel": "",
"observedAt": "2026-11-27T20:02:51.875508+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:04:00.170853+00:00"
},
{
"schema": "brokkr.blender.command_receipt.v0",
"commandId": "3c53313e68aa4d07ab6e3e330396567d",
"commandId": "bea34b7535da46188b741f55b3592707",
"action": "createObject",
"status": "denied",
"message": "Intent has no commandId of 1 to 128 letters, digits, '_' or '-'. (queue key blender/commands/bad-list)",
@ -196,7 +205,8 @@
"requestedBy": "nibu/hands",
"note": "",
"undoLabel": "",
"observedAt": "2026-11-27T20:02:51.901697+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:04:00.225976+00:00"
}
],
"q5": [
@ -210,7 +220,8 @@
"requestedBy": "nibu/hands",
"note": "",
"undoLabel": "",
"observedAt": "2026-11-27T20:02:53.881094+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:04:02.331449+00:00"
},
{
"schema": "brokkr.blender.command_receipt.v0",
@ -222,7 +233,8 @@
"requestedBy": "nibu/hands",
"note": "",
"undoLabel": "",
"observedAt": "2026-11-27T20:02:53.905589+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:04:02.387296+00:00"
},
{
"schema": "brokkr.blender.command_receipt.v0",
@ -234,11 +246,12 @@
"requestedBy": "nibu/hands",
"note": "",
"undoLabel": "",
"observedAt": "2026-11-27T20:02:53.944684+00:00"
"lookPath": "",
"observedAt": "2026-11-28T02:04:02.439331+00:00"
}
]
},
"msgpack": "F:\\aeth-wt\\brokkr-live-pins.e2e\\res\\extensions\\.local\\lib\\python3.13\\site-packages\\msgpack\\__init__.py",
"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

View file

@ -1,4 +1,6 @@
"""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=<path to surfaces/blender/brokkr_bridge> \
blender --factory-startup --python agent_turn_undo.py -- <out>
@ -88,7 +90,7 @@ def s_create():
def s_transform():
intent(action="setObjectTransform", objectName="AgentCube", location=[3, 2, 0])
intent(action="setObjectTransform", targetObjectName="AgentCube", location=[3, 2, 0])
check("transform applied", loc("AgentCube") == [3.0, 2.0, 0.0], loc("AgentCube"))
@ -131,7 +133,7 @@ def s_edit_enter():
def s_edit_agent():
r = intent(action="setObjectTransform", objectName="Cube", location=[0, 0, 5])
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",

View file

@ -197,7 +197,7 @@
"name": "exportGltf and renderStill accepted with no undoLabel",
"ok": true,
"detail": [
"Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes).",
"Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-lmbbnbpa\\object.glb (3484 bytes).",
"Rendered still to object.png."
]
},
@ -270,7 +270,7 @@
"intent": "exportGltf",
"status": "accepted",
"undoLabel": "",
"message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-0ge72kvx\\object.glb (3484 bytes)."
"message": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-live2-lmbbnbpa\\object.glb (3484 bytes)."
},
{
"intent": "renderStill",

View file

@ -1,4 +1,6 @@
"""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.

View file

@ -9,7 +9,7 @@
{
"name": "glb accepted",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\all.glb (72752 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\all.glb (72752 bytes)."
},
{
"name": "glb written, no staging folder",
@ -26,12 +26,12 @@
{
"name": "extras=false leaves them out",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\noextras.glb (72720 bytes)."
"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-aa0ee157\\only.glb (70240 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\only.glb (70240 bytes)."
},
{
"name": "selection restored",
@ -44,7 +44,7 @@
{
"name": "gltf accepted",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\sep\\s.gltf (2840 bytes)."
"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",
@ -108,7 +108,7 @@
{
"name": "the same name then exports",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\fresh\\deep\\x.glb (72752 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-e1blbtu2\\fresh\\deep\\x.glb (72752 bytes)."
}
]
}

View file

@ -1,4 +1,6 @@
"""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=<path to surfaces/blender/brokkr_bridge> \
blender -b --factory-startup --python gn_actions.py -- result.json
@ -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")],

View file

@ -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
}

View file

@ -1,4 +1,6 @@
"""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=<path to surfaces/blender/brokkr_bridge> \
blender -b --factory-startup --python gn_recreation.py -- result.json

View file

@ -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=<scratch dir> BROKKR_ADDON=<path to surfaces/blender/brokkr_bridge> \
blender --background --factory-startup --python surfaces/blender/tests/live/headless_smoke.py

View file

@ -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=<path to surfaces/blender/brokkr_bridge> \
blender -b --factory-startup --python material_colour.py -- result.json

View file

@ -6,7 +6,9 @@
BROKKR_CULTLIB=<CultLib packages dir>
blender --python perception.py -- <out>
Run it in a Blender whose resource path is fresh (BLENDER_USER_RESOURCE_PATH) so the add-on's preferences are the
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 <out>.result.json, then quits.
@ -25,6 +27,14 @@ 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"]

View file

@ -1,6 +1,6 @@
"""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; a fresh BLENDER_USER_RESOURCE_PATH).
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 -- <out>
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.
@ -19,6 +19,14 @@ 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()

View file

@ -5,7 +5,7 @@
"name": "window up: the region capture, source named",
"ok": true,
"detail": {
"commandId": "01a21f023e60712180b8b5afee5b2621",
"commandId": "01a21fe56d007f03a2355733ee33a416",
"action": "look",
"captureSource": "region",
"editSelection": [],
@ -14,15 +14,15 @@
"editedSinceLookNote": "",
"humanEditSeq": 0,
"humanEditsSinceLook": 0,
"lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f023e60712180b8b5afee5b2621.png",
"message": "Captured the 3D view to look/01a21f023e60712180b8b5afee5b2621.png.",
"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-27T21:56:11.107854+00:00",
"observedAt": "2026-11-28T02:04:19.958143+00:00",
"requestedBy": "nibu/hands",
"sceneUpdateSeq": 0,
"schema": "brokkr.blender.command_receipt.v0",
"sessionId": "4385c8bd86ec421db23676bc4d03569f",
"sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162",
"status": "accepted",
"undoLabel": ""
}
@ -87,7 +87,7 @@
"name": "after her link of an object: the receipt says the attribution is coarse",
"ok": true,
"detail": {
"commandId": "01a21f02711f7571991decbd06059938",
"commandId": "01a21fe5a09b70728ba3f974ad47eecc",
"action": "look",
"captureSource": "region",
"editSelection": [],
@ -101,15 +101,15 @@
"editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.",
"humanEditSeq": 4,
"humanEditsSinceLook": 1,
"lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02711f7571991decbd06059938.png",
"message": "Captured the 3D view to look/01a21f02711f7571991decbd06059938.png.",
"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-27T21:56:23.908406+00:00",
"observedAt": "2026-11-28T02:04:32.629832+00:00",
"requestedBy": "nibu/hands",
"sceneUpdateSeq": 5,
"schema": "brokkr.blender.command_receipt.v0",
"sessionId": "4385c8bd86ec421db23676bc4d03569f",
"sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162",
"status": "accepted",
"undoLabel": ""
}
@ -118,7 +118,7 @@
"name": "after a plain move: not coarse, only the Cube named",
"ok": true,
"detail": {
"commandId": "01a21f027a1873a1a21df913136a4d49",
"commandId": "01a21fe5a8a677439cb3f76df5eed508",
"action": "look",
"captureSource": "region",
"editSelection": [],
@ -129,15 +129,15 @@
"editedSinceLookNote": "",
"humanEditSeq": 5,
"humanEditsSinceLook": 1,
"lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027a1873a1a21df913136a4d49.png",
"message": "Captured the 3D view to look/01a21f027a1873a1a21df913136a4d49.png.",
"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-27T21:56:26.306053+00:00",
"observedAt": "2026-11-28T02:04:34.918968+00:00",
"requestedBy": "nibu/hands",
"sceneUpdateSeq": 6,
"schema": "brokkr.blender.command_receipt.v0",
"sessionId": "4385c8bd86ec421db23676bc4d03569f",
"sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162",
"status": "accepted",
"undoLabel": ""
}
@ -146,7 +146,7 @@
"name": "after her undo: coarse",
"ok": true,
"detail": {
"commandId": "01a21f027ec27dd0bda5c62b0974531a",
"commandId": "01a21fe5ad537f33846b930d41821f0e",
"action": "look",
"captureSource": "region",
"editSelection": [],
@ -159,15 +159,15 @@
"editedSinceLookNote": "Coarse: all objects flagged; editedSinceLook may name objects she did not touch.",
"humanEditSeq": 7,
"humanEditsSinceLook": 2,
"lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f027ec27dd0bda5c62b0974531a.png",
"message": "Captured the 3D view to look/01a21f027ec27dd0bda5c62b0974531a.png.",
"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-27T21:56:27.505456+00:00",
"observedAt": "2026-11-28T02:04:36.080195+00:00",
"requestedBy": "nibu/hands",
"sceneUpdateSeq": 7,
"schema": "brokkr.blender.command_receipt.v0",
"sessionId": "4385c8bd86ec421db23676bc4d03569f",
"sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162",
"status": "accepted",
"undoLabel": ""
}
@ -186,21 +186,21 @@
"ok": true,
"detail": {
"new": [
221,
191,
185,
197,
193
262,
192,
187,
188,
187
],
"old": [
977,
950,
974,
1059,
956
1044,
1060,
1010,
1044,
1313
],
"new_median": 193,
"old_median": 974
"new_median": 188,
"old_median": 1044
}
},
{
@ -215,7 +215,7 @@
],
"minimised": {
"a": {
"commandId": "01a21f02458877a186fe6a31fe3b32d6",
"commandId": "01a21fe575527fa0b4a36ecdbdd38ae6",
"action": "look",
"captureSource": "offscreen",
"editSelection": [],
@ -224,20 +224,20 @@
"editedSinceLookNote": "",
"humanEditSeq": 0,
"humanEditsSinceLook": 0,
"lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f02458877a186fe6a31fe3b32d6.png",
"message": "Captured the 3D view to look/01a21f02458877a186fe6a31fe3b32d6.png.",
"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-27T21:56:13.275722+00:00",
"observedAt": "2026-11-28T02:04:22.160175+00:00",
"requestedBy": "nibu/hands",
"sceneUpdateSeq": 0,
"schema": "brokkr.blender.command_receipt.v0",
"sessionId": "4385c8bd86ec421db23676bc4d03569f",
"sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162",
"status": "accepted",
"undoLabel": ""
},
"b": {
"commandId": "01a21f024b1876d0a4ec6281a49404a2",
"commandId": "01a21fe57bb173238bf0f2419a61ec46",
"action": "look",
"captureSource": "offscreen",
"editSelection": [],
@ -248,15 +248,15 @@
"editedSinceLookNote": "",
"humanEditSeq": 1,
"humanEditsSinceLook": 1,
"lookPath": "F:\\aeth-wt\\brokkr-live-5.scratch\\out\\look\\01a21f024b1876d0a4ec6281a49404a2.png",
"message": "Captured the 3D view to look/01a21f024b1876d0a4ec6281a49404a2.png.",
"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-27T21:56:14.485857+00:00",
"observedAt": "2026-11-28T02:04:23.398210+00:00",
"requestedBy": "nibu/hands",
"sceneUpdateSeq": 1,
"schema": "brokkr.blender.command_receipt.v0",
"sessionId": "4385c8bd86ec421db23676bc4d03569f",
"sessionId": "f60fdb7ac4d04d6bbf6e2992d460d162",
"status": "accepted",
"undoLabel": ""
},
@ -271,27 +271,27 @@
"edit_selection_parts_ms": {
"from_edit_mesh": 0.0,
"totals": 0.0,
"verts": 24.7,
"edges": 79.6,
"faces": 33.2
"verts": 27.4,
"edges": 70.9,
"faces": 27.4
},
"edit_selection_ms": {
"new": [
221,
191,
185,
197,
193
262,
192,
187,
188,
187
],
"old": [
977,
950,
974,
1059,
956
1044,
1060,
1010,
1044,
1313
],
"new_median": 193,
"old_median": 974
"new_median": 188,
"old_median": 1044
}
},
"ok": true

View file

@ -1,4 +1,6 @@
"""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=<path to surfaces/blender/brokkr_bridge> \
blender -b --factory-startup --python refusals.py -- result.json
@ -64,9 +66,9 @@ 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"] == "failed" and "MESH" in r["message"], r["message"])
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")
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)

View file

@ -31,17 +31,17 @@
{
"name": "meshType on LIGHT is refused",
"ok": true,
"detail": "meshType applies only to objectType MESH, not LIGHT."
"detail": "meshType applies only when objectType is one of MESH."
},
{
"name": "meshType on EMPTY is refused",
"ok": true,
"detail": "meshType applies only to objectType MESH, not EMPTY."
"detail": "meshType applies only when objectType is one of MESH."
},
{
"name": "meshType on CAMERA is refused",
"ok": true,
"detail": "meshType applies only to objectType MESH, not CAMERA."
"detail": "meshType applies only when objectType is one of MESH."
},
{
"name": "and nothing was created for them",

View file

@ -4,6 +4,7 @@
BROKKR_CTL=<path to the built brokkr-ctl>
BROKKR_ADDON_MODULE=<default bl_ext.user_default.brokkr_bridge, the extension install>
BROKKR_CULTLIB=<CultLib packages dir>
Private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are required (refused otherwise).
blender --factory-startup --python stop_presence.py -- <out>
Run a second Blender on the same store with BROKKR_PHASE=closed for the sink-off, node-closed answer.
@ -23,6 +24,14 @@ 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"]

View file

@ -0,0 +1,212 @@
"""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"))
def validate(action, fields):
try:
at.validate({"action": action, **fields})
except at.IntentInvalid as error:
return str(error)
return "ok"
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()

View file

@ -11,6 +11,7 @@ from pathlib import Path
import test_scene_actions as ts
bt = ts.bt
at = ts.at
SOURCE = Path(bt.__file__)
@ -30,7 +31,7 @@ class AgentTurnTests(unittest.TestCase):
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", objectName="Cube", location=[0, 0, 5])
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"], "")
@ -76,13 +77,15 @@ class AgentTurnTests(unittest.TestCase):
def test_refusal_pushes_nothing(self):
receipt = self.run_action(action="createObject", objectType="BOGUS")
self.assertEqual(receipt["status"], "failed")
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):
with unittest.mock.patch.object(bt, "READ_ACTIONS", ("createObject",)):
self.run_action(action="createObject", objectType="EMPTY")
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):
@ -131,7 +134,7 @@ class AgentTurnTests(unittest.TestCase):
self.assertEqual(self.bpy.undo.pushes, [])
def test_returned_failed_receipt_pushes_nothing(self):
receipt = self.run_action(action="setObjectTransform", objectName="NoSuchObject", location=[1, 2, 3])
receipt = self.run_action(action="setObjectTransform", targetObjectName="NoSuchObject", location=[1, 2, 3])
self.assertEqual(receipt["status"], "failed")
self.assertEqual(self.bpy.undo.pushes, [])
@ -162,7 +165,7 @@ class AgentTurnTests(unittest.TestCase):
# fix batch s2
def test_no_scene_change_set_is_exactly_export_and_render(self):
self.assertEqual(bt.NO_SCENE_CHANGE_ACTIONS, ("exportGltf", "renderStill"))
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)
@ -233,8 +236,11 @@ 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"
@ -245,10 +251,19 @@ class FakeNode:
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):
@ -270,7 +285,7 @@ class DrainTests(unittest.TestCase):
"blender/commands/c-good": self.intent("good-1"),
})
receipts = self.drain(node) # must not raise
self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA]))
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)
@ -295,6 +310,84 @@ class DrainTests(unittest.TestCase):
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()

View file

@ -121,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, [])
@ -143,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):

View file

@ -204,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):

View file

@ -593,7 +593,7 @@ class HumanEditTests(PerceptionFixture):
# 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", objectName="Cube", location=[0, 0, 5])
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)

View file

@ -20,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
@ -218,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")
@ -251,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")
@ -265,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
@ -335,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)
@ -527,7 +517,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]
@ -547,10 +537,13 @@ class ActionTests(unittest.TestCase):
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, [])
@ -563,35 +556,38 @@ 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, [])
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="CYLINDER")
self.assertEqual(receipt["status"], "failed", object_type)
self.assertIn("MESH", receipt["message"])
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, "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)
@ -844,10 +840,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, [])

View file

@ -52,7 +52,7 @@ class StopPendingTests(StopFixture):
self.assertEqual(receipt["undoLabel"], "")
self.assertEqual(receipt["action"], "createObject")
self.assertEqual(receipts["blender/receipts/q-3"]["requestedBy"], "nibu/soul")
self.assertEqual(sorted(node.deleted), sorted(node.docs[bt.COMMAND_INTENT_SCHEMA]))
self.assertEqual(sorted(node.deleted), node.initial)
self.assertEqual(self.bpy.created, []) # none dispatched
self.assertEqual(self.bpy.undo.pushes, [])