Skip to main content

skenion_runtime/
control_state.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5
6use crate::{
7    ControlMessage, ControlValue, GraphDocument, GraphNode, PortDirection, RuntimeDiagnostic,
8    control_value::{
9        BANG_KIND, BOOL_KIND, COLOR_KIND, COMMENT_KIND, FLOAT_KIND, INT_KIND, MESSAGE_KIND,
10        OPERATOR_ADD_KIND, OPERATOR_DIV_KIND, OPERATOR_MAX_KIND, OPERATOR_MIN_KIND,
11        OPERATOR_MUL_KIND, OPERATOR_POW_KIND, OPERATOR_SQRT_KIND, OPERATOR_SUB_KIND, PANEL_KIND,
12        STRING_KIND, UINT_KIND,
13    },
14    convert_control_value_to_stored,
15};
16
17#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
18#[serde(rename_all = "camelCase")]
19pub struct ControlState {
20    pub values: BTreeMap<String, ControlValue>,
21    pub channels: BTreeMap<String, ControlMessage>,
22    #[serde(default)]
23    pub operator_right: BTreeMap<String, ControlValue>,
24}
25
26#[derive(Debug, Clone, PartialEq, Deserialize)]
27#[serde(rename_all = "camelCase")]
28pub struct RuntimeControlEventRequest {
29    pub node_id: String,
30    pub port_id: String,
31    pub message: ControlMessage,
32}
33
34#[derive(Debug, Clone, PartialEq, Serialize)]
35#[serde(rename_all = "camelCase")]
36pub struct RuntimeControlEmission {
37    pub node_id: String,
38    pub port_id: String,
39    pub message: ControlMessage,
40}
41
42#[derive(Debug, Clone, Serialize)]
43#[serde(rename_all = "camelCase")]
44pub struct RuntimeControlEventResponse {
45    pub ok: bool,
46    pub changed: bool,
47    pub control_revision: Option<u64>,
48    pub emitted: Vec<RuntimeControlEmission>,
49    pub diagnostics: Vec<RuntimeDiagnostic>,
50}
51
52#[derive(Debug, Clone, Serialize)]
53#[serde(rename_all = "camelCase")]
54pub struct RuntimeControlStateResponse {
55    pub ok: bool,
56    pub control_revision: u64,
57    pub values: BTreeMap<String, ControlValue>,
58    pub channels: BTreeMap<String, ControlMessage>,
59    pub diagnostics: Vec<RuntimeDiagnostic>,
60}
61
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63#[serde(rename_all = "lowercase")]
64pub enum RuntimeControlReadTarget {
65    Param,
66    Port,
67    State,
68}
69
70#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
71#[serde(rename_all = "camelCase")]
72pub struct RuntimeControlReadRequest {
73    pub node_id: String,
74    pub target: RuntimeControlReadTarget,
75    pub id: String,
76}
77
78#[derive(Debug, Clone, Serialize)]
79#[serde(rename_all = "camelCase")]
80pub struct RuntimeControlReadResponse {
81    pub ok: bool,
82    pub address: RuntimeControlReadRequest,
83    pub value: Option<Value>,
84    pub diagnostics: Vec<RuntimeDiagnostic>,
85}
86
87impl RuntimeControlEventRequest {
88    fn control_message(&self) -> ControlMessage {
89        self.message.clone()
90    }
91}
92
93impl ControlState {
94    pub(crate) fn from_graph(graph: &GraphDocument) -> Self {
95        let values = graph
96            .nodes
97            .iter()
98            .filter_map(|node| {
99                ControlValue::for_node_default(node).map(|value| (node.id.clone(), value))
100            })
101            .collect();
102        let operator_right = graph
103            .nodes
104            .iter()
105            .filter_map(|node| operator_right_default(node).map(|value| (node.id.clone(), value)))
106            .collect();
107        Self {
108            values,
109            channels: BTreeMap::new(),
110            operator_right,
111        }
112    }
113
114    pub fn value_for_node(&self, node_id: &str) -> Option<&ControlValue> {
115        self.values.get(node_id)
116    }
117
118    pub(crate) fn output_value_for_node(
119        &self,
120        node: &GraphNode,
121        port_id: &str,
122    ) -> Option<ControlValue> {
123        if port_id != "value" && !(is_control_operator_kind(&node.kind) && port_id == "out") {
124            return None;
125        }
126        self.values.get(&node.id).cloned()
127    }
128
129    pub(crate) fn apply_event(
130        &mut self,
131        request: RuntimeControlEventRequest,
132        graph: &GraphDocument,
133    ) -> RuntimeControlEventResponse {
134        let mut staged = self.clone();
135        let response = staged.apply_event_direct(request, graph);
136        if !response.ok {
137            return response;
138        }
139
140        let response = staged.propagate_emissions(response, graph);
141        if response.ok {
142            *self = staged;
143        }
144        response
145    }
146
147    fn apply_event_direct(
148        &mut self,
149        request: RuntimeControlEventRequest,
150        graph: &GraphDocument,
151    ) -> RuntimeControlEventResponse {
152        let Some(node) = graph.nodes.iter().find(|node| node.id == request.node_id) else {
153            return RuntimeControlEventResponse::error(format!(
154                "control node {} does not exist",
155                request.node_id
156            ));
157        };
158
159        if !supports_runtime_control_events(&node.kind) {
160            return RuntimeControlEventResponse::error(format!(
161                "node {} ({}) does not support runtime control events",
162                node.id, node.kind
163            ));
164        }
165
166        if node.kind == BANG_KIND {
167            if request.port_id != "in" {
168                return unsupported_runtime_control_port(node, &request.port_id);
169            }
170            return RuntimeControlEventResponse::ok(vec![RuntimeControlEmission {
171                node_id: node.id.clone(),
172                port_id: "out".to_owned(),
173                message: ControlMessage::bang(),
174            }]);
175        }
176
177        if !node
178            .ports
179            .iter()
180            .any(|port| port.id == request.port_id && port.direction == PortDirection::Input)
181        {
182            return RuntimeControlEventResponse::error(format!(
183                "node {} does not support runtime control input port {}",
184                node.id, request.port_id
185            ));
186        }
187
188        let message = request.control_message();
189
190        if is_control_operator_kind(&node.kind) {
191            return self.apply_operator_event(node, &request.port_id, message);
192        }
193
194        let Some(stored) = self.values.get(&node.id).cloned() else {
195            return RuntimeControlEventResponse::error(format!(
196                "node {} has no runtime control state",
197                node.id
198            ));
199        };
200
201        match request.port_id.as_str() {
202            "in" => {
203                if node.kind == MESSAGE_KIND {
204                    if let Some(next) = silent_set_message(&message) {
205                        self.values
206                            .insert(node.id.clone(), ControlValue::string(next));
207                        return RuntimeControlEventResponse::ok(Vec::new());
208                    }
209                    return RuntimeControlEventResponse::ok(vec![RuntimeControlEmission {
210                        node_id: node.id.clone(),
211                        port_id: "out".to_owned(),
212                        message: message_from_message_node_state(&stored),
213                    }]);
214                }
215                if node.kind == COMMENT_KIND || node.kind == PANEL_KIND {
216                    let Some(next) = silent_set_message(&message) else {
217                        return RuntimeControlEventResponse::error(format!(
218                            "control input {} expects set message",
219                            node.id
220                        ));
221                    };
222                    self.values
223                        .insert(node.id.clone(), ControlValue::string(next));
224                    return RuntimeControlEventResponse::ok(Vec::new());
225                }
226                if is_toggle_widget(node) {
227                    return self.apply_toggle_event(node, false, message, stored);
228                }
229                if is_bang_message(&message) {
230                    return RuntimeControlEventResponse::ok(vec![RuntimeControlEmission {
231                        node_id: node.id.clone(),
232                        port_id: "value".to_owned(),
233                        message: ControlMessage::from_value(stored),
234                    }]);
235                }
236                let silent = message.selector == "set";
237                let Some(next) = value_from_message(&message, &stored) else {
238                    return RuntimeControlEventResponse::error(type_error_from_message(
239                        &message, &stored, &node.id,
240                    ));
241                };
242                self.values.insert(node.id.clone(), next.clone());
243                if silent {
244                    RuntimeControlEventResponse::ok(Vec::new())
245                } else {
246                    RuntimeControlEventResponse::ok(vec![RuntimeControlEmission {
247                        node_id: node.id.clone(),
248                        port_id: "value".to_owned(),
249                        message: ControlMessage::from_value(next),
250                    }])
251                }
252            }
253            "cold" => {
254                if node.kind == MESSAGE_KIND {
255                    return unsupported_runtime_control_port(node, &request.port_id);
256                }
257                if is_bang_message(&message) {
258                    return RuntimeControlEventResponse::error(format!(
259                        "control input {}.cold does not accept bang",
260                        node.id
261                    ));
262                }
263                if is_toggle_widget(node) {
264                    return self.apply_toggle_event(node, true, message, stored);
265                }
266                let Some(next) = value_from_message(&message, &stored) else {
267                    return RuntimeControlEventResponse::error(type_error_from_message(
268                        &message, &stored, &node.id,
269                    ));
270                };
271                self.values.insert(node.id.clone(), next);
272                RuntimeControlEventResponse::ok(Vec::new())
273            }
274            port => RuntimeControlEventResponse::error(format!(
275                "node {} does not support runtime control input port {}",
276                node.id, port
277            )),
278        }
279    }
280
281    fn propagate_emissions(
282        &mut self,
283        mut response: RuntimeControlEventResponse,
284        graph: &GraphDocument,
285    ) -> RuntimeControlEventResponse {
286        let mut queue = response.emitted.clone();
287        let mut visited_edges = 0usize;
288        while let Some(emission) = queue.pop() {
289            let channel_response = self.publish_object_channel(&emission, graph);
290            response.diagnostics.extend(channel_response.diagnostics);
291            for channel_emission in channel_response.emitted {
292                queue.push(channel_emission.clone());
293                response.emitted.push(channel_emission);
294            }
295            visited_edges += 1;
296            if visited_edges > graph.edges.len().saturating_mul(2).max(32) {
297                return RuntimeControlEventResponse::error(
298                    "control event propagation exceeded the v0 runtime safety limit",
299                );
300            }
301
302            for edge in graph.edges.iter().filter(|edge| {
303                edge.from.node == emission.node_id && edge.from.port == emission.port_id
304            }) {
305                let Some(target_node) = graph.nodes.iter().find(|node| node.id == edge.to.node)
306                else {
307                    continue;
308                };
309                if !supports_runtime_control_events(&target_node.kind) {
310                    continue;
311                }
312                let target_response = self.apply_event_direct(
313                    RuntimeControlEventRequest {
314                        node_id: target_node.id.clone(),
315                        port_id: edge.to.port.clone(),
316                        message: emission.message.clone(),
317                    },
318                    graph,
319                );
320                if !target_response.ok {
321                    return target_response;
322                }
323                for target_emission in target_response.emitted {
324                    queue.push(target_emission.clone());
325                    response.emitted.push(target_emission);
326                }
327            }
328        }
329
330        response
331    }
332
333    fn publish_object_channel(
334        &mut self,
335        emission: &RuntimeControlEmission,
336        graph: &GraphDocument,
337    ) -> RuntimeControlEventResponse {
338        let Some(source_node) = graph.nodes.iter().find(|node| node.id == emission.node_id) else {
339            return RuntimeControlEventResponse::ok(Vec::new());
340        };
341        let data_kind = data_kind_for_control_message(&emission.message);
342        let Some(channel_name) = read_named_param(source_node, "sendName") else {
343            return RuntimeControlEventResponse::ok(Vec::new());
344        };
345        let key = format!("{data_kind}:{channel_name}");
346        self.channels.insert(key, emission.message.clone());
347        self.apply_receive_name_updates(
348            data_kind,
349            &channel_name,
350            &emission.message,
351            &emission.node_id,
352            graph,
353        )
354    }
355
356    fn apply_receive_name_updates(
357        &mut self,
358        data_kind: &'static str,
359        channel_name: &str,
360        message: &ControlMessage,
361        source_node_id: &str,
362        graph: &GraphDocument,
363    ) -> RuntimeControlEventResponse {
364        let mut emitted = Vec::new();
365        let mut diagnostics = Vec::new();
366        for node in graph.nodes.iter().filter(|node| node.id != source_node_id) {
367            if read_named_param(node, "receiveName").as_deref() != Some(channel_name) {
368                continue;
369            }
370            if !object_accepts_data_kind(node, data_kind) {
371                diagnostics.push(RuntimeDiagnostic::warning(format!(
372                    "receiveName {channel_name} on node {} ignored incompatible routed {data_kind}",
373                    node.id
374                )));
375                continue;
376            }
377            let response = self.apply_event_direct(
378                RuntimeControlEventRequest {
379                    node_id: node.id.clone(),
380                    port_id: "in".to_owned(),
381                    message: message.clone(),
382                },
383                graph,
384            );
385            if response.ok {
386                emitted.extend(response.emitted);
387                diagnostics.extend(response.diagnostics);
388            } else {
389                let detail = response
390                    .diagnostics
391                    .first()
392                    .map(|diagnostic| diagnostic.message.as_str())
393                    .unwrap_or("unknown receiver error");
394                diagnostics.push(RuntimeDiagnostic::warning(format!(
395                    "receiveName {channel_name} on node {} rejected routed {data_kind}: {detail}",
396                    node.id
397                )));
398            }
399        }
400        RuntimeControlEventResponse::ok_with_diagnostics(emitted, diagnostics)
401    }
402
403    fn apply_toggle_event(
404        &mut self,
405        node: &GraphNode,
406        silent: bool,
407        message: ControlMessage,
408        stored: ControlValue,
409    ) -> RuntimeControlEventResponse {
410        let ControlValue::Bool { value: current } = stored else {
411            return RuntimeControlEventResponse::error(format!(
412                "node {} has non-boolean toggle state",
413                node.id
414            ));
415        };
416        let silent = silent || message.selector == "set";
417        let Some(next_bool) = coerce_toggle_input(&message, current) else {
418            return RuntimeControlEventResponse::error(format!(
419                "control input {} expects bang, bool, 0/1, or on/off",
420                node.id
421            ));
422        };
423        let next = ControlValue::bool(next_bool);
424        self.values.insert(node.id.clone(), next.clone());
425        if silent {
426            RuntimeControlEventResponse::ok(Vec::new())
427        } else {
428            RuntimeControlEventResponse::ok(vec![RuntimeControlEmission {
429                node_id: node.id.clone(),
430                port_id: "value".to_owned(),
431                message: ControlMessage::from_value(next),
432            }])
433        }
434    }
435
436    fn apply_operator_event(
437        &mut self,
438        node: &GraphNode,
439        port_id: &str,
440        message: ControlMessage,
441    ) -> RuntimeControlEventResponse {
442        match port_id {
443            "in" => {
444                if is_bang_message(&message) {
445                    let stored = self
446                        .values
447                        .get(&node.id)
448                        .cloned()
449                        .unwrap_or_else(|| ControlValue::float(0.0));
450                    return RuntimeControlEventResponse::ok(vec![RuntimeControlEmission {
451                        node_id: node.id.clone(),
452                        port_id: "out".to_owned(),
453                        message: ControlMessage::from_value(stored),
454                    }]);
455                }
456
457                let silent = message.selector == "set";
458                let Some(input) = numeric_message_value(&message) else {
459                    return RuntimeControlEventResponse::error(format!(
460                        "control operator {} expects a numeric message",
461                        node.id
462                    ));
463                };
464                let right = self
465                    .operator_right
466                    .get(&node.id)
467                    .and_then(control_value_as_f64)
468                    .unwrap_or_else(|| {
469                        operator_right_default(node)
470                            .and_then(|value| control_value_as_f64(&value))
471                            .unwrap_or(0.0)
472                    });
473                let result = ControlValue::float(evaluate_operator(&node.kind, input, right));
474                self.values.insert(node.id.clone(), result.clone());
475                if silent {
476                    RuntimeControlEventResponse::ok(Vec::new())
477                } else {
478                    RuntimeControlEventResponse::ok(vec![RuntimeControlEmission {
479                        node_id: node.id.clone(),
480                        port_id: "out".to_owned(),
481                        message: ControlMessage::from_value(result),
482                    }])
483                }
484            }
485            "right" => {
486                if is_bang_message(&message) {
487                    return RuntimeControlEventResponse::error(format!(
488                        "control operator {}.right does not accept bang",
489                        node.id
490                    ));
491                }
492                let Some(right) = numeric_message_value(&message) else {
493                    return RuntimeControlEventResponse::error(format!(
494                        "control operator {}.right expects a numeric message",
495                        node.id
496                    ));
497                };
498                self.operator_right
499                    .insert(node.id.clone(), ControlValue::float(right));
500                RuntimeControlEventResponse::ok(Vec::new())
501            }
502            port => RuntimeControlEventResponse::error(format!(
503                "node {} does not support runtime control input port {}",
504                node.id, port
505            )),
506        }
507    }
508}
509
510impl RuntimeControlEventResponse {
511    fn ok(emitted: Vec<RuntimeControlEmission>) -> Self {
512        Self {
513            ok: true,
514            changed: false,
515            control_revision: None,
516            emitted,
517            diagnostics: Vec::new(),
518        }
519    }
520
521    fn ok_with_diagnostics(
522        emitted: Vec<RuntimeControlEmission>,
523        diagnostics: Vec<RuntimeDiagnostic>,
524    ) -> Self {
525        Self {
526            ok: true,
527            changed: false,
528            control_revision: None,
529            emitted,
530            diagnostics,
531        }
532    }
533
534    fn error(message: impl Into<String>) -> Self {
535        Self {
536            ok: false,
537            changed: false,
538            control_revision: None,
539            emitted: Vec::new(),
540            diagnostics: vec![RuntimeDiagnostic::error(message)],
541        }
542    }
543
544    pub(crate) fn with_runtime_metadata(mut self, changed: bool, control_revision: u64) -> Self {
545        self.changed = changed;
546        self.control_revision = Some(control_revision);
547        self
548    }
549}
550
551pub fn is_control_value_kind(kind: &str) -> bool {
552    matches!(
553        kind,
554        FLOAT_KIND
555            | INT_KIND
556            | UINT_KIND
557            | BOOL_KIND
558            | COLOR_KIND
559            | STRING_KIND
560            | MESSAGE_KIND
561            | COMMENT_KIND
562            | PANEL_KIND
563    )
564}
565
566pub fn is_control_operator_kind(kind: &str) -> bool {
567    matches!(
568        kind,
569        OPERATOR_ADD_KIND
570            | OPERATOR_SUB_KIND
571            | OPERATOR_MUL_KIND
572            | OPERATOR_DIV_KIND
573            | OPERATOR_POW_KIND
574            | OPERATOR_MIN_KIND
575            | OPERATOR_MAX_KIND
576            | OPERATOR_SQRT_KIND
577    )
578}
579
580pub fn supports_runtime_control_events(kind: &str) -> bool {
581    is_control_value_kind(kind) || is_control_operator_kind(kind) || kind == BANG_KIND
582}
583
584impl RuntimeControlReadResponse {
585    pub fn ok(address: RuntimeControlReadRequest, value: Value) -> Self {
586        Self {
587            ok: true,
588            address,
589            value: Some(value),
590            diagnostics: Vec::new(),
591        }
592    }
593
594    pub fn error(address: RuntimeControlReadRequest, message: impl Into<String>) -> Self {
595        Self {
596            ok: false,
597            address,
598            value: None,
599            diagnostics: vec![RuntimeDiagnostic::error(message)],
600        }
601    }
602}
603
604pub fn read_graph_param(node: &GraphNode, param_id: &str) -> Option<Value> {
605    node.params
606        .get(param_id)
607        .cloned()
608        .map(|value| json!({ "type": "json", "value": value }))
609}
610
611pub fn read_graph_port(node: &GraphNode, port_id: &str) -> Option<Value> {
612    node.ports
613        .iter()
614        .find(|port| port.id == port_id)
615        .and_then(|port| serde_json::to_value(port).ok())
616        .map(|value| json!({ "type": "json", "value": value }))
617}
618
619fn unsupported_runtime_control_port(
620    node: &GraphNode,
621    port_id: &str,
622) -> RuntimeControlEventResponse {
623    RuntimeControlEventResponse::error(format!(
624        "node {} does not support runtime control input port {}",
625        node.id, port_id
626    ))
627}
628
629fn read_named_param(node: &GraphNode, key: &str) -> Option<String> {
630    let value = node.params.get(key)?.as_str()?.trim();
631    if value.is_empty() {
632        return None;
633    }
634    Some(value.to_owned())
635}
636
637fn data_kind_for_control_message(message: &ControlMessage) -> &'static str {
638    if is_bang_message(message) {
639        return "event.bang";
640    }
641    match message.first_atom() {
642        Some(value) => data_kind_for_control_value(value),
643        None => "message.any",
644    }
645}
646
647fn data_kind_for_control_value(value: &ControlValue) -> &'static str {
648    match value {
649        ControlValue::Float { .. } => "number.float",
650        ControlValue::Int { .. } => "number.int",
651        ControlValue::Uint { .. } => "number.uint",
652        ControlValue::Bool { .. } => "boolean",
653        ControlValue::String { .. } => "string",
654        ControlValue::Color { .. } => "color",
655    }
656}
657
658fn object_accepts_data_kind(node: &GraphNode, data_kind: &'static str) -> bool {
659    match node.kind.as_str() {
660        FLOAT_KIND | INT_KIND | UINT_KIND => is_numeric_data_kind(data_kind),
661        kind if is_control_operator_kind(kind) => is_numeric_data_kind(data_kind),
662        BOOL_KIND => data_kind == "boolean",
663        COLOR_KIND => data_kind == "color",
664        STRING_KIND => data_kind == "string",
665        COMMENT_KIND | PANEL_KIND => data_kind == "string" || data_kind == "message.any",
666        MESSAGE_KIND | BANG_KIND => is_control_message_data_kind(data_kind),
667        _ => false,
668    }
669}
670
671fn is_control_message_data_kind(data_kind: &'static str) -> bool {
672    matches!(
673        data_kind,
674        "number.float"
675            | "number.int"
676            | "number.uint"
677            | "boolean"
678            | "color"
679            | "string"
680            | "event.bang"
681            | "message.any"
682    )
683}
684
685fn is_numeric_data_kind(data_kind: &'static str) -> bool {
686    matches!(data_kind, "number.float" | "number.int" | "number.uint")
687}
688
689fn is_toggle_widget(node: &GraphNode) -> bool {
690    node.kind == BOOL_KIND
691        && matches!(
692            node.params.get("widget").and_then(Value::as_str),
693            Some("toggle" | "checkbox")
694        )
695}
696
697fn is_bang_message(message: &ControlMessage) -> bool {
698    message.selector == "bang" && message.atoms.is_empty()
699}
700
701fn value_from_message(message: &ControlMessage, stored: &ControlValue) -> Option<ControlValue> {
702    let atom = message.first_atom();
703    match stored {
704        ControlValue::Float { .. }
705        | ControlValue::Int { .. }
706        | ControlValue::Uint { .. }
707        | ControlValue::Color { .. } => {
708            atom.and_then(|value| convert_control_value_to_stored(value, stored))
709        }
710        ControlValue::Bool { .. } => coerce_toggle_input(message, false).map(ControlValue::bool),
711        ControlValue::String { .. } => {
712            if message.selector == "set" {
713                return Some(ControlValue::string(set_message_text(message)));
714            }
715            if message.selector == "symbol"
716                && let Some(ControlValue::String { value }) = atom
717            {
718                return Some(ControlValue::string(value.clone()));
719            }
720            Some(ControlValue::string(message.to_text()))
721        }
722    }
723}
724
725fn type_error_from_message(
726    message: &ControlMessage,
727    stored: &ControlValue,
728    node_id: &str,
729) -> String {
730    format!(
731        "control input {node_id} expects {}, got message selector {}",
732        stored.kind_label(),
733        message.selector
734    )
735}
736
737fn message_from_message_node_state(stored: &ControlValue) -> ControlMessage {
738    match stored {
739        ControlValue::String { value } => ControlMessage::parse_text(value),
740        value => ControlMessage::from_value(value.clone()),
741    }
742}
743
744fn set_message_text(message: &ControlMessage) -> String {
745    if message.selector == "set" {
746        return message
747            .atoms
748            .iter()
749            .map(control_atom_to_text)
750            .collect::<Vec<_>>()
751            .join(" ");
752    }
753    if message.selector == "symbol"
754        && let Some(ControlValue::String { value }) = message.first_atom()
755    {
756        return value.clone();
757    }
758    message.to_text()
759}
760
761fn silent_set_message(message: &ControlMessage) -> Option<String> {
762    (message.selector == "set").then(|| set_message_text(message))
763}
764
765fn control_atom_to_text(value: &ControlValue) -> String {
766    match value {
767        ControlValue::Float { value, .. } => value.to_string(),
768        ControlValue::Int { value, .. } => value.to_string(),
769        ControlValue::Uint { value, .. } => value.to_string(),
770        ControlValue::Bool { value } => {
771            if *value {
772                "on".to_owned()
773            } else {
774                "off".to_owned()
775            }
776        }
777        ControlValue::String { value } => value.clone(),
778        ControlValue::Color { value, .. } => {
779            format!("color {} {} {} {}", value[0], value[1], value[2], value[3])
780        }
781    }
782}
783
784fn coerce_toggle_input(message: &ControlMessage, current: bool) -> Option<bool> {
785    match message.selector.as_str() {
786        "bang" if message.atoms.is_empty() => Some(!current),
787        "on" | "true" => Some(true),
788        "off" | "false" => Some(false),
789        "set" | "float" | "int" | "uint" | "bool" | "symbol" => match message.first_atom()? {
790            ControlValue::Bool { value } => Some(*value),
791            ControlValue::Int { value, .. } => match value {
792                0 => Some(false),
793                1 => Some(true),
794                _ => None,
795            },
796            ControlValue::Uint { value, .. } => match value {
797                0 => Some(false),
798                1 => Some(true),
799                _ => None,
800            },
801            ControlValue::Float { value, .. } if *value == 0.0 => Some(false),
802            ControlValue::Float { value, .. } if *value == 1.0 => Some(true),
803            ControlValue::String { value } => match value.trim().to_ascii_lowercase().as_str() {
804                "0" | "off" | "false" => Some(false),
805                "1" | "on" | "true" => Some(true),
806                "bang" => Some(!current),
807                _ => None,
808            },
809            _ => None,
810        },
811        "0" => Some(false),
812        "1" => Some(true),
813        _ => None,
814    }
815}
816
817fn operator_right_default(node: &GraphNode) -> Option<ControlValue> {
818    if !is_control_operator_kind(&node.kind) || node.kind == OPERATOR_SQRT_KIND {
819        return None;
820    }
821    Some(ControlValue::float(
822        node.params
823            .get("right")
824            .and_then(Value::as_f64)
825            .unwrap_or(0.0),
826    ))
827}
828
829fn numeric_message_value(message: &ControlMessage) -> Option<f64> {
830    message.first_atom().and_then(control_value_as_f64)
831}
832
833fn control_value_as_f64(value: &ControlValue) -> Option<f64> {
834    match value {
835        ControlValue::Float { value, .. } => Some(sanitize_operator_number(*value)),
836        ControlValue::Int { value, .. } => Some(*value as f64),
837        ControlValue::Uint { value, .. } => Some(*value as f64),
838        _ => None,
839    }
840}
841
842fn evaluate_operator(kind: &str, input: f64, right: f64) -> f64 {
843    let result = match kind {
844        OPERATOR_ADD_KIND => input + right,
845        OPERATOR_SUB_KIND => input - right,
846        OPERATOR_MUL_KIND => input * right,
847        OPERATOR_DIV_KIND => {
848            if right == 0.0 {
849                0.0
850            } else {
851                input / right
852            }
853        }
854        OPERATOR_POW_KIND => input.powf(right),
855        OPERATOR_MIN_KIND => input.min(right),
856        OPERATOR_MAX_KIND => input.max(right),
857        OPERATOR_SQRT_KIND => {
858            if input < 0.0 {
859                0.0
860            } else {
861                input.sqrt()
862            }
863        }
864        _ => 0.0,
865    };
866    sanitize_operator_number(result)
867}
868
869fn sanitize_operator_number(value: f64) -> f64 {
870    if value.is_finite() { value } else { 0.0 }
871}
872
873#[cfg(test)]
874mod tests {
875    use serde_json::{Map, json};
876
877    use super::*;
878    use crate::{DataFlow, DataType, GraphNode, Port, PortActivation};
879
880    fn request(
881        node_id: &str,
882        port_id: &str,
883        message: ControlMessage,
884    ) -> RuntimeControlEventRequest {
885        RuntimeControlEventRequest {
886            node_id: node_id.to_owned(),
887            port_id: port_id.to_owned(),
888            message,
889        }
890    }
891
892    fn value_request(
893        node_id: &str,
894        port_id: &str,
895        value: ControlValue,
896    ) -> RuntimeControlEventRequest {
897        request(node_id, port_id, ControlMessage::from_value(value))
898    }
899
900    fn set_value_request(
901        node_id: &str,
902        port_id: &str,
903        value: ControlValue,
904    ) -> RuntimeControlEventRequest {
905        request(
906            node_id,
907            port_id,
908            ControlMessage {
909                selector: "set".to_owned(),
910                atoms: vec![value],
911            },
912        )
913    }
914
915    fn bang_request(node_id: &str, port_id: &str) -> RuntimeControlEventRequest {
916        request(node_id, port_id, ControlMessage::bang())
917    }
918
919    fn emitted_value(emission: &RuntimeControlEmission) -> Option<ControlValue> {
920        emission.message.first_atom().cloned()
921    }
922
923    #[test]
924    fn initializes_control_values_from_graph() {
925        let state = ControlState::from_graph(&graph(vec![
926            value_node("f32", FLOAT_KIND, json!(1.25)),
927            value_node("i32", INT_KIND, json!(7)),
928            value_node("bool", BOOL_KIND, json!(true)),
929            value_node("rgba", COLOR_KIND, json!([0.1, 0.2, 0.3, 1.0])),
930            value_node("string", STRING_KIND, json!("ready")),
931            value_node("toggle", BOOL_KIND, json!(false)),
932            value_node("message", MESSAGE_KIND, json!("perform")),
933            value_node("slider", FLOAT_KIND, json!(0.75)),
934            value_node("ui_toggle", BOOL_KIND, json!(true)),
935            value_node("other", "debug.sink", json!(10)),
936        ]));
937
938        assert_eq!(state.values.len(), 9);
939        assert!(state.channels.is_empty());
940        assert_eq!(
941            state.value_for_node("f32"),
942            Some(&ControlValue::float(1.25))
943        );
944        assert_eq!(state.value_for_node("i32"), Some(&ControlValue::int(7)));
945        assert_eq!(
946            state.value_for_node("rgba"),
947            Some(&ControlValue::color([0.1, 0.2, 0.3, 1.0]))
948        );
949        assert_eq!(
950            state.value_for_node("string"),
951            Some(&ControlValue::string("ready".to_owned()))
952        );
953        assert_eq!(
954            state.value_for_node("toggle"),
955            Some(&ControlValue::bool(false))
956        );
957        assert_eq!(
958            state.value_for_node("message"),
959            Some(&ControlValue::string("perform".to_owned()))
960        );
961        assert_eq!(
962            state.value_for_node("slider"),
963            Some(&ControlValue::float(0.75))
964        );
965        assert_eq!(
966            state.value_for_node("ui_toggle"),
967            Some(&ControlValue::bool(true))
968        );
969        assert_eq!(state.value_for_node("other"), None);
970    }
971
972    #[test]
973    fn set_updates_without_emission() {
974        let graph = graph(vec![value_node("value_1", FLOAT_KIND, json!(1.0))]);
975        let mut state = ControlState::from_graph(&graph);
976
977        let response = state.apply_event(
978            set_value_request("value_1", "in", ControlValue::float(32.0)),
979            &graph,
980        );
981
982        assert!(response.ok);
983        assert!(response.emitted.is_empty());
984        assert_eq!(
985            state.value_for_node("value_1"),
986            Some(&ControlValue::float(32.0))
987        );
988    }
989
990    #[test]
991    fn cold_updates_without_emission() {
992        let graph = graph(vec![value_node("value_1", FLOAT_KIND, json!(1.0))]);
993        let mut state = ControlState::from_graph(&graph);
994
995        let response = state.apply_event(
996            value_request("value_1", "cold", ControlValue::float(32.0)),
997            &graph,
998        );
999
1000        assert!(response.ok);
1001        assert!(response.emitted.is_empty());
1002        assert_eq!(
1003            state.value_for_node("value_1"),
1004            Some(&ControlValue::float(32.0))
1005        );
1006    }
1007
1008    #[test]
1009    fn in_updates_and_emits() {
1010        let graph = graph(vec![value_node("value_1", INT_KIND, json!(1))]);
1011        let mut state = ControlState::from_graph(&graph);
1012
1013        let response = state.apply_event(
1014            value_request("value_1", "in", ControlValue::int(12)),
1015            &graph,
1016        );
1017
1018        assert!(response.ok);
1019        assert_eq!(
1020            response.emitted,
1021            vec![RuntimeControlEmission {
1022                node_id: "value_1".to_owned(),
1023                port_id: "value".to_owned(),
1024                message: ControlMessage::from_value(ControlValue::int(12))
1025            }]
1026        );
1027        assert_eq!(
1028            state.value_for_node("value_1"),
1029            Some(&ControlValue::int(12))
1030        );
1031    }
1032
1033    #[test]
1034    fn bang_emits_stored_value_without_update() {
1035        let graph = graph(vec![value_node("value_1", BOOL_KIND, json!(true))]);
1036        let mut state = ControlState::from_graph(&graph);
1037
1038        let response = state.apply_event(bang_request("value_1", "in"), &graph);
1039
1040        assert!(response.ok);
1041        assert_eq!(
1042            response.emitted,
1043            vec![RuntimeControlEmission {
1044                node_id: "value_1".to_owned(),
1045                port_id: "value".to_owned(),
1046                message: ControlMessage::from_value(ControlValue::bool(true))
1047            }]
1048        );
1049        assert_eq!(
1050            state.value_for_node("value_1"),
1051            Some(&ControlValue::bool(true))
1052        );
1053    }
1054
1055    #[test]
1056    fn control_operator_hot_cold_and_bang_semantics() {
1057        let graph = graph(vec![operator_node("add_1", OPERATOR_ADD_KIND, Some(1.0))]);
1058        let mut state = ControlState::from_graph(&graph);
1059
1060        assert_eq!(
1061            state.operator_right.get("add_1"),
1062            Some(&ControlValue::float(1.0))
1063        );
1064
1065        let hot = state.apply_event(
1066            value_request("add_1", "in", ControlValue::float(4.0)),
1067            &graph,
1068        );
1069        assert!(hot.ok);
1070        assert_eq!(
1071            hot.emitted,
1072            vec![RuntimeControlEmission {
1073                node_id: "add_1".to_owned(),
1074                port_id: "out".to_owned(),
1075                message: ControlMessage::from_value(ControlValue::float(5.0))
1076            }]
1077        );
1078        assert_eq!(
1079            state.value_for_node("add_1"),
1080            Some(&ControlValue::float(5.0))
1081        );
1082
1083        let cold = state.apply_event(
1084            value_request("add_1", "right", ControlValue::float(2.0)),
1085            &graph,
1086        );
1087        assert!(cold.ok);
1088        assert!(cold.emitted.is_empty());
1089        assert_eq!(
1090            state.operator_right.get("add_1"),
1091            Some(&ControlValue::float(2.0))
1092        );
1093
1094        let silent_hot = state.apply_event(
1095            set_value_request("add_1", "in", ControlValue::float(4.0)),
1096            &graph,
1097        );
1098        assert!(silent_hot.ok);
1099        assert!(silent_hot.emitted.is_empty());
1100        assert_eq!(
1101            state.value_for_node("add_1"),
1102            Some(&ControlValue::float(6.0))
1103        );
1104
1105        let bang = state.apply_event(bang_request("add_1", "in"), &graph);
1106        assert!(bang.ok);
1107        assert_eq!(
1108            bang.emitted,
1109            vec![RuntimeControlEmission {
1110                node_id: "add_1".to_owned(),
1111                port_id: "out".to_owned(),
1112                message: ControlMessage::from_value(ControlValue::float(6.0))
1113            }]
1114        );
1115    }
1116
1117    #[test]
1118    fn control_operator_deterministic_fallbacks() {
1119        let graph = graph(vec![
1120            operator_node("div_1", OPERATOR_DIV_KIND, Some(0.0)),
1121            operator_node("sqrt_1", OPERATOR_SQRT_KIND, None),
1122            operator_node("pow_1", OPERATOR_POW_KIND, Some(0.5)),
1123        ]);
1124        let mut state = ControlState::from_graph(&graph);
1125
1126        let div = state.apply_event(
1127            value_request("div_1", "in", ControlValue::float(10.0)),
1128            &graph,
1129        );
1130        let sqrt = state.apply_event(
1131            value_request("sqrt_1", "in", ControlValue::float(-1.0)),
1132            &graph,
1133        );
1134        let pow = state.apply_event(
1135            value_request("pow_1", "in", ControlValue::float(-1.0)),
1136            &graph,
1137        );
1138
1139        assert!(div.ok);
1140        assert!(sqrt.ok);
1141        assert!(pow.ok);
1142        assert_eq!(
1143            emitted_value(&div.emitted[0]),
1144            Some(ControlValue::float(0.0))
1145        );
1146        assert_eq!(
1147            emitted_value(&sqrt.emitted[0]),
1148            Some(ControlValue::float(0.0))
1149        );
1150        assert_eq!(
1151            emitted_value(&pow.emitted[0]),
1152            Some(ControlValue::float(0.0))
1153        );
1154    }
1155
1156    #[test]
1157    fn control_operator_accepts_integer_inputs_and_reports_invalid_messages() {
1158        let graph = graph(vec![
1159            operator_node("div_1", OPERATOR_DIV_KIND, Some(2.0)),
1160            operator_node("sqrt_1", OPERATOR_SQRT_KIND, None),
1161            operator_node("add_1", OPERATOR_ADD_KIND, Some(1.0)),
1162        ]);
1163        let mut state = ControlState::from_graph(&graph);
1164
1165        let div = state.apply_event(value_request("div_1", "in", ControlValue::int(9)), &graph);
1166        let sqrt = state.apply_event(value_request("sqrt_1", "in", ControlValue::uint(9)), &graph);
1167        let bad_hot = state.apply_event(
1168            RuntimeControlEventRequest {
1169                node_id: "add_1".to_owned(),
1170                port_id: "in".to_owned(),
1171                message: ControlMessage::from_value(ControlValue::string("bad")),
1172            },
1173            &graph,
1174        );
1175        let bad_right_bang = state.apply_event(bang_request("add_1", "right"), &graph);
1176        let bad_right_value = state.apply_event(
1177            RuntimeControlEventRequest {
1178                node_id: "add_1".to_owned(),
1179                port_id: "right".to_owned(),
1180                message: ControlMessage::from_value(ControlValue::string("bad")),
1181            },
1182            &graph,
1183        );
1184        let bad_port = state.apply_event(
1185            value_request("add_1", "missing", ControlValue::float(1.0)),
1186            &graph,
1187        );
1188        let add_node = graph
1189            .nodes
1190            .iter()
1191            .find(|node| node.id == "add_1")
1192            .expect("operator node should exist");
1193        let bad_internal_port = state.apply_operator_event(
1194            add_node,
1195            "missing",
1196            ControlMessage::from_value(ControlValue::float(1.0)),
1197        );
1198
1199        assert!(div.ok);
1200        assert!(sqrt.ok);
1201        assert_eq!(
1202            emitted_value(&div.emitted[0]),
1203            Some(ControlValue::float(4.5))
1204        );
1205        assert_eq!(
1206            emitted_value(&sqrt.emitted[0]),
1207            Some(ControlValue::float(3.0))
1208        );
1209        assert!(!bad_hot.ok);
1210        assert!(!bad_right_bang.ok);
1211        assert!(!bad_right_value.ok);
1212        assert!(!bad_port.ok);
1213        assert!(!bad_internal_port.ok);
1214        assert_eq!(
1215            state.value_for_node("add_1"),
1216            Some(&ControlValue::float(0.0))
1217        );
1218        assert_eq!(
1219            state.operator_right.get("add_1"),
1220            Some(&ControlValue::float(1.0))
1221        );
1222        assert_eq!(evaluate_operator("core.operator.unknown", 2.0, 3.0), 0.0);
1223    }
1224
1225    #[test]
1226    fn control_operator_uses_fallbacks_for_missing_runtime_slots() {
1227        let graph = graph(vec![operator_node("add_1", OPERATOR_ADD_KIND, Some(2.0))]);
1228        let mut state = ControlState::from_graph(&graph);
1229
1230        state.values.remove("add_1");
1231        let bang = state.apply_event(bang_request("add_1", "in"), &graph);
1232        assert!(bang.ok);
1233        assert_eq!(
1234            emitted_value(&bang.emitted[0]),
1235            Some(ControlValue::float(0.0))
1236        );
1237
1238        state.operator_right.remove("add_1");
1239        let numeric = state.apply_event(
1240            value_request("add_1", "in", ControlValue::float(3.0)),
1241            &graph,
1242        );
1243        assert!(numeric.ok);
1244        assert_eq!(
1245            emitted_value(&numeric.emitted[0]),
1246            Some(ControlValue::float(5.0))
1247        );
1248    }
1249
1250    #[test]
1251    fn control_operator_edges_propagate_results() {
1252        let mut graph = graph(vec![
1253            value_node("source_1", FLOAT_KIND, json!(4.0)),
1254            operator_node("mul_1", OPERATOR_MUL_KIND, Some(0.5)),
1255            value_node("target_1", FLOAT_KIND, json!(0.0)),
1256        ]);
1257        graph.edges = vec![
1258            edge("source_1", "value", "mul_1", "in"),
1259            edge("mul_1", "out", "target_1", "in"),
1260        ];
1261        let mut state = ControlState::from_graph(&graph);
1262
1263        let response = state.apply_event(
1264            value_request("source_1", "in", ControlValue::float(8.0)),
1265            &graph,
1266        );
1267
1268        assert!(response.ok);
1269        assert_eq!(
1270            state.value_for_node("mul_1"),
1271            Some(&ControlValue::float(4.0))
1272        );
1273        assert_eq!(
1274            state.value_for_node("target_1"),
1275            Some(&ControlValue::float(4.0))
1276        );
1277        assert_eq!(
1278            response
1279                .emitted
1280                .iter()
1281                .map(|emission| (emission.node_id.as_str(), emission.port_id.as_str()))
1282                .collect::<Vec<_>>(),
1283            vec![
1284                ("source_1", "value"),
1285                ("mul_1", "out"),
1286                ("target_1", "value")
1287            ]
1288        );
1289    }
1290
1291    #[test]
1292    fn toggle_bang_flips_and_emits() {
1293        let graph = graph(vec![value_node("toggle_1", BOOL_KIND, json!(false))]);
1294        let mut state = ControlState::from_graph(&graph);
1295
1296        let response = state.apply_event(bang_request("toggle_1", "in"), &graph);
1297
1298        assert!(response.ok);
1299        assert_eq!(
1300            response.emitted,
1301            vec![RuntimeControlEmission {
1302                node_id: "toggle_1".to_owned(),
1303                port_id: "value".to_owned(),
1304                message: ControlMessage::from_value(ControlValue::bool(true))
1305            }]
1306        );
1307        assert_eq!(
1308            state.value_for_node("toggle_1"),
1309            Some(&ControlValue::bool(true))
1310        );
1311    }
1312
1313    #[test]
1314    fn toggle_accepts_on_off_and_set_messages() {
1315        let graph = graph(vec![
1316            value_node("toggle_1", BOOL_KIND, json!(false)),
1317            value_node("core_toggle_1", BOOL_KIND, json!(false)),
1318        ]);
1319        let mut state = ControlState::from_graph(&graph);
1320
1321        let on = state.apply_event(
1322            request("toggle_1", "in", ControlMessage::parse_text("on")),
1323            &graph,
1324        );
1325        assert!(on.ok);
1326        assert_eq!(
1327            emitted_value(&on.emitted[0]),
1328            Some(ControlValue::bool(true))
1329        );
1330
1331        let set_off = state.apply_event(
1332            request("toggle_1", "in", ControlMessage::parse_text("set off")),
1333            &graph,
1334        );
1335        assert!(set_off.ok);
1336        assert!(set_off.emitted.is_empty());
1337        assert_eq!(
1338            state.value_for_node("toggle_1"),
1339            Some(&ControlValue::bool(false))
1340        );
1341
1342        let core_toggle = state.apply_event(
1343            request("core_toggle_1", "in", ControlMessage::parse_text("set on")),
1344            &graph,
1345        );
1346        assert!(core_toggle.ok);
1347        assert!(core_toggle.emitted.is_empty());
1348        assert_eq!(
1349            state.value_for_node("core_toggle_1"),
1350            Some(&ControlValue::bool(true))
1351        );
1352
1353        let cold_toggle = state.apply_event(
1354            request("core_toggle_1", "cold", ControlMessage::parse_text("off")),
1355            &graph,
1356        );
1357        assert!(cold_toggle.ok);
1358        assert!(cold_toggle.emitted.is_empty());
1359        assert_eq!(
1360            state.value_for_node("core_toggle_1"),
1361            Some(&ControlValue::bool(false))
1362        );
1363
1364        let float_zero = state.apply_event(
1365            value_request("toggle_1", "in", ControlValue::float(0.0)),
1366            &graph,
1367        );
1368        assert!(float_zero.ok);
1369        assert_eq!(
1370            state.value_for_node("toggle_1"),
1371            Some(&ControlValue::bool(false))
1372        );
1373
1374        let float_one = state.apply_event(
1375            value_request("toggle_1", "in", ControlValue::float(1.0)),
1376            &graph,
1377        );
1378        assert!(float_one.ok);
1379        assert_eq!(
1380            state.value_for_node("toggle_1"),
1381            Some(&ControlValue::bool(true))
1382        );
1383
1384        let float_mid_rejected = state.apply_event(
1385            value_request("toggle_1", "in", ControlValue::float(0.5)),
1386            &graph,
1387        );
1388        assert!(!float_mid_rejected.ok);
1389        assert!(
1390            float_mid_rejected.diagnostics[0]
1391                .message
1392                .contains("expects bang, bool, 0/1, or on/off")
1393        );
1394
1395        let color_rejected = state.apply_event(
1396            value_request("toggle_1", "in", ControlValue::color([0.0, 0.0, 0.0, 1.0])),
1397            &graph,
1398        );
1399        assert!(!color_rejected.ok);
1400        assert!(
1401            color_rejected.diagnostics[0]
1402                .message
1403                .contains("expects bang, bool, 0/1, or on/off")
1404        );
1405    }
1406
1407    #[test]
1408    fn string_and_message_controls_emit_strings() {
1409        let graph = graph(vec![
1410            value_node("string_1", STRING_KIND, json!("ready")),
1411            value_node("message_1", MESSAGE_KIND, json!("perform")),
1412        ]);
1413        let mut state = ControlState::from_graph(&graph);
1414
1415        let string_response = state.apply_event(
1416            value_request("string_1", "in", ControlValue::string("running".to_owned())),
1417            &graph,
1418        );
1419        assert!(string_response.ok);
1420        assert_eq!(
1421            emitted_value(&string_response.emitted[0]),
1422            Some(ControlValue::string("running".to_owned()))
1423        );
1424
1425        let message_response = state.apply_event(bang_request("message_1", "in"), &graph);
1426        assert!(message_response.ok);
1427        assert_eq!(
1428            message_response.emitted,
1429            vec![RuntimeControlEmission {
1430                node_id: "message_1".to_owned(),
1431                port_id: "out".to_owned(),
1432                message: ControlMessage::parse_text("perform")
1433            }]
1434        );
1435
1436        let set_response = state.apply_event(
1437            request("message_1", "in", ControlMessage::parse_text("set updated")),
1438            &graph,
1439        );
1440        assert!(set_response.ok);
1441        assert!(set_response.emitted.is_empty());
1442        assert_eq!(
1443            state.value_for_node("message_1"),
1444            Some(&ControlValue::string("updated".to_owned()))
1445        );
1446
1447        let color_set = state.apply_event(
1448            request(
1449                "message_1",
1450                "in",
1451                ControlMessage::parse_text("set color 1 0.5 0.25 1"),
1452            ),
1453            &graph,
1454        );
1455        assert!(color_set.ok);
1456        assert_eq!(
1457            state.value_for_node("message_1"),
1458            Some(&ControlValue::string("color 1 0.5 0.25 1".to_owned()))
1459        );
1460        let color_emit = state.apply_event(bang_request("message_1", "in"), &graph);
1461        assert!(color_emit.ok);
1462        assert_eq!(
1463            color_emit.emitted[0].message,
1464            ControlMessage::from_value(ControlValue::color([1.0, 0.5, 0.25, 1.0]))
1465        );
1466
1467        let silent_in = state.apply_event(
1468            request("message_1", "in", ControlMessage::parse_text("set queued")),
1469            &graph,
1470        );
1471        assert!(silent_in.ok);
1472        assert!(silent_in.emitted.is_empty());
1473        assert_eq!(
1474            state.value_for_node("message_1"),
1475            Some(&ControlValue::string("queued".to_owned()))
1476        );
1477
1478        let cold_message = state.apply_event(
1479            request(
1480                "message_1",
1481                "cold",
1482                ControlMessage::parse_text("set ignored"),
1483            ),
1484            &graph,
1485        );
1486        assert!(!cold_message.ok);
1487        assert!(
1488            cold_message.diagnostics[0]
1489                .message
1490                .contains("does not support runtime control input port cold")
1491        );
1492
1493        let string_set = state.apply_event(
1494            request("string_1", "in", ControlMessage::parse_text("set armed")),
1495            &graph,
1496        );
1497        assert!(string_set.ok);
1498        assert!(string_set.emitted.is_empty());
1499        assert_eq!(
1500            state.value_for_node("string_1"),
1501            Some(&ControlValue::string("armed".to_owned()))
1502        );
1503
1504        let emit_in = state.apply_event(bang_request("message_1", "in"), &graph);
1505        assert!(emit_in.ok);
1506        assert_eq!(
1507            emit_in.emitted,
1508            vec![RuntimeControlEmission {
1509                node_id: "message_1".to_owned(),
1510                port_id: "out".to_owned(),
1511                message: ControlMessage::parse_text("queued")
1512            }]
1513        );
1514    }
1515
1516    #[test]
1517    fn object_send_name_dispatches_to_receive_name_inlet() {
1518        let mut sender = value_node("slider_1", FLOAT_KIND, json!(0.25));
1519        sender.params.insert("sendName".to_owned(), json!("speed"));
1520        let mut receiver = value_node("value_1", FLOAT_KIND, json!(0.0));
1521        receiver
1522            .params
1523            .insert("receiveName".to_owned(), json!("speed"));
1524        let routing_graph = graph(vec![sender, receiver]);
1525        let mut state = ControlState::from_graph(&routing_graph);
1526
1527        let response = state.apply_event(
1528            value_request("slider_1", "in", ControlValue::float(1.25)),
1529            &routing_graph,
1530        );
1531
1532        assert!(response.ok);
1533        assert_eq!(
1534            state.channels.get("number.float:speed"),
1535            Some(&ControlMessage::from_value(ControlValue::float(1.25)))
1536        );
1537        assert_eq!(
1538            response.emitted,
1539            vec![
1540                RuntimeControlEmission {
1541                    node_id: "slider_1".to_owned(),
1542                    port_id: "value".to_owned(),
1543                    message: ControlMessage::from_value(ControlValue::float(1.25)),
1544                },
1545                RuntimeControlEmission {
1546                    node_id: "value_1".to_owned(),
1547                    port_id: "value".to_owned(),
1548                    message: ControlMessage::from_value(ControlValue::float(1.25)),
1549                },
1550            ]
1551        );
1552        assert_eq!(
1553            state.value_for_node("value_1"),
1554            Some(&ControlValue::float(1.25))
1555        );
1556
1557        let mut bang_sender = bang_node("button_1");
1558        bang_sender
1559            .params
1560            .insert("sendName".to_owned(), json!("go"));
1561        let graph = graph(vec![bang_sender]);
1562        let mut state = ControlState::from_graph(&graph);
1563        let bang = state.apply_event(bang_request("button_1", "in"), &graph);
1564        assert!(bang.ok);
1565        assert_eq!(
1566            state.channels.get("event.bang:go"),
1567            Some(&ControlMessage::bang())
1568        );
1569    }
1570
1571    #[test]
1572    fn object_receive_name_dispatches_any_message_to_bang() {
1573        let mut sender = value_node("message_1", MESSAGE_KIND, json!("perform"));
1574        sender.params.insert("sendName".to_owned(), json!("go"));
1575        let mut receiver = bang_node("bang_1");
1576        receiver
1577            .params
1578            .insert("receiveName".to_owned(), json!("go"));
1579        let routing_graph = graph(vec![sender, receiver]);
1580        let mut state = ControlState::from_graph(&routing_graph);
1581
1582        let response = state.apply_event(bang_request("message_1", "in"), &routing_graph);
1583
1584        assert!(response.ok);
1585        assert_eq!(
1586            response.emitted,
1587            vec![
1588                RuntimeControlEmission {
1589                    node_id: "message_1".to_owned(),
1590                    port_id: "out".to_owned(),
1591                    message: ControlMessage::parse_text("perform"),
1592                },
1593                RuntimeControlEmission {
1594                    node_id: "bang_1".to_owned(),
1595                    port_id: "out".to_owned(),
1596                    message: ControlMessage::bang(),
1597                },
1598            ]
1599        );
1600    }
1601
1602    #[test]
1603    fn object_receive_name_dispatches_float_to_bang() {
1604        let mut sender = value_node("slider_1", FLOAT_KIND, json!(0.25));
1605        sender.params.insert("sendName".to_owned(), json!("go"));
1606        let mut receiver = bang_node("bang_1");
1607        receiver
1608            .params
1609            .insert("receiveName".to_owned(), json!("go"));
1610        let routing_graph = graph(vec![sender, receiver]);
1611        let mut state = ControlState::from_graph(&routing_graph);
1612
1613        let response = state.apply_event(
1614            value_request("slider_1", "in", ControlValue::float(1.25)),
1615            &routing_graph,
1616        );
1617
1618        assert!(response.ok);
1619        assert_eq!(
1620            response.emitted,
1621            vec![
1622                RuntimeControlEmission {
1623                    node_id: "slider_1".to_owned(),
1624                    port_id: "value".to_owned(),
1625                    message: ControlMessage::from_value(ControlValue::float(1.25)),
1626                },
1627                RuntimeControlEmission {
1628                    node_id: "bang_1".to_owned(),
1629                    port_id: "out".to_owned(),
1630                    message: ControlMessage::bang(),
1631                },
1632            ]
1633        );
1634    }
1635
1636    #[test]
1637    fn receive_name_dispatch_uses_numeric_conversion_policy() {
1638        let mut sender = value_node("float_sender", FLOAT_KIND, json!(0.25));
1639        sender.params.insert("sendName".to_owned(), json!("number"));
1640        let mut int_receiver = value_node("int_receiver", INT_KIND, json!(0));
1641        int_receiver
1642            .params
1643            .insert("receiveName".to_owned(), json!("number"));
1644        let mut uint_receiver = value_node("uint_receiver", UINT_KIND, json!(0));
1645        uint_receiver
1646            .params
1647            .insert("receiveName".to_owned(), json!("number"));
1648        let routing_graph = graph(vec![sender, int_receiver, uint_receiver]);
1649        let mut state = ControlState::from_graph(&routing_graph);
1650
1651        let response = state.apply_event(
1652            value_request("float_sender", "in", ControlValue::float(12.9)),
1653            &routing_graph,
1654        );
1655
1656        assert!(response.ok);
1657        assert!(
1658            response.diagnostics.is_empty(),
1659            "{:?}",
1660            response.diagnostics
1661        );
1662        assert_eq!(
1663            state.value_for_node("int_receiver"),
1664            Some(&ControlValue::int(12))
1665        );
1666        assert_eq!(
1667            state.value_for_node("uint_receiver"),
1668            Some(&ControlValue::uint(12))
1669        );
1670    }
1671
1672    #[test]
1673    fn panel_inlet_accepts_set_message_silently() {
1674        let graph = graph(vec![panel_node("panel_1")]);
1675        let mut state = ControlState::from_graph(&graph);
1676
1677        let response = state.apply_event(
1678            request("panel_1", "in", ControlMessage::parse_text("set #00ff00")),
1679            &graph,
1680        );
1681
1682        assert!(response.ok);
1683        assert!(response.emitted.is_empty());
1684        assert_eq!(
1685            state.value_for_node("panel_1"),
1686            Some(&ControlValue::string("#00ff00".to_owned()))
1687        );
1688    }
1689
1690    #[test]
1691    fn comment_inlet_accepts_set_message_silently() {
1692        let graph = graph(vec![comment_node("comment_1", "old text")]);
1693        let mut state = ControlState::from_graph(&graph);
1694
1695        let response = state.apply_event(
1696            request(
1697                "comment_1",
1698                "in",
1699                ControlMessage::parse_text("set updated note"),
1700            ),
1701            &graph,
1702        );
1703
1704        assert!(response.ok);
1705        assert!(response.emitted.is_empty());
1706        assert_eq!(
1707            state.value_for_node("comment_1"),
1708            Some(&ControlValue::string("updated note".to_owned()))
1709        );
1710    }
1711
1712    #[test]
1713    fn comment_and_panel_inlets_reject_non_set_messages() {
1714        let graph = graph(vec![
1715            comment_node("comment_1", "old text"),
1716            panel_node("panel_1"),
1717        ]);
1718        let mut state = ControlState::from_graph(&graph);
1719
1720        let comment_response = state.apply_event(
1721            request("comment_1", "in", ControlMessage::parse_text("ignored")),
1722            &graph,
1723        );
1724        let panel_response = state.apply_event(bang_request("panel_1", "in"), &graph);
1725
1726        assert!(!comment_response.ok);
1727        assert!(comment_response.emitted.is_empty());
1728        assert!(
1729            comment_response.diagnostics[0]
1730                .message
1731                .contains("expects set message")
1732        );
1733        assert!(!panel_response.ok);
1734        assert!(panel_response.emitted.is_empty());
1735        assert!(
1736            panel_response.diagnostics[0]
1737                .message
1738                .contains("expects set message")
1739        );
1740        assert_eq!(
1741            state.value_for_node("comment_1"),
1742            Some(&ControlValue::string("old text".to_owned()))
1743        );
1744        assert_eq!(
1745            state.value_for_node("panel_1"),
1746            Some(&ControlValue::string("transparent".to_owned()))
1747        );
1748    }
1749
1750    #[test]
1751    fn object_receive_name_dispatches_set_messages_to_panel_inlet() {
1752        let mut sender = value_node("message_1", MESSAGE_KIND, json!("set #00ff00"));
1753        sender.params.insert("sendName".to_owned(), json!("status"));
1754        let mut receiver = panel_node("panel_1");
1755        receiver
1756            .params
1757            .insert("receiveName".to_owned(), json!("status"));
1758        let routing_graph = graph(vec![sender, receiver]);
1759        let mut state = ControlState::from_graph(&routing_graph);
1760
1761        let response = state.apply_event(bang_request("message_1", "in"), &routing_graph);
1762
1763        assert!(response.ok);
1764        assert_eq!(
1765            response.emitted,
1766            vec![RuntimeControlEmission {
1767                node_id: "message_1".to_owned(),
1768                port_id: "out".to_owned(),
1769                message: ControlMessage::parse_text("set #00ff00"),
1770            }]
1771        );
1772        assert_eq!(
1773            state.value_for_node("panel_1"),
1774            Some(&ControlValue::string("#00ff00".to_owned()))
1775        );
1776    }
1777
1778    #[test]
1779    fn message_set_updates_comment_and_panel_through_inlets() {
1780        let mut graph = graph(vec![
1781            bang_node("button_1"),
1782            value_node("message_1", MESSAGE_KIND, json!("set hello world")),
1783            comment_node("comment_1", "old comment"),
1784            value_node("message_2", MESSAGE_KIND, json!("set #00ff00")),
1785            panel_node("panel_1"),
1786        ]);
1787        graph.edges = vec![
1788            edge("button_1", "out", "message_1", "in"),
1789            edge("message_1", "out", "comment_1", "in"),
1790            edge("button_1", "out", "message_2", "in"),
1791            edge("message_2", "out", "panel_1", "in"),
1792        ];
1793        let mut state = ControlState::from_graph(&graph);
1794
1795        let response = state.apply_event(bang_request("button_1", "in"), &graph);
1796
1797        assert!(response.ok, "{:?}", response.diagnostics);
1798        assert_eq!(
1799            state.value_for_node("comment_1"),
1800            Some(&ControlValue::string("hello world".to_owned()))
1801        );
1802        assert_eq!(
1803            state.value_for_node("panel_1"),
1804            Some(&ControlValue::string("#00ff00".to_owned()))
1805        );
1806    }
1807
1808    #[test]
1809    fn object_channel_helpers_skip_missing_sources_empty_names_and_mismatched_receivers() {
1810        let mut sender = value_node("slider_1", FLOAT_KIND, json!(0.25));
1811        sender.params.insert("sendName".to_owned(), json!("   "));
1812        let mut wrong_receiver = value_node("bool_1", BOOL_KIND, json!(false));
1813        wrong_receiver
1814            .params
1815            .insert("receiveName".to_owned(), json!("speed"));
1816        let empty_name_graph = graph(vec![sender, wrong_receiver]);
1817        let mut state = ControlState::from_graph(&empty_name_graph);
1818
1819        let missing_source = state.publish_object_channel(
1820            &RuntimeControlEmission {
1821                node_id: "missing".to_owned(),
1822                port_id: "value".to_owned(),
1823                message: ControlMessage::from_value(ControlValue::float(1.0)),
1824            },
1825            &empty_name_graph,
1826        );
1827        assert!(missing_source.ok);
1828        let empty_name = state.publish_object_channel(
1829            &RuntimeControlEmission {
1830                node_id: "slider_1".to_owned(),
1831                port_id: "value".to_owned(),
1832                message: ControlMessage::from_value(ControlValue::float(1.0)),
1833            },
1834            &empty_name_graph,
1835        );
1836        assert!(empty_name.ok);
1837        assert!(state.channels.is_empty());
1838        assert_eq!(
1839            state.value_for_node("bool_1"),
1840            Some(&ControlValue::bool(false))
1841        );
1842
1843        let mut sender = value_node("slider_2", FLOAT_KIND, json!(0.25));
1844        sender.params.insert("sendName".to_owned(), json!("speed"));
1845        let mut wrong_receiver = value_node("bool_2", BOOL_KIND, json!(false));
1846        wrong_receiver
1847            .params
1848            .insert("receiveName".to_owned(), json!("speed"));
1849        let mismatched_receiver_graph = graph(vec![sender, wrong_receiver]);
1850        let mut mismatched_state = ControlState::from_graph(&mismatched_receiver_graph);
1851        let mismatched = mismatched_state.publish_object_channel(
1852            &RuntimeControlEmission {
1853                node_id: "slider_2".to_owned(),
1854                port_id: "value".to_owned(),
1855                message: ControlMessage::from_value(ControlValue::float(1.0)),
1856            },
1857            &mismatched_receiver_graph,
1858        );
1859        assert!(mismatched.ok);
1860        assert_eq!(mismatched.diagnostics.len(), 1);
1861        assert!(
1862            mismatched.diagnostics[0]
1863                .message
1864                .contains("ignored incompatible routed number.float")
1865        );
1866        assert_eq!(
1867            mismatched_state.value_for_node("bool_2"),
1868            Some(&ControlValue::bool(false))
1869        );
1870
1871        let mut sender = value_node("string_sender", STRING_KIND, json!("ready"));
1872        sender.params.insert("sendName".to_owned(), json!("label"));
1873        let mut broken_receiver = value_node("string_receiver", STRING_KIND, json!("old"));
1874        broken_receiver
1875            .params
1876            .insert("receiveName".to_owned(), json!("label"));
1877        let rejected_receiver_graph = graph(vec![sender, broken_receiver]);
1878        let mut rejected_state = ControlState::from_graph(&rejected_receiver_graph);
1879        rejected_state
1880            .values
1881            .insert("string_receiver".to_owned(), ControlValue::float(0.0));
1882        let rejected = rejected_state.publish_object_channel(
1883            &RuntimeControlEmission {
1884                node_id: "string_sender".to_owned(),
1885                port_id: "value".to_owned(),
1886                message: ControlMessage::from_value(ControlValue::string("new".to_owned())),
1887            },
1888            &rejected_receiver_graph,
1889        );
1890        assert!(rejected.ok);
1891        assert_eq!(rejected.diagnostics.len(), 1);
1892        assert!(
1893            rejected.diagnostics[0]
1894                .message
1895                .contains("rejected routed string")
1896        );
1897        assert_eq!(
1898            rejected_state.value_for_node("string_receiver"),
1899            Some(&ControlValue::float(0.0))
1900        );
1901
1902        let mut sender = value_node("slider_3", FLOAT_KIND, json!(0.25));
1903        sender.params.insert("sendName".to_owned(), json!("speed"));
1904        let mut other_receiver = value_node("value_3", FLOAT_KIND, json!(0.0));
1905        other_receiver
1906            .params
1907            .insert("receiveName".to_owned(), json!("other"));
1908        let different_name_graph = graph(vec![sender, other_receiver]);
1909        let mut different_name_state = ControlState::from_graph(&different_name_graph);
1910        different_name_state.publish_object_channel(
1911            &RuntimeControlEmission {
1912                node_id: "slider_3".to_owned(),
1913                port_id: "value".to_owned(),
1914                message: ControlMessage::from_value(ControlValue::float(1.0)),
1915            },
1916            &different_name_graph,
1917        );
1918        assert_eq!(
1919            different_name_state.value_for_node("value_3"),
1920            Some(&ControlValue::float(0.0))
1921        );
1922
1923        assert_eq!(
1924            data_kind_for_control_value(&ControlValue::int(1)),
1925            "number.int"
1926        );
1927        assert_eq!(
1928            data_kind_for_control_value(&ControlValue::uint(1)),
1929            "number.uint"
1930        );
1931        assert_eq!(
1932            data_kind_for_control_value(&ControlValue::color([1.0, 0.0, 0.0, 1.0])),
1933            "color"
1934        );
1935        assert!(object_accepts_data_kind(
1936            &value_node("i32_1", INT_KIND, json!(0)),
1937            "number.int"
1938        ));
1939        assert!(object_accepts_data_kind(
1940            &value_node("u32_1", UINT_KIND, json!(0)),
1941            "number.uint"
1942        ));
1943        assert!(object_accepts_data_kind(
1944            &value_node("rgba_1", COLOR_KIND, json!([1.0, 0.0, 0.0, 1.0])),
1945            "color"
1946        ));
1947        assert!(object_accepts_data_kind(
1948            &value_node("message_1", MESSAGE_KIND, json!("go")),
1949            "string"
1950        ));
1951        assert!(object_accepts_data_kind(
1952            &value_node("message_1", MESSAGE_KIND, json!("go")),
1953            "number.float"
1954        ));
1955        assert!(object_accepts_data_kind(
1956            &bang_node("button_1"),
1957            "event.bang"
1958        ));
1959        assert!(object_accepts_data_kind(
1960            &bang_node("button_1"),
1961            "number.float"
1962        ));
1963        assert!(object_accepts_data_kind(&bang_node("button_1"), "string"));
1964        for data_kind in [
1965            "number.float",
1966            "number.int",
1967            "number.uint",
1968            "boolean",
1969            "color",
1970            "string",
1971            "event.bang",
1972            "message.any",
1973        ] {
1974            assert!(
1975                object_accepts_data_kind(&bang_node("button_1"), data_kind),
1976                "bang should accept {data_kind}"
1977            );
1978            assert!(
1979                object_accepts_data_kind(
1980                    &value_node("message_1", MESSAGE_KIND, json!("go")),
1981                    data_kind
1982                ),
1983                "message should accept {data_kind}"
1984            );
1985        }
1986        assert!(!object_accepts_data_kind(
1987            &value_node("target_1", "debug.sink", json!(null)),
1988            "string"
1989        ));
1990    }
1991
1992    #[test]
1993    fn object_set_does_not_update_send_name_channel() {
1994        let mut node = value_node("value_1", FLOAT_KIND, json!(0.25));
1995        node.params.insert("sendName".to_owned(), json!("speed"));
1996        let graph = graph(vec![node]);
1997        let mut state = ControlState::from_graph(&graph);
1998
1999        let response = state.apply_event(
2000            set_value_request("value_1", "in", ControlValue::float(2.0)),
2001            &graph,
2002        );
2003
2004        assert!(response.ok);
2005        assert!(response.emitted.is_empty());
2006        assert_eq!(
2007            state.value_for_node("value_1"),
2008            Some(&ControlValue::float(2.0))
2009        );
2010        assert!(state.channels.is_empty());
2011    }
2012
2013    #[test]
2014    fn object_edges_propagate_to_connected_control_inputs() {
2015        let mut graph = graph(vec![
2016            value_node("slider_1", FLOAT_KIND, json!(0.25)),
2017            value_node("value_1", FLOAT_KIND, json!(0.0)),
2018            value_node("message_1", MESSAGE_KIND, json!("go")),
2019            bang_node("button_1"),
2020        ]);
2021        graph.edges = vec![
2022            edge("slider_1", "value", "value_1", "in"),
2023            edge("button_1", "out", "message_1", "in"),
2024        ];
2025        let mut state = ControlState::from_graph(&graph);
2026
2027        let slider = state.apply_event(
2028            value_request("slider_1", "in", ControlValue::float(1.5)),
2029            &graph,
2030        );
2031        assert!(slider.ok);
2032        assert_eq!(slider.emitted.len(), 2);
2033        assert_eq!(
2034            state.value_for_node("value_1"),
2035            Some(&ControlValue::float(1.5))
2036        );
2037
2038        let button = state.apply_event(bang_request("button_1", "in"), &graph);
2039        assert!(button.ok);
2040        assert_eq!(
2041            button.emitted,
2042            vec![
2043                RuntimeControlEmission {
2044                    node_id: "button_1".to_owned(),
2045                    port_id: "out".to_owned(),
2046                    message: ControlMessage::bang()
2047                },
2048                RuntimeControlEmission {
2049                    node_id: "message_1".to_owned(),
2050                    port_id: "out".to_owned(),
2051                    message: ControlMessage::parse_text("go")
2052                }
2053            ]
2054        );
2055    }
2056
2057    #[test]
2058    fn bang_to_float_to_float_propagates_stored_value() {
2059        let mut graph = graph(vec![
2060            bang_node("button_1"),
2061            value_node("float_a", FLOAT_KIND, json!(7.25)),
2062            value_node("float_b", FLOAT_KIND, json!(0.0)),
2063        ]);
2064        graph.edges = vec![
2065            edge("button_1", "out", "float_a", "in"),
2066            edge("float_a", "value", "float_b", "in"),
2067        ];
2068        let mut state = ControlState::from_graph(&graph);
2069
2070        let response = state.apply_event(bang_request("button_1", "in"), &graph);
2071
2072        assert!(response.ok);
2073        assert_eq!(
2074            response.emitted,
2075            vec![
2076                RuntimeControlEmission {
2077                    node_id: "button_1".to_owned(),
2078                    port_id: "out".to_owned(),
2079                    message: ControlMessage::bang(),
2080                },
2081                RuntimeControlEmission {
2082                    node_id: "float_a".to_owned(),
2083                    port_id: "value".to_owned(),
2084                    message: ControlMessage::from_value(ControlValue::float(7.25)),
2085                },
2086                RuntimeControlEmission {
2087                    node_id: "float_b".to_owned(),
2088                    port_id: "value".to_owned(),
2089                    message: ControlMessage::from_value(ControlValue::float(7.25)),
2090                },
2091            ]
2092        );
2093        assert_eq!(
2094            state.value_for_node("float_b"),
2095            Some(&ControlValue::float(7.25))
2096        );
2097    }
2098
2099    #[test]
2100    fn bang_to_message_to_bang_propagates_as_bang() {
2101        let mut graph = graph(vec![
2102            bang_node("button_1"),
2103            value_node("message_1", MESSAGE_KIND, json!("go")),
2104            bang_node("button_2"),
2105        ]);
2106        graph.edges = vec![
2107            edge("button_1", "out", "message_1", "in"),
2108            edge("message_1", "out", "button_2", "in"),
2109        ];
2110        let mut state = ControlState::from_graph(&graph);
2111
2112        let response = state.apply_event(bang_request("button_1", "in"), &graph);
2113
2114        assert!(response.ok);
2115        assert_eq!(
2116            response.emitted,
2117            vec![
2118                RuntimeControlEmission {
2119                    node_id: "button_1".to_owned(),
2120                    port_id: "out".to_owned(),
2121                    message: ControlMessage::bang(),
2122                },
2123                RuntimeControlEmission {
2124                    node_id: "message_1".to_owned(),
2125                    port_id: "out".to_owned(),
2126                    message: ControlMessage::parse_text("go"),
2127                },
2128                RuntimeControlEmission {
2129                    node_id: "button_2".to_owned(),
2130                    port_id: "out".to_owned(),
2131                    message: ControlMessage::bang(),
2132                },
2133            ]
2134        );
2135    }
2136
2137    #[test]
2138    fn object_edge_propagation_ignores_edges_to_missing_targets() {
2139        let mut graph = graph(vec![
2140            value_node("slider_1", FLOAT_KIND, json!(0.25)),
2141            value_node("sink_1", "debug.sink", json!(null)),
2142        ]);
2143        graph.edges = vec![
2144            edge("slider_1", "value", "missing", "in"),
2145            edge("slider_1", "value", "sink_1", "in"),
2146        ];
2147        let mut state = ControlState::from_graph(&graph);
2148
2149        let response = state.apply_event(
2150            value_request("slider_1", "in", ControlValue::float(1.5)),
2151            &graph,
2152        );
2153
2154        assert!(response.ok);
2155        assert_eq!(response.emitted.len(), 1);
2156        assert!(state.channels.is_empty());
2157    }
2158
2159    #[test]
2160    fn object_edge_propagation_rejects_invalid_target_port() {
2161        let mut graph = graph(vec![
2162            value_node("slider_1", FLOAT_KIND, json!(0.25)),
2163            value_node("value_1", FLOAT_KIND, json!(0.0)),
2164        ]);
2165        graph.edges = vec![edge("slider_1", "value", "value_1", "missing")];
2166        let mut state = ControlState::from_graph(&graph);
2167
2168        let response = state.apply_event(
2169            value_request("slider_1", "in", ControlValue::float(1.5)),
2170            &graph,
2171        );
2172
2173        assert!(!response.ok);
2174        assert!(response.diagnostics[0].message.contains("port missing"));
2175        assert!(state.channels.is_empty());
2176        assert_eq!(
2177            state.value_for_node("slider_1"),
2178            Some(&ControlValue::float(0.25))
2179        );
2180        assert_eq!(
2181            state.value_for_node("value_1"),
2182            Some(&ControlValue::float(0.0))
2183        );
2184    }
2185
2186    #[test]
2187    fn ui_panel_propagation_stops_at_runtime_safety_limit() {
2188        let mut graph = graph(vec![
2189            value_node("slider_1", FLOAT_KIND, json!(0.25)),
2190            value_node("value_1", FLOAT_KIND, json!(0.0)),
2191        ]);
2192        graph.edges = vec![
2193            edge("slider_1", "value", "value_1", "in"),
2194            edge("value_1", "value", "value_1", "in"),
2195        ];
2196        let mut state = ControlState::from_graph(&graph);
2197
2198        let response = state.apply_event(
2199            value_request("slider_1", "in", ControlValue::float(1.5)),
2200            &graph,
2201        );
2202
2203        assert!(!response.ok);
2204        assert!(
2205            response.diagnostics[0]
2206                .message
2207                .contains("runtime safety limit")
2208        );
2209        assert_eq!(
2210            state.value_for_node("slider_1"),
2211            Some(&ControlValue::float(0.25))
2212        );
2213        assert_eq!(
2214            state.value_for_node("value_1"),
2215            Some(&ControlValue::float(0.0))
2216        );
2217    }
2218
2219    #[test]
2220    fn ui_panel_controls_emit_runtime_values() {
2221        let graph = graph(vec![
2222            value_node("slider_1", FLOAT_KIND, json!(0.5)),
2223            value_node("toggle_1", BOOL_KIND, json!(false)),
2224            bang_node("button_1"),
2225        ]);
2226        let mut state = ControlState::from_graph(&graph);
2227
2228        let slider = state.apply_event(
2229            value_request("slider_1", "in", ControlValue::float(1.25)),
2230            &graph,
2231        );
2232        assert!(slider.ok);
2233        assert_eq!(
2234            emitted_value(&slider.emitted[0]),
2235            Some(ControlValue::float(1.25))
2236        );
2237        assert_eq!(
2238            state.value_for_node("slider_1"),
2239            Some(&ControlValue::float(1.25))
2240        );
2241
2242        let toggle = state.apply_event(bang_request("toggle_1", "in"), &graph);
2243        assert!(toggle.ok);
2244        assert_eq!(
2245            emitted_value(&toggle.emitted[0]),
2246            Some(ControlValue::bool(true))
2247        );
2248        assert_eq!(
2249            state.value_for_node("toggle_1"),
2250            Some(&ControlValue::bool(true))
2251        );
2252
2253        let button = state.apply_event(bang_request("button_1", "in"), &graph);
2254        assert!(button.ok);
2255        assert_eq!(button.emitted[0].message, ControlMessage::bang());
2256    }
2257
2258    #[test]
2259    fn ui_panel_controls_reject_wrong_ports_and_types() {
2260        let graph = graph(vec![
2261            value_node("slider_1", FLOAT_KIND, json!(0.5)),
2262            value_node("toggle_1", BOOL_KIND, json!(false)),
2263            bang_node("button_1"),
2264        ]);
2265        let mut state = ControlState::from_graph(&graph);
2266
2267        for request in [
2268            bang_request("button_1", "value"),
2269            value_request("slider_1", "cold", ControlValue::bool(true)),
2270            value_request("slider_1", "in", ControlValue::bool(true)),
2271            value_request("toggle_1", "value", ControlValue::float(2.0)),
2272        ] {
2273            let response = state.apply_event(request, &graph);
2274            assert!(!response.ok);
2275            assert!(response.emitted.is_empty());
2276        }
2277
2278        let any_button = state.apply_event(
2279            value_request("button_1", "in", ControlValue::bool(true)),
2280            &graph,
2281        );
2282        assert!(any_button.ok);
2283        assert_eq!(any_button.emitted[0].message, ControlMessage::bang());
2284
2285        let slider_set = state.apply_event(
2286            set_value_request("slider_1", "in", ControlValue::float(1.0)),
2287            &graph,
2288        );
2289        assert!(slider_set.ok);
2290        assert!(slider_set.emitted.is_empty());
2291        assert_eq!(
2292            state.value_for_node("slider_1"),
2293            Some(&ControlValue::float(1.0))
2294        );
2295
2296        let slider_bang = state.apply_event(bang_request("slider_1", "in"), &graph);
2297        assert!(slider_bang.ok);
2298        assert_eq!(
2299            emitted_value(&slider_bang.emitted[0]),
2300            Some(ControlValue::float(1.0))
2301        );
2302
2303        let slider_bad_bang = state.apply_event(
2304            value_request("slider_1", "in", ControlValue::bool(true)),
2305            &graph,
2306        );
2307        assert!(!slider_bad_bang.ok);
2308
2309        let slider_other = state.apply_event(
2310            value_request("slider_1", "other", ControlValue::float(1.0)),
2311            &graph,
2312        );
2313        assert!(!slider_other.ok);
2314
2315        state.values.remove("slider_1");
2316        let slider_missing_state = state.apply_event(bang_request("slider_1", "in"), &graph);
2317        assert!(!slider_missing_state.ok);
2318        assert!(
2319            slider_missing_state.diagnostics[0]
2320                .message
2321                .contains("has no runtime control state")
2322        );
2323
2324        let bool_toggle = state.apply_event(
2325            value_request("toggle_1", "in", ControlValue::bool(true)),
2326            &graph,
2327        );
2328        assert!(bool_toggle.ok);
2329        assert_eq!(
2330            state.value_for_node("toggle_1"),
2331            Some(&ControlValue::bool(true))
2332        );
2333
2334        state.values.remove("toggle_1");
2335        let missing_state = state.apply_event(bang_request("toggle_1", "in"), &graph);
2336        assert!(!missing_state.ok);
2337        assert!(
2338            missing_state.diagnostics[0]
2339                .message
2340                .contains("has no runtime control state")
2341        );
2342    }
2343
2344    #[test]
2345    fn control_state_response_serializes_values_and_channels() {
2346        let mut values = BTreeMap::new();
2347        values.insert("slider_1".to_owned(), ControlValue::float(0.5));
2348        let mut channels = BTreeMap::new();
2349        channels.insert(
2350            "number.float:speed".to_owned(),
2351            ControlMessage::from_value(ControlValue::float(1.5)),
2352        );
2353
2354        let response = RuntimeControlStateResponse {
2355            ok: true,
2356            control_revision: 7,
2357            values,
2358            channels,
2359            diagnostics: Vec::new(),
2360        };
2361
2362        assert_eq!(
2363            serde_json::to_value(response).unwrap(),
2364            json!({
2365                "ok": true,
2366                "controlRevision": 7,
2367                "values": {
2368                    "slider_1": { "type": "float", "representation": "f32", "value": 0.5 }
2369                },
2370                "channels": {
2371                    "number.float:speed": {
2372                        "selector": "float",
2373                        "atoms": [{ "type": "float", "representation": "f32", "value": 1.5 }]
2374                    }
2375                },
2376                "diagnostics": []
2377            })
2378        );
2379    }
2380
2381    #[test]
2382    fn helper_fallbacks_and_read_responses_are_covered() {
2383        let node = value_node("value_1", FLOAT_KIND, json!(0.5));
2384        let address = RuntimeControlReadRequest {
2385            node_id: "value_1".to_owned(),
2386            target: RuntimeControlReadTarget::Param,
2387            id: "value".to_owned(),
2388        };
2389
2390        assert!(supports_runtime_control_events(BANG_KIND));
2391        assert!(!supports_runtime_control_events("debug.sink"));
2392        assert_eq!(
2393            ControlState::from_graph(&graph(vec![node.clone()]))
2394                .output_value_for_node(&node, "value",),
2395            Some(ControlValue::float(0.5))
2396        );
2397        assert_eq!(
2398            ControlState::from_graph(&graph(vec![node.clone()]))
2399                .output_value_for_node(&node, "other",),
2400            None
2401        );
2402
2403        assert_eq!(
2404            ControlMessage::from_value(ControlValue::float(1.25)).to_text(),
2405            "float 1.25"
2406        );
2407        assert_eq!(
2408            ControlMessage::from_value(ControlValue::int(7)).to_text(),
2409            "int 7"
2410        );
2411        assert_eq!(
2412            ControlMessage::from_value(ControlValue::bool(true)).to_text(),
2413            "bool on"
2414        );
2415        assert_eq!(
2416            ControlMessage::from_value(ControlValue::bool(false)).to_text(),
2417            "bool off"
2418        );
2419        assert_eq!(
2420            ControlMessage::from_value(ControlValue::color([1.0, 0.5, 0.0, 1.0])).to_text(),
2421            "color 1 0.5 0 1"
2422        );
2423        let selector_only = ControlMessage {
2424            selector: "clear".to_owned(),
2425            atoms: Vec::new(),
2426        };
2427        assert_eq!(data_kind_for_control_message(&selector_only), "message.any");
2428        assert_eq!(set_message_text(&selector_only), "clear");
2429        assert_eq!(
2430            set_message_text(&ControlMessage::from_value(ControlValue::string(
2431                "hello".to_owned()
2432            ))),
2433            "hello"
2434        );
2435        assert_eq!(
2436            set_message_text(&ControlMessage {
2437                selector: "set".to_owned(),
2438                atoms: vec![
2439                    ControlValue::float(1.5),
2440                    ControlValue::int(2),
2441                    ControlValue::uint(3),
2442                    ControlValue::bool(true),
2443                    ControlValue::bool(false),
2444                    ControlValue::string("label".to_owned()),
2445                    ControlValue::color([1.0, 0.5, 0.0, 1.0])
2446                ]
2447            }),
2448            "1.5 2 3 on off label color 1 0.5 0 1"
2449        );
2450        assert_eq!(silent_set_message(&ControlMessage::bang()), None);
2451        assert_eq!(
2452            value_from_message(
2453                &ControlMessage::from_value(ControlValue::int(3)),
2454                &ControlValue::float(0.0)
2455            ),
2456            Some(ControlValue::float(3.0))
2457        );
2458        assert_eq!(
2459            value_from_message(
2460                &ControlMessage::from_value(ControlValue::float(3.0)),
2461                &ControlValue::int(0)
2462            ),
2463            Some(ControlValue::int(3))
2464        );
2465        assert_eq!(
2466            value_from_message(
2467                &ControlMessage::from_value(ControlValue::float(3.0)),
2468                &ControlValue::uint(0)
2469            ),
2470            Some(ControlValue::uint(3))
2471        );
2472        assert_eq!(
2473            value_from_message(
2474                &ControlMessage::parse_text("on"),
2475                &ControlValue::bool(false)
2476            ),
2477            Some(ControlValue::bool(true))
2478        );
2479        assert_eq!(
2480            value_from_message(
2481                &ControlMessage::from_value(ControlValue::string("direct".to_owned())),
2482                &ControlValue::string(String::new())
2483            ),
2484            Some(ControlValue::string("direct".to_owned()))
2485        );
2486        assert_eq!(
2487            value_from_message(
2488                &ControlMessage::parse_text("route 1"),
2489                &ControlValue::string(String::new())
2490            ),
2491            Some(ControlValue::string("route 1".to_owned()))
2492        );
2493        assert_eq!(
2494            value_from_message(
2495                &ControlMessage::from_value(ControlValue::color([0.1, 0.2, 0.3, 1.0])),
2496                &ControlValue::color([1.0, 1.0, 1.0, 1.0])
2497            ),
2498            Some(ControlValue::color([0.1, 0.2, 0.3, 1.0]))
2499        );
2500        assert_eq!(
2501            value_from_message(
2502                &ControlMessage::from_value(ControlValue::float(0.5)),
2503                &ControlValue::color([1.0, 1.0, 1.0, 1.0])
2504            ),
2505            None
2506        );
2507        assert_eq!(
2508            message_from_message_node_state(&ControlValue::float(2.0)),
2509            ControlMessage::from_value(ControlValue::float(2.0))
2510        );
2511        assert_eq!(
2512            coerce_toggle_input(&ControlMessage::parse_text("0"), true),
2513            Some(false)
2514        );
2515        assert_eq!(
2516            coerce_toggle_input(&ControlMessage::parse_text("1"), false),
2517            Some(true)
2518        );
2519        assert_eq!(
2520            coerce_toggle_input(&ControlMessage::parse_text("2"), false),
2521            None
2522        );
2523        assert_eq!(
2524            coerce_toggle_input(&ControlMessage::parse_text("bang"), false),
2525            Some(true)
2526        );
2527        assert_eq!(
2528            coerce_toggle_input(&ControlMessage::parse_text("maybe"), false),
2529            None
2530        );
2531        assert_eq!(
2532            coerce_toggle_input(
2533                &ControlMessage {
2534                    selector: "0".to_owned(),
2535                    atoms: Vec::new()
2536                },
2537                true
2538            ),
2539            Some(false)
2540        );
2541        assert_eq!(
2542            coerce_toggle_input(
2543                &ControlMessage {
2544                    selector: "1".to_owned(),
2545                    atoms: Vec::new()
2546                },
2547                false
2548            ),
2549            Some(true)
2550        );
2551        assert_eq!(
2552            coerce_toggle_input(
2553                &ControlMessage {
2554                    selector: "pulse".to_owned(),
2555                    atoms: Vec::new()
2556                },
2557                false
2558            ),
2559            None
2560        );
2561        assert_eq!(
2562            coerce_toggle_input(&ControlMessage::from_value(ControlValue::uint(0)), true),
2563            Some(false)
2564        );
2565        assert_eq!(
2566            coerce_toggle_input(&ControlMessage::from_value(ControlValue::uint(1)), false),
2567            Some(true)
2568        );
2569        assert_eq!(
2570            coerce_toggle_input(&ControlMessage::from_value(ControlValue::uint(2)), false),
2571            None
2572        );
2573
2574        assert_eq!(
2575            RuntimeControlReadResponse::ok(address.clone(), json!({ "type": "json" })).value,
2576            Some(json!({ "type": "json" }))
2577        );
2578        assert!(!RuntimeControlReadResponse::error(address, "missing value").ok);
2579    }
2580
2581    #[test]
2582    fn unsupported_control_kind_is_reported() {
2583        let graph = graph(vec![value_node("custom", "debug.sink", json!(null))]);
2584        let mut state = ControlState::default();
2585
2586        let response = state.apply_event(bang_request("custom", "in"), &graph);
2587
2588        assert!(!response.ok);
2589        assert!(
2590            response.diagnostics[0]
2591                .message
2592                .contains("does not support runtime control events")
2593        );
2594    }
2595
2596    #[test]
2597    fn invalid_events_do_not_mutate_state() {
2598        let graph = graph(vec![value_node("value_1", FLOAT_KIND, json!(1.0))]);
2599        let mut state = ControlState::from_graph(&graph);
2600
2601        for request in [
2602            value_request("missing", "cold", ControlValue::float(2.0)),
2603            value_request("value_1", "value", ControlValue::float(2.0)),
2604            value_request("value_1", "cold", ControlValue::bool(true)),
2605            bang_request("value_1", "cold"),
2606        ] {
2607            let response = state.apply_event(request, &graph);
2608            assert!(!response.ok);
2609            assert!(response.emitted.is_empty());
2610            assert!(!response.diagnostics.is_empty());
2611            assert_eq!(
2612                state.value_for_node("value_1"),
2613                Some(&ControlValue::float(1.0))
2614            );
2615        }
2616    }
2617
2618    #[test]
2619    fn rejects_corrupt_toggle_state_and_existing_unsupported_input_port() {
2620        let mut graph = graph(vec![
2621            value_node("toggle_1", BOOL_KIND, json!(false)),
2622            value_node("value_1", FLOAT_KIND, json!(1.0)),
2623            value_node("message_1", MESSAGE_KIND, json!("go")),
2624        ]);
2625        graph.nodes[0].ports.push(port(
2626            "other",
2627            PortDirection::Input,
2628            DataFlow::Event,
2629            "event.bang",
2630            Some(PortActivation::Trigger),
2631        ));
2632        graph.nodes[1].ports.push(port(
2633            "set",
2634            PortDirection::Input,
2635            DataFlow::Event,
2636            "message.any",
2637            Some(PortActivation::Trigger),
2638        ));
2639        graph.nodes[2].ports.push(port(
2640            "cold",
2641            PortDirection::Input,
2642            DataFlow::Value,
2643            "message.any",
2644            Some(PortActivation::Latched),
2645        ));
2646        let mut state = ControlState::from_graph(&graph);
2647        state.values.insert(
2648            "toggle_1".to_owned(),
2649            ControlValue::string("not-bool".to_owned()),
2650        );
2651
2652        let corrupt = state.apply_event(bang_request("toggle_1", "in"), &graph);
2653        assert!(!corrupt.ok);
2654        assert!(
2655            corrupt.diagnostics[0]
2656                .message
2657                .contains("non-boolean toggle state")
2658        );
2659
2660        state
2661            .values
2662            .insert("toggle_1".to_owned(), ControlValue::bool(false));
2663        let unsupported = state.apply_event(bang_request("toggle_1", "other"), &graph);
2664        assert!(!unsupported.ok);
2665        assert!(
2666            unsupported.diagnostics[0]
2667                .message
2668                .contains("does not support runtime control input port other")
2669        );
2670
2671        let unsupported_set = state.apply_event(
2672            request("value_1", "set", ControlMessage::parse_text("set 2")),
2673            &graph,
2674        );
2675        assert!(!unsupported_set.ok);
2676        assert!(
2677            unsupported_set.diagnostics[0]
2678                .message
2679                .contains("does not support runtime control input port set")
2680        );
2681
2682        let unsupported_message_cold = state.apply_event(
2683            request(
2684                "message_1",
2685                "cold",
2686                ControlMessage::parse_text("set ignored"),
2687            ),
2688            &graph,
2689        );
2690        assert!(!unsupported_message_cold.ok);
2691        assert!(
2692            unsupported_message_cold.diagnostics[0]
2693                .message
2694                .contains("does not support runtime control input port cold")
2695        );
2696    }
2697
2698    #[test]
2699    fn rejects_non_control_nodes_and_missing_control_state() {
2700        let graph = graph(vec![
2701            value_node("value_1", FLOAT_KIND, json!(1.0)),
2702            value_node("target_1", "debug.sink", json!(1.0)),
2703        ]);
2704
2705        let mut state = ControlState::from_graph(&graph);
2706        let non_control = state.apply_event(
2707            value_request("target_1", "cold", ControlValue::float(2.0)),
2708            &graph,
2709        );
2710        assert!(!non_control.ok);
2711        assert!(
2712            non_control.diagnostics[0]
2713                .message
2714                .contains("does not support runtime control events")
2715        );
2716
2717        state.values.remove("value_1");
2718        let missing_state = state.apply_event(
2719            value_request("value_1", "cold", ControlValue::float(2.0)),
2720            &graph,
2721        );
2722        assert!(!missing_state.ok);
2723        assert!(
2724            missing_state.diagnostics[0]
2725                .message
2726                .contains("has no runtime control state")
2727        );
2728    }
2729
2730    fn graph(nodes: Vec<GraphNode>) -> GraphDocument {
2731        GraphDocument {
2732            schema: "skenion.graph".to_owned(),
2733            schema_version: "0.1.0".to_owned(),
2734            id: "control-graph".to_owned(),
2735            revision: "1".to_owned(),
2736            nodes,
2737            edges: Vec::new(),
2738        }
2739    }
2740
2741    fn edge(from_node: &str, from_port: &str, to_node: &str, to_port: &str) -> crate::Edge {
2742        crate::Edge {
2743            from: crate::PortRef {
2744                node: from_node.to_owned(),
2745                port: from_port.to_owned(),
2746            },
2747            to: crate::PortRef {
2748                node: to_node.to_owned(),
2749                port: to_port.to_owned(),
2750            },
2751        }
2752    }
2753
2754    fn value_node(id: &str, kind: &str, value: serde_json::Value) -> GraphNode {
2755        let mut params = Map::new();
2756        params.insert("value".to_owned(), value);
2757        let ports = match kind {
2758            FLOAT_KIND => stored_value_ports("number.float"),
2759            INT_KIND => stored_value_ports("number.int"),
2760            UINT_KIND => stored_value_ports("number.uint"),
2761            BOOL_KIND => stored_value_ports("boolean"),
2762            COLOR_KIND => stored_value_ports("color"),
2763            STRING_KIND => stored_value_ports("string"),
2764            MESSAGE_KIND => message_ports(),
2765            _ => Vec::new(),
2766        };
2767        if id.contains("slider") {
2768            params.insert("widget".to_owned(), json!("slider"));
2769        }
2770        if id.contains("toggle") {
2771            params.insert("widget".to_owned(), json!("toggle"));
2772        }
2773        GraphNode {
2774            id: id.to_owned(),
2775            kind: kind.to_owned(),
2776            kind_version: "0.1.0".to_owned(),
2777            params,
2778            ports,
2779        }
2780    }
2781
2782    fn operator_node(id: &str, kind: &str, right: Option<f64>) -> GraphNode {
2783        let mut params = Map::new();
2784        if let Some(right) = right {
2785            params.insert("right".to_owned(), json!(right));
2786        }
2787        let mut ports = vec![port(
2788            "in",
2789            PortDirection::Input,
2790            DataFlow::Event,
2791            "message.any",
2792            Some(PortActivation::Trigger),
2793        )];
2794        if kind != OPERATOR_SQRT_KIND {
2795            ports.push(port(
2796                "right",
2797                PortDirection::Input,
2798                DataFlow::Value,
2799                "number.float",
2800                Some(PortActivation::Latched),
2801            ));
2802        }
2803        ports.push(port(
2804            "out",
2805            PortDirection::Output,
2806            DataFlow::Value,
2807            "number.float",
2808            None,
2809        ));
2810        GraphNode {
2811            id: id.to_owned(),
2812            kind: kind.to_owned(),
2813            kind_version: "0.1.0".to_owned(),
2814            params,
2815            ports,
2816        }
2817    }
2818
2819    fn panel_node(id: &str) -> GraphNode {
2820        let mut params = Map::new();
2821        params.insert("color".to_owned(), json!(null));
2822        GraphNode {
2823            id: id.to_owned(),
2824            kind: PANEL_KIND.to_owned(),
2825            kind_version: "0.1.0".to_owned(),
2826            params,
2827            ports: vec![port(
2828                "in",
2829                PortDirection::Input,
2830                DataFlow::Event,
2831                "message.any",
2832                Some(PortActivation::Trigger),
2833            )],
2834        }
2835    }
2836
2837    fn comment_node(id: &str, text: &str) -> GraphNode {
2838        let mut params = Map::new();
2839        params.insert("text".to_owned(), json!(text));
2840        GraphNode {
2841            id: id.to_owned(),
2842            kind: COMMENT_KIND.to_owned(),
2843            kind_version: "0.1.0".to_owned(),
2844            params,
2845            ports: vec![port(
2846                "in",
2847                PortDirection::Input,
2848                DataFlow::Event,
2849                "message.any",
2850                Some(PortActivation::Trigger),
2851            )],
2852        }
2853    }
2854
2855    fn bang_node(id: &str) -> GraphNode {
2856        GraphNode {
2857            id: id.to_owned(),
2858            kind: BANG_KIND.to_owned(),
2859            kind_version: "0.1.0".to_owned(),
2860            params: Map::new(),
2861            ports: vec![
2862                port(
2863                    "in",
2864                    PortDirection::Input,
2865                    DataFlow::Event,
2866                    "message.any",
2867                    Some(PortActivation::Trigger),
2868                ),
2869                port(
2870                    "out",
2871                    PortDirection::Output,
2872                    DataFlow::Event,
2873                    "event.bang",
2874                    None,
2875                ),
2876            ],
2877        }
2878    }
2879
2880    fn stored_value_ports(data_kind: &str) -> Vec<Port> {
2881        vec![
2882            port(
2883                "in",
2884                PortDirection::Input,
2885                DataFlow::Event,
2886                "message.any",
2887                Some(PortActivation::Trigger),
2888            ),
2889            port(
2890                "cold",
2891                PortDirection::Input,
2892                DataFlow::Value,
2893                data_kind,
2894                Some(PortActivation::Latched),
2895            ),
2896            port(
2897                "value",
2898                PortDirection::Output,
2899                DataFlow::Value,
2900                data_kind,
2901                None,
2902            ),
2903        ]
2904    }
2905
2906    fn message_ports() -> Vec<Port> {
2907        vec![
2908            port(
2909                "in",
2910                PortDirection::Input,
2911                DataFlow::Event,
2912                "message.any",
2913                Some(PortActivation::Trigger),
2914            ),
2915            port(
2916                "out",
2917                PortDirection::Output,
2918                DataFlow::Event,
2919                "message.any",
2920                None,
2921            ),
2922        ]
2923    }
2924
2925    fn port(
2926        id: &str,
2927        direction: PortDirection,
2928        flow: DataFlow,
2929        data_kind: &str,
2930        activation: Option<PortActivation>,
2931    ) -> Port {
2932        Port {
2933            id: id.to_owned(),
2934            direction,
2935            label: None,
2936            data_type: DataType {
2937                flow,
2938                data_kind: data_kind.to_owned(),
2939                unit: None,
2940                range: None,
2941                shape: None,
2942                channels: None,
2943                sample_rate: None,
2944                format: None,
2945                color_space: None,
2946                frame_rate: None,
2947                alpha_policy: None,
2948                values: None,
2949            },
2950            required: None,
2951            default_value: None,
2952            activation,
2953        }
2954    }
2955}