Skip to main content

agent86_core/
agent86ui.rs

1//! agent86UI in the harness (beyond Python; ADR 0005): the model draws A2UI 1.0
2//! surfaces through `render_ui` (`crate::tools::render_ui`), checked against
3//! the renderer's catalogs by the `agent86-ui` crate, and the loop hands each
4//! validated message to the surface as a [`crate::agent::TurnEvent::Ui`].
5//!
6//! A [`UiSession`] is a surface's renderer as the agent sees it: its catalogs
7//! and the surfaces drawn so far (a headless [`Runtime`]), shared by clones of
8//! the tool context like the secret vault. It exists only when the embedder
9//! declared a renderer; sub-agents never get it.
10
11use crate::config::EgressMode;
12use agent86_ui::runtime::Runtime;
13use agent86_ui::{Action, AgentMessage, Catalog, CompileError, Report, Rules};
14use serde_json::{Map, Value};
15use std::sync::{Mutex, PoisonError};
16
17/// The tool's name.
18pub const RENDER_UI: &str = "render_ui";
19
20/// Where `render_ui` leaves the validated messages in its result's metadata,
21/// for the loop to take out and emit as `TurnEvent::Ui` before the result is
22/// recorded (so nothing new reaches the session or the trace).
23pub const MESSAGES_KEY: &str = "agent86ui_messages";
24
25/// Where it leaves what the trace's `ui_render` event records (the surfaces,
26/// the component count, the verdict), taken out the same way.
27pub const TRACE_KEY: &str = "agent86ui_trace";
28
29/// Where it names the surfaces a `wait: true` call waits on, for the loop,
30/// which asks once it has emitted the call's messages (so the program has
31/// them to draw before it is asked for an answer).
32pub const WAIT_KEY: &str = "agent86ui_wait";
33
34/// What a waiting `render_ui` call asks the program (`sdk::Ui::on_wait`): the
35/// first action the user takes on one of these surfaces, which the call has
36/// just drawn (its `TurnEvent::Ui` messages came first).
37#[derive(Debug, Clone, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct UiWait {
40    /// The surfaces the call drew that are up, in the order it named them.
41    pub surface_ids: Vec<String>,
42}
43
44/// Answers a [`UiWait`]: the action, or `None` when the user dismissed it.
45pub type UiWaiter = std::sync::Arc<dyn Fn(&UiWait) -> Option<Action> + Send + Sync>;
46
47/// The completeness rules a `render_ui` batch is checked under: strict, but an
48/// orphan is a warning, because A2UI 1.0 has no message that removes a
49/// component, so one replaced as a child stays behind and the model could not
50/// fix the error (ADR 0005, third amendment).
51pub const RULES: Rules = Rules::STRICT.allowing_orphans(true);
52
53/// A renderer's catalogs and the surfaces drawn on it so far.
54pub struct UiSession {
55    catalogs: Vec<Catalog>,
56    runtime: Mutex<Runtime>,
57    /// The egress guardrail's mode: in `redact`, every string a surface shows
58    /// is redacted first.
59    egress: EgressMode,
60    /// Media may load from `https` URLs, not only `data:` URLs and workspace
61    /// files.
62    remote_media: bool,
63    /// Answers a waiting call, when the program can. Behind a lock, so a
64    /// surface that installs its answer after the harness is built (the
65    /// interface, once its event channel exists) can set it.
66    waiter: Mutex<Option<UiWaiter>>,
67}
68
69impl std::fmt::Debug for UiSession {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        f.debug_struct("UiSession")
72            .field(
73                "catalogs",
74                &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
75            )
76            .finish_non_exhaustive()
77    }
78}
79
80impl UiSession {
81    /// A renderer that supports `catalogs`, in order of preference.
82    pub fn new(catalogs: Vec<Catalog>) -> Result<Self, CompileError> {
83        let mut runtime = Runtime::new(catalogs.clone())?;
84        runtime.set_rules(RULES);
85        Ok(Self {
86            catalogs,
87            runtime: Mutex::new(runtime),
88            egress: EgressMode::Off,
89            remote_media: false,
90            waiter: Mutex::new(None),
91        })
92    }
93
94    /// Redact what surfaces show as the egress guardrail in `mode` redacts the
95    /// model's text.
96    pub fn with_egress(mut self, mode: EgressMode) -> Self {
97        self.egress = mode;
98        self
99    }
100
101    /// Let media load from `https` URLs too (ADR 0005: off by default, since a
102    /// fetch can track the user or carry data out in its URL).
103    pub fn with_remote_media(mut self, allow: bool) -> Self {
104        self.remote_media = allow;
105        self
106    }
107
108    /// Let a call wait for the user's answer, asking `waiter`.
109    pub fn with_waiter(self, waiter: Option<UiWaiter>) -> Self {
110        self.set_waiter(waiter);
111        self
112    }
113
114    /// Install (or, with `None`, remove) the answer to a waiting call. The
115    /// prompt section is rebuilt per request, so it offers `wait` from the next
116    /// request on.
117    pub fn set_waiter(&self, waiter: Option<UiWaiter>) {
118        *self.waiter.lock().unwrap_or_else(PoisonError::into_inner) = waiter;
119    }
120
121    fn waiter(&self) -> Option<UiWaiter> {
122        self.waiter
123            .lock()
124            .unwrap_or_else(PoisonError::into_inner)
125            .clone()
126    }
127
128    /// Whether a call may wait: someone answers.
129    pub fn can_wait(&self) -> bool {
130        self.waiter().is_some()
131    }
132
133    /// Ask the program for the user's answer (`None`: dismissed, or nobody
134    /// answers). The lock is not held while the program answers.
135    pub fn wait(&self, request: &UiWait) -> Option<Action> {
136        self.waiter().and_then(|waiter| waiter(request))
137    }
138
139    /// Whether `action` could have come from a surface up now: its surface
140    /// exists (and is one of `among`, when given) and holds the component it
141    /// names. What it carries is the user's and is checked as their input is.
142    pub fn check_action(&self, action: &Action, among: Option<&[String]>) -> Result<(), String> {
143        if action.name.is_empty() {
144            return Err("the action has no name".into());
145        }
146        if among.is_some_and(|ids| !ids.contains(&action.surface_id)) {
147            return Err(format!(
148                "the action is for surface {:?}, which this call did not draw",
149                action.surface_id
150            ));
151        }
152        let runtime = self.runtime();
153        let Some(mut components) = runtime.components(&action.surface_id) else {
154            return Err(format!("there is no surface {:?}", action.surface_id));
155        };
156        if !components
157            .any(|c| c.get("id").and_then(Value::as_str) == Some(&action.source_component_id))
158        {
159            return Err(format!(
160                "surface {:?} has no component {:?}",
161                action.surface_id, action.source_component_id
162            ));
163        }
164        Ok(())
165    }
166
167    /// Whether surface `id`, as drawn so far, has a Button whose action sends
168    /// an event: something the user can press to answer.
169    pub fn has_event_button(&self, id: &str) -> bool {
170        self.runtime()
171            .components(id)
172            .is_some_and(|mut components| components.any(is_event_button))
173    }
174
175    pub fn egress(&self) -> EgressMode {
176        self.egress
177    }
178
179    pub fn remote_media(&self) -> bool {
180        self.remote_media
181    }
182
183    pub fn catalogs(&self) -> &[Catalog] {
184        &self.catalogs
185    }
186
187    fn runtime(&self) -> std::sync::MutexGuard<'_, Runtime> {
188        self.runtime.lock().unwrap_or_else(PoisonError::into_inner)
189    }
190
191    /// The top-level keys of surface `surface_id`, if it is up ([`surface_keys`]).
192    pub fn surface_keys(&self, surface_id: &str) -> Vec<String> {
193        surface_keys(&self.runtime(), surface_id)
194    }
195
196    /// Validate a batch and, when it has no errors, apply it to the surfaces.
197    pub fn apply(&self, messages: &[Value]) -> Report {
198        self.runtime().apply(messages)
199    }
200
201    /// Every surface up now as the one `createSurface` that draws it as it is,
202    /// for a program that reopens a session (or draws late) to bring its screen
203    /// up to date.
204    pub fn snapshot(&self) -> Vec<AgentMessage> {
205        self.runtime()
206            .snapshot()
207            .into_iter()
208            .filter_map(|message| serde_json::from_value(message).ok())
209            .collect()
210    }
211
212    /// Rebuild the surfaces from a session's history (ADR 0005: resume replays,
213    /// nothing is stored): every `render_ui` call that drew, in order, through
214    /// the same redaction, policy, and validation as when it ran. A call that
215    /// drew is one whose result is ok or opens with what the tool writes when it
216    /// draws (a waiting call the user dismissed reports a failure, yet drew).
217    /// Steps keep calls the history's compaction summarized away. Returns how
218    /// many calls were replayed.
219    pub fn replay(
220        &self,
221        state: &crate::session::AgentState,
222        ctx: &crate::tools::ToolContext,
223    ) -> usize {
224        let mut runtime = match Runtime::new(self.catalogs.clone()) {
225            Ok(runtime) => runtime,
226            Err(_) => return 0,
227        };
228        runtime.set_rules(RULES);
229        let mut replayed = 0;
230        for step in &state.steps {
231            for call in step.tool_calls.iter().filter(|call| call.name == RENDER_UI) {
232                let drew = step
233                    .results
234                    .iter()
235                    .find(|result| result.call_id == call.id)
236                    .is_some_and(drew);
237                if !drew {
238                    continue;
239                }
240                // The history keeps the call as the model sent it, before the
241                // registry repaired an array sent as a JSON string.
242                let messages = match call.arguments.get("messages") {
243                    Some(Value::Array(messages)) => messages.clone(),
244                    Some(Value::String(text)) => match serde_json::from_str(text) {
245                        Ok(Value::Array(messages)) => messages,
246                        _ => continue,
247                    },
248                    _ => continue,
249                };
250                let messages: Vec<Value> = messages
251                    .iter()
252                    .map(|message| tidy(&sanitize(message, &ctx.secrets, self.egress)).0)
253                    .collect();
254                let (messages, _) = complete(&messages, |id| surface_keys(&runtime, id));
255                if !policy(&messages, &ctx.policy, self.remote_media).is_empty() {
256                    continue;
257                }
258                if runtime.apply(&messages).is_ok() {
259                    replayed += 1;
260                }
261            }
262        }
263        *self.runtime() = runtime;
264        replayed
265    }
266
267    /// The ids of the surfaces up now.
268    pub fn surface_ids(&self) -> Vec<String> {
269        self.runtime().surface_ids().map(String::from).collect()
270    }
271
272    /// The system-prompt section: how to use `render_ui`, then each catalog's
273    /// own instructions and a compact reference to its components and
274    /// functions. Rebuilt per request, like the MCP section.
275    pub fn prompt_section(&self) -> String {
276        let mut section = String::from(PROMPT);
277        let media = if self.remote_media {
278            "a data: URL, an https URL, or the path of a file in the workspace"
279        } else {
280            "a data: URL or the path of a file in the workspace (remote URLs are not loaded)"
281        };
282        if self.can_wait() {
283            section.push_str(
284                "\n- With `\"wait\": true` the call waits for the user's first action on \
285                 the surface and returns it as its result (`[ui action] ...`). Use it for a \
286                 form you need answered before you can go on; otherwise leave it out and \
287                 carry on.",
288            );
289        }
290        section.push_str(&format!(
291            "\n- Never ask for a password, key, or token in a surface (no TextField with \
292             variant \"obscured\"): call request_secret, which asks through a masked prompt \
293             and never shows you the value.\n- The url (and a Video's posterUrl) of Image, \
294             Video, and AudioPlayer must be a literal string: {media}.\n- openUrl opens only \
295             http and https URLs."
296        ));
297        if let Some(catalog) = self.catalogs.first() {
298            section.push_str(&format!(
299                "\n\nA complete call, a choice with a Submit button (`surfaceId` goes \
300                 inside createSurface, never beside it):\n{}",
301                example(catalog.id(), self.can_wait())
302            ));
303        }
304        for catalog in &self.catalogs {
305            section.push_str(&format!("\n\n### Catalog `{}`\n", catalog.id()));
306            if let Some(instructions) = catalog.instructions() {
307                section.push('\n');
308                section.push_str(instructions.trim());
309                section.push('\n');
310            }
311            section.push_str(&reference(catalog));
312        }
313        section
314    }
315}
316
317/// The keys that name what an A2UI 1.0 message is; an envelope holds
318/// `version` and exactly one of them.
319const KINDS: &[&str] = &[
320    "createSurface",
321    "updateComponents",
322    "updateDataModel",
323    "deleteSurface",
324    "callRendererFunction",
325    "agentFunctionResponse",
326];
327
328/// Beyond the protocol: a message whose fields sit beside its kind instead of
329/// inside it (`{"version": "1.0", "createSurface": {...}, "surfaceId": "x"}`,
330/// the mistake models make most often) has them moved in, when the kind's body
331/// does not already have them. Such a message is never valid as written, so
332/// the move only turns an error into what the model plainly meant. Returns the
333/// message and the fields moved, for the result to mention. `render_ui` and
334/// replay both apply it, so a session written either way replays the same.
335pub fn tidy(message: &Value) -> (Value, Vec<String>) {
336    let Some(envelope) = message.as_object() else {
337        return (message.clone(), Vec::new());
338    };
339    let kinds: Vec<&String> = envelope
340        .keys()
341        .filter(|key| KINDS.contains(&key.as_str()))
342        .collect();
343    let [kind] = kinds.as_slice() else {
344        return (message.clone(), Vec::new());
345    };
346    let kind = (*kind).clone();
347    let Some(body) = envelope.get(&kind).and_then(Value::as_object) else {
348        return (message.clone(), Vec::new());
349    };
350    let strays: Vec<String> = envelope
351        .keys()
352        .filter(|key| *key != "version" && **key != kind && !body.contains_key(*key))
353        .cloned()
354        .collect();
355    if strays.is_empty() {
356        return (message.clone(), Vec::new());
357    }
358    let mut envelope = envelope.clone();
359    let mut body = body.clone();
360    for key in &strays {
361        if let Some(value) = envelope.remove(key) {
362            body.insert(key.clone(), value);
363        }
364    }
365    envelope.insert(kind.clone(), Value::Object(body));
366    let moved = strays
367        .into_iter()
368        .map(|key| format!("{key} into {kind}"))
369        .collect();
370    (Value::Object(envelope), moved)
371}
372
373/// Beyond the protocol (ADR 0006), after [`tidy`]: two shapes A2UI accepts but
374/// that do not do what the model meant are completed, so the form works.
375///
376/// - **A binding written with 0.9.1's key.** Inside components, an object that
377///   is exactly `{"path": "/..."}` is a literal object to A2UI 1.0, so a Button
378///   would send back `{"path": "/scope"}` instead of the user's choice. It
379///   becomes `{"@path": "/..."}`, and the result notes it so the model learns.
380///   (A ChildList template has `componentId` beside its `path`, so it is never
381///   touched.)
382/// - **A Button event with no `context`.** The action would carry nothing, so
383///   it gets a context binding every top-level value of its surface: the keys
384///   of the data model and the first segment of every absolute path the
385///   surface's components bind, from this batch and, for a surface drawn
386///   earlier, from `existing`. This is what the prompt promises, which keeps
387///   the deepest nesting out of every form the model writes.
388///
389/// `existing` gives the top-level keys of a surface already up
390/// ([`surface_keys`]). `render_ui` and replay both apply it, so a session
391/// replays the same. Returns the messages and the notes for the model.
392pub fn complete(
393    messages: &[Value],
394    existing: impl Fn(&str) -> Vec<String>,
395) -> (Vec<Value>, Vec<String>) {
396    let mut keys: std::collections::HashMap<String, Vec<String>> = Default::default();
397    let mut notes = Vec::new();
398    let mut out = Vec::with_capacity(messages.len());
399    for (index, message) in messages.iter().enumerate() {
400        let mut message = message.clone();
401        if let Some(create) = message.get_mut("createSurface") {
402            let id = surface_of(create);
403            let mut known = Vec::new();
404            if let Some(Value::Object(model)) = create.get("dataModel") {
405                extend_unique(&mut known, model.keys().cloned());
406            }
407            rebind(
408                create,
409                &format!("messages/{index}/createSurface"),
410                &mut notes,
411            );
412            extend_unique(&mut known, bound_keys(create.get("components")));
413            fill_contexts(create, &known);
414            keys.insert(id, known);
415        } else if let Some(update) = message.get_mut("updateComponents") {
416            let id = surface_of(update);
417            let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
418            rebind(
419                update,
420                &format!("messages/{index}/updateComponents"),
421                &mut notes,
422            );
423            extend_unique(known, bound_keys(update.get("components")));
424            fill_contexts(update, known);
425        } else if let Some(update) = message.get("updateDataModel") {
426            let id = surface_of(update);
427            let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
428            match update.get("path").and_then(Value::as_str) {
429                None | Some("" | "/") => {
430                    if let Some(Value::Object(model)) = update.get("value") {
431                        extend_unique(known, model.keys().cloned());
432                    }
433                }
434                Some(path) => extend_unique(known, top_segment(path)),
435            }
436        }
437        out.push(message);
438    }
439    (out, notes)
440}
441
442/// The top-level keys of surface `surface_id` in `runtime`: its data model's,
443/// then the first segment of every absolute path its components bind.
444pub fn surface_keys(runtime: &Runtime, surface_id: &str) -> Vec<String> {
445    let mut keys = Vec::new();
446    if let Some(Value::Object(model)) = runtime.data_model(surface_id) {
447        extend_unique(&mut keys, model.keys().cloned());
448    }
449    if let Some(components) = runtime.components(surface_id) {
450        let components = Value::Array(components.cloned().collect());
451        extend_unique(&mut keys, bound_keys(Some(&components)));
452    }
453    keys
454}
455
456fn surface_of(body: &Value) -> String {
457    body.get("surfaceId")
458        .and_then(Value::as_str)
459        .unwrap_or_default()
460        .to_owned()
461}
462
463fn extend_unique(keys: &mut Vec<String>, more: impl IntoIterator<Item = String>) {
464    for key in more {
465        if !keys.contains(&key) {
466            keys.push(key);
467        }
468    }
469}
470
471/// The key of an absolute JSON Pointer's first segment, unescaped.
472fn top_segment(path: &str) -> Option<String> {
473    let rest = path.strip_prefix('/')?;
474    let segment = rest.split('/').next().unwrap_or_default();
475    (!segment.is_empty()).then(|| segment.replace("~1", "/").replace("~0", "~"))
476}
477
478/// The first segment of every absolute `@path` under `value`.
479fn bound_keys(value: Option<&Value>) -> Vec<String> {
480    fn walk(value: &Value, keys: &mut Vec<String>) {
481        match value {
482            Value::Object(map) => {
483                if let Some(Value::String(path)) = map.get("@path") {
484                    extend_unique(keys, top_segment(path));
485                }
486                map.values().for_each(|value| walk(value, keys));
487            }
488            Value::Array(items) => items.iter().for_each(|value| walk(value, keys)),
489            _ => {}
490        }
491    }
492    let mut keys = Vec::new();
493    if let Some(value) = value {
494        walk(value, &mut keys);
495    }
496    keys
497}
498
499/// Turn each `{"path": "/..."}` among `body`'s components into a binding,
500/// noting each component that had one.
501fn rebind(body: &mut Value, at: &str, notes: &mut Vec<String>) {
502    fn walk(value: &mut Value) -> bool {
503        match value {
504            Value::Object(map) => {
505                let lone_path = map.len() == 1
506                    && map
507                        .get("path")
508                        .and_then(Value::as_str)
509                        .is_some_and(|path| path.starts_with('/'));
510                if lone_path {
511                    let path = map.remove("path").expect("checked above");
512                    map.insert("@path".to_owned(), path);
513                    return true;
514                }
515                let mut changed = false;
516                for value in map.values_mut() {
517                    changed |= walk(value);
518                }
519                changed
520            }
521            Value::Array(items) => items
522                .iter_mut()
523                .fold(false, |changed, item| walk(item) | changed),
524            _ => false,
525        }
526    }
527    let Some(Value::Array(components)) = body.get_mut("components") else {
528        return;
529    };
530    for (index, component) in components.iter_mut().enumerate() {
531        let Value::Object(fields) = component else {
532            continue;
533        };
534        let mut changed = false;
535        for (key, value) in fields.iter_mut() {
536            if key != "id" && key != "component" {
537                changed |= walk(value);
538            }
539        }
540        if changed {
541            let id = fields.get("id").and_then(Value::as_str).unwrap_or("?");
542            notes.push(format!(
543                "Note: read {{\"path\": ...}} as {{\"@path\": ...}} in {at}/components/{index} \
544                 ({id}); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal."
545            ));
546        }
547    }
548}
549
550/// Give every event Button among `body`'s components with no `context` one
551/// binding each of `keys`.
552fn fill_contexts(body: &mut Value, keys: &[String]) {
553    let Some(Value::Array(components)) = body.get_mut("components") else {
554        return;
555    };
556    for component in components.iter_mut() {
557        if component.get("component").and_then(Value::as_str) != Some("Button") {
558            continue;
559        }
560        let Some(Value::Object(event)) = component.pointer_mut("/action/event") else {
561            continue;
562        };
563        if event.contains_key("context") {
564            continue;
565        }
566        let context: Map<String, Value> = keys
567            .iter()
568            .map(|key| {
569                let pointer = format!("/{}", key.replace('~', "~0").replace('/', "~1"));
570                (key.clone(), serde_json::json!({"@path": pointer}))
571            })
572            .collect();
573        event.insert("context".to_owned(), Value::Object(context));
574    }
575}
576
577/// Whether a component is a Button whose action sends an event (rather than
578/// running a local function such as `openUrl`).
579pub fn is_event_button(component: &Value) -> bool {
580    component.get("component").and_then(Value::as_str) == Some("Button")
581        && component.pointer("/action/event").is_some()
582}
583
584/// The prompt's example call, on one line, in `catalog_id`.
585fn example(catalog_id: &str, wait: bool) -> String {
586    let mut call = serde_json::json!({"messages": [{"version": "1.0", "createSurface": {
587        "surfaceId": "plan",
588        "catalogId": catalog_id,
589        "components": [
590            {"id": "root", "component": "Column", "children": ["choice", "submit"]},
591            {"id": "choice", "component": "ChoicePicker", "label": "Which plan?",
592             "variant": "mutuallyExclusive", "value": {"@path": "/plan"},
593             "options": [{"label": "Basic", "value": "basic"}, {"label": "Pro", "value": "pro"}]},
594            {"id": "submit", "component": "Button", "child": "submit_label",
595             "action": {"event": {"name": "submit"}}},
596            {"id": "submit_label", "component": "Text", "text": "Submit"}
597        ],
598        "dataModel": {"plan": []}
599    }}]});
600    if wait {
601        call["wait"] = Value::Bool(true);
602    }
603    call.to_string()
604}
605
606/// What every `render_ui` prompt says, whatever the catalogs.
607const PROMPT: &str = "## agent86UI: drawing UI with render_ui
608
609You can show the user interactive UI (forms, choices, confirmations, small \
610dashboards) by calling render_ui with A2UI 1.0 messages; the user's screen draws \
611them with its own widgets. Use it when you need a structured answer (pick one of \
612several options, fill in a few fields, confirm a plan) or when a layout says more \
613than prose. Otherwise answer in plain text.
614
615- `messages` is a list of A2UI messages, each `{\"version\": \"1.0\", ...}` with \
616exactly one of `createSurface`, `updateComponents`, `updateDataModel`, or \
617`deleteSurface`. Create a surface once with createSurface (a new `surfaceId`, a \
618`catalogId` from below, and usually its `components` and `dataModel` inline), \
619change it later with updateComponents (a component replaces the one with the same \
620id) and updateDataModel (`path` and `value`), and remove it with deleteSurface.
621- Components are a flat list linked by id, and exactly one has the id \"root\". \
622Every child id must be defined in the same call or an earlier one. An id is an \
623identifier: letters, digits, and `_`, starting with a letter or `_` (`submit_label`, \
624never `submit-label`).
625- A value is a literal, a binding to the surface's data model (`{\"@path\": \
626\"/form/name\"}`), or a function call (`{\"@call\": \"formatString\", \"args\": \
627{...}}`). Input components write what the user enters back to the path they are \
628bound to. A `ChildList` is an array of ids, or a template over a list in the data \
629model (`{\"path\": \"/items\", \"componentId\": \"row\"}`) whose bindings are \
630relative to each item.
631- A button's action is `{\"event\": {\"name\": \"submit\"}}`, and it sends every \
632top-level value of the surface's data model. To send something else, give the \
633event a `context` beside `name` (`{\"event\": {\"name\": \"pick\", \"context\": \
634{\"plan\": \"pro\"}}}`), never beside `event`. When the user presses it, a later \
635user message reads `[ui action] submit on <surfaceId>: <values as JSON>`; the \
636surface stays up meanwhile.
637- Only a Button whose action is an event sends the user's answer: choosing an \
638option or typing only changes the data model. So every form needs a Button (for \
639example Submit).
640- Keep each call short: a surface's JSON breaks most often when it is large. For \
641a form of more than about four inputs, send createSurface with the root and the \
642first few components, then add the rest in further calls with updateComponents, \
643sending the root again with its longer `children`; put `wait` only on the last call.
644- render_ui's result is the validator's verdict. If it lists problems, nothing \
645was drawn: fix them and send the corrected messages again.
646- Renderer functions (`callRendererFunction`) and agent functions are not \
647available.";
648
649/// A compact reference to a catalog's components and functions, from their
650/// schemas: each component's properties (`?` marks an optional one) with their
651/// types, and each function's arguments and return type.
652pub fn reference(catalog: &Catalog) -> String {
653    let document = catalog.document();
654    let mut out = String::from("\nComponents:\n");
655    for (name, schema) in document
656        .get("components")
657        .and_then(Value::as_object)
658        .into_iter()
659        .flatten()
660    {
661        let (properties, required, checkable) = gather(schema);
662        let fields: Vec<String> = properties
663            .iter()
664            .filter(|(key, _)| *key != "component" && *key != "id")
665            .map(|(key, property)| {
666                let optional = if required.iter().any(|r| r == key) {
667                    ""
668                } else {
669                    "?"
670                };
671                format!("{key}{optional}: {}", type_of(property, document))
672            })
673            .collect();
674        let checks = if checkable { " (accepts @checks)" } else { "" };
675        out.push_str(&format!("- {name} {{ {} }}{checks}\n", fields.join(", ")));
676    }
677    let functions: Vec<String> = document
678        .get("functions")
679        .and_then(Value::as_object)
680        .into_iter()
681        .flatten()
682        .filter(|(name, _)| {
683            catalog
684                .function(name)
685                .is_none_or(|def| def.callers != agent86_ui::Callers::AgentOnly)
686        })
687        .map(|(name, schema)| {
688            let args = schema.pointer("/properties/args");
689            let required: Vec<&str> = args
690                .and_then(|a| a.get("required"))
691                .and_then(Value::as_array)
692                .into_iter()
693                .flatten()
694                .filter_map(Value::as_str)
695                .collect();
696            let params: Vec<String> = args
697                .and_then(|a| a.get("properties"))
698                .and_then(Value::as_object)
699                .into_iter()
700                .flatten()
701                .map(|(key, property)| {
702                    let optional = if required.contains(&key.as_str()) {
703                        ""
704                    } else {
705                        "?"
706                    };
707                    format!("{key}{optional}: {}", type_of(property, document))
708                })
709                .collect();
710            let returns = schema
711                .get("returnType")
712                .and_then(Value::as_str)
713                .unwrap_or("any");
714            format!("- {name}({}) -> {returns}\n", params.join(", "))
715        })
716        .collect();
717    if !functions.is_empty() {
718        out.push_str("\nFunctions:\n");
719        out.extend(functions);
720    }
721    out
722}
723
724/// A component schema's properties and required names, from its own
725/// `properties` and its `allOf` parts, and whether it takes `@checks`.
726fn gather(schema: &Value) -> (Map<String, Value>, Vec<String>, bool) {
727    let mut properties = Map::new();
728    let mut required = Vec::new();
729    let mut checkable = false;
730    let mut parts = vec![schema];
731    if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
732        parts.extend(all);
733    }
734    for part in parts {
735        if part
736            .get("$ref")
737            .and_then(Value::as_str)
738            .is_some_and(|r| r.ends_with("/Checkable"))
739        {
740            checkable = true;
741        }
742        if let Some(own) = part.get("properties").and_then(Value::as_object) {
743            for (key, value) in own {
744                properties.insert(key.clone(), value.clone());
745            }
746        }
747        required.extend(
748            part.get("required")
749                .and_then(Value::as_array)
750                .into_iter()
751                .flatten()
752                .filter_map(Value::as_str)
753                .map(String::from),
754        );
755    }
756    (properties, required, checkable)
757}
758
759/// A property's type, briefly: a common type by name, a catalog's own
760/// definition by what it is (its `Weight` is a number, not a name to guess
761/// at), an enum's values, or the JSON type.
762fn type_of(property: &Value, document: &Value) -> String {
763    if let Some(target) = property.get("$ref").and_then(Value::as_str) {
764        if let Some(local) = target.strip_prefix("#/$defs/") {
765            if let Some(def) = document.pointer(&format!("/$defs/{local}")) {
766                if def.get("$ref").is_none() {
767                    return type_of(def, document);
768                }
769            }
770        }
771        return target.rsplit('/').next().unwrap_or(target).to_string();
772    }
773    if let Some(values) = property.get("enum").and_then(Value::as_array) {
774        return values
775            .iter()
776            .map(|v| v.to_string())
777            .collect::<Vec<_>>()
778            .join("|");
779    }
780    match property.get("type").and_then(Value::as_str) {
781        Some("array") => match property.get("items") {
782            Some(items) => format!("array of {}", type_of(items, document)),
783            None => "array".into(),
784        },
785        Some(kind) => kind.to_string(),
786        None => "any".into(),
787    }
788}
789
790/// What a `render_ui` result carries for the loop, taken out of its metadata,
791/// so it is emitted and recorded as agent86UI's own and never kept in the
792/// session: the validated messages, and the `ui_render` trace fields.
793pub fn take_drawn(metadata: &mut Map<String, Value>) -> (Vec<AgentMessage>, Option<Value>) {
794    let messages = match metadata.remove(MESSAGES_KEY) {
795        Some(Value::Array(items)) => items
796            .into_iter()
797            .filter_map(|item| serde_json::from_value(item).ok())
798            .collect(),
799        _ => Vec::new(),
800    };
801    (messages, metadata.remove(TRACE_KEY))
802}
803
804/// What `render_ui`'s result opens with when the call drew.
805const DREW: &[&str] = &["Rendered surface ", "Deleted surface ", "Applied."];
806
807/// Whether a `render_ui` result says the call drew. A waiting call that was not
808/// answered says so first and what it drew after (earlier versions wrote the
809/// drawing first), so every line is looked at.
810fn drew(result: &crate::types::ToolResult) -> bool {
811    let text = if result.ok {
812        result.content.as_str()
813    } else {
814        result.error.as_deref().unwrap_or_default()
815    };
816    result.ok
817        || text
818            .lines()
819            .any(|line| DREW.iter().any(|opening| line.starts_with(opening)))
820}
821
822/// The surfaces a waiting call waits on, taken out of its result's metadata.
823pub fn take_wait(metadata: &mut Map<String, Value>) -> Option<Vec<String>> {
824    match metadata.remove(WAIT_KEY)? {
825        Value::Array(ids) => Some(
826            ids.into_iter()
827                .filter_map(|id| id.as_str().map(String::from))
828                .collect(),
829        ),
830        _ => None,
831    }
832}
833
834/// An action as the model reads it, a waiting call's result or the next user
835/// message: `[ui action] <name> on <surfaceId>: <context as JSON>`, then the
836/// event's `userMessage` on a line of its own when it has one.
837pub fn action_text(action: &Action) -> String {
838    let context = crate::pyjson::python_json_dumps(&Value::Object(action.context.clone()), false);
839    let mut text = format!(
840        "[ui action] {} on {}: {context}",
841        action.name, action.surface_id
842    );
843    if let Some(message) = action.user_message.as_deref().filter(|m| !m.is_empty()) {
844        text.push('\n');
845        text.push_str(message);
846    }
847    text
848}
849
850impl crate::agent::Harness {
851    /// Declare a renderer: put `session` on the tool context and offer the
852    /// model `render_ui`. Both assembly paths (`sdk::AgentBuilder::ui` and the
853    /// binary's interface, through `setup::attach_renderer`) go through it.
854    /// Sub-agents never draw: `ToolContext::fork` drops the session.
855    pub fn attach_ui(&mut self, session: UiSession) -> Result<(), String> {
856        self.registry
857            .register(Box::new(crate::tools::render_ui::RenderUiTool))?;
858        self.context.ui = Some(std::sync::Arc::new(session));
859        Ok(())
860    }
861
862    /// Take an action from a surface no call was waiting on (ADR 0005: it
863    /// becomes the next user message): check that it could have come from a
864    /// surface up now, record it as `ui_action` (never its values), and give
865    /// the text the turn runs on, `[ui action] <name> on <surfaceId>: ...`. The
866    /// caller runs that as a plain turn, whose own vault redaction and ingress
867    /// guardrail cover it as they cover typed input. `Err` names what was
868    /// wrong, never the values, and nothing is recorded.
869    pub fn accept_ui_action(&self, sid: &str, action: &Action) -> Result<String, String> {
870        let ui = self
871            .context
872            .ui
873            .as_deref()
874            .ok_or_else(|| String::from("this agent has no renderer"))?;
875        ui.check_action(action, None)?;
876        self.recorder.event(
877            sid,
878            "ui_action",
879            vec![
880                ("surface", serde_json::json!(action.surface_id)),
881                ("name", serde_json::json!(action.name)),
882                ("component", serde_json::json!(action.source_component_id)),
883                ("waited", serde_json::json!(false)),
884            ],
885        );
886        Ok(action_text(action))
887    }
888
889    /// Wait for the user's answer to a `wait: true` call, through the prompt
890    /// queue like a secret prompt (one question at a time, declined once the
891    /// turn is cancelled), and make it the call's result. The answer goes
892    /// through the vault and the ingress guardrail, as typed input does, and is
893    /// recorded as `ui_action`, without its values.
894    pub(crate) fn ui_wait(
895        &self,
896        call: &crate::types::ToolCall,
897        drawn: crate::types::ToolResult,
898        surfaces: Vec<String>,
899        sid: &str,
900    ) -> crate::types::ToolResult {
901        use crate::tools::{failure, success};
902        let Some(ui) = self.context.ui.as_deref() else {
903            return drawn;
904        };
905        if surfaces.is_empty() {
906            return drawn;
907        }
908        let request = UiWait {
909            surface_ids: surfaces.clone(),
910        };
911        let question = crate::approval::Question {
912            tool: Some(RENDER_UI.into()),
913            call: Some(call.id.clone()),
914            ..crate::approval::Question::new(crate::approval::QuestionKind::Ui)
915        };
916        let shown = drawn.content.clone();
917        let answered = |result: crate::types::ToolResult| crate::types::ToolResult {
918            call_id: drawn.call_id.clone(),
919            ..result
920        };
921        let action = match self.gate.queue.ask(question, || ui.wait(&request)) {
922            None => {
923                return answered(failure(
924                    RENDER_UI,
925                    format!(
926                        "The turn was cancelled before the user answered. The surface stays \
927                         up; an action on it later comes as a user message.\n{shown}"
928                    ),
929                ))
930            }
931            Some(None) => {
932                return answered(failure(
933                    RENDER_UI,
934                    format!(
935                        "The user did not answer (they dismissed it). The surface stays up; an \
936                         action on it later comes as a user message.\n{shown}"
937                    ),
938                ))
939            }
940            Some(Some(action)) => action,
941        };
942        if let Err(why) = ui.check_action(&action, Some(&surfaces)) {
943            return answered(failure(
944                RENDER_UI,
945                format!("The screen's answer could not be used: {why}.\n{shown}"),
946            ));
947        }
948        let text = self.context.secrets.redact(&action_text(&action));
949        let report = self.guardrails.inspect_ingress(&text);
950        if report.flagged() {
951            self.recorder.event(
952                sid,
953                "guardrail",
954                vec![
955                    ("stage", serde_json::json!("ingress")),
956                    ("source", serde_json::json!("ui_action")),
957                    ("findings", serde_json::json!(report.summary())),
958                ],
959            );
960        }
961        self.recorder.event(
962            sid,
963            "ui_action",
964            vec![
965                ("surface", serde_json::json!(action.surface_id)),
966                ("name", serde_json::json!(action.name)),
967                ("component", serde_json::json!(action.source_component_id)),
968                ("waited", serde_json::json!(true)),
969            ],
970        );
971        if self.guardrails.should_block(&report) {
972            return answered(failure(
973                RENDER_UI,
974                format!(
975                    "The user's answer was refused by the input guardrail ({}).\n{shown}",
976                    report.summary()
977                ),
978            ));
979        }
980        answered(success(RENDER_UI, format!("{shown}\n{text}")))
981    }
982}
983
984/// Every string in `value`, through the secret vault's redaction and, with the
985/// egress guardrail in `redact` mode, its redaction too: what a surface shows
986/// reaches the user as the model's text does. Object keys are left alone.
987pub fn sanitize(value: &Value, vault: &crate::vault::SecretVault, egress: EgressMode) -> Value {
988    match value {
989        Value::String(text) => {
990            let text = vault.redact(text);
991            Value::String(if egress == EgressMode::Redact {
992                crate::guardrails::redact(&text).0
993            } else {
994                text
995            })
996        }
997        Value::Array(items) => Value::Array(
998            items
999                .iter()
1000                .map(|item| sanitize(item, vault, egress))
1001                .collect(),
1002        ),
1003        Value::Object(map) => Value::Object(
1004            map.iter()
1005                .map(|(key, item)| (key.clone(), sanitize(item, vault, egress)))
1006                .collect(),
1007        ),
1008        other => other.clone(),
1009    }
1010}
1011
1012/// Something agent86's policy refuses in a batch (ADR 0005), where the
1013/// protocol would allow it: a JSON Pointer into the batch and why.
1014#[derive(Debug, Clone, PartialEq, Eq)]
1015pub struct Refusal {
1016    pub path: String,
1017    pub message: String,
1018}
1019
1020impl std::fmt::Display for Refusal {
1021    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1022        write!(f, "REFUSED at {}: {}", self.path, self.message)
1023    }
1024}
1025
1026/// The media components of the basic catalog and the properties that load a
1027/// URL. A custom catalog's component of the same name is held to the same rule.
1028const MEDIA: &[(&str, &[&str])] = &[
1029    ("Image", &["url"]),
1030    ("Video", &["url", "posterUrl"]),
1031    ("AudioPlayer", &["url"]),
1032];
1033
1034/// What agent86 refuses in a batch the protocol allows (ADR 0005):
1035/// - a `TextField` with `"variant": "obscured"`: secrets are never collected
1036///   through a surface, so the value never reaches the model;
1037/// - media from anywhere but a `data:` URL or a file in the workspace (or an
1038///   `https` URL, with `remote_media`), and from a binding or a call, whose
1039///   value is not known until the renderer resolves it;
1040/// - `openUrl` with a literal URL that is not `http` or `https` (a dynamic one
1041///   is the renderer's to check before it opens it, after showing it);
1042/// - `callRendererFunction` and agent functions, left out of the first version.
1043pub fn policy(
1044    messages: &[Value],
1045    jail: &crate::tools::SandboxPolicy,
1046    remote_media: bool,
1047) -> Vec<Refusal> {
1048    let mut refusals = Vec::new();
1049    let mut refuse = |path: String, message: String| refusals.push(Refusal { path, message });
1050    for (index, message) in messages.iter().enumerate() {
1051        if message.get("callRendererFunction").is_some() {
1052            refuse(
1053                format!("/{index}/callRendererFunction"),
1054                "renderer functions are not available here; draw with components and change \
1055                 them with updateComponents and updateDataModel instead"
1056                    .into(),
1057            );
1058        }
1059        if message.get("agentFunctionResponse").is_some() {
1060            refuse(
1061                format!("/{index}/agentFunctionResponse"),
1062                "agent functions are not available here".into(),
1063            );
1064        }
1065        for kind in ["createSurface", "updateComponents"] {
1066            let Some(components) = message
1067                .get(kind)
1068                .and_then(|body| body.get("components"))
1069                .and_then(Value::as_array)
1070            else {
1071                continue;
1072            };
1073            for (number, component) in components.iter().enumerate() {
1074                let at = format!("/{index}/{kind}/components/{number}");
1075                let type_name = component.get("component").and_then(Value::as_str);
1076                let id = component
1077                    .get("id")
1078                    .and_then(Value::as_str)
1079                    .unwrap_or("this component");
1080                if type_name == Some("TextField")
1081                    && component.get("variant").and_then(Value::as_str) == Some("obscured")
1082                {
1083                    refuse(
1084                        format!("{at}/variant"),
1085                        format!(
1086                            "TextField {id} is \"obscured\", a password field, but a surface never \
1087                             collects secrets: call request_secret instead, which asks the user \
1088                             through a masked prompt and never shows you the value"
1089                        ),
1090                    );
1091                }
1092                if let Some((_, properties)) =
1093                    MEDIA.iter().find(|(name, _)| Some(*name) == type_name)
1094                {
1095                    for property in *properties {
1096                        let Some(value) = component.get(*property) else {
1097                            continue;
1098                        };
1099                        let path = format!("{at}/{property}");
1100                        match value.as_str() {
1101                            Some(url) => {
1102                                if let Some(why) = media_problem(url, jail, remote_media) {
1103                                    refuse(path, format!("{id}'s {property} {why}"));
1104                                }
1105                            }
1106                            None => refuse(
1107                                path,
1108                                format!(
1109                                    "{id}'s {property} must be a literal string: what a surface \
1110                                     loads is checked before it is drawn, so it cannot come from a \
1111                                     binding or a function call"
1112                                ),
1113                            ),
1114                        }
1115                    }
1116                }
1117                open_urls(component, &at, &mut refuse);
1118            }
1119        }
1120    }
1121    refusals
1122}
1123
1124/// Why a media URL may not load, or `None` when it may.
1125fn media_problem(
1126    url: &str,
1127    jail: &crate::tools::SandboxPolicy,
1128    remote_media: bool,
1129) -> Option<String> {
1130    match scheme(url) {
1131        Some(scheme) if scheme == "data" => None,
1132        Some(scheme) if scheme == "https" && remote_media => None,
1133        Some(scheme) if scheme == "https" || scheme == "http" => Some(format!(
1134            "{url:?} is a remote URL, and remote media is off here (a fetch can track the user \
1135             or carry data out in its URL): use a data: URL or a file in the workspace"
1136        )),
1137        Some(scheme) => Some(format!(
1138            "{url:?} uses {scheme}:, which a surface may not load: use a data: URL or a file in \
1139             the workspace"
1140        )),
1141        None => match jail.resolve_within(url) {
1142            Err(_) => Some(format!("{url:?} is outside the workspace")),
1143            Ok(path) if !path.is_file() => Some(format!("{url:?} is not a file in the workspace")),
1144            Ok(_) => None,
1145        },
1146    }
1147}
1148
1149/// A URL's scheme, lowercased, when it has one. A single letter before the
1150/// colon is a Windows drive, not a scheme.
1151fn scheme(url: &str) -> Option<String> {
1152    let (scheme, _) = url.split_once(':')?;
1153    let valid = scheme.len() > 1
1154        && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
1155        && scheme
1156            .chars()
1157            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
1158    valid.then(|| scheme.to_ascii_lowercase())
1159}
1160
1161/// Refuse each `openUrl` call in `value` whose literal URL is not `http` or
1162/// `https`.
1163fn open_urls(value: &Value, at: &str, refuse: &mut impl FnMut(String, String)) {
1164    match value {
1165        Value::Object(map) => {
1166            if map.get("@call").and_then(Value::as_str) == Some("openUrl") {
1167                if let Some(url) = value.pointer("/args/url").and_then(Value::as_str) {
1168                    let scheme = scheme(url);
1169                    if !matches!(scheme.as_deref(), Some("http" | "https")) {
1170                        refuse(
1171                            format!("{at}/args/url"),
1172                            format!("openUrl only opens http and https URLs, not {url:?}"),
1173                        );
1174                    }
1175                }
1176            }
1177            for (key, item) in map {
1178                let segment = key.replace('~', "~0").replace('/', "~1");
1179                open_urls(item, &format!("{at}/{segment}"), refuse);
1180            }
1181        }
1182        Value::Array(items) => {
1183            for (index, item) in items.iter().enumerate() {
1184                open_urls(item, &format!("{at}/{index}"), refuse);
1185            }
1186        }
1187        _ => {}
1188    }
1189}
1190
1191#[cfg(test)]
1192mod tests {
1193    use super::*;
1194
1195    use crate::tools::SandboxPolicy;
1196    use serde_json::json;
1197
1198    struct Jail(std::path::PathBuf, SandboxPolicy);
1199
1200    fn jail(name: &str) -> Jail {
1201        let root = std::env::temp_dir().join(format!("agent86-ui-{name}-{}", std::process::id()));
1202        let _ = std::fs::remove_dir_all(&root);
1203        std::fs::create_dir_all(root.join("img")).unwrap();
1204        std::fs::write(root.join("img/cat.png"), b"png").unwrap();
1205        let policy = SandboxPolicy::new(&root).unwrap();
1206        Jail(root, policy)
1207    }
1208
1209    impl Drop for Jail {
1210        fn drop(&mut self) {
1211            let _ = std::fs::remove_dir_all(&self.0);
1212        }
1213    }
1214
1215    fn with_components(components: Value) -> Vec<Value> {
1216        vec![json!({"version": "1.0", "createSurface": {
1217            "surfaceId": "s", "catalogId": "c", "components": components
1218        }})]
1219    }
1220
1221    fn refused(messages: &[Value], jail: &Jail, remote: bool) -> Vec<String> {
1222        policy(messages, &jail.1, remote)
1223            .into_iter()
1224            .map(|r| format!("{} {}", r.path, r.message))
1225            .collect()
1226    }
1227
1228    #[test]
1229    fn a_password_field_is_refused_with_request_secret_named() {
1230        let jail = jail("obscured");
1231        let got = refused(
1232            &with_components(json!([
1233                {"id": "root", "component": "TextField", "label": "Password", "variant": "obscured"},
1234                {"id": "note", "component": "TextField", "label": "Note", "variant": "longText"}
1235            ])),
1236            &jail,
1237            false,
1238        );
1239        assert_eq!(got.len(), 1, "{got:?}");
1240        assert!(got[0].starts_with("/0/createSurface/components/0/variant TextField root"));
1241        assert!(got[0].contains("request_secret"));
1242    }
1243
1244    #[test]
1245    fn media_loads_only_data_urls_and_workspace_files_unless_remote_is_on() {
1246        let jail = jail("media");
1247        let image =
1248            |url: Value| with_components(json!([{"id": "root", "component": "Image", "url": url}]));
1249        let ok = |url: Value, remote| refused(&image(url), &jail, remote).is_empty();
1250        assert!(ok(json!("data:image/png;base64,iVBORw0KGgo="), false));
1251        assert!(ok(json!("img/cat.png"), false));
1252        assert!(!ok(json!("img/dog.png"), false), "missing file");
1253        assert!(!ok(json!("../outside.png"), false), "outside the jail");
1254        assert!(!ok(json!("https://example.com/cat.png"), false));
1255        assert!(ok(json!("https://example.com/cat.png"), true));
1256        assert!(!ok(json!("http://example.com/cat.png"), true), "only https");
1257        assert!(!ok(json!("file:///etc/passwd"), true));
1258        let bound = refused(&image(json!({"@path": "/url"})), &jail, true);
1259        assert!(bound[0].contains("must be a literal string"), "{bound:?}");
1260        // A Video's poster is held to the same rule.
1261        let video = with_components(json!([{"id": "root", "component": "Video",
1262            "url": "data:video/mp4;base64,AAAA", "posterUrl": "https://example.com/p.png"}]));
1263        let got = refused(&video, &jail, false);
1264        assert_eq!(got.len(), 1);
1265        assert!(got[0].starts_with("/0/createSurface/components/0/posterUrl"));
1266    }
1267
1268    #[test]
1269    fn open_url_takes_only_http_and_https_literals() {
1270        let jail = jail("open");
1271        let button = |url: Value| {
1272            with_components(json!([
1273                {"id": "root", "component": "Button", "child": "t",
1274                 "action": {"functionCall": {"@call": "openUrl", "args": {"url": url}}}},
1275                {"id": "t", "component": "Text", "text": "Go"}
1276            ]))
1277        };
1278        assert!(refused(&button(json!("https://example.com")), &jail, false).is_empty());
1279        assert!(refused(&button(json!("http://example.com")), &jail, false).is_empty());
1280        // A dynamic URL is the renderer's to check, after showing it.
1281        assert!(refused(&button(json!({"@path": "/link"})), &jail, false).is_empty());
1282        let got = refused(&button(json!("javascript:alert(1)")), &jail, false);
1283        assert_eq!(
1284            got,
1285            ["/0/createSurface/components/0/action/functionCall/args/url openUrl only opens http and https URLs, not \"javascript:alert(1)\""]
1286        );
1287    }
1288
1289    #[test]
1290    fn renderer_and_agent_functions_are_refused() {
1291        let jail = jail("functions");
1292        let got = refused(
1293            &[
1294                json!({"version": "1.0", "callRendererFunction": {"surfaceId": "s", "functionCallId": "f", "call": {"@call": "x"}}}),
1295                json!({"version": "1.0", "agentFunctionResponse": {"functionCallId": "f", "value": 1}}),
1296            ],
1297            &jail,
1298            false,
1299        );
1300        assert!(got[0].starts_with("/0/callRendererFunction renderer functions are not available"));
1301        assert!(got[1].starts_with("/1/agentFunctionResponse agent functions are not available"));
1302    }
1303
1304    #[test]
1305    fn a_drive_letter_is_not_a_scheme() {
1306        assert_eq!(scheme("C:\\img\\cat.png"), None);
1307        assert_eq!(scheme("HTTPS://x"), Some("https".into()));
1308        assert_eq!(scheme("img/cat.png"), None);
1309    }
1310
1311    #[test]
1312    fn sanitize_redacts_secrets_and_with_egress_redact_what_the_guardrail_finds() {
1313        let vault = crate::vault::SecretVault::default();
1314        vault.set("API_TOKEN", "tok-abcdef-123456".into());
1315        let message =
1316            json!({"text": "use tok-abcdef-123456", "aws": "AKIAABCDEFGHIJKLMNOP", "n": 3});
1317        let kept = sanitize(&message, &vault, EgressMode::Warn);
1318        assert_eq!(kept["text"], "use ${secret:API_TOKEN}");
1319        assert_eq!(kept["aws"], "AKIAABCDEFGHIJKLMNOP");
1320        assert_eq!(kept["n"], 3);
1321        let redacted = sanitize(&message, &vault, EgressMode::Redact);
1322        assert_ne!(redacted["aws"], "AKIAABCDEFGHIJKLMNOP");
1323        assert!(!redacted.to_string().contains("AKIA"), "{redacted}");
1324    }
1325
1326    #[test]
1327    fn the_basic_catalog_reference_names_components_and_functions() {
1328        let reference = reference(Catalog::basic());
1329        assert!(
1330            reference.contains(
1331                "- Button { child: Child, variant?: \"default\"|\"primary\"|\"borderless\", action: Action, weight?: number } (accepts @checks)"
1332            ),
1333            "{reference}"
1334        );
1335        assert!(reference.contains("- TextField {"), "{reference}");
1336        assert!(
1337            reference.contains("- formatString(value: DynamicString) -> string"),
1338            "{reference}"
1339        );
1340        assert!(!reference.contains("component:"), "{reference}");
1341    }
1342
1343    #[test]
1344    fn the_prompt_section_carries_the_catalog_instructions() {
1345        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1346        let section = session.prompt_section();
1347        assert!(section.starts_with("## agent86UI: drawing UI with render_ui"));
1348        assert!(section.contains(&format!("### Catalog `{}`", agent86_ui::BASIC_CATALOG_ID)));
1349        assert!(section.contains("## Catalog Guidelines"));
1350        assert!(section.contains("[ui action] submit on <surfaceId>"));
1351    }
1352
1353    #[test]
1354    fn fields_beside_the_kind_are_moved_inside_it() {
1355        let (tidied, moved) = tidy(&serde_json::json!({
1356            "version": "1.0",
1357            "createSurface": {"catalogId": "c", "components": []},
1358            "surfaceId": "plan"
1359        }));
1360        assert_eq!(
1361            tidied,
1362            serde_json::json!({"version": "1.0",
1363                "createSurface": {"catalogId": "c", "components": [], "surfaceId": "plan"}})
1364        );
1365        assert_eq!(moved, ["surfaceId into createSurface"]);
1366
1367        // Never over a field the body has, and never with no kind or two kinds.
1368        for message in [
1369            serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}, "surfaceId": "b"}),
1370            serde_json::json!({"version": "1.0", "surfaceId": "b"}),
1371            serde_json::json!({"version": "1.0", "deleteSurface": {}, "updateDataModel": {}, "x": 1}),
1372            serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}}),
1373        ] {
1374            assert_eq!(tidy(&message), (message.clone(), Vec::new()), "{message}");
1375        }
1376    }
1377
1378    #[test]
1379    fn the_prompt_s_example_is_valid() {
1380        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1381        let call: Value =
1382            serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, true)).unwrap();
1383        let messages = call["messages"].as_array().unwrap();
1384        let report = session.apply(messages);
1385        assert!(report.is_ok(), "{:?}", report.errors);
1386        assert!(report.warnings.is_empty(), "{:?}", report.warnings);
1387        let section = session.prompt_section();
1388        assert!(section.contains("surfaceId` goes inside createSurface"));
1389        assert!(
1390            !section.contains("\"wait\":true"),
1391            "no waiter, no wait in the example"
1392        );
1393    }
1394
1395    #[test]
1396    fn a_waiter_set_later_offers_wait_from_then_on() {
1397        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1398        let request = UiWait {
1399            surface_ids: vec!["s".into()],
1400        };
1401        assert!(!session.can_wait());
1402        assert!(!session.prompt_section().contains("\"wait\": true"));
1403        assert_eq!(session.wait(&request), None);
1404
1405        session.set_waiter(Some(std::sync::Arc::new(|wait: &UiWait| {
1406            Some(Action::new(
1407                "ok",
1408                wait.surface_ids[0].clone(),
1409                "root",
1410                "2026-11-22T00:00:00Z",
1411                Map::new(),
1412            ))
1413        })));
1414        assert!(session.can_wait());
1415        assert!(session.prompt_section().contains("\"wait\": true"));
1416        assert_eq!(session.wait(&request).map(|a| a.name), Some("ok".into()));
1417
1418        session.set_waiter(None);
1419        assert!(!session.can_wait());
1420    }
1421
1422    #[test]
1423    fn orphans_are_warnings_and_dangling_references_errors() {
1424        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1425        let create = |components: Value| {
1426            serde_json::json!({"version": "1.0", "createSurface": {
1427                "surfaceId": "s",
1428                "catalogId": agent86_ui::BASIC_CATALOG_ID,
1429                "components": components,
1430            }})
1431        };
1432        let report = session.apply(&[create(serde_json::json!([
1433            {"id": "root", "component": "Column", "children": ["missing"]}
1434        ]))]);
1435        assert!(report.errors[0].message.starts_with("Dangling reference"));
1436        let report = session.apply(&[create(serde_json::json!([
1437            {"id": "root", "component": "Text", "text": "hi"},
1438            {"id": "spare", "component": "Text", "text": "nobody shows me"}
1439        ]))]);
1440        assert!(report.is_ok(), "{:?}", report.errors);
1441        assert!(report.warnings[0].message.contains("not reachable"));
1442        assert_eq!(session.surface_ids(), ["s"]);
1443    }
1444
1445    fn create_with(components: Value, data_model: Option<Value>) -> Value {
1446        let mut body = json!({
1447            "surfaceId": "s",
1448            "catalogId": agent86_ui::BASIC_CATALOG_ID,
1449            "components": components,
1450        });
1451        if let Some(model) = data_model {
1452            body["dataModel"] = model;
1453        }
1454        json!({"version": "1.0", "createSurface": body})
1455    }
1456
1457    fn submit_button() -> Value {
1458        json!({"id": "go", "component": "Button", "child": "go_label",
1459               "action": {"event": {"name": "submit"}}})
1460    }
1461
1462    #[test]
1463    fn a_button_without_context_sends_every_top_level_value() {
1464        // The data model's keys, then the first segment of every absolute path
1465        // the components bind (here one with no data model entry yet).
1466        let message = create_with(
1467            json!([
1468                {"id": "root", "component": "Column", "children": ["plan", "note", "go"]},
1469                {"id": "plan", "component": "ChoicePicker", "value": {"@path": "/plan"},
1470                 "options": [{"label": "A", "value": "a"}]},
1471                {"id": "note", "component": "TextField", "label": "Note",
1472                 "value": {"@path": "/extra/note"}},
1473                submit_button(),
1474            ]),
1475            Some(json!({"plan": [], "size": 1})),
1476        );
1477        let (messages, notes) = complete(&[message], |_| Vec::new());
1478        assert!(notes.is_empty(), "{notes:?}");
1479        assert_eq!(
1480            messages[0].pointer("/createSurface/components/3/action/event/context"),
1481            Some(&json!({
1482                "plan": {"@path": "/plan"},
1483                "size": {"@path": "/size"},
1484                "extra": {"@path": "/extra"}
1485            }))
1486        );
1487    }
1488
1489    #[test]
1490    fn a_context_the_model_gave_is_kept() {
1491        let mut button = submit_button();
1492        button["action"]["event"]["context"] = json!({"choice": "pro"});
1493        let message = create_with(
1494            json!([{"id": "root", "component": "Column", "children": ["go"]}, button]),
1495            Some(json!({"plan": []})),
1496        );
1497        let (messages, _) = complete(&[message], |_| Vec::new());
1498        assert_eq!(
1499            messages[0].pointer("/createSurface/components/1/action/event/context"),
1500            Some(&json!({"choice": "pro"}))
1501        );
1502    }
1503
1504    #[test]
1505    fn a_button_added_later_sends_the_values_of_the_surface_already_up() {
1506        let update = json!({"version": "1.0", "updateComponents": {
1507            "surfaceId": "s",
1508            "components": [submit_button()],
1509        }});
1510        let (messages, _) = complete(&[update], |id| {
1511            assert_eq!(id, "s");
1512            vec!["name".to_owned(), "a/b".to_owned()]
1513        });
1514        assert_eq!(
1515            messages[0].pointer("/updateComponents/components/0/action/event/context"),
1516            Some(&json!({"name": {"@path": "/name"}, "a/b": {"@path": "/a~1b"}}))
1517        );
1518    }
1519
1520    #[test]
1521    fn a_lone_path_is_read_as_a_binding_and_noted() {
1522        let mut button = submit_button();
1523        button["action"]["event"]["context"] = json!({"plan": {"path": "/plan"}});
1524        let message = create_with(
1525            json!([
1526                {"id": "root", "component": "Column",
1527                 "children": {"path": "/items", "componentId": "row"}},
1528                {"id": "row", "component": "Text", "text": {"path": "/label"}},
1529                button,
1530            ]),
1531            Some(json!({"items": []})),
1532        );
1533        let (messages, notes) = complete(&[message], |_| Vec::new());
1534        let components = &messages[0]["createSurface"]["components"];
1535        // A template keeps its `path`, which has a componentId beside it.
1536        assert_eq!(
1537            components[0]["children"],
1538            json!({"path": "/items", "componentId": "row"})
1539        );
1540        assert_eq!(components[1]["text"], json!({"@path": "/label"}));
1541        assert_eq!(
1542            components[2]["action"]["event"]["context"],
1543            json!({"plan": {"@path": "/plan"}})
1544        );
1545        assert_eq!(
1546            notes,
1547            [
1548                "Note: read {\"path\": ...} as {\"@path\": ...} in messages/0/createSurface/components/1 (row); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal.",
1549                "Note: read {\"path\": ...} as {\"@path\": ...} in messages/0/createSurface/components/2 (go); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal.",
1550            ]
1551        );
1552    }
1553
1554    #[test]
1555    fn the_completed_example_validates_and_its_button_sends_the_choice() {
1556        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1557        let call: Value =
1558            serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, false)).unwrap();
1559        let messages = call["messages"].as_array().unwrap().clone();
1560        let (messages, _) = complete(&messages, |id| session.surface_keys(id));
1561        assert!(session.apply(&messages).is_ok());
1562        let submit = messages[0]["createSurface"]["components"]
1563            .as_array()
1564            .unwrap()
1565            .iter()
1566            .find(|component| component["id"] == "submit")
1567            .unwrap();
1568        assert_eq!(
1569            submit["action"]["event"]["context"],
1570            json!({"plan": {"@path": "/plan"}})
1571        );
1572    }
1573}