Skip to main content

agent86_ui/runtime/
surface.rs

1//! Surfaces: the state a renderer keeps for each surface, and what it derives
2//! from it.
3//!
4//! [`Runtime::apply`] takes a batch the way [`crate::Validator`] does (all or
5//! nothing) and, beyond validating it, applies it: components are stored, the
6//! data model updated (`null` deletes), and every touched surface evaluated, so
7//! a template that does not parse or an `@index` outside a list is reported to
8//! the agent rather than shown as a broken surface.
9//!
10//! [`Runtime::tree`] resolves a surface for drawing: a [`Node`] per component
11//! instance (a list template gives one per item), its properties with every
12//! binding and call evaluated, its failing checks, and its children.
13//! [`Runtime::input`] writes what the user enters (two-way binding), and
14//! [`Runtime::dispatch`] runs a component's action on the user's gesture,
15//! giving the `action` to send the agent or the effects of a local function.
16
17use super::data::{self, DataModel};
18use super::functions::{coerce_bool, validity, Effect, EvalError, Evaluator, LocalFunction, Scope};
19use crate::catalog::{Catalog, ChildRef, FunctionDef};
20use crate::message::Action;
21use crate::schema::CompileError;
22use crate::validate::{problem, Code, Problem, Report, Validator};
23use serde_json::{Map, Value};
24use std::collections::{BTreeMap, BTreeSet};
25
26/// How deep a component tree may nest before resolution stops, so a cycle the
27/// validator did not see cannot recurse without end.
28pub const MAX_TREE_DEPTH: usize = 64;
29
30#[derive(Debug, Clone)]
31struct SurfaceState {
32    catalog_id: Option<String>,
33    send_data_model: bool,
34    /// `createSurface`'s `metadata` (its `extensions`), as sent.
35    metadata: Option<Value>,
36    components: BTreeMap<String, Value>,
37    data: DataModel,
38}
39
40/// One component instance, resolved for drawing.
41#[derive(Debug, Clone, PartialEq)]
42#[non_exhaustive]
43pub struct Node {
44    /// The component's id.
45    pub id: String,
46    /// The component type (`""` for a placeholder).
47    pub component: String,
48    /// The data context: `/` at the root, the item's path inside a template.
49    pub data_path: String,
50    /// The item's index inside the innermost template.
51    pub index: Option<usize>,
52    /// The properties with every binding and call resolved. Properties that
53    /// only hold child ids and actions are left out: children are in
54    /// [`Node::children`], and an action runs through [`Runtime::dispatch`]. A
55    /// property holding children with other fields (Tabs' `tabs`, with each
56    /// tab's title) is kept.
57    pub properties: Map<String, Value>,
58    /// `@accessibility`, resolved.
59    pub accessibility: Option<Map<String, Value>>,
60    /// The failing check results, in order, each with `valid`, `message`,
61    /// `severity` (default `error`), and any `code`.
62    pub failures: Vec<Value>,
63    /// What failed to evaluate on this node (`EXPRESSION_ERROR`): the property
64    /// resolved to `null`, the node still shows.
65    pub errors: Vec<String>,
66    /// The child nodes, by the property that holds them, in catalog order.
67    pub children: Vec<(String, Vec<Node>)>,
68    /// The component is referenced but not defined yet: draw a placeholder.
69    pub placeholder: bool,
70}
71
72impl Node {
73    /// Whether no check fails with severity `error` (a button with a failing
74    /// check is disabled).
75    pub fn is_valid(&self) -> bool {
76        !self.failures.iter().any(is_error)
77    }
78
79    /// The messages of the failing `error` checks, in order.
80    pub fn validation_errors(&self) -> Vec<String> {
81        self.failures
82            .iter()
83            .filter(|failure| is_error(failure))
84            .map(|failure| {
85                failure
86                    .get("message")
87                    .and_then(Value::as_str)
88                    .unwrap_or_default()
89                    .to_string()
90            })
91            .collect()
92    }
93
94    /// The first failing check, or `{"valid": true}`.
95    pub fn validation_result(&self) -> Value {
96        self.failures
97            .first()
98            .cloned()
99            .unwrap_or_else(|| serde_json::json!({"valid": true}))
100    }
101
102    /// Every node in this subtree, this one first.
103    pub fn walk(&self) -> Vec<&Node> {
104        let mut out = vec![self];
105        for (_, nodes) in &self.children {
106            for node in nodes {
107                out.extend(node.walk());
108            }
109        }
110        out
111    }
112}
113
114fn is_error(failure: &Value) -> bool {
115    failure
116        .get("severity")
117        .and_then(Value::as_str)
118        .unwrap_or("error")
119        == "error"
120}
121
122/// Why an action could not run.
123#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
124#[error("{code}: {message}")]
125#[non_exhaustive]
126pub struct ActionError {
127    /// `INVALID_ACTION`, `EXPRESSION_ERROR`, or `EXECUTION_ERROR`.
128    pub code: String,
129    /// What went wrong.
130    pub message: String,
131    /// The surface the action was on.
132    pub surface_id: String,
133}
134
135/// What a gesture produced.
136#[derive(Debug, Clone, PartialEq, Default)]
137#[non_exhaustive]
138pub struct Dispatch {
139    /// The `action` to send the agent, for an event.
140    pub action: Option<Action>,
141    /// What local functions asked for (`openUrl`); data writes are already
142    /// applied.
143    pub effects: Vec<Effect>,
144}
145
146/// Where a gesture came from.
147#[derive(Debug, Clone, PartialEq, Eq)]
148#[non_exhaustive]
149pub struct Gesture {
150    /// The surface.
151    pub surface_id: String,
152    /// The component the user interacted with.
153    pub source_component_id: String,
154    /// The component instance's data context (its [`Node::data_path`]).
155    pub data_path: String,
156    /// Its template index (its [`Node::index`]).
157    pub index: Option<usize>,
158    /// Whether this is a real user activation (a click, a key press), which
159    /// `openUrl` and other gesture-only functions require.
160    pub activation: bool,
161    /// When it happened, RFC 3339; `None` uses the current time.
162    pub timestamp: Option<String>,
163    /// Renderer metadata sent with the action (`{"extensions": {...}}`).
164    pub metadata: Option<Value>,
165}
166
167impl Gesture {
168    /// A user activation on a component at the root data context, now.
169    pub fn new(surface_id: impl Into<String>, source_component_id: impl Into<String>) -> Self {
170        Self {
171            surface_id: surface_id.into(),
172            source_component_id: source_component_id.into(),
173            data_path: "/".into(),
174            index: None,
175            activation: true,
176            timestamp: None,
177            metadata: None,
178        }
179    }
180
181    /// A user activation on a component instance.
182    pub fn on(node: &Node, surface_id: impl Into<String>) -> Self {
183        Self {
184            surface_id: surface_id.into(),
185            source_component_id: node.id.clone(),
186            data_path: node.data_path.clone(),
187            index: node.index,
188            activation: true,
189            timestamp: None,
190            metadata: None,
191        }
192    }
193}
194
195/// A renderer's surfaces, headless.
196#[derive(Debug)]
197pub struct Runtime {
198    validator: Validator,
199    catalogs: Vec<Catalog>,
200    evaluator: Evaluator,
201    surfaces: BTreeMap<String, SurfaceState>,
202}
203
204impl Runtime {
205    /// A runtime for a renderer that supports `catalogs`.
206    pub fn new(catalogs: impl IntoIterator<Item = Catalog>) -> Result<Self, CompileError> {
207        let catalogs: Vec<Catalog> = catalogs.into_iter().collect();
208        Ok(Self {
209            validator: Validator::new(catalogs.clone())?,
210            evaluator: Evaluator::new(catalogs.clone()),
211            catalogs,
212            surfaces: BTreeMap::new(),
213        })
214    }
215
216    /// A runtime for the basic catalog alone.
217    pub fn basic() -> Self {
218        Self::new([Catalog::basic().clone()]).expect("the basic catalog compiles")
219    }
220
221    /// The completeness rules batches are applied under from now on (see
222    /// [`crate::Rules`]; strict by default).
223    pub fn set_rules(&mut self, rules: crate::Rules) {
224        self.validator.set_rules(rules);
225    }
226
227    /// Implement a function on the renderer (see [`Evaluator::register`]).
228    pub fn register(&mut self, name: impl Into<String>, def: FunctionDef, function: LocalFunction) {
229        self.evaluator.register(name, def, function);
230    }
231
232    /// The surfaces, by id.
233    pub fn surface_ids(&self) -> impl Iterator<Item = &str> {
234        self.surfaces.keys().map(String::as_str)
235    }
236
237    /// A surface's data model.
238    pub fn data_model(&self, surface_id: &str) -> Option<&Value> {
239        self.surfaces
240            .get(surface_id)
241            .map(|surface| surface.data.root())
242    }
243
244    /// A surface's components as the agent sent them (the latest of each id).
245    pub fn components(&self, surface_id: &str) -> Option<impl Iterator<Item = &Value>> {
246        self.surfaces
247            .get(surface_id)
248            .map(|surface| surface.components.values())
249    }
250
251    /// A surface's `metadata` from `createSurface` (its `extensions`).
252    pub fn surface_metadata(&self, surface_id: &str) -> Option<&Value> {
253        self.surfaces
254            .get(surface_id)
255            .and_then(|surface| surface.metadata.as_ref())
256    }
257
258    /// Whether the surface asked for its data model with every message.
259    pub fn sends_data_model(&self, surface_id: &str) -> bool {
260        self.surfaces
261            .get(surface_id)
262            .is_some_and(|surface| surface.send_data_model)
263    }
264
265    /// Each surface as the one `createSurface` message that draws it as it is
266    /// now: its catalog, `sendDataModel` when set, its components (the latest of
267    /// each id, by id), and its data model. A renderer that reopens, or joins
268    /// late, can be brought up to date with these alone, in surface id order.
269    pub fn snapshot(&self) -> Vec<Value> {
270        self.surfaces
271            .iter()
272            .map(|(id, surface)| {
273                let mut body = Map::new();
274                body.insert("surfaceId".into(), Value::from(id.as_str()));
275                if let Some(catalog) = &surface.catalog_id {
276                    body.insert("catalogId".into(), Value::from(catalog.as_str()));
277                }
278                if surface.send_data_model {
279                    body.insert("sendDataModel".into(), Value::Bool(true));
280                }
281                if let Some(metadata) = &surface.metadata {
282                    body.insert("metadata".into(), metadata.clone());
283                }
284                body.insert(
285                    "components".into(),
286                    surface.components.values().cloned().collect(),
287                );
288                body.insert("dataModel".into(), surface.data.root().clone());
289                serde_json::json!({"version": crate::PROTOCOL_VERSION, "createSurface": body})
290            })
291            .collect()
292    }
293
294    /// The renderer's capabilities (`renderer_capabilities.json`): the ids of
295    /// its catalogs and, with `inline`, the catalog documents themselves.
296    pub fn capabilities(&self, inline: bool) -> Value {
297        let mut caps = Map::new();
298        caps.insert(
299            "supportedCatalogIds".into(),
300            self.catalogs.iter().map(|c| Value::from(c.id())).collect(),
301        );
302        if inline {
303            caps.insert(
304                "inlineCatalogs".into(),
305                self.catalogs.iter().map(|c| c.document().clone()).collect(),
306            );
307        }
308        serde_json::json!({ crate::PROTOCOL_VERSION: caps })
309    }
310
311    /// The renderer data model to send with a message (`renderer_data_model.json`):
312    /// the surfaces that set `sendDataModel`, or `None` if none did.
313    pub fn renderer_data_model(&self) -> Option<Value> {
314        let surfaces: Map<String, Value> = self
315            .surfaces
316            .iter()
317            .filter(|(_, surface)| surface.send_data_model)
318            .map(|(id, surface)| (id.clone(), surface.data.root().clone()))
319            .collect();
320        (!surfaces.is_empty())
321            .then(|| serde_json::json!({"version": crate::PROTOCOL_VERSION, "surfaces": surfaces}))
322    }
323
324    /// Validate and apply a batch, all or nothing. See the module docs.
325    pub fn apply(&mut self, messages: &[Value]) -> Report {
326        // The batch as checked: legacy envelope keys moved to their `@`
327        // spellings, so what is stored is what was validated.
328        let (mut report, messages) = self.validator.check_normalized(messages);
329        if !report.is_ok() {
330            return report;
331        }
332        let messages = &messages[..];
333        let mut surfaces = self.surfaces.clone();
334        let mut touched = BTreeSet::new();
335        for (index, message) in messages.iter().enumerate() {
336            if let Err(problem) = apply_one(&mut surfaces, message, index, &mut touched) {
337                report.errors.push(problem);
338            }
339        }
340        for id in &touched {
341            if let Some(surface) = surfaces.get(id) {
342                for (path, error) in self.evaluate_all(surface) {
343                    report
344                        .errors
345                        .push(problem(Code::ExpressionError, Some(id), path, error));
346                }
347            }
348        }
349        if report.is_ok() {
350            // Record the batch in the validator too, so later batches are
351            // checked against these surfaces.
352            let recorded = self.validator.apply(messages);
353            debug_assert!(recorded.is_ok());
354            self.surfaces = surfaces;
355        } else {
356            report.messages.clear();
357        }
358        report
359    }
360
361    /// Every evaluation error a surface's tree has, as (path, message).
362    fn evaluate_all(&self, surface: &SurfaceState) -> Vec<(String, String)> {
363        let mut errors = Vec::new();
364        if surface.components.contains_key("root") {
365            let tree = self.resolve(surface, "root", "/", None, 0, &mut Vec::new());
366            for node in tree.walk() {
367                for error in &node.errors {
368                    errors.push((String::new(), format!("{}: {error}", node.id)));
369                }
370            }
371        }
372        errors
373    }
374
375    /// Resolve a surface for drawing, from its `root` (`None` when the
376    /// surface does not exist or has no root yet).
377    pub fn tree(&self, surface_id: &str) -> Option<Node> {
378        let surface = self.surfaces.get(surface_id)?;
379        surface
380            .components
381            .contains_key("root")
382            .then(|| self.resolve(surface, "root", "/", None, 0, &mut Vec::new()))
383    }
384
385    /// Resolve one component at the root data context, whether or not it is
386    /// reachable from `root`.
387    pub fn node(&self, surface_id: &str, component_id: &str) -> Option<Node> {
388        let surface = self.surfaces.get(surface_id)?;
389        surface
390            .components
391            .contains_key(component_id)
392            .then(|| self.resolve(surface, component_id, "/", None, 0, &mut Vec::new()))
393    }
394
395    fn resolve(
396        &self,
397        surface: &SurfaceState,
398        id: &str,
399        data_path: &str,
400        index: Option<usize>,
401        depth: usize,
402        stack: &mut Vec<String>,
403    ) -> Node {
404        let mut node = Node {
405            id: id.to_string(),
406            component: String::new(),
407            data_path: data_path.to_string(),
408            index,
409            properties: Map::new(),
410            accessibility: None,
411            failures: Vec::new(),
412            errors: Vec::new(),
413            children: Vec::new(),
414            placeholder: false,
415        };
416        let Some(component) = surface.components.get(id) else {
417            node.placeholder = true;
418            return node;
419        };
420        if depth > MAX_TREE_DEPTH || stack.iter().any(|seen| seen == id) {
421            node.placeholder = true;
422            node.errors
423                .push("the component tree nests too deeply or forms a cycle here".into());
424            return node;
425        }
426        node.component = component
427            .get("component")
428            .and_then(Value::as_str)
429            .unwrap_or_default()
430            .to_string();
431        let catalog_id = component
432            .get("@catalogId")
433            .and_then(Value::as_str)
434            .or(surface.catalog_id.as_deref());
435        let def = catalog_id
436            .and_then(|id| self.catalogs.iter().find(|catalog| catalog.id() == id))
437            .and_then(|catalog| catalog.component(&node.component))
438            .cloned()
439            .unwrap_or_default();
440
441        let mut scope = Scope::root(&surface.data, surface.catalog_id.as_deref());
442        scope.path = data_path.to_string();
443        scope.index = index;
444
445        let object = component.as_object().cloned().unwrap_or_default();
446        for (key, value) in &object {
447            // An items property (Tabs' `tabs`) holds more than ids (each tab's
448            // title), so it stays among the properties as well.
449            let only_ids = matches!(
450                def.children.get(key),
451                Some(ChildRef::Single | ChildRef::List)
452            );
453            if matches!(
454                key.as_str(),
455                "id" | "component" | "@catalogId" | "@metadata" | "@checks"
456            ) || only_ids
457                || def.actions.contains(key)
458            {
459                continue;
460            }
461            if key == "@accessibility" {
462                let resolved = self.deep(value, &scope, &mut node.errors, key);
463                node.accessibility = resolved.as_object().cloned();
464                continue;
465            }
466            let resolved = self.deep(value, &scope, &mut node.errors, key);
467            node.properties.insert(key.clone(), resolved);
468        }
469        // Checks: in order, failures only.
470        if let Some(checks) = object.get("@checks").and_then(Value::as_array) {
471            for rule in checks {
472                if let Some(failure) = self.check(rule, &scope) {
473                    node.failures.push(failure);
474                }
475            }
476        }
477        // Children.
478        stack.push(id.to_string());
479        for (property, kind) in &def.children {
480            let Some(value) = object.get(property) else {
481                continue;
482            };
483            let mut nodes = Vec::new();
484            match (kind, value) {
485                (ChildRef::Single, Value::String(child)) => {
486                    nodes.push(self.resolve(surface, child, data_path, index, depth + 1, stack));
487                }
488                (ChildRef::List, Value::Array(ids)) => {
489                    for child in ids.iter().filter_map(Value::as_str) {
490                        nodes.push(self.resolve(
491                            surface,
492                            child,
493                            data_path,
494                            index,
495                            depth + 1,
496                            stack,
497                        ));
498                    }
499                }
500                (ChildRef::List, Value::Object(template)) => {
501                    let template_id = template
502                        .get("componentId")
503                        .and_then(Value::as_str)
504                        .unwrap_or_default();
505                    let list_path = data::resolve(
506                        data_path,
507                        template.get("path").and_then(Value::as_str).unwrap_or(""),
508                    );
509                    match surface.data.get(&list_path) {
510                        Ok(Some(Value::Array(items))) => {
511                            let base = list_path.trim_end_matches('/');
512                            for i in 0..items.len() {
513                                let item_path = format!("{base}/{i}");
514                                nodes.push(self.resolve(
515                                    surface,
516                                    template_id,
517                                    &item_path,
518                                    Some(i),
519                                    depth + 1,
520                                    stack,
521                                ));
522                            }
523                        }
524                        Ok(_) => {}
525                        Err(error) => node.errors.push(format!("{property}: {error}")),
526                    }
527                }
528                (ChildRef::Items(field), Value::Array(items)) => {
529                    for child in items
530                        .iter()
531                        .filter_map(|item| item.get(field).and_then(Value::as_str))
532                    {
533                        nodes.push(self.resolve(
534                            surface,
535                            child,
536                            data_path,
537                            index,
538                            depth + 1,
539                            stack,
540                        ));
541                    }
542                }
543                _ => {}
544            }
545            node.children.push((property.clone(), nodes));
546        }
547        stack.pop();
548        node
549    }
550
551    /// Resolve every binding and call inside a property value, deeply; a
552    /// failure becomes `null` and a recorded error.
553    fn deep(&self, value: &Value, scope: &Scope<'_>, errors: &mut Vec<String>, at: &str) -> Value {
554        let dynamic = value.as_object().is_some_and(|map| {
555            map.contains_key("@path") || map.get("@call").is_some_and(Value::is_string)
556        });
557        if dynamic {
558            return match self.evaluator.evaluate(value, scope) {
559                Ok(resolved) => {
560                    // Effects from a binding (a write, an open) never happen.
561                    scope.take_effects();
562                    resolved
563                }
564                Err(error) => {
565                    errors.push(format!("{at}: {error}"));
566                    Value::Null
567                }
568            };
569        }
570        match value {
571            Value::Array(items) => Value::Array(
572                items
573                    .iter()
574                    .enumerate()
575                    .map(|(i, item)| self.deep(item, scope, errors, &format!("{at}/{i}")))
576                    .collect(),
577            ),
578            Value::Object(map) => {
579                let mut out = Map::new();
580                for (key, inner) in map {
581                    let key_out = key
582                        .strip_prefix("@@")
583                        .map_or_else(|| key.clone(), |rest| format!("@{rest}"));
584                    out.insert(
585                        key_out,
586                        self.deep(inner, scope, errors, &format!("{at}/{key}")),
587                    );
588                }
589                Value::Object(out)
590            }
591            other => other.clone(),
592        }
593    }
594
595    /// Evaluate one check rule, returning its failure (normalized) or `None`
596    /// when it passes. A boolean or a validation result from a function takes
597    /// the rule's `message` when it has one; a validation result read from the
598    /// data model keeps its own message (the specification's coercion rules
599    /// and the shared suites' comparison rules).
600    fn check(&self, rule: &Value, scope: &Scope<'_>) -> Option<Value> {
601        let condition = rule.get("condition")?;
602        let rule_message = rule.get("message").and_then(Value::as_str);
603        let from_data = condition.get("@path").is_some();
604        let outcome = self.evaluator.evaluate(condition, scope);
605        scope.take_effects();
606        let mut failure = match outcome {
607            Ok(value) => match validity(&value) {
608                Some(true) => return None,
609                Some(false) => {
610                    let mut failure = value.as_object().cloned().unwrap_or_default();
611                    let own = failure
612                        .get("message")
613                        .and_then(Value::as_str)
614                        .map(String::from);
615                    let message = if from_data {
616                        own.or(rule_message.map(String::from))
617                    } else {
618                        rule_message.map(String::from).or(own)
619                    };
620                    if let Some(message) = message {
621                        failure.insert("message".into(), Value::String(message));
622                    }
623                    failure
624                }
625                None => {
626                    if coerce_bool(&value) {
627                        return None;
628                    }
629                    let mut failure = Map::new();
630                    failure.insert("valid".into(), Value::Bool(false));
631                    if let Some(message) = rule_message {
632                        failure.insert("message".into(), Value::String(message.into()));
633                    }
634                    failure
635                }
636            },
637            Err(error) => {
638                let mut failure = Map::new();
639                failure.insert("valid".into(), Value::Bool(false));
640                failure.insert(
641                    "message".into(),
642                    Value::String(rule_message.map_or_else(|| error.to_string(), String::from)),
643                );
644                failure
645            }
646        };
647        failure
648            .entry("severity")
649            .or_insert_with(|| Value::String("error".into()));
650        Some(Value::Object(failure))
651    }
652
653    /// Write what the user entered at an absolute data model path (two-way
654    /// binding): the input component's bound path, resolved against its
655    /// node's data context.
656    pub fn input(
657        &mut self,
658        surface_id: &str,
659        path: &str,
660        value: Value,
661    ) -> Result<(), data::DataError> {
662        let Some(surface) = self.surfaces.get_mut(surface_id) else {
663            return Ok(());
664        };
665        surface.data.set(path, value).map(|_| ())
666    }
667
668    /// Run an action (a component's `action` property, as sent) for a
669    /// gesture: an event becomes the `action` message to send, with its context
670    /// resolved; a function call runs locally, its data writes applied and its
671    /// other effects returned.
672    pub fn dispatch(&mut self, action: &Value, gesture: &Gesture) -> Result<Dispatch, ActionError> {
673        let fail = |code: &str, message: String| ActionError {
674            code: code.into(),
675            message,
676            surface_id: gesture.surface_id.clone(),
677        };
678        let Some(surface) = self.surfaces.get(&gesture.surface_id) else {
679            return Err(fail(
680                "INVALID_ACTION",
681                format!("surface {:?} does not exist", gesture.surface_id),
682            ));
683        };
684        let mut scope = Scope::root(&surface.data, surface.catalog_id.as_deref());
685        scope.path = gesture.data_path.clone();
686        scope.index = gesture.index;
687        scope.activation = gesture.activation;
688
689        if let Some(call) = action.get("functionCall").and_then(Value::as_object) {
690            let outcome = self.evaluator.call(call, &scope);
691            let effects = scope.take_effects();
692            match outcome {
693                Ok(_) => {}
694                Err(EvalError::Execution(message)) => return Err(fail("EXECUTION_ERROR", message)),
695                Err(error) => return Err(fail("EXPRESSION_ERROR", error.to_string())),
696            }
697            let (writes, effects): (Vec<Effect>, Vec<Effect>) = effects
698                .into_iter()
699                .partition(|effect| matches!(effect, Effect::SetData { .. }));
700            drop(scope);
701            if let Some(surface) = self.surfaces.get_mut(&gesture.surface_id) {
702                for write in writes {
703                    if let Effect::SetData { path, value } = write {
704                        surface
705                            .data
706                            .set(&path, value)
707                            .map_err(|e| fail("EXECUTION_ERROR", e.message))?;
708                    }
709                }
710            }
711            return Ok(Dispatch {
712                action: None,
713                effects,
714            });
715        }
716
717        let Some(event) = action.get("event").and_then(Value::as_object) else {
718            return Err(fail(
719                "INVALID_ACTION",
720                "an action holds an event or a functionCall".into(),
721            ));
722        };
723        let Some(name) = event.get("name").and_then(Value::as_str) else {
724            return Err(fail(
725                "INVALID_ACTION",
726                "an event needs a string name".into(),
727            ));
728        };
729        let mut context = Map::new();
730        if let Some(entries) = event.get("context").and_then(Value::as_object) {
731            for (key, value) in entries {
732                let resolved = self
733                    .evaluator
734                    .evaluate(value, &scope)
735                    .map_err(|error| fail("EXPRESSION_ERROR", format!("context {key}: {error}")))?;
736                context.insert(key.clone(), resolved);
737            }
738        }
739        let user_message = match event.get("userMessage") {
740            None => None,
741            Some(value @ (Value::String(_) | Value::Object(_))) => {
742                match self.evaluator.evaluate(value, &scope) {
743                    Ok(Value::String(text)) => Some(text),
744                    Ok(Value::Null) => None,
745                    Ok(other) => Some(super::format::to_string(&other)),
746                    Err(error) => {
747                        return Err(fail("EXPRESSION_ERROR", format!("userMessage: {error}")))
748                    }
749                }
750            }
751            Some(_) => {
752                return Err(fail(
753                    "INVALID_ACTION",
754                    "userMessage must be a string or a binding".into(),
755                ))
756            }
757        };
758        scope.take_effects();
759        if let Some(metadata) = &gesture.metadata {
760            let keys = metadata
761                .get("extensions")
762                .and_then(Value::as_object)
763                .into_iter()
764                .flatten();
765            for (key, _) in keys {
766                if !crate::ident::is_identifier(key) {
767                    return Err(fail(
768                        "VALIDATION_FAILED",
769                        format!("metadata extension key {key:?} is not an identifier"),
770                    ));
771                }
772            }
773        }
774        let timestamp = gesture
775            .timestamp
776            .clone()
777            .unwrap_or_else(|| jiff::Timestamp::now().to_string());
778        let mut action = Action::new(
779            name,
780            &gesture.surface_id,
781            &gesture.source_component_id,
782            timestamp,
783            context,
784        );
785        action.user_message = user_message;
786        action.metadata = gesture.metadata.clone();
787        Ok(Dispatch {
788            action: Some(action),
789            effects: Vec::new(),
790        })
791    }
792}
793
794/// Apply one validated message to the surfaces.
795fn apply_one(
796    surfaces: &mut BTreeMap<String, SurfaceState>,
797    message: &Value,
798    index: usize,
799    touched: &mut BTreeSet<String>,
800) -> Result<(), Problem> {
801    let data_error = |id: &str, kind: &str, error: data::DataError| {
802        problem(
803            Code::DataError,
804            Some(id),
805            format!("/{index}/{kind}/path"),
806            error.message,
807        )
808    };
809    if let Some(body) = message.get("createSurface") {
810        let id = body["surfaceId"].as_str().unwrap_or_default().to_string();
811        let mut state = SurfaceState {
812            catalog_id: body
813                .get("catalogId")
814                .and_then(Value::as_str)
815                .map(String::from),
816            send_data_model: body
817                .get("sendDataModel")
818                .and_then(Value::as_bool)
819                .unwrap_or(false),
820            metadata: body.get("metadata").cloned(),
821            components: BTreeMap::new(),
822            data: DataModel::new(
823                body.get("dataModel")
824                    .cloned()
825                    .unwrap_or_else(|| Value::Object(Map::new())),
826            ),
827        };
828        store(&mut state, body);
829        surfaces.insert(id.clone(), state);
830        touched.insert(id);
831    } else if let Some(body) = message.get("updateComponents") {
832        let id = body["surfaceId"].as_str().unwrap_or_default();
833        if let Some(state) = surfaces.get_mut(id) {
834            store(state, body);
835            touched.insert(id.to_string());
836        }
837    } else if let Some(body) = message.get("updateDataModel") {
838        let id = body["surfaceId"].as_str().unwrap_or_default();
839        if let Some(state) = surfaces.get_mut(id) {
840            let path = body.get("path").and_then(Value::as_str).unwrap_or("/");
841            let value = body.get("value").cloned().unwrap_or(Value::Null);
842            let outcome = if value.is_null() {
843                state.data.delete(path)
844            } else {
845                state.data.set(path, value)
846            };
847            outcome.map_err(|error| data_error(id, "updateDataModel", error))?;
848            touched.insert(id.to_string());
849        }
850    } else if let Some(body) = message.get("deleteSurface") {
851        let id = body["surfaceId"].as_str().unwrap_or_default();
852        surfaces.remove(id);
853        touched.remove(id);
854    }
855    Ok(())
856}
857
858fn store(state: &mut SurfaceState, body: &Value) {
859    for component in body
860        .get("components")
861        .and_then(Value::as_array)
862        .into_iter()
863        .flatten()
864    {
865        if let Some(id) = component.get("id").and_then(Value::as_str) {
866            state.components.insert(id.to_string(), component.clone());
867        }
868    }
869}