Skip to main content

adk_surface/genui/
wire.rs

1//! A2UI versions on the wire (spec 3.3 §6.1 `genui`): a drawing is stored and checked in
2//! one internal form (the A2UI v0.9.1 shape of [`A2uiMessage`]) and written in the version a
3//! renderer speaks. A2UI 1.0 is the default; v0.9.1 is kept for renderers that offer nothing
4//! newer.
5//!
6//! | 1.0 on the wire | Internal |
7//! |---|---|
8//! | `{"@path": "/to"}` where a value is dynamic | `{"path": "/to"}` |
9//! | `{"@call": "formatNumber", "args": {…}}` | `{"call": "formatNumber", "args": {…}}` |
10//! | `@accessibility`, `@checks` at a component's root | `accessibility`, `checks` |
11//! | `@catalogId` on an extension component; the surface's default catalog is `forms` | the drawing's one catalog |
12//! | a literal key `"@@x"` | `"@x"` |
13//! | `createSurface` carrying `components` and `dataModel` | `createSurface`, `updateComponents`, `updateDataModel` |
14//! | `updateDataModel.value: null` | no value (removes the path) |
15//! | `createSurface.metadata.extensions.adkrust_display_only` | implied: every drawing follows rule 5 |
16//!
17//! Every 1.0 `createSurface` claims the display-only extension ([`DISPLAY_ONLY_EXTENSION`],
18//! `docs/design/a2ui-extension-display-only.md`): a drawing shows; only the host decides.
19//!
20//! Reading 1.0 refuses what the internal form cannot hold without changing its meaning: an
21//! unknown `@` key, a literal object whose only key is `path` or that has a `call` key (the
22//! internal form would read it as a binding or a call), `@metadata`, `@index`, and surface
23//! metadata other than the display-only claim.
24
25use serde_json::{Map, Value, json};
26
27use super::a2ui::{A2UI_VERSION, A2uiBody, A2uiMessage};
28use super::catalog::{Catalog, FORMS_CATALOG_ID};
29
30/// The A2UI 1.0 extension every drawing `genui` writes claims in its `createSurface`
31/// (`metadata.extensions`): the surface only shows, no string in it reads as a decision, a
32/// secret or a link, and a send only asks the host for a call the person then decides on
33/// (spec 3.3 §7.4 rule 5; `docs/design/a2ui-extension-display-only.md`).
34///
35/// # Example
36///
37/// ```rust
38/// use adk_surface::genui::{A2uiMessage, A2uiVersion, Catalog, DISPLAY_ONLY_EXTENSION, to_wire};
39///
40/// let wire = to_wire(&[A2uiMessage::create_surface("s")], Catalog::forms(), A2uiVersion::V1_0);
41/// let claim = &wire[0]["createSurface"]["metadata"]["extensions"][DISPLAY_ONLY_EXTENSION];
42/// assert_eq!(claim["version"], "1.0");
43/// ```
44pub const DISPLAY_ONLY_EXTENSION: &str = "adkrust_display_only";
45
46/// The version of [`DISPLAY_ONLY_EXTENSION`] this build follows.
47pub const DISPLAY_ONLY_EXTENSION_VERSION: &str = "1.0";
48
49/// An A2UI protocol version `genui` reads and writes.
50///
51/// # Example
52///
53/// ```rust
54/// use adk_surface::genui::A2uiVersion;
55///
56/// assert_eq!(A2uiVersion::CURRENT, A2uiVersion::V1_0);
57/// assert_eq!(A2uiVersion::of_wire("v0.9.1"), Some(A2uiVersion::V0_9_1));
58/// assert_eq!(A2uiVersion::V1_0.wire(), "1.0");
59/// ```
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
61pub enum A2uiVersion {
62    /// A2UI v0.9.1, the version drawings are stored in.
63    V0_9_1,
64    /// A2UI 1.0, the current version.
65    V1_0,
66}
67
68impl A2uiVersion {
69    /// The version written when a renderer says nothing about what it speaks.
70    pub const CURRENT: Self = Self::V1_0;
71
72    /// Every version, oldest first.
73    pub const ALL: [Self; 2] = [Self::V0_9_1, Self::V1_0];
74
75    /// The `version` field of a message in this version.
76    pub fn wire(self) -> &'static str {
77        match self {
78            Self::V0_9_1 => A2UI_VERSION,
79            Self::V1_0 => "1.0",
80        }
81    }
82
83    /// The key a capabilities object lists this version's catalogs under.
84    pub fn capability_key(self) -> &'static str {
85        match self {
86            Self::V0_9_1 => "v0.9",
87            Self::V1_0 => "1.0",
88        }
89    }
90
91    /// The version a message's `version` field (or a capabilities key) names.
92    pub fn of_wire(version: &str) -> Option<Self> {
93        match version.trim() {
94            "v0.9" | "v0.9.1" | "0.9" | "0.9.1" => Some(Self::V0_9_1),
95            "1.0" | "v1.0" | "1" => Some(Self::V1_0),
96            _ => None,
97        }
98    }
99}
100
101impl Default for A2uiVersion {
102    fn default() -> Self {
103        Self::CURRENT
104    }
105}
106
107impl std::fmt::Display for A2uiVersion {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.write_str(self.wire())
110    }
111}
112
113/// Why A2UI from the wire cannot be read.
114#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
115#[error("{at}: {reason}")]
116pub struct WireError {
117    /// Where, as a JSON pointer into what was read.
118    pub at: String,
119    /// What is wrong, in words a model can act on.
120    pub reason: String,
121}
122
123impl WireError {
124    pub(crate) fn new(at: &str, reason: impl Into<String>) -> Self {
125        Self {
126            at: if at.is_empty() { "/".to_string() } else { at.to_string() },
127            reason: reason.into(),
128        }
129    }
130}
131
132/// Whether `components` are written in A2UI 1.0's syntax: a reserved `@` key anywhere.
133///
134/// # Example
135///
136/// ```rust
137/// use adk_surface::genui::is_v1_0_syntax;
138/// use serde_json::json;
139///
140/// assert!(is_v1_0_syntax(&[json!({ "id": "root", "component": "Text", "text": { "@path": "/t" } })]));
141/// assert!(!is_v1_0_syntax(&[json!({ "id": "root", "component": "Text", "text": { "path": "/t" } })]));
142/// ```
143pub fn is_v1_0_syntax(components: &[Value]) -> bool {
144    fn has_reserved(value: &Value) -> bool {
145        match value {
146            Value::Object(map) => {
147                map.keys().any(|key| key.starts_with('@')) || map.values().any(has_reserved)
148            }
149            Value::Array(items) => items.iter().any(has_reserved),
150            _ => false,
151        }
152    }
153    components.iter().any(has_reserved)
154}
155
156/// The catalog a component of a drawing in `catalog` comes from: `forms` for the forms
157/// components, `catalog` itself for the ones it adds.
158fn component_catalog<'a>(catalog: &'a Catalog, component: &str) -> &'a str {
159    if catalog.is_extension() && !Catalog::forms().has_component(component) {
160        catalog.id()
161    } else {
162        FORMS_CATALOG_ID
163    }
164}
165
166/// Whether `map` is what the internal form reads as a data binding.
167fn is_binding(map: &Map<String, Value>) -> bool {
168    map.len() == 1 && map.get("path").is_some_and(Value::is_string)
169}
170
171/// Whether `map` is what the internal form reads as a function call.
172fn is_call(map: &Map<String, Value>) -> bool {
173    map.get("call").is_some_and(Value::is_string)
174}
175
176/// A dynamic value in 1.0's syntax.
177fn dynamic_to_v1_0(value: &Value) -> Value {
178    match value {
179        Value::Object(map) if is_binding(map) => json!({ "@path": map["path"] }),
180        Value::Object(map) if is_call(map) => {
181            let mut out = Map::new();
182            out.insert("@call".to_string(), map["call"].clone());
183            if let Some(args) = map.get("args") {
184                out.insert("args".to_string(), dynamic_to_v1_0(args));
185            }
186            Value::Object(out)
187        }
188        Value::Object(map) => Value::Object(
189            map.iter()
190                .map(|(key, value)| {
191                    let key = if key.starts_with('@') { format!("@{key}") } else { key.clone() };
192                    (key, dynamic_to_v1_0(value))
193                })
194                .collect(),
195        ),
196        Value::Array(items) => Value::Array(items.iter().map(dynamic_to_v1_0).collect()),
197        other => other.clone(),
198    }
199}
200
201/// One component of a drawing in `catalog`, in 1.0's syntax.
202///
203/// # Example
204///
205/// ```rust
206/// use adk_surface::genui::{Catalog, component_to_v1_0};
207/// use serde_json::json;
208///
209/// let text = json!({ "id": "t", "component": "Text", "text": { "path": "/title" },
210///     "accessibility": { "label": "Title" } });
211/// let wire = component_to_v1_0(&text, Catalog::forms());
212/// assert_eq!(wire["text"], json!({ "@path": "/title" }));
213/// assert_eq!(wire["@accessibility"], json!({ "label": "Title" }));
214/// ```
215pub fn component_to_v1_0(component: &Value, catalog: &Catalog) -> Value {
216    let Value::Object(map) = component else {
217        return component.clone();
218    };
219    let mut out = Map::new();
220    for (key, value) in map {
221        match key.as_str() {
222            "id" | "component" => {
223                out.insert(key.clone(), value.clone());
224            }
225            "accessibility" | "checks" => {
226                out.insert(format!("@{key}"), dynamic_to_v1_0(value));
227            }
228            _ => {
229                out.insert(key.clone(), dynamic_to_v1_0(value));
230            }
231        }
232    }
233    let kind = map.get("component").and_then(Value::as_str).unwrap_or_default();
234    let from = component_catalog(catalog, kind);
235    if from != FORMS_CATALOG_ID {
236        out.insert("@catalogId".to_string(), json!(from));
237    }
238    Value::Object(out)
239}
240
241/// A drawing's messages in `version`'s wire shape. In 1.0, a surface's `createSurface`, its
242/// first `updateComponents` and a whole-model `updateDataModel` that follow it become one
243/// `createSurface`; the surface's default catalog is `forms`, and each extension component
244/// names its own.
245///
246/// # Example
247///
248/// ```rust
249/// use adk_surface::genui::{A2uiMessage, A2uiVersion, Catalog, to_wire};
250/// use serde_json::json;
251///
252/// let messages = vec![
253///     A2uiMessage::create_surface("s"),
254///     A2uiMessage::update_components("s", vec![json!({ "id": "root", "component": "Text", "text": "Hi" })]),
255///     A2uiMessage::update_data_model("s", None, Some(json!({}))),
256/// ];
257/// let wire = to_wire(&messages, Catalog::forms(), A2uiVersion::V1_0);
258/// assert_eq!(wire.len(), 1);
259/// assert_eq!(wire[0]["version"], "1.0");
260/// assert_eq!(wire[0]["createSurface"]["components"][0]["text"], "Hi");
261/// assert_eq!(to_wire(&messages, Catalog::forms(), A2uiVersion::V0_9_1).len(), 3);
262/// ```
263pub fn to_wire(messages: &[A2uiMessage], catalog: &Catalog, version: A2uiVersion) -> Vec<Value> {
264    if version == A2uiVersion::V0_9_1 {
265        return messages
266            .iter()
267            .map(|message| serde_json::to_value(message).unwrap_or_default())
268            .collect();
269    }
270    let mut out: Vec<Value> = Vec::new();
271    let mut index = 0;
272    while index < messages.len() {
273        let message = &messages[index];
274        index += 1;
275        let body = match &message.body {
276            A2uiBody::CreateSurface(create) => {
277                let mut body = Map::new();
278                body.insert("surfaceId".to_string(), json!(create.surface_id));
279                body.insert("catalogId".to_string(), json!(FORMS_CATALOG_ID));
280                if let Some(send) = create.send_data_model {
281                    body.insert("sendDataModel".to_string(), json!(send));
282                }
283                body.insert(
284                    "metadata".to_string(),
285                    json!({ "extensions": {
286                        DISPLAY_ONLY_EXTENSION: { "version": DISPLAY_ONLY_EXTENSION_VERSION }
287                    } }),
288                );
289                // One message for a new surface: its components and whole data model inline.
290                if let Some(A2uiBody::UpdateComponents(update)) =
291                    messages.get(index).map(|m| &m.body)
292                    && update.surface_id == create.surface_id
293                {
294                    body.insert(
295                        "components".to_string(),
296                        Value::Array(
297                            update
298                                .components
299                                .iter()
300                                .map(|c| component_to_v1_0(c, catalog))
301                                .collect(),
302                        ),
303                    );
304                    index += 1;
305                    if let Some(A2uiBody::UpdateDataModel(data)) =
306                        messages.get(index).map(|m| &m.body)
307                        && data.surface_id == create.surface_id
308                        && data.path.as_deref().is_none_or(|path| path == "/")
309                        && let Some(value) = &data.value
310                    {
311                        body.insert("dataModel".to_string(), value.clone());
312                        index += 1;
313                    }
314                }
315                json!({ "createSurface": body })
316            }
317            A2uiBody::UpdateComponents(update) => json!({
318                "updateComponents": {
319                    "surfaceId": update.surface_id,
320                    "components": update
321                        .components
322                        .iter()
323                        .map(|component| component_to_v1_0(component, catalog))
324                        .collect::<Vec<_>>(),
325                }
326            }),
327            A2uiBody::UpdateDataModel(data) => {
328                let mut body = Map::new();
329                body.insert("surfaceId".to_string(), json!(data.surface_id));
330                if let Some(path) = &data.path {
331                    body.insert("path".to_string(), json!(path));
332                }
333                body.insert("value".to_string(), data.value.clone().unwrap_or(Value::Null));
334                json!({ "updateDataModel": body })
335            }
336            A2uiBody::DeleteSurface(delete) => {
337                json!({ "deleteSurface": { "surfaceId": delete.surface_id } })
338            }
339        };
340        let mut body = body;
341        body["version"] = json!(A2uiVersion::V1_0.wire());
342        out.push(body);
343    }
344    out
345}
346
347/// A dynamic value read from 1.0's syntax into the internal form.
348fn dynamic_from_v1_0(value: &Value, catalog: &Catalog, at: &str) -> Result<Value, WireError> {
349    match value {
350        Value::Object(map) if map.contains_key("@path") => {
351            let path = map.get("@path").filter(|path| path.is_string()).ok_or_else(|| {
352                WireError::new(at, "@path is a data model path, a string such as \"/total\"")
353            })?;
354            if map.len() > 1 {
355                return Err(WireError::new(at, "a binding has only @path"));
356            }
357            Ok(json!({ "path": path }))
358        }
359        Value::Object(map) if map.contains_key("@call") => {
360            let call = map.get("@call").and_then(Value::as_str).ok_or_else(|| {
361                WireError::new(
362                    at,
363                    "@call names a catalog function, a string such as \"formatNumber\"",
364                )
365            })?;
366            if call == "@index" {
367                return Err(WireError::new(
368                    at,
369                    "@index is not available in a drawing; put the index in the data model instead",
370                ));
371            }
372            let mut out = Map::new();
373            out.insert("call".to_string(), json!(call));
374            for (key, value) in map {
375                match key.as_str() {
376                    "@call" => {}
377                    "args" => {
378                        out.insert(
379                            "args".to_string(),
380                            dynamic_from_v1_0(value, catalog, &format!("{at}/args"))?,
381                        );
382                    }
383                    "catalogId" => {
384                        let id = value.as_str().unwrap_or_default();
385                        if id != FORMS_CATALOG_ID && id != catalog.id() {
386                            return Err(WireError::new(
387                                &format!("{at}/catalogId"),
388                                format!("functions come from {FORMS_CATALOG_ID}, not {id}"),
389                            ));
390                        }
391                    }
392                    other => {
393                        return Err(WireError::new(
394                            at,
395                            format!("a function call has @call, args and catalogId, not {other}"),
396                        ));
397                    }
398                }
399            }
400            Ok(Value::Object(out))
401        }
402        Value::Object(map) => {
403            let mut out = Map::new();
404            for (key, value) in map {
405                let here = format!("{at}/{}", key.replace('~', "~0").replace('/', "~1"));
406                let key = if let Some(literal) = key.strip_prefix("@@") {
407                    format!("@{literal}")
408                } else if key.starts_with('@') {
409                    return Err(WireError::new(
410                        &here,
411                        format!(
412                            "{key} is a reserved key here; write \"@{key}\" for a literal \"{key}\""
413                        ),
414                    ));
415                } else {
416                    key.clone()
417                };
418                out.insert(key, dynamic_from_v1_0(value, catalog, &here)?);
419            }
420            if is_binding(&out) || is_call(&out) {
421                return Err(WireError::new(
422                    at,
423                    "a literal object with a `path` or `call` key cannot be drawn: bind it from the \
424                     data model instead",
425                ));
426            }
427            Ok(Value::Object(out))
428        }
429        Value::Array(items) => items
430            .iter()
431            .enumerate()
432            .map(|(index, item)| dynamic_from_v1_0(item, catalog, &format!("{at}/{index}")))
433            .collect(),
434        other => Ok(other.clone()),
435    }
436}
437
438/// One component read from 1.0's syntax into the internal form of a drawing in `catalog`.
439fn component_from_v1_0(component: &Value, catalog: &Catalog, at: &str) -> Result<Value, WireError> {
440    let Value::Object(map) = component else {
441        return Err(WireError::new(at, "a component is an object with an id and a component"));
442    };
443    let kind = map.get("component").and_then(Value::as_str).unwrap_or_default();
444    let mut out = Map::new();
445    for (key, value) in map {
446        let here = format!("{at}/{key}");
447        match key.as_str() {
448            "id" | "component" => {
449                out.insert(key.clone(), value.clone());
450            }
451            "@accessibility" | "@checks" => {
452                let bare = &key[1..];
453                if map.contains_key(bare) {
454                    return Err(WireError::new(
455                        &here,
456                        format!("a component has {key} or {bare}, not both"),
457                    ));
458                }
459                out.insert(bare.to_string(), dynamic_from_v1_0(value, catalog, &here)?);
460            }
461            "@catalogId" => {
462                let id = value.as_str().unwrap_or_default();
463                let expected = component_catalog(catalog, kind);
464                if id != expected && id != catalog.id() {
465                    return Err(WireError::new(
466                        &here,
467                        format!("{kind} comes from {expected}, not {id}"),
468                    ));
469                }
470            }
471            "@metadata" => {
472                return Err(WireError::new(
473                    &here,
474                    "a drawing carries no extension metadata; leave @metadata out",
475                ));
476            }
477            other if other.starts_with('@') => {
478                return Err(WireError::new(
479                    &here,
480                    format!(
481                        "{other} is not a component key; a component's reserved keys are \
482                             @accessibility, @checks and @catalogId"
483                    ),
484                ));
485            }
486            _ => {
487                out.insert(key.clone(), dynamic_from_v1_0(value, catalog, &here)?);
488            }
489        }
490    }
491    Ok(Value::Object(out))
492}
493
494/// Components written in either version, in the internal form of a drawing in `catalog`:
495/// 1.0's syntax is read when any reserved `@` key appears, and v0.9.1's is kept as it is.
496///
497/// # Errors
498///
499/// Returns a [`WireError`] naming the first value 1.0's syntax does not allow, or that the
500/// internal form would read differently.
501///
502/// # Example
503///
504/// ```rust
505/// use adk_surface::genui::{Catalog, components_in};
506/// use serde_json::json;
507///
508/// let read = components_in(
509///     vec![json!({ "id": "root", "component": "Text", "text": { "@path": "/t" } })],
510///     Catalog::forms(),
511/// )?;
512/// assert_eq!(read[0]["text"], json!({ "path": "/t" }));
513/// # Ok::<(), adk_surface::genui::WireError>(())
514/// ```
515pub fn components_in(components: Vec<Value>, catalog: &Catalog) -> Result<Vec<Value>, WireError> {
516    if !is_v1_0_syntax(&components) {
517        return Ok(components);
518    }
519    components
520        .iter()
521        .enumerate()
522        .map(|(index, component)| component_from_v1_0(component, catalog, &format!("/{index}")))
523        .collect()
524}
525
526/// Checks a 1.0 `createSurface.metadata`: nothing but the display-only claim, which every
527/// drawing this home keeps follows anyway. Any other extension would ask the renderer for
528/// behavior the stored drawing cannot carry, so it is refused rather than dropped.
529fn display_only_claim(metadata: &Value) -> Result<(), WireError> {
530    const AT: &str = "/createSurface/metadata";
531    let refuse = |what: &str| {
532        Err(WireError::new(
533            AT,
534            format!(
535                "a drawing's metadata holds only the {DISPLAY_ONLY_EXTENSION} extension, not {what}"
536            ),
537        ))
538    };
539    let Some(metadata) = metadata.as_object() else { return refuse("a non-object") };
540    if let Some(key) = metadata.keys().find(|key| *key != "extensions") {
541        return refuse(key);
542    }
543    let Some(extensions) = metadata.get("extensions") else { return Ok(()) };
544    let Some(extensions) = extensions.as_object() else { return refuse("a non-object extensions") };
545    match extensions.keys().find(|key| *key != DISPLAY_ONLY_EXTENSION) {
546        Some(key) => refuse(key),
547        None => Ok(()),
548    }
549}
550
551/// One message from the wire, in either version, as internal messages: a 1.0 `createSurface`
552/// that carries components and a data model becomes three.
553///
554/// # Errors
555///
556/// Returns a [`WireError`] for an unknown version, a message `genui` does not read (a function
557/// call or response), or a component 1.0's syntax does not allow.
558///
559/// # Example
560///
561/// ```rust
562/// use adk_surface::genui::{A2uiBody, Catalog, from_wire};
563/// use serde_json::json;
564///
565/// let read = from_wire(
566///     &json!({ "version": "1.0", "createSurface": {
567///         "surfaceId": "s", "components": [{ "id": "root", "component": "Text", "text": "Hi" }],
568///         "dataModel": { "a": 1 } } }),
569///     Catalog::forms(),
570/// )?;
571/// assert_eq!(read.len(), 3);
572/// assert!(matches!(read[1].body, A2uiBody::UpdateComponents(_)));
573/// # Ok::<(), adk_surface::genui::WireError>(())
574/// ```
575pub fn from_wire(message: &Value, catalog: &Catalog) -> Result<Vec<A2uiMessage>, WireError> {
576    let version =
577        message.get("version").and_then(Value::as_str).and_then(A2uiVersion::of_wire).ok_or_else(
578            || WireError::new("/version", "an A2UI message names version \"1.0\" or \"v0.9.1\""),
579        )?;
580    if version == A2uiVersion::V0_9_1 {
581        let read: A2uiMessage = serde_json::from_value(message.clone())
582            .map_err(|error| WireError::new("/", error.to_string()))?;
583        return Ok(vec![read]);
584    }
585    let Value::Object(map) = message else {
586        return Err(WireError::new("/", "an A2UI message is an object"));
587    };
588    let mut bodies = map.iter().filter(|(key, _)| key.as_str() != "version");
589    let (Some((kind, body)), None) = (bodies.next(), bodies.next()) else {
590        return Err(WireError::new("/", "an A2UI message has its version and one body"));
591    };
592    let surface = |body: &Value| -> Result<String, WireError> {
593        body.get("surfaceId")
594            .and_then(Value::as_str)
595            .map(str::to_string)
596            .ok_or_else(|| WireError::new(&format!("/{kind}/surfaceId"), "a surfaceId is required"))
597    };
598    let components = |body: &Value, at: &str| -> Result<Vec<Value>, WireError> {
599        body.get("components")
600            .and_then(Value::as_array)
601            .ok_or_else(|| WireError::new(at, "components is a list"))?
602            .iter()
603            .enumerate()
604            .map(|(index, component)| {
605                component_from_v1_0(component, catalog, &format!("{at}/{index}"))
606            })
607            .collect()
608    };
609    match kind.as_str() {
610        "createSurface" => {
611            let surface_id = surface(body)?;
612            if body.get("theme").is_some() {
613                return Err(WireError::new("/createSurface/theme", "A2UI 1.0 has no theme"));
614            }
615            if let Some(metadata) = body.get("metadata") {
616                display_only_claim(metadata)?;
617            }
618            if let Some(id) = body.get("catalogId").and_then(Value::as_str)
619                && id != FORMS_CATALOG_ID
620                && id != catalog.id()
621            {
622                return Err(WireError::new(
623                    "/createSurface/catalogId",
624                    format!("this home draws {FORMS_CATALOG_ID} and {}, not {id}", catalog.id()),
625                ));
626            }
627            let mut create = A2uiMessage::create_surface(surface_id.clone());
628            if let A2uiBody::CreateSurface(inner) = &mut create.body {
629                inner.catalog_id = catalog.id().to_string();
630                inner.send_data_model = body.get("sendDataModel").and_then(Value::as_bool);
631            }
632            let mut out = vec![create];
633            if body.get("components").is_some() {
634                out.push(A2uiMessage::update_components(
635                    surface_id.clone(),
636                    components(body, "/createSurface/components")?,
637                ));
638            }
639            if let Some(model) = body.get("dataModel") {
640                out.push(A2uiMessage::update_data_model(surface_id, None, Some(model.clone())));
641            }
642            Ok(out)
643        }
644        "updateComponents" => Ok(vec![A2uiMessage::update_components(
645            surface(body)?,
646            components(body, "/updateComponents/components")?,
647        )]),
648        "updateDataModel" => {
649            if body.get("value").is_none() {
650                return Err(WireError::new(
651                    "/updateDataModel/value",
652                    "A2UI 1.0 requires value; null removes the path",
653                ));
654            }
655            let value = body.get("value").filter(|value| !value.is_null()).cloned();
656            let path = body.get("path").and_then(Value::as_str).map(str::to_string);
657            Ok(vec![A2uiMessage::update_data_model(surface(body)?, path, value)])
658        }
659        "deleteSurface" => Ok(vec![A2uiMessage::delete_surface(surface(body)?)]),
660        function if super::functions::FUNCTION_MESSAGES.contains(&function) => Err(WireError::new(
661            &format!("/{function}"),
662            format!(
663                "{function} is a function call or its answer, not part of a drawing: read it \
664                 with read_function_message"
665            ),
666        )),
667        other => Err(WireError::new(
668            &format!("/{other}"),
669            format!("{other} is not a message a drawing is made of"),
670        )),
671    }
672}
673
674#[cfg(test)]
675mod tests {
676    use super::*;
677
678    fn drawing() -> Vec<A2uiMessage> {
679        vec![
680            A2uiMessage::create_surface("s"),
681            A2uiMessage::update_components(
682                "s",
683                vec![
684                    json!({ "id": "root", "component": "Column", "children": ["t", "list"] }),
685                    json!({ "id": "t", "component": "Text",
686                        "text": { "call": "formatString", "args": { "value": "Hi ${/name}" }, "returnType": "string" },
687                        "accessibility": { "label": { "path": "/name" } } }),
688                    json!({ "id": "list", "component": "List",
689                        "children": { "componentId": "row", "path": "/rows" } }),
690                    json!({ "id": "row", "component": "Text", "text": { "path": "label" } }),
691                    json!({ "id": "f", "component": "TextField", "label": "Name", "value": { "path": "/name" },
692                        "checks": [{ "condition": { "call": "required", "args": { "value": { "path": "/name" } } },
693                            "message": "Required" }] }),
694                ],
695            ),
696            A2uiMessage::update_data_model("s", None, Some(json!({ "name": "Ana", "rows": [] }))),
697            A2uiMessage::update_data_model("s", Some("/name".to_string()), None),
698        ]
699    }
700
701    #[test]
702    fn a_drawing_is_written_in_1_0_with_one_create_and_reserved_keys() {
703        let wire = to_wire(&drawing(), Catalog::forms(), A2uiVersion::V1_0);
704        assert_eq!(wire.len(), 2, "{wire:#?}");
705        let create = &wire[0]["createSurface"];
706        assert_eq!(wire[0]["version"], "1.0");
707        assert_eq!(create["catalogId"], FORMS_CATALOG_ID);
708        assert_eq!(
709            create["metadata"],
710            json!({ "extensions": { "adkrust_display_only": { "version": "1.0" } } })
711        );
712        assert_eq!(create["dataModel"]["name"], "Ana");
713        let components = create["components"].as_array().unwrap();
714        assert_eq!(components[1]["text"]["@call"], "formatString");
715        assert!(components[1]["text"].get("returnType").is_none());
716        assert_eq!(components[1]["@accessibility"]["label"], json!({ "@path": "/name" }));
717        // A template keeps its plain `path`; a relative binding takes the prefix.
718        assert_eq!(components[2]["children"], json!({ "componentId": "row", "path": "/rows" }));
719        assert_eq!(components[3]["text"], json!({ "@path": "label" }));
720        assert_eq!(
721            components[4]["@checks"][0]["condition"]["args"]["value"],
722            json!({ "@path": "/name" })
723        );
724        // A removal writes value null, which 1.0 requires.
725        assert_eq!(
726            wire[1]["updateDataModel"],
727            json!({ "surfaceId": "s", "path": "/name", "value": null })
728        );
729    }
730
731    #[test]
732    fn what_1_0_writes_reads_back_to_the_same_drawing() {
733        let original = drawing();
734        let wire = to_wire(&original, Catalog::forms(), A2uiVersion::V1_0);
735        let read: Vec<A2uiMessage> =
736            wire.iter().flat_map(|message| from_wire(message, Catalog::forms()).unwrap()).collect();
737        // Only the call's returnType, which 1.0 leaves to the catalog, is not carried.
738        let mut expected = original;
739        if let A2uiBody::UpdateComponents(update) = &mut expected[1].body {
740            update.components[1]["text"].as_object_mut().unwrap().remove("returnType");
741        }
742        assert_eq!(read, expected);
743    }
744
745    #[test]
746    fn v0_9_1_is_written_as_stored() {
747        let messages = drawing();
748        let wire = to_wire(&messages, Catalog::forms(), A2uiVersion::V0_9_1);
749        assert_eq!(wire.len(), 4);
750        assert_eq!(wire[0]["version"], "v0.9.1");
751        assert_eq!(from_wire(&wire[1], Catalog::forms()).unwrap()[0], messages[1]);
752    }
753
754    #[test]
755    fn literal_at_keys_are_escaped_and_unescaped() {
756        let component =
757            json!({ "id": "t", "component": "Text", "text": "x", "extra": { "@type": "a" } });
758        let wire = component_to_v1_0(&component, Catalog::forms());
759        assert_eq!(wire["extra"], json!({ "@@type": "a" }));
760        let read = components_in(vec![wire], Catalog::forms()).unwrap();
761        assert_eq!(read[0]["extra"], json!({ "@type": "a" }));
762    }
763
764    #[test]
765    fn reading_1_0_refuses_what_the_internal_form_would_misread() {
766        for (component, says) in [
767            (
768                json!({ "id": "t", "component": "Text", "text": { "@path": "/a" }, "x": { "path": "/b" } }),
769                "literal object",
770            ),
771            (
772                json!({ "id": "t", "component": "Text", "text": { "@path": "/a" }, "x": { "call": "y" } }),
773                "literal object",
774            ),
775            (
776                json!({ "id": "t", "component": "Text", "text": { "@path": "/a" }, "x": { "@type": "a" } }),
777                "reserved key",
778            ),
779            (json!({ "id": "t", "component": "Text", "text": { "@call": "@index" } }), "@index"),
780            (
781                json!({ "id": "t", "component": "Text", "text": "a", "@metadata": { "extensions": {} } }),
782                "metadata",
783            ),
784            (
785                json!({ "id": "t", "component": "Text", "text": "a", "@style": 1 }),
786                "not a component key",
787            ),
788            (
789                json!({ "id": "t", "component": "Text", "text": "a", "@catalogId": "https://x.test/c.json" }),
790                "comes from",
791            ),
792            (
793                json!({ "id": "t", "component": "Text", "text": "a", "@checks": [], "checks": [] }),
794                "not both",
795            ),
796        ] {
797            let error = components_in(vec![component.clone()], Catalog::forms()).unwrap_err();
798            assert!(error.to_string().contains(says), "{component}: {error}");
799        }
800    }
801
802    #[test]
803    fn reading_1_0_messages_refuses_theme_metadata_and_missing_values() {
804        for (message, says) in [
805            (
806                json!({ "version": "1.0", "createSurface": { "surfaceId": "s", "theme": {} } }),
807                "theme",
808            ),
809            (
810                json!({ "version": "1.0", "createSurface": { "surfaceId": "s", "metadata": { "extensions": { "org_example_theme": {} } } } }),
811                "not org_example_theme",
812            ),
813            (
814                json!({ "version": "1.0", "createSurface": { "surfaceId": "s", "metadata": { "theme": {} } } }),
815                "not theme",
816            ),
817            (
818                json!({ "version": "1.0", "createSurface": { "surfaceId": "s", "catalogId": "https://x.test/c.json" } }),
819                "not https://x.test",
820            ),
821            (
822                json!({ "version": "1.0", "updateDataModel": { "surfaceId": "s", "path": "/a" } }),
823                "requires value",
824            ),
825            (
826                json!({ "version": "1.0", "callRendererFunction": { "functionCallId": "1" } }),
827                "read_function_message",
828            ),
829            (json!({ "version": "2.0", "deleteSurface": { "surfaceId": "s" } }), "version"),
830        ] {
831            let error = from_wire(&message, Catalog::forms()).unwrap_err();
832            assert!(error.to_string().contains(says), "{message}: {error}");
833        }
834    }
835
836    #[test]
837    fn versions_are_named_as_the_wire_names_them() {
838        for (name, version) in [
839            ("v0.9", A2uiVersion::V0_9_1),
840            ("v0.9.1", A2uiVersion::V0_9_1),
841            ("1.0", A2uiVersion::V1_0),
842        ] {
843            assert_eq!(A2uiVersion::of_wire(name), Some(version));
844        }
845        assert_eq!(A2uiVersion::of_wire("0.8"), None);
846        assert_eq!(A2uiVersion::V0_9_1.capability_key(), "v0.9");
847        assert_eq!(A2uiVersion::V1_0.capability_key(), "1.0");
848    }
849}