Skip to main content

adk_surface/genui/
draw.rs

1//! The render tools (spec 3.3 §6.1 `genui`, §7.4 rule 5): what an agent draws with, each
2//! drawing checked whole by the [`Validator`] and recorded under [`DRAWN_STATE_KEY`].
3
4use std::collections::{HashMap, VecDeque};
5use std::fmt::Write as _;
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, Instant};
8
9use adk_core::{
10    AdkError, DRAW_TOOL_NAMES, ErrorCategory, ErrorComponent, ReadonlyContext, Result,
11    TOOL_INVALID_ARGUMENTS_CODE, Tool, ToolContext, ToolEffect, Toolset,
12};
13use async_trait::async_trait;
14use schemars::JsonSchema;
15use serde::de::DeserializeOwned;
16use serde::{Deserialize, Serialize};
17use serde_json::{Value, json};
18use sha2::{Digest, Sha256};
19
20use super::a2ui::{A2uiBody, A2uiMessage, DataModel};
21use super::catalog::{Catalog, FORMS_CATALOG_ID};
22use super::drawn::DrawnKind;
23use super::validate::{DrawRefusal, DrawnAction, SurfaceDraft, Validator};
24
25/// The reserved session state key every drawing writes, `{ surfaceId, version, digest }`:
26/// the proof that a drawing tool result came from these tools, checked against the digest of
27/// the result's `drawn` record (spec 3.3 §6.1 `genui`).
28pub const DRAWN_STATE_KEY: &str = "adk.surface.drawn";
29
30/// The reserved session state key a refused drawing writes, its [`DrawRefusal`]: the proof
31/// that a render tool's error came from these tools, so the thread shows the refusal's plain
32/// notice and an MCP server's tool of the same name stays an ordinary failed result
33/// (spec 3.3 §7.4 rule 5).
34pub const REFUSED_STATE_KEY: &str = "adk.surface.refused";
35
36/// The prefix of the session state keys holding the latest version of each surface a
37/// session drew, `adk.surface.versions.<surface id>`, so versions keep rising after a
38/// restart or a compaction.
39const VERSIONS_STATE_KEY: &str = "adk.surface.versions";
40
41/// How many times `patch_surface` may change one surface in a minute. A live view updated
42/// every two seconds fits; a model patching in a loop is told to batch its changes, so the
43/// person's view (and every approval card over it) is not redrawn faster than it can be read.
44pub const MAX_PATCHES_PER_MINUTE: usize = 30;
45
46/// A surface in one session: app, user, session and surface ids.
47type SurfaceKey = (String, String, String, String);
48
49/// What [`DRAWN_STATE_KEY`] holds: the latest drawing of the session.
50///
51/// # Example
52///
53/// ```rust
54/// use adk_surface::genui::DrawnRecord;
55///
56/// let record = DrawnRecord { surface_id: "invoice-10".into(), version: 2, digest: "ab".into() };
57/// assert_eq!(serde_json::to_value(&record).unwrap()["surfaceId"], "invoice-10");
58/// ```
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
60#[serde(rename_all = "camelCase")]
61pub struct DrawnRecord {
62    /// The surface drawn.
63    pub surface_id: String,
64    /// Its version.
65    pub version: u64,
66    /// The SHA-256 of the drawing's [`DrawnEnvelope`], hex.
67    pub digest: String,
68}
69
70/// One drawing as a drawing tool's result records it, under `drawn`: the A2UI messages that
71/// rebuild the whole surface, and the actions its buttons ask for (spec 3.3 §6.1 `genui`).
72///
73/// # Example
74///
75/// ```rust
76/// use adk_surface::genui::{A2uiMessage, DrawnEnvelope, DrawnKind, FORMS_CATALOG_ID};
77///
78/// let envelope = DrawnEnvelope {
79///     surface_id: "s".into(),
80///     version: 1,
81///     kind: DrawnKind::Card,
82///     catalog_id: FORMS_CATALOG_ID.into(),
83///     title: None,
84///     messages: vec![A2uiMessage::create_surface("s")],
85///     actions: Vec::new(),
86///     deleted: false,
87/// };
88/// assert_eq!(envelope.digest(), envelope.clone().digest());
89/// assert_eq!(envelope.digest().len(), 64);
90/// ```
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
92#[serde(rename_all = "camelCase")]
93pub struct DrawnEnvelope {
94    /// The surface.
95    pub surface_id: String,
96    /// Its version: one more than any earlier drawing of the surface in the session.
97    pub version: u64,
98    /// What it is.
99    pub kind: DrawnKind,
100    /// The catalog it was checked against.
101    pub catalog_id: String,
102    /// The title above it.
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub title: Option<String>,
105    /// The A2UI messages that draw it: `createSurface`, `updateComponents` and
106    /// `updateDataModel`, or `deleteSurface`.
107    pub messages: Vec<A2uiMessage>,
108    /// The actions its buttons ask for.
109    #[serde(default, skip_serializing_if = "Vec::is_empty")]
110    pub actions: Vec<DrawnAction>,
111    /// Whether this version removes the surface.
112    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
113    pub deleted: bool,
114}
115
116impl DrawnEnvelope {
117    /// The SHA-256 of the envelope's canonical JSON (keys sorted), hex.
118    pub fn digest(&self) -> String {
119        let mut canonical = String::new();
120        write_canonical(&serde_json::to_value(self).unwrap_or_default(), &mut canonical);
121        let hash = Sha256::digest(canonical.as_bytes());
122        hash.iter().fold(String::with_capacity(64), |mut hex, byte| {
123            let _ = write!(hex, "{byte:02x}");
124            hex
125        })
126    }
127
128    /// The drawing its messages describe, or `None` for a removal.
129    ///
130    /// # Example
131    ///
132    /// ```rust
133    /// use adk_surface::genui::{A2uiMessage, DrawnEnvelope, DrawnKind, FORMS_CATALOG_ID};
134    /// use serde_json::json;
135    ///
136    /// let envelope = DrawnEnvelope {
137    ///     surface_id: "s".into(),
138    ///     version: 1,
139    ///     kind: DrawnKind::Card,
140    ///     catalog_id: FORMS_CATALOG_ID.into(),
141    ///     title: None,
142    ///     messages: vec![
143    ///         A2uiMessage::create_surface("s"),
144    ///         A2uiMessage::update_components(
145    ///             "s",
146    ///             vec![json!({ "id": "root", "component": "Text", "text": { "path": "/t" } })],
147    ///         ),
148    ///         A2uiMessage::update_data_model("s", None, Some(json!({ "t": "Hello" }))),
149    ///     ],
150    ///     actions: Vec::new(),
151    ///     deleted: false,
152    /// };
153    /// assert_eq!(envelope.draft().unwrap().data_model, json!({ "t": "Hello" }));
154    /// ```
155    pub fn draft(&self) -> Option<SurfaceDraft> {
156        if self.deleted {
157            return None;
158        }
159        let mut components = Vec::new();
160        let mut model = DataModel::default();
161        for message in
162            self.messages.iter().filter(|message| message.surface_id() == self.surface_id)
163        {
164            match &message.body {
165                A2uiBody::CreateSurface(_) => {}
166                A2uiBody::UpdateComponents(update) => components.clone_from(&update.components),
167                A2uiBody::UpdateDataModel(update) => {
168                    model.apply(update.path.as_deref(), update.value.clone()).ok()?;
169                }
170                A2uiBody::DeleteSurface(_) => return None,
171            }
172        }
173        Some(SurfaceDraft {
174            surface_id: self.surface_id.clone(),
175            kind: self.kind,
176            title: self.title.clone(),
177            components,
178            data_model: model.value().clone(),
179            actions: self.actions.clone(),
180        })
181    }
182
183    /// The envelope a drawing tool's `response` records under `drawn`, if any.
184    pub fn from_response(response: &Value) -> Option<Self> {
185        serde_json::from_value(response.get("drawn")?.clone()).ok()
186    }
187
188    /// The A2UI messages that turn a renderer showing `previous` into one showing this
189    /// version: one `updateComponents` with the components that are new or changed, then an
190    /// `updateDataModel` for each data path that changed (no value where one was removed).
191    /// Empty when nothing changed. An envelope keeps the whole drawing, so its digest and
192    /// what a person approves stay whole; a transport that knows which version a renderer
193    /// holds (a socket, an A2A task) sends this instead of the whole drawing.
194    ///
195    /// A2UI has no message that removes a component: a component dropped from the drawing is
196    /// no longer referenced by its changed parent, so the renderer stops drawing it.
197    ///
198    /// `None` when there is no sound base: either is a removal, they are different surfaces
199    /// or catalogs, or `previous` is not older.
200    ///
201    /// # Example
202    ///
203    /// ```rust
204    /// use adk_surface::genui::{A2uiBody, A2uiMessage, DrawnEnvelope, DrawnKind, FORMS_CATALOG_ID};
205    /// use serde_json::json;
206    ///
207    /// let version = |n: u64, total: i64| DrawnEnvelope {
208    ///     surface_id: "s".into(), version: n, kind: DrawnKind::Screen,
209    ///     catalog_id: FORMS_CATALOG_ID.into(), title: None,
210    ///     messages: vec![
211    ///         A2uiMessage::create_surface("s"),
212    ///         A2uiMessage::update_components("s", vec![
213    ///             json!({ "id": "root", "component": "Text", "text": { "path": "/total" } })]),
214    ///         A2uiMessage::update_data_model("s", None, Some(json!({ "total": total, "currency": "USD" }))),
215    ///     ],
216    ///     actions: Vec::new(), deleted: false,
217    /// };
218    /// let delta = version(2, 12).delta_from(&version(1, 10)).unwrap();
219    /// assert_eq!(delta.len(), 1);
220    /// let A2uiBody::UpdateDataModel(update) = &delta[0].body else { panic!() };
221    /// assert_eq!(update.path.as_deref(), Some("/total"));
222    /// assert_eq!(update.value, Some(json!(12)));
223    /// ```
224    pub fn delta_from(&self, previous: &DrawnEnvelope) -> Option<Vec<A2uiMessage>> {
225        if self.surface_id != previous.surface_id
226            || self.catalog_id != previous.catalog_id
227            || self.version <= previous.version
228        {
229            return None;
230        }
231        let (now, before) = (self.draft()?, previous.draft()?);
232        let mut messages = Vec::new();
233        let changed: Vec<Value> = now
234            .components
235            .iter()
236            .filter(|component| !before.components.contains(component))
237            .cloned()
238            .collect();
239        if !changed.is_empty() {
240            messages.push(A2uiMessage::update_components(self.surface_id.clone(), changed));
241        }
242        let mut paths = Vec::new();
243        data_delta(&before.data_model, &now.data_model, String::new(), &mut paths);
244        for (path, value) in paths {
245            let path = if path.is_empty() { None } else { Some(path) };
246            messages.push(A2uiMessage::update_data_model(self.surface_id.clone(), path, value));
247        }
248        Some(messages)
249    }
250
251    /// The envelope of `draft`, at `version`.
252    fn of(draft: &SurfaceDraft, version: u64, catalog_id: &str) -> Self {
253        let surface = draft.surface_id.clone();
254        let data_model = (!draft.data_model.is_null()).then(|| draft.data_model.clone());
255        let mut create = A2uiMessage::create_surface(surface.clone());
256        if let A2uiBody::CreateSurface(body) = &mut create.body {
257            body.catalog_id = catalog_id.to_string();
258        }
259        Self {
260            surface_id: surface.clone(),
261            version,
262            kind: draft.kind,
263            catalog_id: catalog_id.to_string(),
264            title: draft.title.clone(),
265            messages: vec![
266                create,
267                A2uiMessage::update_components(surface.clone(), draft.components.clone()),
268                A2uiMessage::update_data_model(surface, None, data_model),
269            ],
270            actions: draft.actions.clone(),
271            deleted: false,
272        }
273    }
274}
275
276/// The data changes that turn `before` into `now`, as (JSON pointer, new value) in order: an
277/// object is compared key by key, anything else is replaced whole, and a removed key has no
278/// value. The empty pointer is the whole model.
279fn data_delta(before: &Value, now: &Value, at: String, out: &mut Vec<(String, Option<Value>)>) {
280    if before == now {
281        return;
282    }
283    match (before, now) {
284        (Value::Object(before), Value::Object(now)) => {
285            for (key, old) in before {
286                let path = format!("{at}/{}", key.replace('~', "~0").replace('/', "~1"));
287                match now.get(key) {
288                    Some(new) => data_delta(old, new, path, out),
289                    None => out.push((path, None)),
290                }
291            }
292            for (key, new) in now.iter().filter(|(key, _)| !before.contains_key(*key)) {
293                let path = format!("{at}/{}", key.replace('~', "~0").replace('/', "~1"));
294                out.push((path, Some(new.clone())));
295            }
296        }
297        (_, Value::Null) => out.push((at, None)),
298        _ => out.push((at, Some(now.clone()))),
299    }
300}
301
302/// Writes `value` as JSON with every object's keys sorted.
303fn write_canonical(value: &Value, out: &mut String) {
304    match value {
305        Value::Object(map) => {
306            out.push('{');
307            let mut keys: Vec<&String> = map.keys().collect();
308            keys.sort();
309            for (index, key) in keys.into_iter().enumerate() {
310                if index > 0 {
311                    out.push(',');
312                }
313                out.push_str(&Value::String(key.clone()).to_string());
314                out.push(':');
315                write_canonical(&map[key], out);
316            }
317            out.push('}');
318        }
319        Value::Array(items) => {
320            out.push('[');
321            for (index, item) in items.iter().enumerate() {
322                if index > 0 {
323                    out.push(',');
324                }
325                write_canonical(item, out);
326            }
327            out.push(']');
328        }
329        scalar => out.push_str(&scalar.to_string()),
330    }
331}
332
333/// The render tools, bound to one catalog through their [`Validator`] (spec 3.3 §6.1
334/// `genui`): `render_form`, `render_card`, `render_table`, `render_screen`, `patch_surface`
335/// and `delete_surface`.
336///
337/// Every tool is read-only and safe to run beside others: drawing changes nothing but what
338/// the person's threads show, and a form's Send asks the person before anything runs. Each
339/// result records the drawing under `drawn` and writes [`DRAWN_STATE_KEY`]; a refused
340/// drawing is a tool error whose message says why in plain words.
341///
342/// # Example
343///
344/// ```rust
345/// use adk_core::Tool;
346/// use adk_surface::genui::DrawToolset;
347///
348/// let tools = DrawToolset::forms().tools();
349/// let names: Vec<&str> = tools.iter().map(|tool| tool.name()).collect();
350/// assert_eq!(names, adk_core::DRAW_TOOL_NAMES);
351/// assert!(tools.iter().all(|tool| tool.is_read_only() && tool.is_concurrency_safe()));
352/// ```
353#[derive(Debug, Clone)]
354pub struct DrawToolset {
355    shared: Arc<Shared>,
356}
357
358#[derive(Debug)]
359struct Shared {
360    validator: Validator,
361    /// Versions given out in this process, by app, user, session and surface, so drawings
362    /// made side by side in one turn get their own.
363    issued: Mutex<HashMap<SurfaceKey, u64>>,
364    /// When each surface was patched in the last minute, by app, user, session and surface.
365    patched: Mutex<HashMap<SurfaceKey, VecDeque<Instant>>>,
366    /// What `render_screen` tells the model: the catalog's components, and each extension
367    /// component's usage.
368    screen_description: String,
369    /// `render_screen`'s parameters, its components described by the catalog.
370    screen_schema: Value,
371}
372
373impl DrawToolset {
374    /// Render tools that check every drawing with `validator`, in its catalog: `forms`, or an
375    /// extension catalog ([`Catalog::extend`]), whose components `render_screen` draws and
376    /// describes to the model. The tools keep their names in every catalog, so give an agent
377    /// one `DrawToolset`.
378    pub fn new(validator: Validator) -> Self {
379        let catalog = validator.catalog();
380        Self {
381            shared: Arc::new(Shared {
382                screen_description: screen_description(catalog),
383                screen_schema: screen_schema(catalog),
384                validator,
385                issued: Mutex::new(HashMap::new()),
386                patched: Mutex::new(HashMap::new()),
387            }),
388        }
389    }
390
391    /// Render tools on the `forms` 1.0 catalog.
392    pub fn forms() -> Self {
393        Self::new(Validator::forms())
394    }
395
396    /// The catalog these tools draw in: register it with the engine that shows the drawings
397    /// (`SurfaceEngineBuilder::with_catalog`).
398    pub fn catalog(&self) -> &'static Catalog {
399        self.shared.validator.catalog()
400    }
401
402    /// The tools.
403    pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
404        [Op::Form, Op::Card, Op::Table, Op::Screen, Op::Patch, Op::Delete]
405            .into_iter()
406            .map(|op| Arc::new(DrawTool { op, shared: Arc::clone(&self.shared) }) as Arc<dyn Tool>)
407            .collect()
408    }
409}
410
411#[async_trait]
412impl Toolset for DrawToolset {
413    fn name(&self) -> &str {
414        "genui"
415    }
416
417    async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
418        Ok(DrawToolset::tools(self))
419    }
420}
421
422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423enum Op {
424    Form,
425    Card,
426    Table,
427    Screen,
428    Patch,
429    Delete,
430}
431
432impl Op {
433    /// The tool's name, one of [`DRAW_TOOL_NAMES`].
434    fn name(self) -> &'static str {
435        match self {
436            Self::Form => "render_form",
437            Self::Card => "render_card",
438            Self::Table => "render_table",
439            Self::Screen => "render_screen",
440            Self::Patch => "patch_surface",
441            Self::Delete => "delete_surface",
442        }
443    }
444}
445
446struct DrawTool {
447    op: Op,
448    shared: Arc<Shared>,
449}
450
451/// A field of a form.
452#[derive(Debug, Clone, Deserialize, JsonSchema)]
453#[serde(rename_all = "camelCase", deny_unknown_fields)]
454struct FormField {
455    /// The field's name: letters, digits, `_` or `-`. Its value is at the data path `/<name>`.
456    name: String,
457    /// What the person reads beside it.
458    label: String,
459    /// `text` (default), `longText`, `number`, `email`, `date`, `checkbox` or `choice`.
460    #[serde(rename = "type", default)]
461    field_type: FieldType,
462    /// The value it starts with.
463    #[serde(default)]
464    value: Option<Value>,
465    /// Whether the person must fill it in.
466    #[serde(default)]
467    required: bool,
468    /// The choices of a `choice` field.
469    #[serde(default)]
470    options: Vec<ChoiceOption>,
471}
472
473#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, JsonSchema)]
474#[serde(rename_all = "camelCase")]
475enum FieldType {
476    #[default]
477    Text,
478    LongText,
479    Number,
480    Email,
481    Date,
482    Checkbox,
483    Choice,
484}
485
486/// One choice of a `choice` field.
487#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
488#[serde(deny_unknown_fields)]
489struct ChoiceOption {
490    /// What the person reads.
491    label: String,
492    /// The value sent.
493    value: String,
494}
495
496/// `render_form`: fields and the actions their buttons ask for.
497#[derive(Debug, Clone, Deserialize, JsonSchema)]
498#[serde(rename_all = "camelCase", deny_unknown_fields)]
499struct FormParams {
500    /// The surface to draw; drawing it again makes a new version. Defaults to one from the title.
501    #[serde(default)]
502    surface_id: Option<String>,
503    /// The form's title.
504    title: String,
505    /// A line under the title.
506    #[serde(default)]
507    description: Option<String>,
508    /// The fields, in order.
509    fields: Vec<FormField>,
510    /// What the buttons ask for: `{ id, label, tool, args }`, each argument a constant or
511    /// `{ "path": "/<field name>" }`. Sending asks the person before the tool runs.
512    actions: Vec<DrawnAction>,
513}
514
515/// One row of a card.
516#[derive(Debug, Clone, Deserialize, JsonSchema)]
517#[serde(deny_unknown_fields)]
518struct CardRow {
519    /// The row's label.
520    label: String,
521    /// Its value: text or a number.
522    value: Value,
523}
524
525/// `render_card`: label and value rows to read.
526#[derive(Debug, Clone, Deserialize, JsonSchema)]
527#[serde(rename_all = "camelCase", deny_unknown_fields)]
528struct CardParams {
529    /// The surface to draw. Defaults to one from the title.
530    #[serde(default)]
531    surface_id: Option<String>,
532    /// The card's title.
533    title: String,
534    /// The rows, in order.
535    rows: Vec<CardRow>,
536    /// A line under the rows.
537    #[serde(default)]
538    note: Option<String>,
539}
540
541/// `render_table`: columns and rows to read.
542#[derive(Debug, Clone, Deserialize, JsonSchema)]
543#[serde(rename_all = "camelCase", deny_unknown_fields)]
544struct TableParams {
545    /// The surface to draw. Defaults to one from the title.
546    #[serde(default)]
547    surface_id: Option<String>,
548    /// The table's title.
549    title: String,
550    /// The column headings.
551    columns: Vec<String>,
552    /// The rows, each a list of cells: text or numbers.
553    rows: Vec<Vec<Value>>,
554}
555
556/// `render_screen`: A2UI components of the catalog.
557#[derive(Debug, Clone, Deserialize, JsonSchema)]
558#[serde(rename_all = "camelCase", deny_unknown_fields)]
559struct ScreenParams {
560    /// The surface to draw.
561    surface_id: String,
562    /// The title above it.
563    #[serde(default)]
564    title: Option<String>,
565    /// A2UI components of the forms catalog, one with id `root`, in 1.0's syntax
566    /// (`{"@path": "/x"}`) or v0.9.1's (`{"path": "/x"}`).
567    components: Vec<Value>,
568    /// The data model the components bind to.
569    #[serde(default)]
570    data_model: Option<Value>,
571    /// What its buttons ask for, as in `render_form`.
572    #[serde(default)]
573    actions: Vec<DrawnAction>,
574}
575
576/// A change to a drawn surface's data model.
577#[derive(Debug, Clone, Deserialize, JsonSchema)]
578#[serde(deny_unknown_fields)]
579struct DataChange {
580    /// Where, as a data path such as `/total`.
581    path: String,
582    /// The new value; absent or `null` removes it.
583    #[serde(default)]
584    value: Option<Value>,
585}
586
587/// `patch_surface`: changes to a surface drawn earlier, which make its next version.
588#[derive(Debug, Clone, Deserialize, JsonSchema)]
589#[serde(rename_all = "camelCase", deny_unknown_fields)]
590struct PatchParams {
591    /// The surface to change.
592    surface_id: String,
593    /// Data model changes, in order.
594    #[serde(default)]
595    data: Vec<DataChange>,
596    /// Components to add, or to replace by id.
597    #[serde(default)]
598    components: Vec<Value>,
599    /// Ids of components to remove.
600    #[serde(default)]
601    remove: Vec<String>,
602}
603
604/// `delete_surface`: removes a surface drawn earlier.
605#[derive(Debug, Clone, Deserialize, JsonSchema)]
606#[serde(rename_all = "camelCase", deny_unknown_fields)]
607struct DeleteParams {
608    /// The surface to remove.
609    surface_id: String,
610}
611
612/// The forms catalog's `render_screen` description, unchanged for a `forms` toolset.
613const FORMS_SCREEN_DESCRIPTION: &str = "Show the person a screen of A2UI 1.0 (or v0.9.1) components from \
614     the forms catalog (Text, Row, Column, List, Card, Tabs, Divider, Button, TextField, \
615     CheckBox, ChoicePicker, Slider, DateTimeInput), one with id root. Buttons dispatch only \
616     declared actions, which ask the person before a tool runs.";
617
618/// What `render_screen` tells the model about `catalog`.
619fn screen_description(catalog: &Catalog) -> String {
620    if !catalog.is_extension() {
621        return FORMS_SCREEN_DESCRIPTION.to_string();
622    }
623    let added: Vec<&str> = catalog.extensions().collect();
624    let mut out = format!(
625        "Show the person a screen of A2UI 1.0 (or v0.9.1) components from the {} catalog, one with id \
626         root: the forms components (Text, Row, Column, List, Card, Tabs, Divider, Button, \
627         TextField, CheckBox, ChoicePicker, Slider, DateTimeInput) and {}. Bind data with \
628         {{\"@path\": \"/...\"}} (or v0.9.1's {{\"path\": \"/...\"}}) into dataModel.",
629        catalog.label(),
630        added.join(", ")
631    );
632    for usage in catalog.usage() {
633        let _ = write!(out, " {usage}");
634    }
635    out.push_str(
636        " Only buttons dispatch declared actions, which ask the person before a tool runs; the \
637         other components only show.",
638    );
639    out
640}
641
642/// `render_screen`'s parameters, its components described by `catalog`.
643fn screen_schema(catalog: &Catalog) -> Value {
644    let mut schema = schema_of::<ScreenParams>();
645    if catalog.is_extension()
646        && let Some(components) = schema.pointer_mut("/properties/components")
647    {
648        components["description"] = json!(format!(
649            "A2UI components of the {} catalog, one with id `root`, in 1.0's syntax or v0.9.1's.",
650            catalog.label()
651        ));
652    }
653    schema
654}
655
656fn schema_of<T: JsonSchema>() -> Value {
657    let mut schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or_default();
658    if let Some(map) = schema.as_object_mut() {
659        map.remove("$schema");
660        map.remove("title");
661    }
662    schema
663}
664
665fn invalid(tool: &str, error: impl std::fmt::Display) -> AdkError {
666    AdkError::new(
667        ErrorComponent::Tool,
668        ErrorCategory::InvalidInput,
669        TOOL_INVALID_ARGUMENTS_CODE,
670        format!("invalid arguments for '{tool}': {error}. Correct them and call it again."),
671    )
672}
673
674/// A refusal as the tool's error: its message, then the same in A2UI 1.0's `ValidationResult`
675/// shape so an agent can act on its code.
676fn refused(refusal: &DrawRefusal) -> AdkError {
677    let result = serde_json::to_string(&refusal.validation_result()).unwrap_or_default();
678    AdkError::new(
679        ErrorComponent::Tool,
680        ErrorCategory::Forbidden,
681        refusal.code(),
682        format!("{}\nvalidationResult: {result}", refusal.message()),
683    )
684}
685
686fn params<T: DeserializeOwned>(tool: &str, args: Value) -> Result<T> {
687    serde_json::from_value(args).map_err(|error| invalid(tool, error))
688}
689
690/// A surface id from `title`: `<kind>-` and the title's letters and digits, lowercased.
691fn surface_id_from(kind: &str, title: &str) -> String {
692    let mut slug = String::new();
693    for c in title.chars().flat_map(char::to_lowercase) {
694        if c.is_ascii_alphanumeric() {
695            slug.push(c);
696        } else if !slug.ends_with('-') && !slug.is_empty() {
697            slug.push('-');
698        }
699    }
700    let slug: String = slug.trim_end_matches('-').chars().take(48).collect();
701    if slug.is_empty() { kind.to_string() } else { format!("{kind}-{slug}") }
702}
703
704/// The components of a form.
705fn form(params: FormParams) -> Result<SurfaceDraft> {
706    let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("form", &params.title));
707    let mut components = vec![
708        json!({ "id": "root", "component": "Card", "child": "body" }),
709        json!({ "id": "title", "component": "Text", "text": params.title, "variant": "h3" }),
710    ];
711    let mut body = vec![json!("title")];
712    if let Some(description) = params.description {
713        components.push(json!({ "id": "description", "component": "Text", "text": description }));
714        body.push(json!("description"));
715    }
716    let mut model = serde_json::Map::new();
717    for field in params.fields {
718        let name = &field.name;
719        if name.is_empty()
720            || name.len() > 48
721            || !name.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
722        {
723            return Err(invalid(
724                Op::Form.name(),
725                format!("field name '{name}' is not 1 to 48 letters, digits, '_' or '-'"),
726            ));
727        }
728        let id = format!("field-{name}");
729        let path = format!("/{name}");
730        let binding = json!({ "path": path });
731        let mut checks = Vec::new();
732        if field.required {
733            checks.push(json!({
734                "condition": { "call": "required", "args": { "value": binding } },
735                "message": "Fill this in"
736            }));
737        }
738        let (component, initial) = match field.field_type {
739            FieldType::Text | FieldType::Email | FieldType::Number | FieldType::LongText => {
740                let variant = match field.field_type {
741                    FieldType::LongText => "longText",
742                    FieldType::Number => "number",
743                    _ => "shortText",
744                };
745                if field.field_type == FieldType::Email {
746                    checks.push(json!({
747                        "condition": { "call": "email", "args": { "value": binding } },
748                        "message": "Enter an email address"
749                    }));
750                }
751                (
752                    json!({
753                        "id": id, "component": "TextField", "label": field.label,
754                        "value": binding, "variant": variant
755                    }),
756                    json!(""),
757                )
758            }
759            FieldType::Date => (
760                json!({
761                    "id": id, "component": "DateTimeInput", "label": field.label,
762                    "value": binding, "enableDate": true
763                }),
764                json!(""),
765            ),
766            FieldType::Checkbox => (
767                json!({
768                    "id": id, "component": "CheckBox", "label": field.label, "value": binding
769                }),
770                json!(false),
771            ),
772            FieldType::Choice => (
773                json!({
774                    "id": id, "component": "ChoicePicker", "label": field.label, "value": binding,
775                    "options": field.options, "variant": "mutuallyExclusive"
776                }),
777                json!([]),
778            ),
779        };
780        let mut component = component;
781        if !checks.is_empty() {
782            component["checks"] = Value::Array(checks);
783        }
784        model.insert(name.clone(), field.value.unwrap_or(initial));
785        components.push(component);
786        body.push(json!(id));
787    }
788    let mut buttons = Vec::new();
789    for (index, action) in params.actions.iter().enumerate() {
790        let button = format!("action-{}", action.id);
791        let label = format!("action-{}-label", action.id);
792        components.push(json!({ "id": label, "component": "Text", "text": action.label }));
793        components.push(json!({
794            "id": button, "component": "Button", "child": label,
795            "variant": if index == 0 { "primary" } else { "default" },
796            "action": { "event": { "name": action.id } }
797        }));
798        buttons.push(json!(button));
799    }
800    if !buttons.is_empty() {
801        components.push(json!({ "id": "actions", "component": "Row", "children": buttons }));
802        body.push(json!("actions"));
803    }
804    components.push(json!({ "id": "body", "component": "Column", "children": body }));
805    Ok(SurfaceDraft {
806        surface_id,
807        kind: DrawnKind::Form,
808        title: Some(params.title),
809        components,
810        data_model: Value::Object(model),
811        actions: params.actions,
812    })
813}
814
815/// The components of a card.
816fn card(params: CardParams) -> SurfaceDraft {
817    let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("card", &params.title));
818    let mut components = vec![
819        json!({ "id": "root", "component": "Card", "child": "body" }),
820        json!({ "id": "title", "component": "Text", "text": params.title, "variant": "h3" }),
821    ];
822    let mut body = vec![json!("title")];
823    for (index, row) in params.rows.into_iter().enumerate() {
824        let value = match row.value {
825            Value::String(text) => text,
826            other => other.to_string(),
827        };
828        components.push(json!({
829            "id": format!("row-{index}-label"), "component": "Text", "text": row.label,
830            "variant": "caption"
831        }));
832        components.push(
833            json!({ "id": format!("row-{index}-value"), "component": "Text", "text": value }),
834        );
835        components.push(json!({
836            "id": format!("row-{index}"), "component": "Row", "justify": "spaceBetween",
837            "children": [format!("row-{index}-label"), format!("row-{index}-value")]
838        }));
839        body.push(json!(format!("row-{index}")));
840    }
841    if let Some(note) = params.note {
842        components
843            .push(json!({ "id": "note", "component": "Text", "text": note, "variant": "caption" }));
844        body.push(json!("note"));
845    }
846    components.push(json!({ "id": "body", "component": "Column", "children": body }));
847    SurfaceDraft {
848        surface_id,
849        kind: DrawnKind::Card,
850        title: Some(params.title),
851        components,
852        data_model: json!({}),
853        actions: Vec::new(),
854    }
855}
856
857/// The components of a table: a header row, then one row per item of `/rows`, rendered by a
858/// template.
859fn table(params: TableParams) -> SurfaceDraft {
860    let surface_id = params.surface_id.unwrap_or_else(|| surface_id_from("table", &params.title));
861    let mut components = vec![
862        json!({ "id": "root", "component": "Card", "child": "body" }),
863        json!({ "id": "title", "component": "Text", "text": params.title, "variant": "h3" }),
864    ];
865    let mut header = Vec::new();
866    let mut cells = Vec::new();
867    for (index, column) in params.columns.iter().enumerate() {
868        components.push(json!({
869            "id": format!("head-{index}"), "component": "Text", "text": column,
870            "variant": "caption"
871        }));
872        components.push(json!({
873            "id": format!("cell-{index}"), "component": "Text",
874            "text": { "path": index.to_string() }
875        }));
876        header.push(json!(format!("head-{index}")));
877        cells.push(json!(format!("cell-{index}")));
878    }
879    let rows: Vec<Value> = params
880        .rows
881        .into_iter()
882        .map(|row| {
883            Value::Array(
884                row.into_iter()
885                    .map(|cell| match cell {
886                        Value::String(text) => Value::String(text),
887                        other => Value::String(other.to_string()),
888                    })
889                    .collect(),
890            )
891        })
892        .collect();
893    components.push(json!({ "id": "header", "component": "Row", "children": header }));
894    components.push(json!({ "id": "row", "component": "Row", "children": cells }));
895    components.push(json!({
896        "id": "rows", "component": "List",
897        "children": { "componentId": "row", "path": "/rows" }
898    }));
899    components.push(
900        json!({ "id": "body", "component": "Column", "children": ["title", "header", "rows"] }),
901    );
902    SurfaceDraft {
903        surface_id,
904        kind: DrawnKind::Table,
905        title: Some(params.title),
906        components,
907        data_model: json!({ "rows": rows }),
908        actions: Vec::new(),
909    }
910}
911
912impl DrawTool {
913    fn description(&self) -> &str {
914        match self.op {
915            Op::Form => {
916                "Show the person a form in this thread. Each field's value is at the data path \
917                 /<name>. Each action is a button that asks to run one of your tools with \
918                 constants and field values; pressing it never runs the tool: it asks the \
919                 person first, on the home's own card. Never draw decision words or controls \
920                 (Allow once, Deny, Approve...), links, or password fields."
921            }
922            Op::Card => {
923                "Show the person a card in this thread: a title and label and value rows. Plain \
924                 text only; no buttons, links or decision words."
925            }
926            Op::Table => {
927                "Show the person a table in this thread: a title, column headings and rows of \
928                 text or numbers. No buttons, links or decision words."
929            }
930            Op::Screen => &self.shared.screen_description,
931            Op::Patch => {
932                "Change a surface you drew in this session: set or remove data model values, \
933                 add or replace components by id, or remove components. The whole surface is \
934                 checked again."
935            }
936            Op::Delete => "Remove a surface you drew in this session from the person's thread.",
937        }
938    }
939
940    /// The latest drawing of `surface_id` in the session, from earlier tool results.
941    fn latest(&self, ctx: &dyn ToolContext, surface_id: &str) -> Option<DrawnEnvelope> {
942        let history = ctx.session()?.conversation_history();
943        history
944            .iter()
945            .flat_map(|content| &content.parts)
946            .filter_map(|part| match part {
947                adk_core::Part::FunctionResponse { function_response, .. }
948                    if DRAW_TOOL_NAMES.contains(&function_response.name.as_str()) =>
949                {
950                    DrawnEnvelope::from_response(&function_response.response)
951                }
952                _ => None,
953            })
954            .filter(|envelope| envelope.surface_id == surface_id)
955            .max_by_key(|envelope| envelope.version)
956    }
957
958    /// The next version of `surface_id`: one more than any version the session state, the
959    /// session's earlier results or this process gave it.
960    fn next_version(
961        &self,
962        ctx: &dyn ToolContext,
963        surface_id: &str,
964        latest: Option<&DrawnEnvelope>,
965    ) -> u64 {
966        let stored = ctx
967            .session()
968            .and_then(|session| session.state().get(&format!("{VERSIONS_STATE_KEY}.{surface_id}")))
969            .and_then(|version| version.as_u64())
970            .unwrap_or(0);
971        let seen = latest.map_or(0, |envelope| envelope.version);
972        let key = (
973            ctx.app_name().to_string(),
974            ctx.user_id().to_string(),
975            ctx.session_id().to_string(),
976            surface_id.to_string(),
977        );
978        let mut issued =
979            self.shared.issued.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
980        let version =
981            stored.max(seen).max(issued.get(&key).copied().unwrap_or(0)).saturating_add(1);
982        issued.insert(key, version);
983        version
984    }
985
986    /// Records `envelope` as the session's latest drawing and answers the call.
987    fn shown(&self, ctx: &dyn ToolContext, envelope: DrawnEnvelope) -> Value {
988        let record = DrawnRecord {
989            surface_id: envelope.surface_id.clone(),
990            version: envelope.version,
991            digest: envelope.digest(),
992        };
993        let mut actions = ctx.actions();
994        actions.state_delta.insert(DRAWN_STATE_KEY.to_string(), json!(record));
995        // One key per surface: drawings made side by side in one turn each keep theirs.
996        actions.state_delta.insert(
997            format!("{VERSIONS_STATE_KEY}.{}", envelope.surface_id),
998            json!(envelope.version),
999        );
1000        ctx.set_actions(actions);
1001        tracing::info!(
1002            surface.id = %envelope.surface_id,
1003            surface.version = envelope.version,
1004            surface.deleted = envelope.deleted,
1005            "drawing recorded"
1006        );
1007        let message = if envelope.deleted {
1008            format!("Removed '{}' from the person's thread.", envelope.surface_id)
1009        } else if envelope.actions.is_empty() {
1010            format!(
1011                "Shown to the person as version {} of '{}'.",
1012                envelope.version, envelope.surface_id
1013            )
1014        } else {
1015            format!(
1016                "Shown to the person as version {} of '{}'. Sending asks them first; you are told \
1017                 when they decide.",
1018                envelope.version, envelope.surface_id
1019            )
1020        };
1021        json!({
1022            "status": if envelope.deleted { "removed" } else { "shown" },
1023            "message": message,
1024            "drawn": envelope,
1025        })
1026    }
1027
1028    /// Checks `draft` and records it as the next version of its surface.
1029    fn draw(&self, ctx: &dyn ToolContext, draft: SurfaceDraft) -> Result<Value> {
1030        // An action names one of the drawing agent's own tools, so "Sending runs …" under its
1031        // button is true from the start (spec 3.3 §7.4 rule 5).
1032        let own_tools = ctx
1033            .agent_tool_names()
1034            .map(|tools| self.shared.validator.clone().with_bindable_tools(tools));
1035        let validator = own_tools.as_ref().unwrap_or(&self.shared.validator);
1036        let validated = match validator.validate(&draft) {
1037            Ok(validated) => validated,
1038            Err(refusal) => {
1039                tracing::info!(
1040                    surface.id = %draft.surface_id,
1041                    refusal.code = refusal.code(),
1042                    refusal.reason = %refusal.technical(),
1043                    "drawing refused"
1044                );
1045                let mut actions = ctx.actions();
1046                actions.state_delta.insert(REFUSED_STATE_KEY.to_string(), json!(refusal));
1047                ctx.set_actions(actions);
1048                return Err(refused(&refusal));
1049            }
1050        };
1051        let latest = self.latest(ctx, &draft.surface_id);
1052        let version = self.next_version(ctx, &draft.surface_id, latest.as_ref());
1053        let mut result =
1054            self.shown(ctx, DrawnEnvelope::of(&draft, version, validator.catalog().id()));
1055        // Shown, and the agent is told what pressures the person, to draw it plainly next time.
1056        if !validated.warnings.is_empty() {
1057            tracing::info!(
1058                surface.id = %draft.surface_id,
1059                warnings = validated.warnings.len(),
1060                "drawing shown with warnings"
1061            );
1062            let said: Vec<String> =
1063                validated.warnings.iter().filter_map(|warning| warning.message.clone()).collect();
1064            if let Some(message) = result.get("message").and_then(Value::as_str) {
1065                result["message"] = json!(format!("{message} Change it: {}", said.join(" ")));
1066            }
1067            result["warnings"] = json!(validated.warnings);
1068        }
1069        Ok(result)
1070    }
1071
1072    fn patch(&self, ctx: &dyn ToolContext, params: PatchParams) -> Result<Value> {
1073        let tool = Op::Patch.name();
1074        let latest = self.latest(ctx, &params.surface_id);
1075        // A change is checked in these tools' catalog: a drawing in another catalog cannot be
1076        // checked here, except one in forms, which every extension catalog holds whole.
1077        let own = self.shared.validator.catalog().id();
1078        if let Some(previous) = latest.as_ref()
1079            && previous.catalog_id != own
1080            && previous.catalog_id != FORMS_CATALOG_ID
1081        {
1082            return Err(invalid(
1083                tool,
1084                format!(
1085                    "surface '{}' was drawn in the catalog {}, which these tools do not draw in; \
1086                     draw it again instead",
1087                    params.surface_id, previous.catalog_id
1088                ),
1089            ));
1090        }
1091        let Some(mut draft) = latest.as_ref().and_then(DrawnEnvelope::draft) else {
1092            return Err(invalid(
1093                tool,
1094                format!(
1095                    "no surface '{}' is shown in this session; draw it first",
1096                    params.surface_id
1097                ),
1098            ));
1099        };
1100        self.within_patch_budget(ctx, &params.surface_id)?;
1101        let mut model = DataModel::new(draft.data_model.clone());
1102        for change in params.data {
1103            model.apply(Some(&change.path), change.value).map_err(|error| invalid(tool, error))?;
1104        }
1105        draft.data_model = model.value().clone();
1106        draft.components.retain(|component| {
1107            let id = component.get("id").and_then(Value::as_str).unwrap_or_default();
1108            !params.remove.iter().any(|removed| removed == id)
1109        });
1110        let components =
1111            super::wire::components_in(params.components, self.shared.validator.catalog())
1112                .map_err(|error| invalid(tool, format!("components{error}")))?;
1113        for component in components {
1114            let id = component.get("id").and_then(Value::as_str).unwrap_or_default().to_string();
1115            match draft
1116                .components
1117                .iter_mut()
1118                .find(|existing| existing.get("id").and_then(Value::as_str) == Some(id.as_str()))
1119            {
1120                Some(existing) => *existing = component,
1121                None => draft.components.push(component),
1122            }
1123        }
1124        let mut result = self.draw(ctx, draft)?;
1125        // What changed, so the agent can tell an empty patch from a real one.
1126        if let (Some(previous), Some(now)) =
1127            (latest.as_ref(), DrawnEnvelope::from_response(&result))
1128            && let Some(delta) = now.delta_from(previous)
1129        {
1130            let mut components = Vec::new();
1131            let mut data = Vec::new();
1132            for message in &delta {
1133                match &message.body {
1134                    A2uiBody::UpdateComponents(update) => components
1135                        .extend(update.components.iter().filter_map(|c| c.get("id").cloned())),
1136                    A2uiBody::UpdateDataModel(update) => {
1137                        data.push(json!(update.path.as_deref().unwrap_or("/")));
1138                    }
1139                    _ => {}
1140                }
1141            }
1142            result["changed"] = json!({ "components": components, "data": data });
1143        }
1144        Ok(result)
1145    }
1146
1147    /// Refuses a patch past [`MAX_PATCHES_PER_MINUTE`] for `surface_id` in this session.
1148    fn within_patch_budget(&self, ctx: &dyn ToolContext, surface_id: &str) -> Result<()> {
1149        let key = (
1150            ctx.app_name().to_string(),
1151            ctx.user_id().to_string(),
1152            ctx.session_id().to_string(),
1153            surface_id.to_string(),
1154        );
1155        let now = Instant::now();
1156        let mut patched =
1157            self.shared.patched.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
1158        let times = patched.entry(key).or_default();
1159        while times.front().is_some_and(|at| now.duration_since(*at) >= Duration::from_secs(60)) {
1160            times.pop_front();
1161        }
1162        if times.len() >= MAX_PATCHES_PER_MINUTE {
1163            return Err(invalid(
1164                Op::Patch.name(),
1165                format!(
1166                    "surface '{surface_id}' was changed {MAX_PATCHES_PER_MINUTE} times in the last \
1167                     minute; put changes together in one patch (it takes many data changes and \
1168                     components) and patch less often"
1169                ),
1170            ));
1171        }
1172        times.push_back(now);
1173        Ok(())
1174    }
1175
1176    fn delete(&self, ctx: &dyn ToolContext, params: DeleteParams) -> Result<Value> {
1177        let latest = self.latest(ctx, &params.surface_id);
1178        let Some(previous) = latest.as_ref().filter(|envelope| !envelope.deleted) else {
1179            return Err(invalid(
1180                Op::Delete.name(),
1181                format!("no surface '{}' is shown in this session", params.surface_id),
1182            ));
1183        };
1184        let version = self.next_version(ctx, &params.surface_id, latest.as_ref());
1185        let envelope = DrawnEnvelope {
1186            surface_id: params.surface_id.clone(),
1187            version,
1188            kind: previous.kind,
1189            catalog_id: previous.catalog_id.clone(),
1190            title: None,
1191            messages: vec![A2uiMessage::delete_surface(params.surface_id)],
1192            actions: Vec::new(),
1193            deleted: true,
1194        };
1195        Ok(self.shown(ctx, envelope))
1196    }
1197}
1198
1199#[async_trait]
1200impl Tool for DrawTool {
1201    fn name(&self) -> &str {
1202        self.op.name()
1203    }
1204
1205    fn description(&self) -> &str {
1206        DrawTool::description(self)
1207    }
1208
1209    fn parameters_schema(&self) -> Option<Value> {
1210        Some(match self.op {
1211            Op::Form => schema_of::<FormParams>(),
1212            Op::Card => schema_of::<CardParams>(),
1213            Op::Table => schema_of::<TableParams>(),
1214            Op::Screen => self.shared.screen_schema.clone(),
1215            Op::Patch => schema_of::<PatchParams>(),
1216            Op::Delete => schema_of::<DeleteParams>(),
1217        })
1218    }
1219
1220    fn is_read_only(&self) -> bool {
1221        true
1222    }
1223
1224    fn effect(&self) -> ToolEffect {
1225        ToolEffect::ReadOnly
1226    }
1227
1228    fn is_concurrency_safe(&self) -> bool {
1229        true
1230    }
1231
1232    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
1233        let tool = self.op.name();
1234        let ctx = ctx.as_ref();
1235        match self.op {
1236            Op::Form => self.draw(ctx, form(params(tool, args)?)?),
1237            Op::Card => self.draw(ctx, card(params(tool, args)?)),
1238            Op::Table => self.draw(ctx, table(params(tool, args)?)),
1239            Op::Screen => {
1240                let screen: ScreenParams = params(tool, args)?;
1241                // Components in A2UI 1.0's syntax are read into the internal form first.
1242                let components =
1243                    super::wire::components_in(screen.components, self.shared.validator.catalog())
1244                        .map_err(|error| invalid(tool, format!("components{error}")))?;
1245                self.draw(
1246                    ctx,
1247                    SurfaceDraft {
1248                        surface_id: screen.surface_id,
1249                        kind: DrawnKind::Screen,
1250                        title: screen.title,
1251                        components,
1252                        data_model: screen.data_model.unwrap_or_else(|| json!({})),
1253                        actions: screen.actions,
1254                    },
1255                )
1256            }
1257            Op::Patch => self.patch(ctx, params(tool, args)?),
1258            Op::Delete => self.delete(ctx, params(tool, args)?),
1259        }
1260    }
1261}
1262
1263#[cfg(test)]
1264mod tests {
1265    use super::*;
1266
1267    #[test]
1268    fn a_data_delta_names_each_changed_path() {
1269        let before = json!({ "a": 1, "b": { "c": 2, "d": 3 }, "rows": [1, 2], "gone": true });
1270        let now = json!({ "a": 1, "b": { "c": 5, "d": 3 }, "rows": [1, 2, 3], "x/y": "new" });
1271        let mut out = Vec::new();
1272        data_delta(&before, &now, String::new(), &mut out);
1273        assert_eq!(
1274            out,
1275            vec![
1276                ("/b/c".to_string(), Some(json!(5))),
1277                ("/gone".to_string(), None),
1278                ("/rows".to_string(), Some(json!([1, 2, 3]))),
1279                ("/x~1y".to_string(), Some(json!("new"))),
1280            ]
1281        );
1282        let mut whole = Vec::new();
1283        data_delta(&Value::Null, &json!({ "a": 1 }), String::new(), &mut whole);
1284        assert_eq!(whole, vec![(String::new(), Some(json!({ "a": 1 })))]);
1285    }
1286}