Skip to main content

universal_exports/moneypenny/
views.rs

1//! Views Moneypenny shows: A2UI v1.0 payloads validated against AI6's strict catalog
2//! (`dev.coqui.ai6/views/1.0`) and rendered natively in Outer Office.
3//!
4//! She builds a view with the `show` tool (`{"messages": [...]}`) and may inspect the catalog
5//! on demand via `ui_catalog`. The gateway validates every message with Draft 2020-12 JSON
6//! Schema (in-memory retrieval only; external URIs are refused), A2UI v1.0 graph/parent/child
7//! and identifier rules, `ViewLimits`, SVG allow-listing ([`svg::sanitize`]), app-only routes
8//! ([`Route::parse_uri`]), `propose_*` tool checks and `guatiao_intake` form checks. Nothing in
9//! a view runs scripts or fetches from outside the app; all catalog functions are pure and
10//! `rendererOnly`.
11
12use std::borrow::Cow;
13use std::collections::{HashMap, HashSet};
14use std::error::Error;
15use std::sync::LazyLock;
16
17use coqui_acp_api::mcp::{ToolCall, ToolInfo};
18use guatiao::schema::{KindBuilder, SchemaDoc};
19use guatiao::value::types::Value as Held;
20use guatiao::{Alloc, FromValue, Kinds, MapError, Schema};
21use serde::{Deserialize, Serialize};
22use serde_json::Number;
23
24use self::model::{
25    CardKind, Chart, ChartKind, Children, Component, DataModel, Dynamic, Form, Function, Graph,
26    GraphEdge, GraphLayout, KeyValue, Kind, Message, MessageBody, Scalar, ScheduleRow,
27    ScheduleTime,
28};
29pub(crate) use self::model::{DataObject, DataValue};
30use ai6::directorates::section_00::assistant::valid_identity_within;
31
32use super::checks::short_within;
33use super::routes::{self, Field, Page, Route};
34use super::{actions, mcp, svg};
35
36mod live;
37mod model;
38
39pub(crate) use self::live::FEEDS;
40
41/// The A2UI catalog identifier this gateway serves and accepts.
42pub(crate) const CATALOG_ID: &str = "dev.coqui.ai6/views/1.0";
43
44/// The A2UI protocol version this gateway speaks.
45pub(crate) const PROTOCOL_VERSION: &str = "1.0";
46
47/// The MCP read tool returning AI6's A2UI v1.0 catalog document.
48pub(crate) const CATALOG_TOOL: &str = "ui_catalog";
49
50const AGENT_TO_RENDERER_SCHEMA: &str = include_str!("a2ui/agent_to_renderer.json");
51const COMMON_TYPES_SCHEMA: &str = include_str!("a2ui/common_types.json");
52const AI6_CATALOG_JSON: &str = include_str!("a2ui/ai6_views_catalog.json");
53
54#[cfg(test)]
55const CATALOG_DEFINITION_SCHEMA: &str = include_str!("a2ui/catalog_definition.json");
56
57/// The bounds a view is held to; each is at least 1. The app is sent them with a
58/// conversation and checks views against the same values.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(default)]
61pub struct ViewLimits {
62    /// Content blocks in one view (default 24).
63    pub blocks: usize,
64    /// Bytes of one view as JSON (default 64 KiB).
65    pub view_bytes: usize,
66    /// Bytes of a text block's Markdown (default 8 KiB).
67    pub text_bytes: usize,
68    /// Bytes of a title, label, cell or other short text (default 512).
69    pub short_bytes: usize,
70    /// Columns of a table (default 12).
71    pub columns: usize,
72    /// Rows of a table (default 200).
73    pub rows: usize,
74    /// Items of a key-value list or a timeline (default 100).
75    pub items: usize,
76    /// Series of a chart (default 8).
77    pub series: usize,
78    /// Points of one series (default 200).
79    pub points: usize,
80    /// Slices of a pie (default 12).
81    pub pie_slices: usize,
82    /// Bytes of each side of a diff (default 16 KiB).
83    pub diff_bytes: usize,
84    /// Fields of a form or a card (default 20).
85    pub fields: usize,
86    /// Rows of a schedule (default 50).
87    pub schedule_rows: usize,
88    /// Nodes of a graph (default 60).
89    pub graph_nodes: usize,
90    /// Edges of a graph (default 120).
91    pub graph_edges: usize,
92    /// Bytes of an SVG drawing (default 32 KiB).
93    pub svg_bytes: usize,
94    /// Elements of an SVG drawing (default 2,000).
95    pub svg_elements: usize,
96    /// How deep an SVG drawing nests its elements (default 16).
97    pub svg_depth: usize,
98    /// Bytes of the label of a page she offers with `navigate` (default 120).
99    pub navigate_label_bytes: usize,
100    /// Bytes of an `id` in an SVG drawing (default 64).
101    pub svg_id_bytes: usize,
102    /// Components a view defines across its messages (default 256).
103    pub components: usize,
104    /// Messages in one view (default 32).
105    pub messages: usize,
106    /// How deep components nest from the root; the root is at depth 0 (default 16).
107    pub depth: usize,
108    /// Layout components (Column and Row) in one view (default 48).
109    pub layouts: usize,
110    /// Bytes of an identifier: a graph node's, a form's field name, an entity ID (default 256).
111    pub identifier_bytes: usize,
112}
113
114impl Default for ViewLimits {
115    /// The defaults the `assistant` record's `views` table declares.
116    fn default() -> Self {
117        let declared = ai6::AssistantViewLimits::defaults();
118        let bound = |value: Option<u64>| {
119            value
120                .and_then(|value| usize::try_from(value).ok())
121                .unwrap_or(usize::MAX)
122        };
123        Self {
124            blocks: bound(declared.blocks),
125            view_bytes: bound(declared.view_bytes),
126            text_bytes: bound(declared.text_bytes),
127            short_bytes: bound(declared.short_bytes),
128            columns: bound(declared.columns),
129            rows: bound(declared.rows),
130            items: bound(declared.items),
131            series: bound(declared.series),
132            points: bound(declared.points),
133            pie_slices: bound(declared.pie_slices),
134            diff_bytes: bound(declared.diff_bytes),
135            fields: bound(declared.fields),
136            schedule_rows: bound(declared.schedule_rows),
137            graph_nodes: bound(declared.graph_nodes),
138            graph_edges: bound(declared.graph_edges),
139            svg_bytes: bound(declared.svg_bytes),
140            svg_elements: bound(declared.svg_elements),
141            svg_depth: bound(declared.svg_depth),
142            navigate_label_bytes: bound(declared.navigate_label_bytes),
143            svg_id_bytes: bound(declared.svg_id_bytes),
144            components: bound(declared.components),
145            messages: bound(declared.messages),
146            depth: bound(declared.depth),
147            layouts: bound(declared.layouts),
148            identifier_bytes: bound(declared.identifier_bytes),
149        }
150    }
151}
152
153impl ViewLimits {
154    /// These limits with every zero raised to 1.
155    #[must_use]
156    pub(crate) fn at_least_one(mut self) -> Self {
157        for limit in [
158            &mut self.blocks,
159            &mut self.view_bytes,
160            &mut self.text_bytes,
161            &mut self.short_bytes,
162            &mut self.columns,
163            &mut self.rows,
164            &mut self.items,
165            &mut self.series,
166            &mut self.points,
167            &mut self.pie_slices,
168            &mut self.diff_bytes,
169            &mut self.fields,
170            &mut self.schedule_rows,
171            &mut self.graph_nodes,
172            &mut self.graph_edges,
173            &mut self.svg_bytes,
174            &mut self.svg_elements,
175            &mut self.svg_depth,
176            &mut self.navigate_label_bytes,
177            &mut self.svg_id_bytes,
178            &mut self.components,
179            &mut self.messages,
180            &mut self.depth,
181            &mut self.layouts,
182            &mut self.identifier_bytes,
183        ] {
184            *limit = (*limit).max(1);
185        }
186        self
187    }
188
189    fn short(&self, what: &str, text: &str) -> Result<(), String> {
190        short_within(what, text, self.short_bytes)
191    }
192
193    /// An identifier by the rule AI6 records identities by, held to `identifier_bytes`.
194    fn identifier(&self, what: &str, text: &str) -> Result<(), String> {
195        if valid_identity_within(text, self.identifier_bytes) {
196            Ok(())
197        } else {
198            Err(format!("{what} is not an identifier"))
199        }
200    }
201
202    fn scalar(&self, what: &str, value: &Scalar) -> Result<(), String> {
203        match value {
204            Scalar::Null | Scalar::Bool(_) => Ok(()),
205            Scalar::Number(number) if number.as_f64().is_some_and(f64::is_finite) => Ok(()),
206            Scalar::Text(text) => self.short(what, text),
207            Scalar::Number(_) => Err(format!("{what} must be a finite number")),
208        }
209    }
210}
211
212pub(crate) use model::View;
213
214impl View {
215    /// The surface root's title, when it is text known here.
216    pub(crate) fn title(&self) -> Option<String> {
217        let mut data_model = DataModel::new(None);
218        let mut title: Option<&Dynamic<String>> = None;
219        for message in &self.messages {
220            match &message.body {
221                MessageBody::CreateSurface(create) => {
222                    data_model = DataModel::new(create.data_model.as_ref());
223                }
224                MessageBody::UpdateDataModel(update) => {
225                    let _ = data_model.apply(update);
226                }
227                MessageBody::UpdateComponents(_) => {}
228            }
229            for comp in defined_by(message) {
230                if comp.id == "root"
231                    && let Kind::Ai6View(root) = &comp.kind
232                {
233                    title = root.title.as_ref();
234                }
235            }
236        }
237        title?.get(&data_model).ok().flatten().map(Cow::into_owned)
238    }
239}
240
241/// A JSON Schema document the gateway embeds: AI6's catalog, the A2UI message schema, the
242/// common types. It is held as the document it is, named by its `$id`, until guatiao's owned
243/// schema type (`SchemaDoc`, newer than the pinned revision) can carry it.
244#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
245pub(crate) struct SchemaDocument {
246    #[serde(rename = "$id")]
247    id: String,
248    #[serde(flatten)]
249    members: DataObject,
250}
251
252impl SchemaDocument {
253    fn read(name: &str, text: &str) -> Result<Self, String> {
254        serde_json::from_str(text).map_err(|err| format!("{name}: {err}"))
255    }
256}
257
258/// AI6's catalog (`dev.coqui.ai6/views/1.0`): the components and pure functions it allows.
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260#[serde(transparent)]
261pub(crate) struct Catalog(SchemaDocument);
262
263impl Catalog {
264    /// The names of the components the catalog declares.
265    fn component_names(&self) -> Vec<&str> {
266        self.0
267            .members
268            .member("components")
269            .and_then(DataValue::object)
270            .map(|components| components.keys().map(String::as_str).collect())
271            .unwrap_or_default()
272    }
273}
274
275/// AI6's catalog document.
276pub(crate) fn catalog() -> &'static Catalog {
277    static CATALOG: LazyLock<Catalog> = LazyLock::new(|| {
278        Catalog(
279            SchemaDocument::read("ai6_views_catalog.json", AI6_CATALOG_JSON)
280                .expect("ai6_views_catalog.json is a schema document"),
281        )
282    });
283    &CATALOG
284}
285
286/// What the `ui_catalog` tool says it reads: the components are those the catalog declares.
287pub(crate) fn catalog_description() -> String {
288    format!(
289        "Read AI6's A2UI v1.0 view catalog document ({CATALOG_ID}): all allowed components \
290         ({}), their strict JSON schemas, and the pure rendererOnly helper functions.",
291        catalog().component_names().join(", ")
292    )
293}
294
295/// MCP `tools/call` output for `ui_catalog`.
296pub(crate) fn catalog_outcome() -> super::tools::Outcome {
297    super::tools::Outcome {
298        text: AI6_CATALOG_JSON.to_owned(),
299        is_error: false,
300    }
301}
302
303// typed-boundary: free-form the JSON document the jsonschema crate's validator and retriever take
304type SchemaJson = serde_json::Value;
305
306/// In-memory Draft 2020-12 URI retriever that serves only the schemas embedded here, each at
307/// the `$id` it declares, refusing every other URI with no network I/O. The A2UI message schema
308/// names the catalog as the `catalog.json` beside itself; AI6's catalog is served there too.
309struct CatalogRetriever {
310    documents: Vec<(String, SchemaDocument)>,
311}
312
313impl CatalogRetriever {
314    fn embedded() -> Result<Self, String> {
315        let message = SchemaDocument::read("agent_to_renderer.json", AGENT_TO_RENDERER_SCHEMA)?;
316        let common = SchemaDocument::read("common_types.json", COMMON_TYPES_SCHEMA)?;
317        let catalog = SchemaDocument::read("ai6_views_catalog.json", AI6_CATALOG_JSON)?;
318        let beside_message = message
319            .id
320            .rsplit_once('/')
321            .map(|(directory, _)| format!("{directory}/catalog.json"))
322            .ok_or_else(|| format!("{} is not a URI with a path", message.id))?;
323        Ok(Self {
324            documents: vec![
325                (common.id.clone(), common),
326                (catalog.id.clone(), catalog.clone()),
327                (beside_message, catalog),
328            ],
329        })
330    }
331}
332
333impl jsonschema::Retrieve for CatalogRetriever {
334    fn retrieve(
335        &self,
336        uri: &jsonschema::Uri<String>,
337    ) -> Result<SchemaJson, Box<dyn Error + Send + Sync>> {
338        let (_, document) = self
339            .documents
340            .iter()
341            .find(|(id, _)| id == uri.as_str())
342            .ok_or_else(|| format!("external URI retrieval is refused: {uri}"))?;
343        Ok(serde_json::to_value(document)?)
344    }
345}
346
347static MESSAGE_VALIDATOR: LazyLock<Result<jsonschema::Validator, String>> = LazyLock::new(|| {
348    let schema = SchemaDocument::read("agent_to_renderer.json", AGENT_TO_RENDERER_SCHEMA)?;
349    let retriever = CatalogRetriever::embedded()?;
350    let schema =
351        serde_json::to_value(&schema).map_err(|err| format!("agent_to_renderer.json: {err}"))?;
352    jsonschema::draft202012::options()
353        .with_retriever(retriever)
354        .build(&schema)
355        .map_err(|err| format!("compiling A2UI message schema: {err}"))
356});
357
358static UAX31_ID: LazyLock<regex::Regex> = LazyLock::new(|| {
359    regex::Regex::new(r"^[\p{XID_Start}_]\p{XID_Continue}*$").expect("valid UAX #31 regex")
360});
361
362fn is_uax31_identifier(text: &str) -> bool {
363    !text.is_empty() && UAX31_ID.is_match(text)
364}
365
366fn has_bidi_control(text: &str) -> bool {
367    text.chars()
368        .any(|c| ('\u{202A}'..='\u{202E}').contains(&c) || ('\u{2066}'..='\u{2069}').contains(&c))
369}
370
371/// How deep JSON may nest inside a message: the renderer's core refuses a message nested deeper.
372const JSON_NESTING: usize = 50;
373
374/// Reads every object, key and string of `message` once, without recursion: JSON no deeper than
375/// the renderer reads, no hidden bidirectional control character, no catalog but AI6's, and
376/// every data path of a syntax the renderer reads.
377fn scan(what: &str, message: &DataValue) -> Result<(), String> {
378    let mut pending = vec![(message, 0_usize)];
379    while let Some((value, depth)) = pending.pop() {
380        if depth > JSON_NESTING {
381            return Err(format!("{what} nests JSON more than {JSON_NESTING} deep"));
382        }
383        match value {
384            DataValue::Text(text) => {
385                if has_bidi_control(text) {
386                    return Err(format!(
387                        "{what} contains forbidden bidirectional control characters"
388                    ));
389                }
390            }
391            DataValue::List(items) => {
392                pending.extend(items.iter().map(|item| (item, depth + 1)));
393            }
394            DataValue::Object(map) => {
395                if let Some(DataValue::Text(path)) = map.member("@path") {
396                    DataModel::check_pointer(path)?;
397                }
398                if matches!(map.member("componentId"), Some(DataValue::Text(_)))
399                    && let Some(DataValue::Text(path)) = map.member("path")
400                {
401                    DataModel::check_pointer(path)?;
402                }
403                for (key, value) in map.iter() {
404                    if has_bidi_control(key) {
405                        return Err(format!(
406                            "{what} key contains forbidden bidirectional control characters"
407                        ));
408                    }
409                    if matches!(key.as_str(), "catalogId" | "@catalogId")
410                        && let Some(catalog) = value.text()
411                        && catalog != CATALOG_ID
412                    {
413                        return Err(format!("{key} must be {CATALOG_ID:?}, not {catalog:?}"));
414                    }
415                    pending.push((value, depth + 1));
416                }
417            }
418            _ => {}
419        }
420    }
421    Ok(())
422}
423
424/// Where a component is defined: the message, and its place in that message's list.
425#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426struct Loc {
427    message: usize,
428    index: usize,
429}
430
431/// The components a message defines.
432fn defined_by(message: &Message) -> &[Component] {
433    match &message.body {
434        MessageBody::CreateSurface(create) => create.components.as_deref().unwrap_or_default(),
435        MessageBody::UpdateComponents(update) => &update.components,
436        MessageBody::UpdateDataModel(_) => &[],
437    }
438}
439
440fn component_mut(messages: &mut [Message], at: Loc) -> &mut Component {
441    let list: &mut [Component] = match &mut messages[at.message].body {
442        MessageBody::CreateSurface(create) => create.components.as_deref_mut().unwrap_or_default(),
443        MessageBody::UpdateComponents(update) => &mut update.components,
444        MessageBody::UpdateDataModel(_) => &mut [],
445    };
446    &mut list[at.index]
447}
448
449/// How many components `message` defines, read from the JSON before it is typed.
450fn components_defined(message: &DataValue) -> usize {
451    ["createSurface", "updateComponents"]
452        .iter()
453        .filter_map(|key| {
454            message
455                .object()?
456                .member(key)?
457                .object()?
458                .member("components")?
459                .list()
460        })
461        .map(<[DataValue]>::len)
462        .sum()
463}
464
465/// Arguments for `show`, and a live report's surface. The messages follow the A2UI protocol and
466/// are decoded into `Message`s after size checks and catalog validation.
467#[derive(FromValue, Schema, Serialize)]
468#[map(deny_unknown_fields)]
469pub(crate) struct ShowArgs {
470    messages: Vec<IncomingMessage>,
471}
472
473/// An A2UI message before validation against the versioned catalog.
474#[derive(Serialize)]
475#[serde(transparent)]
476struct IncomingMessage(DataValue);
477
478impl FromValue for IncomingMessage {
479    const KINDS: Kinds = Kinds::ANY;
480
481    fn from_value(value: &Held) -> Result<Self, MapError> {
482        DataValue::of(&guatiao_serde::Serializable::new(
483            value,
484            guatiao_serde::Presentation::default(),
485        ))
486        .map(Self)
487        .map_err(|why| MapError::bad_value(why.to_string()))
488    }
489}
490
491impl Schema for IncomingMessage {
492    fn kind(alloc: Alloc) -> KindBuilder {
493        KindBuilder::map_in(alloc, Vec::new())
494    }
495}
496
497pub(super) fn from_call(
498    call: &ToolCall,
499    limits: &ViewLimits,
500    route: routes::Limits,
501) -> Result<View, String> {
502    from_surface(&mcp::arguments::<ShowArgs>(call)?, limits, route)
503}
504
505/// The view `input` holds, checked against the catalog and `limits`.
506pub(super) fn from_surface(
507    input: &ShowArgs,
508    limits: &ViewLimits,
509    route: routes::Limits,
510) -> Result<View, String> {
511    let size = serde_json::to_vec(input).map_or(usize::MAX, |bytes| bytes.len());
512    parse(
513        input.messages.iter().map(|message| &message.0),
514        size,
515        limits,
516        route,
517    )
518}
519
520/// The view `input` holds as the surface of a live report reading `feeds`: a view as `show`
521/// takes, whose bindings read only those feeds and all of them.
522pub(super) fn from_live_surface(
523    input: &ShowArgs,
524    feeds: &[&str],
525    limits: &ViewLimits,
526    route: routes::Limits,
527) -> Result<View, String> {
528    let view = from_surface(input, limits, route)?;
529    live::check(&view, feeds)?;
530    Ok(view)
531}
532
533/// Validates the messages against the catalog and normalizes their final component definitions.
534fn parse<'a>(
535    raw_messages: impl ExactSizeIterator<Item = &'a DataValue> + Clone,
536    size: usize,
537    limits: &ViewLimits,
538    route: routes::Limits,
539) -> Result<View, String> {
540    let limits = limits.at_least_one();
541    if size > limits.view_bytes {
542        return Err(format!("a view is at most {} bytes", limits.view_bytes));
543    }
544    if raw_messages.len() == 0 {
545        return Err("messages must contain at least one A2UI message".to_owned());
546    }
547    if raw_messages.len() > limits.messages {
548        return Err(format!("a view has at most {} messages", limits.messages));
549    }
550    let defined: usize = raw_messages.clone().map(components_defined).sum();
551    if defined > limits.components {
552        return Err(format!(
553            "a view defines at most {} components",
554            limits.components
555        ));
556    }
557
558    let validator = MESSAGE_VALIDATOR
559        .as_ref()
560        .map_err(|err| format!("internal validator error: {err}"))?;
561
562    let mut messages: Vec<Message> = Vec::with_capacity(raw_messages.len());
563    let mut surface_id: Option<&str> = None;
564    let mut data_model = DataModel::new(None);
565
566    for (index, msg) in raw_messages.enumerate() {
567        let obj = msg
568            .object()
569            .ok_or_else(|| format!("message {index}: must be an object"))?;
570        match obj.member("version").and_then(DataValue::text) {
571            Some(PROTOCOL_VERSION) => {}
572            Some(other) => {
573                return Err(format!(
574                    "message {index}: version must be {PROTOCOL_VERSION:?} (A2UI v1.0), not {other:?}"
575                ));
576            }
577            None => {
578                return Err(format!(
579                    "message {index}: missing required A2UI version {PROTOCOL_VERSION:?}"
580                ));
581            }
582        }
583        if let Some(cs) = obj.member("createSurface").and_then(DataValue::object)
584            && cs.contains("theme")
585        {
586            return Err(format!(
587                "message {index}: createSurface.theme is a v0.9 field and not allowed in A2UI v1.0"
588            ));
589        }
590        if obj.contains("callRendererFunction")
591            || obj.contains("deleteSurface")
592            || obj.contains("agentFunctionResponse")
593        {
594            return Err(format!(
595                "message {index}: show accepts createSurface, updateComponents and updateDataModel only"
596            ));
597        }
598        let json = serde_json::to_value(msg).map_err(|err| format!("message {index}: {err}"))?;
599        if let Some(error) = validator.iter_errors(&json).next() {
600            let path = error.instance_path().to_string();
601            return Err(if path.is_empty() {
602                format!("message {index}: does not match A2UI schema: {error}")
603            } else {
604                format!("message {index} at {path}: does not match A2UI schema: {error}")
605            });
606        }
607        scan(&format!("message {index}"), msg)?;
608        let message = Message::deserialize(msg).map_err(|err| format!("message {index}: {err}"))?;
609
610        match &message.body {
611            MessageBody::CreateSurface(create) => {
612                if surface_id.is_some() {
613                    return Err(format!(
614                        "message {index}: only one createSurface message is allowed per view"
615                    ));
616                }
617                if create.surface_id.is_empty() {
618                    return Err(format!("message {index}: surfaceId must not be empty"));
619                }
620                if create.catalog_id != CATALOG_ID {
621                    return Err(format!(
622                        "message {index}: catalogId must be {CATALOG_ID:?}, not {:?}",
623                        create.catalog_id
624                    ));
625                }
626                surface_id = obj
627                    .member("createSurface")
628                    .and_then(DataValue::object)
629                    .and_then(|create| create.member("surfaceId"))
630                    .and_then(DataValue::text);
631                data_model = DataModel::new(create.data_model.as_ref());
632            }
633            MessageBody::UpdateComponents(update) => {
634                same_surface(index, surface_id, &update.surface_id)?;
635            }
636            MessageBody::UpdateDataModel(update) => {
637                same_surface(index, surface_id, &update.surface_id)?;
638                data_model
639                    .apply(update)
640                    .map_err(|reason| format!("message {index}: {reason}"))?;
641            }
642        }
643        messages.push(message);
644    }
645
646    if surface_id.is_none() {
647        return Err("messages must start with createSurface".to_owned());
648    }
649
650    // The final definition of each component, by id. Ids are UAX #31 identifiers and appear
651    // once in a message.
652    let mut finals: HashMap<&str, Loc> = HashMap::new();
653    let mut first_seen: Vec<&str> = Vec::new();
654    for (message, parsed) in messages.iter().enumerate() {
655        let mut in_message = HashSet::new();
656        for (index, comp) in defined_by(parsed).iter().enumerate() {
657            let id = comp.id.as_str();
658            if !is_uax31_identifier(id) {
659                return Err(format!(
660                    "component id {id:?} must be a valid UAX #31 identifier"
661                ));
662            }
663            if !in_message.insert(id) {
664                return Err(format!(
665                    "duplicate component id {id:?} in message {message}"
666                ));
667            }
668            if finals.insert(id, Loc { message, index }).is_none() {
669                first_seen.push(id);
670            }
671        }
672    }
673
674    if !finals.contains_key("root") {
675        return Err("a view must define a \"root\" component".to_owned());
676    }
677    let comps: HashMap<&str, &Component> = finals
678        .iter()
679        .map(|(&id, &at)| (id, &defined_by(&messages[at.message])[at.index]))
680        .collect();
681    let root = comps["root"];
682    if !matches!(root.kind, Kind::Ai6View(_)) {
683        return Err(format!(
684            "root component must be \"Ai6View\", not {:?}",
685            root.kind.name()
686        ));
687    }
688
689    let Walk {
690        order: reachable_ids,
691        content_blocks,
692        layouts,
693        forms,
694    } = walk_graph("root", &comps, &data_model, limits.depth)?;
695
696    // What is not reachable from the root is never shown, so it is never checked either.
697    let reachable: HashSet<&str> = reachable_ids.iter().copied().collect();
698    if let Some(orphan) = first_seen.iter().find(|id| !reachable.contains(*id)) {
699        return Err(format!("component {orphan:?} is not reachable from root"));
700    }
701
702    if content_blocks == 0 || content_blocks > limits.blocks {
703        return Err(format!("a view has 1 to {} blocks", limits.blocks));
704    }
705    if forms > 1 {
706        return Err("a view has at most one form".to_owned());
707    }
708    if layouts > limits.layouts {
709        return Err(format!(
710            "a view has at most {} layout components",
711            limits.layouts
712        ));
713    }
714
715    // Each reachable component's own rules and limits, canonicalizing SVG in place.
716    let to_check: Vec<(String, Loc)> = reachable_ids
717        .iter()
718        .map(|id| ((*id).to_owned(), finals[id]))
719        .collect();
720    let finals: HashMap<String, Loc> = finals
721        .into_iter()
722        .map(|(id, at)| (id.to_owned(), at))
723        .collect();
724    drop(comps);
725    for (id, at) in &to_check {
726        validate_component(
727            &mut component_mut(&mut messages, *at).kind,
728            &data_model,
729            &limits,
730            route,
731        )
732        .map_err(|reason| format!("component {id:?}: {reason}"))?;
733    }
734
735    keep_final_definitions(&mut messages, &finals);
736    let view = View { messages };
737
738    // Canonical SVG may differ in size from what she sent.
739    let size = serde_json::to_vec(&view).map_or(usize::MAX, |bytes| bytes.len());
740    if size > limits.view_bytes {
741        return Err(format!("a view is at most {} bytes", limits.view_bytes));
742    }
743    Ok(view)
744}
745
746/// An update names the surface the view created.
747fn same_surface(index: usize, created: Option<&str>, named: &str) -> Result<(), String> {
748    if created == Some(named) {
749        Ok(())
750    } else {
751        Err(format!(
752            "message {index}: surfaceId {named:?} must match a prior createSurface"
753        ))
754    }
755}
756
757/// Drops every definition a later message replaced, and the messages and lists that leaves
758/// empty, so the view holds exactly the components the app shows: those `finals` names.
759fn keep_final_definitions(messages: &mut Vec<Message>, finals: &HashMap<String, Loc>) {
760    for (message, parsed) in messages.iter_mut().enumerate() {
761        let list = match &mut parsed.body {
762            MessageBody::CreateSurface(create) => match create.components.as_mut() {
763                Some(list) => list,
764                None => continue,
765            },
766            MessageBody::UpdateComponents(update) => &mut update.components,
767            MessageBody::UpdateDataModel(_) => continue,
768        };
769        let mut index = 0;
770        list.retain(|comp| {
771            let keep = finals.get(&comp.id) == Some(&Loc { message, index });
772            index += 1;
773            keep
774        });
775        if let MessageBody::CreateSurface(create) = &mut parsed.body
776            && create.components.as_ref().is_some_and(Vec::is_empty)
777        {
778            create.components = None;
779        }
780    }
781    // A components update with no components is not a message.
782    messages.retain(|parsed| match &parsed.body {
783        MessageBody::UpdateComponents(update) => !update.components.is_empty(),
784        _ => true,
785    });
786}
787
788/// What the walk from the root found.
789struct Walk<'a> {
790    /// Every reachable component, in the order the walk first reached it.
791    order: Vec<&'a str>,
792    content_blocks: usize,
793    layouts: usize,
794    forms: usize,
795}
796
797/// One component the walk is inside of, and the children it has yet to visit.
798struct Frame<'a> {
799    id: &'a str,
800    children: Vec<&'a str>,
801    next: usize,
802}
803
804/// Walks the component graph from `root` without recursion, so a long chain cannot overflow the
805/// stack, and refuses a chain deeper than `max_depth` (the root is at depth 0) and a component
806/// two parents share.
807fn walk_graph<'a>(
808    root: &'a str,
809    comps: &HashMap<&'a str, &'a Component>,
810    data_model: &DataModel,
811    max_depth: usize,
812) -> Result<Walk<'a>, String> {
813    let mut walk = Walk {
814        order: Vec::new(),
815        content_blocks: 0,
816        layouts: 0,
817        forms: 0,
818    };
819    let mut visited: HashSet<&str> = HashSet::new();
820    let mut on_path: HashSet<&str> = HashSet::new();
821    let mut frames: Vec<Frame<'a>> = Vec::new();
822    visited.insert(root);
823    on_path.insert(root);
824    frames.push(enter(root, comps, data_model, &mut walk)?);
825    while let Some(frame) = frames.last_mut() {
826        let Some(&child) = frame.children.get(frame.next) else {
827            on_path.remove(frame.id);
828            frames.pop();
829            continue;
830        };
831        frame.next += 1;
832        if on_path.contains(child) {
833            return Err(format!("component graph contains a cycle at {child:?}"));
834        }
835        if !visited.insert(child) {
836            return Err(format!("component {child:?} is used more than once"));
837        }
838        if frames.len() > max_depth {
839            return Err(format!("components nest at most {max_depth} deep"));
840        }
841        on_path.insert(child);
842        let entered = enter(child, comps, data_model, &mut walk)?;
843        frames.push(entered);
844    }
845    Ok(walk)
846}
847
848/// Counts the component `id` and lists the components it names as children.
849fn enter<'a>(
850    id: &'a str,
851    comps: &HashMap<&'a str, &'a Component>,
852    data_model: &DataModel,
853    walk: &mut Walk<'a>,
854) -> Result<Frame<'a>, String> {
855    walk.order.push(id);
856    let comp = comps
857        .get(id)
858        .ok_or_else(|| format!("missing referenced component {id:?}"))?;
859    if !comp.kind.is_container() {
860        walk.content_blocks += 1;
861    }
862    if matches!(comp.kind, Kind::Column(_) | Kind::Row(_)) {
863        walk.layouts += 1;
864    }
865    if matches!(comp.kind, Kind::Ai6Form(_)) {
866        walk.forms += 1;
867    }
868    let mut children = Vec::new();
869    match comp.kind.children() {
870        Some(Children::List(ids)) => {
871            for child in ids {
872                let named: &'a Component = comps.get(child.as_str()).copied().ok_or_else(|| {
873                    format!("component {id:?} references missing child {child:?}")
874                })?;
875                if matches!(named.kind, Kind::Ai6View(_)) {
876                    return Err("Ai6View may only appear as root".to_owned());
877                }
878                children.push(named.id.as_str());
879            }
880        }
881        Some(Children::Template(template)) => {
882            let named: &'a Component = comps
883                .get(template.component_id.as_str())
884                .copied()
885                .ok_or_else(|| {
886                    format!(
887                        "template in {id:?} references missing component {:?}",
888                        template.component_id
889                    )
890                })?;
891            if matches!(named.kind, Kind::Ai6View(_)) {
892                return Err("Ai6View may only appear as root".to_owned());
893            }
894            let count = data_model
895                .lookup(&template.path)?
896                .and_then(DataValue::list)
897                .map_or(0, <[DataValue]>::len);
898            // The template defines one prototype component; count instances for the block limit.
899            if count > 1 {
900                walk.content_blocks += count - 1;
901            }
902            children.push(named.id.as_str());
903        }
904        None => {}
905    }
906    Ok(Frame {
907        id,
908        children,
909        next: 0,
910    })
911}
912
913/// Checks Markdown text, resolving static values or validating `formatString` template literals
914/// so outside links cannot slip in.
915fn check_dynamic_markdown(
916    raw: &Dynamic<String>,
917    data_model: &DataModel,
918    limits: &ViewLimits,
919    route: routes::Limits,
920) -> Result<(), String> {
921    if let Dynamic::Call(call) = raw {
922        if let Function::FormatString { args } = &call.function {
923            return check_dynamic_markdown(&args.value, data_model, limits, route);
924        }
925        return Ok(());
926    }
927    if let Some(markdown) = raw.get(data_model)? {
928        if markdown.trim().is_empty() || markdown.len() > limits.text_bytes {
929            return Err(format!("text is 1 to {} bytes", limits.text_bytes));
930        }
931        return links_stay_in_the_app(&markdown, route);
932    }
933    Ok(())
934}
935
936/// A short text, when it is known here.
937fn check_short(
938    raw: &Dynamic<String>,
939    what: &str,
940    data_model: &DataModel,
941    limits: &ViewLimits,
942) -> Result<(), String> {
943    if let Some(text) = raw.get(data_model)? {
944        limits.short(what, &text)?;
945    }
946    Ok(())
947}
948
949/// A short text that may be absent.
950fn check_optional_short(
951    raw: Option<&Dynamic<String>>,
952    what: &str,
953    data_model: &DataModel,
954    limits: &ViewLimits,
955) -> Result<(), String> {
956    raw.map_or(Ok(()), |raw| check_short(raw, what, data_model, limits))
957}
958
959fn check_pairs_value(
960    raw: &Dynamic<Vec<KeyValue>>,
961    data_model: &DataModel,
962    limits: &ViewLimits,
963    min: usize,
964    max: usize,
965    what: &str,
966) -> Result<(), String> {
967    let Some(items) = raw.get(data_model)? else {
968        return Ok(());
969    };
970    if items.len() < min || items.len() > max {
971        return Err(format!("{what} has {min} to {max} items"));
972    }
973    for item in items.iter() {
974        let key = item
975            .key
976            .get(data_model)?
977            .ok_or_else(|| "a key must be text".to_owned())?;
978        limits.short("a key", &key)?;
979        if let Some(value) = item.value.get(data_model)? {
980            limits.scalar("a value", &value)?;
981        }
982    }
983    Ok(())
984}
985
986fn validate_component(
987    kind: &mut Kind,
988    data_model: &DataModel,
989    limits: &ViewLimits,
990    route: routes::Limits,
991) -> Result<(), String> {
992    match kind {
993        Kind::Ai6View(view) => {
994            check_optional_short(view.title.as_ref(), "title", data_model, limits)
995        }
996        Kind::Column(_) | Kind::Row(_) => Ok(()),
997        Kind::Ai6Text(text) => check_dynamic_markdown(&text.markdown, data_model, limits, route),
998        Kind::Ai6Table(table) => {
999            let col_len = if let Some(columns) = table.columns.get(data_model)? {
1000                if columns.is_empty() || columns.len() > limits.columns {
1001                    return Err(format!("a table has 1 to {} columns", limits.columns));
1002                }
1003                for column in columns.iter() {
1004                    limits.short("a column", column)?;
1005                }
1006                Some(columns.len())
1007            } else {
1008                None
1009            };
1010            if let Some(rows) = table.rows.get(data_model)? {
1011                if rows.len() > limits.rows {
1012                    return Err(format!("a table has at most {} rows", limits.rows));
1013                }
1014                for cells in rows.iter() {
1015                    if let Some(expected) = col_len
1016                        && cells.len() != expected
1017                    {
1018                        return Err("every row has one cell per column".to_owned());
1019                    }
1020                    for cell in cells {
1021                        if let Some(value) = cell.get(data_model)? {
1022                            limits.scalar("a cell", &value)?;
1023                        }
1024                    }
1025                }
1026            }
1027            Ok(())
1028        }
1029        Kind::Ai6KeyValues(list) => check_pairs_value(
1030            &list.items,
1031            data_model,
1032            limits,
1033            1,
1034            limits.items,
1035            "a key-value list",
1036        ),
1037        Kind::Ai6Chart(chart) => {
1038            let stacked = match &chart.stacked {
1039                Some(stacked) => stacked.get(data_model)?.is_some_and(|stacked| *stacked),
1040                None => false,
1041            };
1042            for label in [&chart.title, &chart.x_label, &chart.y_label] {
1043                check_optional_short(label.as_ref(), "a chart label", data_model, limits)?;
1044            }
1045            chart_bounds(chart, stacked, data_model, limits)
1046        }
1047        Kind::Ai6Schedule(schedule) => {
1048            check_optional_short(schedule.title.as_ref(), "title", data_model, limits)?;
1049            schedule_bounds(&schedule.rows, data_model, limits, route)
1050        }
1051        Kind::Ai6Graph(graph) => {
1052            check_optional_short(graph.title.as_ref(), "title", data_model, limits)?;
1053            graph_bounds(graph, data_model, limits, route)
1054        }
1055        Kind::Ai6Svg(drawing) => {
1056            if let Some(title) = drawing.title.get(data_model)? {
1057                limits.short("title", &title)?;
1058                if title.trim().is_empty() {
1059                    return Err("an SVG has a title".to_owned());
1060                }
1061            }
1062            drawing.svg = svg::sanitize(&drawing.svg, limits)?;
1063            Ok(())
1064        }
1065        Kind::Ai6Card(card) => {
1066            limits.identifier("entityId", &card.entity_id)?;
1067            if let Some(operation) = &card.operation_id {
1068                limits.identifier("operation_id", operation)?;
1069            }
1070            if card.card == CardKind::Mission && card.operation_id.is_none() {
1071                return Err("a Mission card names its operation_id".to_owned());
1072            }
1073            card_route(
1074                card.card,
1075                &card.entity_id,
1076                card.operation_id.as_deref(),
1077                route,
1078            )?;
1079            check_optional_short(card.state.as_ref(), "state", data_model, limits)?;
1080            if let Some(fields) = &card.fields {
1081                check_pairs_value(fields, data_model, limits, 0, limits.fields, "a card")?;
1082            }
1083            Ok(())
1084        }
1085        Kind::Ai6Timeline(timeline) => {
1086            let Some(items) = timeline.items.get(data_model)? else {
1087                return Ok(());
1088            };
1089            if items.is_empty() || items.len() > limits.items {
1090                return Err(format!("a timeline has 1 to {} items", limits.items));
1091            }
1092            for item in items.iter() {
1093                if let Some(at) = item.at.get(data_model)?.and_then(|at| seconds(&at))
1094                    && (!at.is_finite() || at < 0.0)
1095                {
1096                    return Err("at is Unix seconds".to_owned());
1097                }
1098                check_short(&item.label, "a label", data_model, limits)?;
1099                check_optional_short(item.detail.as_ref(), "a detail", data_model, limits)?;
1100            }
1101            Ok(())
1102        }
1103        Kind::Ai6Diff(diff) => {
1104            check_optional_short(diff.title.as_ref(), "title", data_model, limits)?;
1105            for side in [&diff.before, &diff.after] {
1106                if let Some(text) = side.get(data_model)?
1107                    && text.len() > limits.diff_bytes
1108                {
1109                    return Err(format!(
1110                        "each side of a diff is at most {} bytes",
1111                        limits.diff_bytes
1112                    ));
1113                }
1114            }
1115            Ok(())
1116        }
1117        Kind::Ai6Form(form) => validate_form(form, data_model, limits),
1118    }
1119}
1120
1121fn validate_form(form: &Form, data_model: &DataModel, limits: &ViewLimits) -> Result<(), String> {
1122    let tool = form.tool.as_str();
1123    if !actions::write_tools()
1124        .iter()
1125        .any(|write| write.name == tool)
1126    {
1127        return Err(format!(
1128            "a form drafts one of the propose_* tools, not {tool:?}"
1129        ));
1130    }
1131    if let Some(title) = form.title.get(data_model)? {
1132        limits.short("title", &title)?;
1133        if title.trim().is_empty() {
1134            return Err("a form has a title".to_owned());
1135        }
1136    }
1137    if let Some(fixed) = &form.fixed {
1138        for value in fixed.values() {
1139            if serde_json::to_vec(value).map_or(usize::MAX, |bytes| bytes.len()) > limits.text_bytes
1140            {
1141                return Err("a fixed value is too long".to_owned());
1142            }
1143        }
1144    }
1145    let props = form
1146        .schema
1147        .properties()
1148        .ok_or_else(|| "a form's schema must declare object properties".to_owned())?;
1149    if props.is_empty() || props.len() > limits.fields {
1150        return Err(format!("a form has 1 to {} fields", limits.fields));
1151    }
1152    for name in props.keys() {
1153        limits.identifier("a field name", name)?;
1154        if form.fixed.as_ref().is_some_and(|f| f.contains(name)) {
1155            return Err(format!("{name} is both fixed and a field"));
1156        }
1157    }
1158
1159    let g_schema = guatiao_serde::from_serde(form.schema.document())
1160        .map_err(|err| format!("form schema is not a guatiao value: {err}"))?;
1161    let schema_ref = guatiao::schema::read::SchemaRef::new(&g_schema)
1162        .ok_or_else(|| "form schema is not a valid guatiao-intake schema".to_owned())?;
1163    let generated = guatiao_intake::for_schema(schema_ref, guatiao::Alloc::rust())
1164        .map_err(|err| format!("form schema cannot generate an intake form: {err}"))?;
1165    if let Some(layout) = &form.form {
1166        let g_form = guatiao_serde::from_serde(layout)
1167            .map_err(|err| format!("form layout is not a guatiao value: {err}"))?;
1168        let form_ref = guatiao_intake::FormRef::new(&g_form)
1169            .ok_or_else(|| "form layout is not a valid guatiao-intake form".to_owned())?;
1170        guatiao_intake::check(schema_ref, form_ref)
1171            .map_err(|err| format!("form layout does not match schema: {err}"))?;
1172    } else if let Some(form_ref) = guatiao_intake::FormRef::new(&generated) {
1173        guatiao_intake::check(schema_ref, form_ref)
1174            .map_err(|err| format!("form schema check failed: {err}"))?;
1175    }
1176    Ok(())
1177}
1178
1179/// A number as the Unix seconds the renderer reads.
1180fn seconds(number: &Number) -> Option<f64> {
1181    number.as_f64()
1182}
1183
1184fn chart_bounds(
1185    chart: &Chart,
1186    stacked: bool,
1187    data_model: &DataModel,
1188    limits: &ViewLimits,
1189) -> Result<(), String> {
1190    let kind = chart.chart;
1191    if stacked && kind != ChartKind::Bar {
1192        return Err("only a bar chart is stacked".to_owned());
1193    }
1194    let Some(series) = chart.series.get(data_model)? else {
1195        return Ok(());
1196    };
1197    if series.is_empty() || series.len() > limits.series {
1198        return Err(format!("a chart has 1 to {} series", limits.series));
1199    }
1200    for line in series.iter() {
1201        check_short(&line.name, "a series name", data_model, limits)?;
1202        if line.points.is_empty() || line.points.len() > limits.points {
1203            return Err(format!("a series has 1 to {} points", limits.points));
1204        }
1205        let mut seen = HashSet::new();
1206        for point in &line.points {
1207            if let Some(x) = point.x.get(data_model)? {
1208                limits.scalar("x", &x)?;
1209                if kind != ChartKind::Line
1210                    && !seen.insert(serde_json::to_string(&*x).unwrap_or_default())
1211                {
1212                    let shown = serde_json::to_string(&*x).unwrap_or_default();
1213                    return Err(format!("a series names each x once, not {shown} twice"));
1214                }
1215            }
1216            if let Some(y) = point.y.get(data_model)? {
1217                let y = y
1218                    .as_f64()
1219                    .filter(|v| v.is_finite())
1220                    .ok_or_else(|| "y must be a finite number".to_owned())?;
1221                if stacked && y < 0.0 {
1222                    return Err("a stacked bar's values are 0 or more".to_owned());
1223                }
1224            }
1225        }
1226    }
1227    if kind == ChartKind::Pie {
1228        let [only] = series.as_slice() else {
1229            return Err("a pie has one series".to_owned());
1230        };
1231        if only.points.len() > limits.pie_slices {
1232            return Err(format!("a pie has at most {} slices", limits.pie_slices));
1233        }
1234        let mut any_positive = false;
1235        for point in &only.points {
1236            if let Some(y) = point.y.get(data_model)? {
1237                let y = y.as_f64().unwrap_or(0.0);
1238                if y < 0.0 {
1239                    return Err("a pie's values are 0 or more".to_owned());
1240                }
1241                if y > 0.0 {
1242                    any_positive = true;
1243                }
1244            }
1245        }
1246        if !any_positive {
1247            return Err("a pie has a value above 0".to_owned());
1248        }
1249    }
1250    Ok(())
1251}
1252
1253/// Unix seconds of an RFC 3339 time (`2026-10-29T08:00:00Z`, `2026-10-29T08:00:00.5+07:00`),
1254/// or `None` when `text` is not one.
1255pub(crate) fn rfc3339(text: &str) -> Option<f64> {
1256    if !matches!(text.as_bytes().get(10), Some(b'T' | b't')) {
1257        return None;
1258    }
1259    let at =
1260        time::OffsetDateTime::parse(text, &time::format_description::well_known::Rfc3339).ok()?;
1261    #[allow(clippy::cast_precision_loss)]
1262    Some(at.unix_timestamp() as f64 + f64::from(at.nanosecond()) / 1e9)
1263}
1264
1265/// A time of a schedule: whether it is an RFC 3339 time, and its Unix seconds or number.
1266fn moment(value: &ScheduleTime) -> Result<(bool, f64), String> {
1267    match value {
1268        ScheduleTime::Text(text) => rfc3339(text)
1269            .map(|at| (true, at))
1270            .ok_or_else(|| format!("{text:?} is not an RFC 3339 time")),
1271        ScheduleTime::Number(number) => number
1272            .as_f64()
1273            .filter(|at| at.is_finite())
1274            .map(|at| (false, at))
1275            .ok_or_else(|| "a time is a finite number".to_owned()),
1276    }
1277}
1278
1279/// Every Markdown link is an app route (`app:/<page>?...`).
1280fn links_stay_in_the_app(markdown: &str, route: routes::Limits) -> Result<(), String> {
1281    let mut rest = markdown;
1282    while let Some(at) = rest.find("](") {
1283        let target = &rest[at + 2..];
1284        if !target.starts_with("app:/") {
1285            return Err(
1286                "a link must point into the app (app:/...); outside links are not shown".to_owned(),
1287            );
1288        }
1289        let end = target.find(')').unwrap_or(target.len());
1290        Route::parse_uri(&target[..end], route)
1291            .map_err(|reason| format!("a link is not an app route: {reason}"))?;
1292        rest = target;
1293    }
1294    Ok(())
1295}
1296
1297/// The link of a schedule row or a graph node: literal text or a path to it, never a function
1298/// call, whose result the gateway cannot check.
1299fn check_link(
1300    link: Option<&Dynamic<String>>,
1301    data_model: &DataModel,
1302    limits: &ViewLimits,
1303    route: routes::Limits,
1304) -> Result<(), String> {
1305    let Some(link) = link else {
1306        return Ok(());
1307    };
1308    if link.is_call() {
1309        return Err("a link is literal text or a path, not a function call".to_owned());
1310    }
1311    match link.get(data_model)? {
1312        Some(text) => app_link("a link", &text, limits, route),
1313        None => Ok(()),
1314    }
1315}
1316
1317/// A link to a page of the app: an app route in its link form (`app:/<page>?...`).
1318fn app_link(
1319    what: &str,
1320    link: &str,
1321    limits: &ViewLimits,
1322    route: routes::Limits,
1323) -> Result<(), String> {
1324    if !link.starts_with("app:/") {
1325        return Err(format!(
1326            "{what} must point into the app (app:/...); outside links are not shown"
1327        ));
1328    }
1329    limits.short(what, link)?;
1330    Route::parse_uri(link, route)
1331        .map(|_| ())
1332        .map_err(|reason| format!("{what} is not an app route: {reason}"))
1333}
1334
1335/// The page a card opens.
1336fn card_route(
1337    card: CardKind,
1338    id: &str,
1339    operation_id: Option<&str>,
1340    route: routes::Limits,
1341) -> Result<Route, String> {
1342    let text = |name, value: &str| (name, Field::Text(value.to_owned()));
1343    let (page, fields) = match (card, operation_id) {
1344        (CardKind::Mission, Some(operation)) => (
1345            Page::Missions,
1346            vec![text("operation_id", operation), text("mission_id", id)],
1347        ),
1348        (CardKind::Mission, None) => {
1349            return Err("a Mission card names its operation_id".to_owned());
1350        }
1351        (CardKind::Station, _) => (Page::Stations, vec![text("station_id", id)]),
1352        (CardKind::Theater, _) => (Page::Stations, vec![text("tab", "theaters")]),
1353    };
1354    Route::at(page, fields, route)
1355}
1356
1357fn schedule_bounds(
1358    rows: &Dynamic<Vec<ScheduleRow>>,
1359    data_model: &DataModel,
1360    limits: &ViewLimits,
1361    route: routes::Limits,
1362) -> Result<(), String> {
1363    let Some(rows) = rows.get(data_model)? else {
1364        return Ok(());
1365    };
1366    if rows.is_empty() || rows.len() > limits.schedule_rows {
1367        return Err(format!("a schedule has 1 to {} rows", limits.schedule_rows));
1368    }
1369    let mut times = None;
1370    for row in rows.iter() {
1371        let label = row.label.get(data_model)?.unwrap_or_default();
1372        limits.short("a label", &label)?;
1373        check_optional_short(row.state.as_ref(), "state", data_model, limits)?;
1374        check_link(row.link.as_ref(), data_model, limits, route)?;
1375        if let (Some(start), Some(end)) = (row.start.get(data_model)?, row.end.get(data_model)?) {
1376            let (start_is_time, start) = moment(&start)?;
1377            let (end_is_time, end) = moment(&end)?;
1378            if start_is_time != end_is_time || *times.get_or_insert(start_is_time) != start_is_time
1379            {
1380                return Err("a schedule's times are all RFC 3339 times or all numbers".to_owned());
1381            }
1382            if start >= end {
1383                return Err(format!("every row starts before it ends ({label:?})"));
1384            }
1385        }
1386    }
1387    Ok(())
1388}
1389
1390fn graph_bounds(
1391    graph: &Graph,
1392    data_model: &DataModel,
1393    limits: &ViewLimits,
1394    route: routes::Limits,
1395) -> Result<(), String> {
1396    let tree = graph.layout == Some(GraphLayout::Tree);
1397    let Some(nodes) = graph.nodes.get(data_model)? else {
1398        return Ok(());
1399    };
1400    if nodes.is_empty() || nodes.len() > limits.graph_nodes {
1401        return Err(format!("a graph has 1 to {} nodes", limits.graph_nodes));
1402    }
1403    let edges = match &graph.edges {
1404        Some(edges) => edges.get(data_model)?,
1405        None => None,
1406    };
1407    let edges: &[GraphEdge] = edges.as_deref().map_or(&[], Vec::as_slice);
1408    if edges.len() > limits.graph_edges {
1409        return Err(format!("a graph has at most {} edges", limits.graph_edges));
1410    }
1411    let mut ids = HashSet::new();
1412    for node in nodes.iter() {
1413        limits.identifier("a node id", &node.id)?;
1414        if !ids.insert(node.id.as_str()) {
1415            return Err(format!("the node id {:?} is used twice", node.id));
1416        }
1417        check_short(&node.label, "a node label", data_model, limits)?;
1418        check_optional_short(node.state.as_ref(), "state", data_model, limits)?;
1419        check_link(node.link.as_ref(), data_model, limits, route)?;
1420    }
1421    let mut parents: HashMap<&str, &str> = HashMap::new();
1422    for edge in edges {
1423        let (from, to) = (edge.from.as_str(), edge.to.as_str());
1424        for end in [from, to] {
1425            if !ids.contains(end) {
1426                return Err(format!("an edge names an unknown node {end:?}"));
1427            }
1428        }
1429        if from == to {
1430            return Err(format!("an edge joins two nodes, not {from:?} to itself"));
1431        }
1432        check_optional_short(edge.label.as_ref(), "an edge label", data_model, limits)?;
1433        if tree && parents.insert(to, from).is_some() {
1434            return Err(format!(
1435                "in a tree each node has at most one parent; {to:?} has two"
1436            ));
1437        }
1438    }
1439    for start in &ids {
1440        let mut at = *start;
1441        for _ in 0..nodes.len() {
1442            match parents.get(at) {
1443                Some(parent) => at = parent,
1444                None => break,
1445            }
1446        }
1447        if parents.contains_key(at) {
1448            return Err("a tree has no cycle".to_owned());
1449        }
1450    }
1451    let roots = nodes
1452        .iter()
1453        .filter(|node| !parents.contains_key(node.id.as_str()))
1454        .count();
1455    if tree && roots != 1 {
1456        return Err(format!("a tree has one root, not {roots}"));
1457    }
1458    Ok(())
1459}
1460
1461/// Builds the input of the `propose_*` tool of a view's one form from its `fixed` values and the
1462/// submitted values. The view is normalized, so the form is the one the person is shown.
1463pub(crate) fn form_input(view: &View, values: &DataObject) -> Result<(String, DataObject), String> {
1464    let form = view
1465        .messages
1466        .iter()
1467        .flat_map(defined_by)
1468        .find_map(|comp| match &comp.kind {
1469            Kind::Ai6Form(form) => Some(form),
1470            _ => None,
1471        })
1472        .ok_or("the view has no form")?;
1473    let tool = form.tool.clone();
1474    let mut input = form.fixed.clone().unwrap_or_default();
1475    let props = form
1476        .schema
1477        .properties()
1478        .ok_or("the form schema has no properties")?;
1479
1480    for (name, value) in values.iter() {
1481        if input.contains(name) {
1482            return Err(format!("{name} is not a field of the form"));
1483        }
1484        let prop = props
1485            .member(name)
1486            .and_then(DataValue::object)
1487            .ok_or_else(|| format!("{name} is not a field of the form"))?;
1488        let names =
1489            |key: &str, wanted: &str| prop.member(key).and_then(DataValue::text) == Some(wanted);
1490        let is_object_or_json = names("type", "object") || names("format", "json");
1491        let coerced = match value {
1492            DataValue::Text(text) if is_object_or_json => {
1493                serde_json::from_str::<DataValue>(text)
1494                    .map_err(|_| format!("{name} is not valid JSON"))?
1495            }
1496            _ => value.clone(),
1497        };
1498        if let Some(choices) = prop.member("enum").and_then(DataValue::list)
1499            && !choices.contains(&coerced)
1500        {
1501            return Err(format!("{name} is not one of its choices"));
1502        }
1503        input.insert(name.clone(), coerced);
1504    }
1505
1506    Ok((tool, input))
1507}
1508
1509/// The `show` listing points to `ui_catalog` for the complete component and function schemas.
1510pub(super) fn show_listing(description: String, limits: &ViewLimits) -> ToolInfo {
1511    mcp::taking_with::<ShowArgs>("show", description, true, None, |schema| {
1512        describe_messages(schema, limits);
1513    })
1514}
1515
1516/// Spells out, in the schema of a [`ShowArgs`], the messages the catalog allows: what a harness
1517/// that checks its input against the listing needs to send one. Used where a surface is taken
1518/// as `show` takes it.
1519pub(super) fn describe_messages(schema: &mut SchemaDoc, limits: &ViewLimits) {
1520    let messages = schema
1521        .property_mut("messages")
1522        .expect("a surface takes messages");
1523    messages.set_description(Some(&format!(
1524        "Ordered A2UI v1.0 messages targeting catalog {CATALOG_ID:?}. Must start with \
1525         createSurface (catalogId {CATALOG_ID:?}, no theme field), followed by optional \
1526         updateComponents and updateDataModel messages defining a root Ai6View and at most {} \
1527         content blocks (within {} bytes total). Call {CATALOG_TOOL} to inspect the full JSON \
1528         Schema catalog.",
1529        limits.blocks, limits.view_bytes,
1530    )));
1531    messages
1532        .set_extra("minItems", 1_u32)
1533        .expect("minItems is editable");
1534
1535    let item = messages.items_mut().expect("show messages are a list");
1536    let mut version = SchemaDoc::new();
1537    version
1538        .set_extra("const", PROTOCOL_VERSION)
1539        .expect("const is editable");
1540    item.insert_property("version", version, true);
1541    for name in ["createSurface", "updateComponents", "updateDataModel"] {
1542        let mut object = SchemaDoc::new();
1543        object
1544            .set_extra("type", "object")
1545            .expect("type is editable");
1546        item.insert_property(name, object, false);
1547    }
1548    item.set_extra("additionalProperties", false)
1549        .expect("additionalProperties is editable");
1550}
1551
1552pub(super) fn catalog_listing() -> ToolInfo {
1553    mcp::taking::<mcp::NoArguments>(CATALOG_TOOL, catalog_description(), true, None)
1554}
1555
1556pub(super) fn read_catalog(call: &ToolCall) -> super::tools::Outcome {
1557    match mcp::arguments::<mcp::NoArguments>(call) {
1558        Ok(mcp::NoArguments {}) => catalog_outcome(),
1559        Err(why) => super::tools::Outcome::error(why),
1560    }
1561}
1562
1563#[cfg(test)]
1564mod tests {
1565    use serde_json::{Value, json};
1566
1567    use super::*;
1568
1569    fn parse_data(
1570        input: &DataValue,
1571        limits: &ViewLimits,
1572        route: routes::Limits,
1573    ) -> Result<View, String> {
1574        let raw = input
1575            .object()
1576            .and_then(|root| root.member("messages"))
1577            .and_then(DataValue::list)
1578            .expect("the fixture is a list of messages");
1579        let size = serde_json::to_vec(input).unwrap().len();
1580        super::parse(raw.iter(), size, limits, route)
1581    }
1582
1583    fn data(json: &Value) -> DataValue {
1584        DataValue::of(json).unwrap()
1585    }
1586
1587    fn values_of(json: &Value) -> DataObject {
1588        DataObject::of(json).unwrap()
1589    }
1590
1591    fn parse(input: &Value) -> Result<View, String> {
1592        parse_data(
1593            &data(input),
1594            &ViewLimits::default(),
1595            routes::Limits::default(),
1596        )
1597    }
1598
1599    pub(crate) fn fixture() -> Value {
1600        serde_json::from_str(include_str!(
1601            "../../../../clients/outer-office/test/fixtures/assistant_views.json"
1602        ))
1603        .unwrap()
1604    }
1605
1606    #[test]
1607    fn catalog_conforms_to_a2ui_v1_catalog_definition_schema() {
1608        let def_schema: Value = serde_json::from_str(CATALOG_DEFINITION_SCHEMA).unwrap();
1609        let retriever = CatalogRetriever::embedded().unwrap();
1610        let compiled = jsonschema::draft202012::options()
1611            .with_retriever(retriever)
1612            .build(&def_schema)
1613            .expect("catalog_definition.json compiles");
1614        let catalog = serde_json::to_value(catalog()).unwrap();
1615        let errors: Vec<String> = compiled
1616            .iter_errors(&catalog)
1617            .map(|e| format!("{} at {}", e, e.instance_path()))
1618            .collect();
1619        assert!(errors.is_empty(), "catalog definition errors: {errors:?}");
1620        // Verify every function is rendererOnly and none require user activation.
1621        for (name, def) in catalog["functions"].as_object().unwrap() {
1622            assert_eq!(def["allowedCallers"], "rendererOnly", "{name}");
1623            assert_eq!(def["requiresUserActivation"], false, "{name}");
1624        }
1625    }
1626
1627    #[test]
1628    fn the_retriever_serves_each_embedded_schema_at_its_declared_id() {
1629        use jsonschema::Retrieve;
1630        let retriever = CatalogRetriever::embedded().unwrap();
1631        for (text, id) in [
1632            (
1633                COMMON_TYPES_SCHEMA,
1634                "https://a2ui.org/specification/v1_0/common_types.json",
1635            ),
1636            (
1637                AI6_CATALOG_JSON,
1638                "https://dev.coqui.ai6/views/1.0/catalog.json",
1639            ),
1640            (
1641                AI6_CATALOG_JSON,
1642                "https://a2ui.org/specification/v1_0/catalog.json",
1643            ),
1644        ] {
1645            let served = retriever.retrieve(&id.parse().unwrap()).unwrap();
1646            let embedded: SchemaDocument = serde_json::from_str(text).unwrap();
1647            assert_eq!(served, serde_json::to_value(&embedded).unwrap(), "{id}");
1648            let raw: Value = serde_json::from_str(text).unwrap();
1649            assert_eq!(
1650                served, raw,
1651                "{id}: the typed document writes back what is embedded"
1652            );
1653        }
1654    }
1655
1656    #[test]
1657    fn ui_catalog_names_every_component_of_the_catalog() {
1658        let described = catalog_description();
1659        let components = catalog().component_names();
1660        assert!(components.len() >= 14);
1661        for name in components {
1662            assert!(described.contains(name), "{name} in {described}");
1663        }
1664    }
1665
1666    #[test]
1667    fn external_uri_retrieval_is_refused() {
1668        use jsonschema::Retrieve;
1669        let retriever = CatalogRetriever::embedded().unwrap();
1670        let evil: jsonschema::Uri<String> = "https://evil.example/catalog.json".parse().unwrap();
1671        let err = retriever.retrieve(&evil).unwrap_err();
1672        assert!(
1673            err.to_string().contains("refused"),
1674            "unexpected error: {err}"
1675        );
1676    }
1677
1678    #[test]
1679    fn every_kind_of_the_fixture_is_accepted() {
1680        let fixture = fixture();
1681        for (name, view) in fixture["valid"].as_object().unwrap() {
1682            let parsed = parse(view);
1683            assert!(parsed.is_ok(), "{name}: {parsed:?}");
1684            assert_eq!(
1685                &serde_json::to_value(parsed.unwrap()).unwrap(),
1686                view,
1687                "{name}: the typed view writes back what she sent"
1688            );
1689        }
1690    }
1691
1692    /// The limits a fixture case sets over the defaults (`limits`, by the names the app is sent).
1693    fn limits_of(case: &Value) -> ViewLimits {
1694        let mut limits = serde_json::to_value(ViewLimits::default()).unwrap();
1695        if let Some(set) = case.get("limits").and_then(Value::as_object) {
1696            limits.as_object_mut().unwrap().extend(set.clone());
1697        }
1698        serde_json::from_value(limits).unwrap()
1699    }
1700
1701    #[test]
1702    fn every_invalid_view_of_the_fixture_is_refused_with_its_reason() {
1703        let fixture = fixture();
1704        for case in fixture["invalid"].as_array().unwrap() {
1705            let Err(refused) = parse_data(
1706                &data(&case["view"]),
1707                &limits_of(case),
1708                routes::Limits::default(),
1709            ) else {
1710                panic!("{} was shown", case["name"]);
1711            };
1712            let reason = case["reason"].as_str().unwrap();
1713            assert!(
1714                refused.contains(reason),
1715                "{refused:?} should name {reason:?}"
1716            );
1717        }
1718    }
1719
1720    #[test]
1721    fn a_regex_pattern_beyond_the_catalogs_bound_is_refused() {
1722        let pattern = &serde_json::to_value(catalog()).unwrap()["functions"]["regex"]["properties"]
1723            ["args"]["properties"]["pattern"];
1724        let validator = jsonschema::draft202012::options().build(pattern).unwrap();
1725        assert!(validator.is_valid(&json!("a".repeat(256))));
1726        assert!(!validator.is_valid(&json!("a".repeat(257))));
1727    }
1728
1729    #[test]
1730    fn an_svg_is_held_in_canonical_form_which_parses_again_unchanged() {
1731        let messy = "<?xml version=\"1.0\"?>\n<svg viewBox=\"0 0 10 10\">\n  <!-- a note -->\n  \
1732                     <title>t</title>\n  <rect width=\"5\" height=\"5\"></rect>\n</svg>";
1733        let payload = json!({
1734            "messages": [{
1735                "version": "1.0",
1736                "createSurface": {
1737                    "surfaceId": "svg_test",
1738                    "catalogId": CATALOG_ID,
1739                    "components": [
1740                        {"id": "root", "component": "Ai6View", "children": ["drawing"]},
1741                        {"id": "drawing", "component": "Ai6Svg", "title": "t", "svg": messy}
1742                    ]
1743                }
1744            }]
1745        });
1746        let view = parse(&payload).unwrap();
1747        let written = serde_json::to_value(&view).unwrap();
1748        let svg = written["messages"][0]["createSurface"]["components"][1]["svg"]
1749            .as_str()
1750            .unwrap();
1751        assert_eq!(
1752            svg,
1753            "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 10 10\"><title>t</title>\
1754             <rect width=\"5\" height=\"5\"/></svg>"
1755        );
1756        let again = parse(&written).unwrap();
1757        assert_eq!(again, view);
1758        let fixture = fixture();
1759        let shown = parse(&fixture["valid"]["svg"]).unwrap();
1760        assert_eq!(
1761            serde_json::to_value(&shown).unwrap(),
1762            fixture["valid"]["svg"]
1763        );
1764    }
1765
1766    #[test]
1767    fn rfc3339_times_are_read_as_unix_seconds() {
1768        assert_eq!(rfc3339("1970-01-01T00:00:00Z"), Some(0.0));
1769        assert_eq!(rfc3339("2000-03-01T00:00:00Z"), Some(951_868_800.0));
1770        assert_eq!(rfc3339("2000-03-01t00:00:00.25z"), Some(951_868_800.25));
1771        assert_eq!(
1772            rfc3339("2026-10-29T09:10:00+01:00"),
1773            rfc3339("2026-10-29T08:10:00Z")
1774        );
1775        assert_eq!(
1776            rfc3339("1969-12-31T19:00:00-05:00"),
1777            Some(0.0),
1778            "an offset west of UTC"
1779        );
1780        assert_eq!(
1781            rfc3339("2024-02-29T23:59:59-08:00"),
1782            Some(1_709_279_999.0),
1783            "a leap day west of UTC"
1784        );
1785        assert_eq!(rfc3339("2100-03-01T00:00:00Z"), Some(4_107_542_400.0));
1786        assert_eq!(rfc3339("1900-03-01T00:00:00Z"), Some(-2_203_891_200.0));
1787        for refused in [
1788            "2100-02-29T00:00:00Z",
1789            "2026-02-29T00:00:00Z",
1790            "2026-10-29 08:00:00Z",
1791            "2026-10-29T08:00:00",
1792            "2026-10-29T24:00:00Z",
1793            "2026-10-29T08:00:00.Z",
1794            "2026-10-29T08:00:00+0100",
1795            "2026-1реж-29T08:00:00Z",
1796        ] {
1797            assert_eq!(rfc3339(refused), None, "{refused}");
1798        }
1799    }
1800
1801    #[test]
1802    fn a_form_fills_its_tool_from_fixed_values_and_intake_schema() {
1803        let payload = json!({
1804            "messages": [{
1805                "version": "1.0",
1806                "createSurface": {
1807                    "surfaceId": "form_test",
1808                    "catalogId": CATALOG_ID,
1809                    "components": [
1810                        {"id": "root", "component": "Ai6View", "children": ["form_1"]},
1811                        {
1812                            "id": "form_1",
1813                            "component": "Ai6Form",
1814                            "tool": "propose_roster_edit",
1815                            "title": "Edit Agent 008",
1816                            "fixed": {"kind": "agents", "key": "008"},
1817                            "schema": {
1818                                "type": "object",
1819                                "properties": {
1820                                    "definition": {
1821                                        "type": "object",
1822                                        "title": "Settings",
1823                                        "properties": {
1824                                            "priority": {"type": "integer", "title": "Priority"}
1825                                        }
1826                                    }
1827                                }
1828                            }
1829                        }
1830                    ]
1831                }
1832            }]
1833        });
1834        let view = parse(&payload).unwrap();
1835        let values = json!({"definition": {"priority": 3}});
1836        let (tool, input) = form_input(&view, &values_of(&values)).unwrap();
1837        let input = serde_json::to_value(&input).unwrap();
1838        assert_eq!(tool, "propose_roster_edit");
1839        assert_eq!(
1840            input,
1841            json!({"kind": "agents", "key": "008", "definition": {"priority": 3}})
1842        );
1843        let sneaky = json!({"key": "007"});
1844        assert!(form_input(&view, &values_of(&sneaky)).is_err());
1845    }
1846
1847    /// A view whose `root` holds a chain of `depth` nested Columns ending in one text block.
1848    fn deep_chain(depth: usize) -> Value {
1849        let mut components =
1850            vec![json!({"id": "root", "component": "Ai6View", "children": ["c0"]})];
1851        for level in 0..depth {
1852            components.push(json!({
1853                "id": format!("c{level}"), "component": "Column", "children": [format!("c{}", level + 1)]
1854            }));
1855        }
1856        components
1857            .push(json!({"id": format!("c{depth}"), "component": "Ai6Text", "markdown": "end"}));
1858        json!({"messages": [{"version": "1.0", "createSurface": {
1859            "surfaceId": "deep", "catalogId": CATALOG_ID, "components": components
1860        }}]})
1861    }
1862
1863    /// Runs `parse` on a thread with a stack too small for a recursive walk of the chain.
1864    fn parse_on_a_small_stack(input: Value, limits: ViewLimits) -> Result<View, String> {
1865        let input = data(&input);
1866        std::thread::Builder::new()
1867            .stack_size(512 * 1024)
1868            .spawn(move || parse_data(&input, &limits, routes::Limits::default()))
1869            .unwrap()
1870            .join()
1871            .expect("the walk never overflows its stack")
1872    }
1873
1874    #[test]
1875    fn a_chain_of_forty_thousand_components_is_refused_without_a_crash() {
1876        let refused =
1877            parse_on_a_small_stack(deep_chain(40_000), ViewLimits::default()).unwrap_err();
1878        assert!(refused.contains("a view is at most"), "{refused}");
1879    }
1880
1881    #[test]
1882    fn a_chain_past_the_depth_limit_is_refused_by_a_walk_that_does_not_recurse() {
1883        let raised = ViewLimits {
1884            view_bytes: usize::MAX,
1885            components: usize::MAX,
1886            ..ViewLimits::default()
1887        };
1888        let refused = parse_on_a_small_stack(deep_chain(5_000), raised).unwrap_err();
1889        assert!(
1890            refused.contains("components nest at most 16 deep"),
1891            "{refused}"
1892        );
1893        // With the depth limit out of the way the walk goes the whole chain and ends in the next
1894        // limit, on the same small stack.
1895        let unbounded = ViewLimits {
1896            depth: usize::MAX,
1897            ..raised
1898        };
1899        let refused = parse_on_a_small_stack(deep_chain(5_000), unbounded).unwrap_err();
1900        assert!(refused.contains("layout components"), "{refused}");
1901    }
1902
1903    /// The scenario of the review: a form that is not the one shown must never be the one
1904    /// submitted.
1905    fn roster_form(id: &str) -> Value {
1906        json!({
1907            "id": id, "component": "Ai6Form", "tool": "propose_roster_edit", "title": "Edit",
1908            "fixed": {"kind": "agents", "key": "008"},
1909            "schema": {"type": "object", "properties": {
1910                "definition": {"type": "object", "properties": {"priority": {"type": "integer"}}}
1911            }}
1912        })
1913    }
1914
1915    fn access_form(id: &str) -> Value {
1916        json!({
1917            "id": id, "component": "Ai6Form", "tool": "propose_access_change", "title": "Access",
1918            "fixed": {"kind": "grant", "subject": "mallory"},
1919            "schema": {"type": "object", "properties": {"note": {"type": "string"}}}
1920        })
1921    }
1922
1923    fn view_of(messages: Vec<Value>) -> Value {
1924        json!({"messages": messages})
1925    }
1926
1927    fn create(components: Vec<Value>) -> Value {
1928        json!({"version": "1.0", "createSurface": {
1929            "surfaceId": "s", "catalogId": CATALOG_ID, "components": components
1930        }})
1931    }
1932
1933    fn update(components: Vec<Value>) -> Value {
1934        json!({"version": "1.0", "updateComponents": {"surfaceId": "s", "components": components}})
1935    }
1936
1937    fn root_of(children: &[&str]) -> Value {
1938        json!({"id": "root", "component": "Ai6View", "children": children})
1939    }
1940
1941    #[test]
1942    fn a_form_no_root_reaches_is_refused_not_submitted() {
1943        let hidden = view_of(vec![create(vec![
1944            root_of(&["shown"]),
1945            roster_form("shown"),
1946            access_form("hidden"),
1947        ])]);
1948        let refused = parse(&hidden).unwrap_err();
1949        assert!(refused.contains("not reachable from root"), "{refused}");
1950    }
1951
1952    #[test]
1953    fn a_superseded_form_is_not_the_one_a_submit_reaches() {
1954        let superseded = view_of(vec![
1955            create(vec![root_of(&["f"]), access_form("f")]),
1956            update(vec![
1957                json!({"id": "f", "component": "Ai6Text", "markdown": "No form."}),
1958            ]),
1959        ]);
1960        let view = parse(&superseded).unwrap();
1961        let values = json!({});
1962        let refused = form_input(&view, &values_of(&values)).unwrap_err();
1963        assert!(refused.contains("no form"), "{refused}");
1964
1965        let replaced = view_of(vec![
1966            create(vec![root_of(&["f"]), access_form("f")]),
1967            update(vec![roster_form("f")]),
1968        ]);
1969        let view = parse(&replaced).unwrap();
1970        let values = json!({"definition": {"priority": 3}});
1971        let (tool, input) = form_input(&view, &values_of(&values)).unwrap();
1972        let input = serde_json::to_value(&input).unwrap();
1973        assert_eq!(tool, "propose_roster_edit");
1974        assert_eq!(input["key"], "008");
1975        assert!(
1976            !serde_json::to_string(&view).unwrap().contains("mallory"),
1977            "the superseded definition is dropped from the view"
1978        );
1979    }
1980
1981    #[test]
1982    fn a_value_read_from_the_data_model_is_what_its_field_takes() {
1983        let view = |value: Value| {
1984            json!({"messages": [{"version": "1.0", "createSurface": {
1985                "surfaceId": "s", "catalogId": CATALOG_ID,
1986                "dataModel": {"n": value},
1987                "components": [
1988                    {"id": "root", "component": "Ai6View", "children": ["t"]},
1989                    {"id": "t", "component": "Ai6Text", "markdown": {"@path": "/n"}}
1990                ]
1991            }}]})
1992        };
1993        assert!(parse(&view(json!("Hello"))).is_ok());
1994        let refused = parse(&view(json!(7))).unwrap_err();
1995        assert!(refused.contains("is not what its field takes"), "{refused}");
1996    }
1997
1998    #[test]
1999    fn json_nested_deeper_than_the_renderer_reads_is_refused() {
2000        let mut nested = json!("leaf");
2001        for _ in 0..200 {
2002            nested = json!({"k": nested});
2003        }
2004        let view = json!({"messages": [{"version": "1.0", "createSurface": {
2005            "surfaceId": "s", "catalogId": CATALOG_ID,
2006            "dataModel": {"deep": nested},
2007            "components": [
2008                {"id": "root", "component": "Ai6View", "children": ["t"]},
2009                {"id": "t", "component": "Ai6Text", "markdown": "x"}
2010            ]
2011        }}]});
2012        let refused = parse(&view).unwrap_err();
2013        assert!(
2014            refused.contains("nests JSON more than 50 deep"),
2015            "{refused}"
2016        );
2017    }
2018}