use crate::config::EgressMode;
use agent86_ui::runtime::Runtime;
use agent86_ui::{Action, AgentMessage, Catalog, CompileError, Report, Rules};
use serde_json::{Map, Value};
use std::sync::{Mutex, PoisonError};
pub const RENDER_UI: &str = "render_ui";
pub const MESSAGES_KEY: &str = "agent86ui_messages";
pub const TRACE_KEY: &str = "agent86ui_trace";
pub const WAIT_KEY: &str = "agent86ui_wait";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UiWait {
pub surface_ids: Vec<String>,
}
pub type UiWaiter = std::sync::Arc<dyn Fn(&UiWait) -> Option<Action> + Send + Sync>;
pub const RULES: Rules = Rules::STRICT.allowing_orphans(true);
pub struct UiSession {
catalogs: Vec<Catalog>,
runtime: Mutex<Runtime>,
egress: EgressMode,
remote_media: bool,
waiter: Mutex<Option<UiWaiter>>,
}
impl std::fmt::Debug for UiSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UiSession")
.field(
"catalogs",
&self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
)
.finish_non_exhaustive()
}
}
impl UiSession {
pub fn new(catalogs: Vec<Catalog>) -> Result<Self, CompileError> {
let mut runtime = Runtime::new(catalogs.clone())?;
runtime.set_rules(RULES);
Ok(Self {
catalogs,
runtime: Mutex::new(runtime),
egress: EgressMode::Off,
remote_media: false,
waiter: Mutex::new(None),
})
}
pub fn with_egress(mut self, mode: EgressMode) -> Self {
self.egress = mode;
self
}
pub fn with_remote_media(mut self, allow: bool) -> Self {
self.remote_media = allow;
self
}
pub fn with_waiter(self, waiter: Option<UiWaiter>) -> Self {
self.set_waiter(waiter);
self
}
pub fn set_waiter(&self, waiter: Option<UiWaiter>) {
*self.waiter.lock().unwrap_or_else(PoisonError::into_inner) = waiter;
}
fn waiter(&self) -> Option<UiWaiter> {
self.waiter
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
pub fn can_wait(&self) -> bool {
self.waiter().is_some()
}
pub fn wait(&self, request: &UiWait) -> Option<Action> {
self.waiter().and_then(|waiter| waiter(request))
}
pub fn check_action(&self, action: &Action, among: Option<&[String]>) -> Result<(), String> {
if action.name.is_empty() {
return Err("the action has no name".into());
}
if among.is_some_and(|ids| !ids.contains(&action.surface_id)) {
return Err(format!(
"the action is for surface {:?}, which this call did not draw",
action.surface_id
));
}
let runtime = self.runtime();
let Some(mut components) = runtime.components(&action.surface_id) else {
return Err(format!("there is no surface {:?}", action.surface_id));
};
if !components
.any(|c| c.get("id").and_then(Value::as_str) == Some(&action.source_component_id))
{
return Err(format!(
"surface {:?} has no component {:?}",
action.surface_id, action.source_component_id
));
}
Ok(())
}
pub fn has_event_button(&self, id: &str) -> bool {
self.runtime()
.components(id)
.is_some_and(|mut components| components.any(is_event_button))
}
pub fn egress(&self) -> EgressMode {
self.egress
}
pub fn remote_media(&self) -> bool {
self.remote_media
}
pub fn catalogs(&self) -> &[Catalog] {
&self.catalogs
}
fn runtime(&self) -> std::sync::MutexGuard<'_, Runtime> {
self.runtime.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn surface_keys(&self, surface_id: &str) -> Vec<String> {
surface_keys(&self.runtime(), surface_id)
}
pub fn apply(&self, messages: &[Value]) -> Report {
self.runtime().apply(messages)
}
pub fn snapshot(&self) -> Vec<AgentMessage> {
self.runtime()
.snapshot()
.into_iter()
.filter_map(|message| serde_json::from_value(message).ok())
.collect()
}
pub fn replay(
&self,
state: &crate::session::AgentState,
ctx: &crate::tools::ToolContext,
) -> usize {
let mut runtime = match Runtime::new(self.catalogs.clone()) {
Ok(runtime) => runtime,
Err(_) => return 0,
};
runtime.set_rules(RULES);
let mut replayed = 0;
for step in &state.steps {
for call in step.tool_calls.iter().filter(|call| call.name == RENDER_UI) {
let drew = step
.results
.iter()
.find(|result| result.call_id == call.id)
.is_some_and(drew);
if !drew {
continue;
}
let messages = match call.arguments.get("messages") {
Some(Value::Array(messages)) => messages.clone(),
Some(Value::String(text)) => match serde_json::from_str(text) {
Ok(Value::Array(messages)) => messages,
_ => continue,
},
_ => continue,
};
let messages: Vec<Value> = messages
.iter()
.map(|message| tidy(&sanitize(message, &ctx.secrets, self.egress)).0)
.collect();
let (messages, _) = complete(&messages, |id| surface_keys(&runtime, id));
if !policy(&messages, &ctx.policy, self.remote_media).is_empty() {
continue;
}
if runtime.apply(&messages).is_ok() {
replayed += 1;
}
}
}
*self.runtime() = runtime;
replayed
}
pub fn surface_ids(&self) -> Vec<String> {
self.runtime().surface_ids().map(String::from).collect()
}
pub fn surface_texts(&self) -> Vec<String> {
let runtime = self.runtime();
let ids: Vec<String> = runtime.surface_ids().map(String::from).collect();
ids.iter()
.filter_map(|id| runtime.tree(id).map(|tree| surface_text(id, &tree)))
.collect()
}
pub fn prompt_section(&self) -> String {
let mut section = String::from(PROMPT);
let media = if self.remote_media {
"a data: URL, an https URL, or the path of a file in the workspace"
} else {
"a data: URL or the path of a file in the workspace (remote URLs are not loaded)"
};
if self.can_wait() {
section.push_str(
"\n- With `\"wait\": true` the call waits for the user's first action on \
the surface and returns it as its result (`[ui action] ...`). Use it for a \
form you need answered before you can go on; otherwise leave it out and \
carry on.",
);
}
section.push_str(&format!(
"\n- Never ask for a password, key, or token in a surface (no TextField with \
variant \"obscured\"): call request_secret, which asks through a masked prompt \
and never shows you the value.\n- The url (and a Video's posterUrl) of Image, \
Video, and AudioPlayer must be a literal string: {media}.\n- openUrl opens only \
http and https URLs."
));
if let Some(catalog) = self.catalogs.first() {
section.push_str(&format!(
"\n\nA complete call, a choice with a Submit button (`surfaceId` goes \
inside createSurface, never beside it):\n{}",
example(catalog.id(), self.can_wait())
));
}
for catalog in &self.catalogs {
section.push_str(&format!("\n\n### Catalog `{}`\n", catalog.id()));
if let Some(instructions) = catalog.instructions() {
section.push('\n');
section.push_str(instructions.trim());
section.push('\n');
}
section.push_str(&reference(catalog));
}
section
}
}
const KINDS: &[&str] = &[
"createSurface",
"updateComponents",
"updateDataModel",
"deleteSurface",
"callRendererFunction",
"agentFunctionResponse",
];
pub fn tidy(message: &Value) -> (Value, Vec<String>) {
let Some(envelope) = message.as_object() else {
return (message.clone(), Vec::new());
};
let kinds: Vec<&String> = envelope
.keys()
.filter(|key| KINDS.contains(&key.as_str()))
.collect();
let [kind] = kinds.as_slice() else {
return (message.clone(), Vec::new());
};
let kind = (*kind).clone();
let Some(body) = envelope.get(&kind).and_then(Value::as_object) else {
return (message.clone(), Vec::new());
};
let strays: Vec<String> = envelope
.keys()
.filter(|key| *key != "version" && **key != kind && !body.contains_key(*key))
.cloned()
.collect();
if strays.is_empty() {
return (message.clone(), Vec::new());
}
let mut envelope = envelope.clone();
let mut body = body.clone();
for key in &strays {
if let Some(value) = envelope.remove(key) {
body.insert(key.clone(), value);
}
}
envelope.insert(kind.clone(), Value::Object(body));
let moved = strays
.into_iter()
.map(|key| format!("{key} into {kind}"))
.collect();
(Value::Object(envelope), moved)
}
pub fn complete(
messages: &[Value],
existing: impl Fn(&str) -> Vec<String>,
) -> (Vec<Value>, Vec<String>) {
let mut keys: std::collections::HashMap<String, Vec<String>> = Default::default();
let mut notes = Vec::new();
let mut out = Vec::with_capacity(messages.len());
for (index, message) in messages.iter().enumerate() {
let mut message = message.clone();
if let Some(create) = message.get_mut("createSurface") {
let id = surface_of(create);
let mut known = Vec::new();
if let Some(Value::Object(model)) = create.get("dataModel") {
extend_unique(&mut known, model.keys().cloned());
}
rebind(
create,
&format!("messages/{index}/createSurface"),
&mut notes,
);
extend_unique(&mut known, bound_keys(create.get("components")));
fill_contexts(create, &known);
keys.insert(id, known);
} else if let Some(update) = message.get_mut("updateComponents") {
let id = surface_of(update);
let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
rebind(
update,
&format!("messages/{index}/updateComponents"),
&mut notes,
);
extend_unique(known, bound_keys(update.get("components")));
fill_contexts(update, known);
} else if let Some(update) = message.get("updateDataModel") {
let id = surface_of(update);
let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
match update.get("path").and_then(Value::as_str) {
None | Some("" | "/") => {
if let Some(Value::Object(model)) = update.get("value") {
extend_unique(known, model.keys().cloned());
}
}
Some(path) => extend_unique(known, top_segment(path)),
}
}
out.push(message);
}
(out, notes)
}
pub fn surface_keys(runtime: &Runtime, surface_id: &str) -> Vec<String> {
let mut keys = Vec::new();
if let Some(Value::Object(model)) = runtime.data_model(surface_id) {
extend_unique(&mut keys, model.keys().cloned());
}
if let Some(components) = runtime.components(surface_id) {
let components = Value::Array(components.cloned().collect());
extend_unique(&mut keys, bound_keys(Some(&components)));
}
keys
}
fn surface_of(body: &Value) -> String {
body.get("surfaceId")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned()
}
fn extend_unique(keys: &mut Vec<String>, more: impl IntoIterator<Item = String>) {
for key in more {
if !keys.contains(&key) {
keys.push(key);
}
}
}
fn top_segment(path: &str) -> Option<String> {
let rest = path.strip_prefix('/')?;
let segment = rest.split('/').next().unwrap_or_default();
(!segment.is_empty()).then(|| segment.replace("~1", "/").replace("~0", "~"))
}
fn bound_keys(value: Option<&Value>) -> Vec<String> {
fn walk(value: &Value, keys: &mut Vec<String>) {
match value {
Value::Object(map) => {
if let Some(Value::String(path)) = map.get("@path") {
extend_unique(keys, top_segment(path));
}
map.values().for_each(|value| walk(value, keys));
}
Value::Array(items) => items.iter().for_each(|value| walk(value, keys)),
_ => {}
}
}
let mut keys = Vec::new();
if let Some(value) = value {
walk(value, &mut keys);
}
keys
}
fn rebind(body: &mut Value, at: &str, notes: &mut Vec<String>) {
fn walk(value: &mut Value) -> bool {
match value {
Value::Object(map) => {
let lone_path = map.len() == 1
&& map
.get("path")
.and_then(Value::as_str)
.is_some_and(|path| path.starts_with('/'));
if lone_path {
let path = map.remove("path").expect("checked above");
map.insert("@path".to_owned(), path);
return true;
}
let mut changed = false;
for value in map.values_mut() {
changed |= walk(value);
}
changed
}
Value::Array(items) => items
.iter_mut()
.fold(false, |changed, item| walk(item) | changed),
_ => false,
}
}
let Some(Value::Array(components)) = body.get_mut("components") else {
return;
};
for (index, component) in components.iter_mut().enumerate() {
let Value::Object(fields) = component else {
continue;
};
let mut changed = false;
for (key, value) in fields.iter_mut() {
if key != "id" && key != "component" {
changed |= walk(value);
}
}
if changed {
let id = fields.get("id").and_then(Value::as_str).unwrap_or("?");
notes.push(format!(
"Note: read {{\"path\": ...}} as {{\"@path\": ...}} in {at}/components/{index} \
({id}); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal."
));
}
}
}
fn fill_contexts(body: &mut Value, keys: &[String]) {
let Some(Value::Array(components)) = body.get_mut("components") else {
return;
};
for component in components.iter_mut() {
if component.get("component").and_then(Value::as_str) != Some("Button") {
continue;
}
let Some(Value::Object(event)) = component.pointer_mut("/action/event") else {
continue;
};
if event.contains_key("context") {
continue;
}
let context: Map<String, Value> = keys
.iter()
.map(|key| {
let pointer = format!("/{}", key.replace('~', "~0").replace('/', "~1"));
(key.clone(), serde_json::json!({"@path": pointer}))
})
.collect();
event.insert("context".to_owned(), Value::Object(context));
}
}
pub fn is_event_button(component: &Value) -> bool {
component.get("component").and_then(Value::as_str) == Some("Button")
&& component.pointer("/action/event").is_some()
}
fn example(catalog_id: &str, wait: bool) -> String {
let mut call = serde_json::json!({"messages": [{"version": "1.0", "createSurface": {
"surfaceId": "plan",
"catalogId": catalog_id,
"components": [
{"id": "root", "component": "Column", "children": ["choice", "submit"]},
{"id": "choice", "component": "ChoicePicker", "label": "Which plan?",
"variant": "mutuallyExclusive", "value": {"@path": "/plan"},
"options": [{"label": "Basic", "value": "basic"}, {"label": "Pro", "value": "pro"}]},
{"id": "submit", "component": "Button", "child": "submit_label",
"action": {"event": {"name": "submit"}}},
{"id": "submit_label", "component": "Text", "text": "Submit"}
],
"dataModel": {"plan": []}
}}]});
if wait {
call["wait"] = Value::Bool(true);
}
call.to_string()
}
const PROMPT: &str = "## agent86UI: drawing UI with render_ui
You can show the user interactive UI (forms, choices, confirmations, small \
dashboards) by calling render_ui with A2UI 1.0 messages; the user's screen draws \
them with its own widgets. Use it when you need a structured answer (pick one of \
several options, fill in a few fields, confirm a plan) or when a layout says more \
than prose. Otherwise answer in plain text.
- `messages` is a list of A2UI messages, each `{\"version\": \"1.0\", ...}` with \
exactly one of `createSurface`, `updateComponents`, `updateDataModel`, or \
`deleteSurface`. Create a surface once with createSurface (a new `surfaceId`, a \
`catalogId` from below, and usually its `components` and `dataModel` inline), \
change it later with updateComponents (a component replaces the one with the same \
id) and updateDataModel (`path` and `value`), and remove it with deleteSurface.
- Components are a flat list linked by id, and exactly one has the id \"root\". \
Every child id must be defined in the same call or an earlier one. An id is an \
identifier: letters, digits, and `_`, starting with a letter or `_` (`submit_label`, \
never `submit-label`).
- A value is a literal, a binding to the surface's data model (`{\"@path\": \
\"/form/name\"}`), or a function call (`{\"@call\": \"formatString\", \"args\": \
{...}}`). Input components write what the user enters back to the path they are \
bound to. A `ChildList` is an array of ids, or a template over a list in the data \
model (`{\"path\": \"/items\", \"componentId\": \"row\"}`) whose bindings are \
relative to each item.
- A button's action is `{\"event\": {\"name\": \"submit\"}}`, and it sends every \
top-level value of the surface's data model. To send something else, give the \
event a `context` beside `name` (`{\"event\": {\"name\": \"pick\", \"context\": \
{\"plan\": \"pro\"}}}`), never beside `event`. When the user presses it, a later \
user message reads `[ui action] submit on <surfaceId>: <values as JSON>`; the \
surface stays up meanwhile.
- Only a Button whose action is an event sends the user's answer: choosing an \
option or typing only changes the data model. So every form needs a Button (for \
example Submit).
- Keep each call short: a surface's JSON breaks most often when it is large. For \
a form of more than about four inputs, send createSurface with the root and the \
first few components, then add the rest in further calls with updateComponents, \
sending the root again with its longer `children`; put `wait` only on the last call.
- render_ui's result is the validator's verdict. If it lists problems, nothing \
was drawn: fix them and send the corrected messages again.
- Renderer functions (`callRendererFunction`) and agent functions are not \
available.";
pub fn reference(catalog: &Catalog) -> String {
let document = catalog.document();
let mut out = String::from("\nComponents:\n");
for (name, schema) in document
.get("components")
.and_then(Value::as_object)
.into_iter()
.flatten()
{
let (properties, required, checkable) = gather(schema);
let fields: Vec<String> = properties
.iter()
.filter(|(key, _)| *key != "component" && *key != "id")
.map(|(key, property)| {
let optional = if required.iter().any(|r| r == key) {
""
} else {
"?"
};
format!("{key}{optional}: {}", type_of(property, document))
})
.collect();
let checks = if checkable { " (accepts @checks)" } else { "" };
out.push_str(&format!("- {name} {{ {} }}{checks}\n", fields.join(", ")));
}
let functions: Vec<String> = document
.get("functions")
.and_then(Value::as_object)
.into_iter()
.flatten()
.filter(|(name, _)| {
catalog
.function(name)
.is_none_or(|def| def.callers != agent86_ui::Callers::AgentOnly)
})
.map(|(name, schema)| {
let args = schema.pointer("/properties/args");
let required: Vec<&str> = args
.and_then(|a| a.get("required"))
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let params: Vec<String> = args
.and_then(|a| a.get("properties"))
.and_then(Value::as_object)
.into_iter()
.flatten()
.map(|(key, property)| {
let optional = if required.contains(&key.as_str()) {
""
} else {
"?"
};
format!("{key}{optional}: {}", type_of(property, document))
})
.collect();
let returns = schema
.get("returnType")
.and_then(Value::as_str)
.unwrap_or("any");
format!("- {name}({}) -> {returns}\n", params.join(", "))
})
.collect();
if !functions.is_empty() {
out.push_str("\nFunctions:\n");
out.extend(functions);
}
out
}
fn gather(schema: &Value) -> (Map<String, Value>, Vec<String>, bool) {
let mut properties = Map::new();
let mut required = Vec::new();
let mut checkable = false;
let mut parts = vec![schema];
if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
parts.extend(all);
}
for part in parts {
if part
.get("$ref")
.and_then(Value::as_str)
.is_some_and(|r| r.ends_with("/Checkable"))
{
checkable = true;
}
if let Some(own) = part.get("properties").and_then(Value::as_object) {
for (key, value) in own {
properties.insert(key.clone(), value.clone());
}
}
required.extend(
part.get("required")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(String::from),
);
}
(properties, required, checkable)
}
fn type_of(property: &Value, document: &Value) -> String {
if let Some(target) = property.get("$ref").and_then(Value::as_str) {
if let Some(local) = target.strip_prefix("#/$defs/") {
if let Some(def) = document.pointer(&format!("/$defs/{local}")) {
if def.get("$ref").is_none() {
return type_of(def, document);
}
}
}
return target.rsplit('/').next().unwrap_or(target).to_string();
}
if let Some(values) = property.get("enum").and_then(Value::as_array) {
return values
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join("|");
}
match property.get("type").and_then(Value::as_str) {
Some("array") => match property.get("items") {
Some(items) => format!("array of {}", type_of(items, document)),
None => "array".into(),
},
Some(kind) => kind.to_string(),
None => "any".into(),
}
}
pub fn take_drawn(metadata: &mut Map<String, Value>) -> (Vec<AgentMessage>, Option<Value>) {
let messages = match metadata.remove(MESSAGES_KEY) {
Some(Value::Array(items)) => items
.into_iter()
.filter_map(|item| serde_json::from_value(item).ok())
.collect(),
_ => Vec::new(),
};
(messages, metadata.remove(TRACE_KEY))
}
const DREW: &[&str] = &["Rendered surface ", "Deleted surface ", "Applied."];
fn drew(result: &crate::types::ToolResult) -> bool {
let text = if result.ok {
result.content.as_str()
} else {
result.error.as_deref().unwrap_or_default()
};
result.ok
|| text
.lines()
.any(|line| DREW.iter().any(|opening| line.starts_with(opening)))
}
pub fn take_wait(metadata: &mut Map<String, Value>) -> Option<Vec<String>> {
match metadata.remove(WAIT_KEY)? {
Value::Array(ids) => Some(
ids.into_iter()
.filter_map(|id| id.as_str().map(String::from))
.collect(),
),
_ => None,
}
}
pub fn action_text(action: &Action) -> String {
let context = crate::pyjson::python_json_dumps(&Value::Object(action.context.clone()), false);
let mut text = format!(
"[ui action] {} on {}: {context}",
action.name, action.surface_id
);
if let Some(message) = action.user_message.as_deref().filter(|m| !m.is_empty()) {
text.push('\n');
text.push_str(message);
}
text
}
impl crate::agent::Harness {
pub fn attach_ui(&mut self, session: UiSession) -> Result<(), String> {
self.registry
.register(Box::new(crate::tools::render_ui::RenderUiTool))?;
self.context.ui = Some(std::sync::Arc::new(session));
Ok(())
}
pub fn accept_ui_action(&self, sid: &str, action: &Action) -> Result<String, String> {
let ui = self
.context
.ui
.as_deref()
.ok_or_else(|| String::from("this agent has no renderer"))?;
ui.check_action(action, None)?;
self.recorder.event(
sid,
"ui_action",
vec![
("surface", serde_json::json!(action.surface_id)),
("name", serde_json::json!(action.name)),
("component", serde_json::json!(action.source_component_id)),
("waited", serde_json::json!(false)),
],
);
Ok(action_text(action))
}
pub(crate) fn ui_wait(
&self,
call: &crate::types::ToolCall,
drawn: crate::types::ToolResult,
surfaces: Vec<String>,
sid: &str,
) -> crate::types::ToolResult {
use crate::tools::{failure, success};
let Some(ui) = self.context.ui.as_deref() else {
return drawn;
};
if surfaces.is_empty() {
return drawn;
}
let request = UiWait {
surface_ids: surfaces.clone(),
};
let question = crate::approval::Question {
tool: Some(RENDER_UI.into()),
call: Some(call.id.clone()),
..crate::approval::Question::new(crate::approval::QuestionKind::Ui)
};
let shown = drawn.content.clone();
let answered = |result: crate::types::ToolResult| crate::types::ToolResult {
call_id: drawn.call_id.clone(),
..result
};
let action = match self.gate.queue.ask(question, || ui.wait(&request)) {
None => {
return answered(failure(
RENDER_UI,
format!(
"The turn was cancelled before the user answered. The surface stays \
up; an action on it later comes as a user message.\n{shown}"
),
))
}
Some(None) => {
return answered(failure(
RENDER_UI,
format!(
"The user did not answer (they dismissed it). The surface stays up; an \
action on it later comes as a user message.\n{shown}"
),
))
}
Some(Some(action)) => action,
};
if let Err(why) = ui.check_action(&action, Some(&surfaces)) {
return answered(failure(
RENDER_UI,
format!("The screen's answer could not be used: {why}.\n{shown}"),
));
}
let text = self.context.secrets.redact(&action_text(&action));
let report = self.guardrails.inspect_ingress(&text);
if report.flagged() {
self.recorder.event(
sid,
"guardrail",
vec![
("stage", serde_json::json!("ingress")),
("source", serde_json::json!("ui_action")),
("findings", serde_json::json!(report.summary())),
],
);
}
self.recorder.event(
sid,
"ui_action",
vec![
("surface", serde_json::json!(action.surface_id)),
("name", serde_json::json!(action.name)),
("component", serde_json::json!(action.source_component_id)),
("waited", serde_json::json!(true)),
],
);
if self.guardrails.should_block(&report) {
return answered(failure(
RENDER_UI,
format!(
"The user's answer was refused by the input guardrail ({}).\n{shown}",
report.summary()
),
));
}
answered(success(RENDER_UI, format!("{shown}\n{text}")))
}
}
pub fn sanitize(value: &Value, vault: &crate::vault::SecretVault, egress: EgressMode) -> Value {
match value {
Value::String(text) => {
let text = vault.redact(text);
Value::String(if egress == EgressMode::Redact {
crate::guardrails::redact(&text).0
} else {
text
})
}
Value::Array(items) => Value::Array(
items
.iter()
.map(|item| sanitize(item, vault, egress))
.collect(),
),
Value::Object(map) => Value::Object(
map.iter()
.map(|(key, item)| (key.clone(), sanitize(item, vault, egress)))
.collect(),
),
other => other.clone(),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
pub path: String,
pub message: String,
}
impl std::fmt::Display for Refusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "REFUSED at {}: {}", self.path, self.message)
}
}
const MEDIA: &[(&str, &[&str])] = &[
("Image", &["url"]),
("Video", &["url", "posterUrl"]),
("AudioPlayer", &["url"]),
];
pub fn policy(
messages: &[Value],
jail: &crate::tools::SandboxPolicy,
remote_media: bool,
) -> Vec<Refusal> {
let mut refusals = Vec::new();
let mut refuse = |path: String, message: String| refusals.push(Refusal { path, message });
for (index, message) in messages.iter().enumerate() {
if message.get("callRendererFunction").is_some() {
refuse(
format!("/{index}/callRendererFunction"),
"renderer functions are not available here; draw with components and change \
them with updateComponents and updateDataModel instead"
.into(),
);
}
if message.get("agentFunctionResponse").is_some() {
refuse(
format!("/{index}/agentFunctionResponse"),
"agent functions are not available here".into(),
);
}
for kind in ["createSurface", "updateComponents"] {
let Some(components) = message
.get(kind)
.and_then(|body| body.get("components"))
.and_then(Value::as_array)
else {
continue;
};
for (number, component) in components.iter().enumerate() {
let at = format!("/{index}/{kind}/components/{number}");
let type_name = component.get("component").and_then(Value::as_str);
let id = component
.get("id")
.and_then(Value::as_str)
.unwrap_or("this component");
if type_name == Some("TextField")
&& component.get("variant").and_then(Value::as_str) == Some("obscured")
{
refuse(
format!("{at}/variant"),
format!(
"TextField {id} is \"obscured\", a password field, but a surface never \
collects secrets: call request_secret instead, which asks the user \
through a masked prompt and never shows you the value"
),
);
}
if let Some((_, properties)) =
MEDIA.iter().find(|(name, _)| Some(*name) == type_name)
{
for property in *properties {
let Some(value) = component.get(*property) else {
continue;
};
let path = format!("{at}/{property}");
match value.as_str() {
Some(url) => {
if let Some(why) = media_problem(url, jail, remote_media) {
refuse(path, format!("{id}'s {property} {why}"));
}
}
None => refuse(
path,
format!(
"{id}'s {property} must be a literal string: what a surface \
loads is checked before it is drawn, so it cannot come from a \
binding or a function call"
),
),
}
}
}
open_urls(component, &at, &mut refuse);
}
}
}
refusals
}
fn media_problem(
url: &str,
jail: &crate::tools::SandboxPolicy,
remote_media: bool,
) -> Option<String> {
match scheme(url) {
Some(scheme) if scheme == "data" => None,
Some(scheme) if scheme == "https" && remote_media => None,
Some(scheme) if scheme == "https" || scheme == "http" => Some(format!(
"{url:?} is a remote URL, and remote media is off here (a fetch can track the user \
or carry data out in its URL): use a data: URL or a file in the workspace"
)),
Some(scheme) => Some(format!(
"{url:?} uses {scheme}:, which a surface may not load: use a data: URL or a file in \
the workspace"
)),
None => match jail.resolve_within(url) {
Err(_) => Some(format!("{url:?} is outside the workspace")),
Ok(path) if !path.is_file() => Some(format!("{url:?} is not a file in the workspace")),
Ok(_) => None,
},
}
}
fn scheme(url: &str) -> Option<String> {
let (scheme, _) = url.split_once(':')?;
let valid = scheme.len() > 1
&& scheme.starts_with(|c: char| c.is_ascii_alphabetic())
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
valid.then(|| scheme.to_ascii_lowercase())
}
fn open_urls(value: &Value, at: &str, refuse: &mut impl FnMut(String, String)) {
match value {
Value::Object(map) => {
if map.get("@call").and_then(Value::as_str) == Some("openUrl") {
if let Some(url) = value.pointer("/args/url").and_then(Value::as_str) {
let scheme = scheme(url);
if !matches!(scheme.as_deref(), Some("http" | "https")) {
refuse(
format!("{at}/args/url"),
format!("openUrl only opens http and https URLs, not {url:?}"),
);
}
}
}
for (key, item) in map {
let segment = key.replace('~', "~0").replace('/', "~1");
open_urls(item, &format!("{at}/{segment}"), refuse);
}
}
Value::Array(items) => {
for (index, item) in items.iter().enumerate() {
open_urls(item, &format!("{at}/{index}"), refuse);
}
}
_ => {}
}
}
pub fn surface_text(surface_id: &str, tree: &agent86_ui::runtime::Node) -> String {
let mut lines = vec![format!(
"[agent86UI surface {:?}: this client cannot draw it, so it is shown as text; \
answer in your reply]",
crate::escape::show_controls(surface_id)
)];
node_text(tree, &mut lines);
lines.join("\n")
}
fn prop(node: &agent86_ui::runtime::Node, key: &str) -> String {
let text = match node.properties.get(key) {
Some(Value::String(text)) => text.clone(),
Some(Value::Null) | None => String::new(),
Some(Value::Number(number)) => number.to_string(),
Some(Value::Bool(flag)) => flag.to_string(),
Some(other) => other.to_string(),
};
crate::escape::show_controls(&text)
}
fn kids<'a>(node: &'a agent86_ui::runtime::Node, key: &str) -> &'a [agent86_ui::runtime::Node] {
node.children
.iter()
.find(|(name, _)| name == key)
.map(|(_, nodes)| nodes.as_slice())
.unwrap_or_default()
}
fn labeled(label: &str, rest: &str) -> String {
if label.is_empty() {
rest.to_owned()
} else {
format!("{label}: {rest}")
}
}
fn node_text(node: &agent86_ui::runtime::Node, out: &mut Vec<String>) {
if node.placeholder {
out.push("…".into());
return;
}
match node.component.as_str() {
"Text" => {
let text = prop(node, "text");
if !text.is_empty() {
out.push(text);
}
}
"Column" | "List" | "Row" => {
for child in kids(node, "children") {
node_text(child, out);
}
}
"Card" => {
for child in kids(node, "child") {
node_text(child, out);
}
}
"Divider" => out.push("---".into()),
"Button" => {
let label: Vec<String> = kids(node, "child")
.iter()
.flat_map(|child| child.walk())
.filter(|n| n.component == "Text")
.map(|n| prop(n, "text"))
.filter(|text| !text.is_empty())
.collect();
let label = if label.is_empty() {
crate::escape::show_controls(&node.id)
} else {
label.join(" ").replace('\n', " ")
};
out.push(format!("[{label}]"));
}
"TextField" | "DateTimeInput" => {
let value = prop(node, "value");
let shown = if value.is_empty() {
"(empty)".to_owned()
} else {
value
};
out.push(labeled(&prop(node, "label"), &shown));
}
"CheckBox" => {
let checked = node.properties.get("value").and_then(Value::as_bool) == Some(true);
let mark = if checked { "[x]" } else { "[ ]" };
out.push(format!("{mark} {}", prop(node, "label")));
}
"ChoicePicker" => {
let chosen: Vec<String> = match node.properties.get("value") {
Some(Value::Array(items)) => items
.iter()
.filter_map(|item| item.as_str().map(String::from))
.collect(),
Some(Value::String(one)) => vec![one.clone()],
_ => Vec::new(),
};
let options = node
.properties
.get("options")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let lettered: Vec<String> = options
.iter()
.enumerate()
.map(|(index, option)| {
let value = option.get("value").and_then(Value::as_str).unwrap_or("");
let label = match option.get("label") {
Some(Value::String(text)) => text.clone(),
Some(other) if !other.is_null() => other.to_string(),
_ => value.to_owned(),
};
let letter = char::from(b'a' + (index % 26) as u8);
let on = if chosen.iter().any(|c| c == value) {
" (chosen)"
} else {
""
};
format!("{letter}) {}{on}", crate::escape::show_controls(&label))
})
.collect();
out.push(labeled(&prop(node, "label"), &lettered.join(" ")));
}
"Slider" => {
let number = |key: &str| node.properties.get(key).and_then(Value::as_f64);
let show = |value: f64| {
if value.fract() == 0.0 && value.abs() < 1e15 {
format!("{}", value as i64)
} else {
format!("{value}")
}
};
let (min, max) = (number("min").unwrap_or(0.0), number("max").unwrap_or(100.0));
let value = number("value").unwrap_or(min);
out.push(labeled(
&prop(node, "label"),
&format!("{} ({} to {})", show(value), show(min), show(max)),
));
}
kind @ ("Image" | "Video" | "AudioPlayer") => {
let what = match kind {
"Image" => "image",
"Video" => "video",
_ => "audio",
};
let mut text = format!("[{what}]");
let description = prop(node, "description");
if !description.is_empty() {
text.push(' ');
text.push_str(&description);
}
let url = prop(node, "url");
if !url.is_empty() && !url.starts_with("data:") {
text.push(' ');
text.push_str(&url);
}
out.push(text);
}
"Icon" => out.push(format!("[{}]", prop(node, "name"))),
other => {
let name = if other.is_empty() { "?" } else { other };
out.push(format!(
"(a {} is not shown as text)",
crate::escape::show_controls(name)
));
}
}
for message in node.validation_errors() {
out.push(format!(" ! {}", crate::escape::show_controls(&message)));
}
for error in &node.errors {
out.push(format!("! {}", crate::escape::show_controls(error)));
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tools::SandboxPolicy;
use serde_json::json;
struct Jail(std::path::PathBuf, SandboxPolicy);
fn jail(name: &str) -> Jail {
let root = std::env::temp_dir().join(format!("agent86-ui-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("img")).unwrap();
std::fs::write(root.join("img/cat.png"), b"png").unwrap();
let policy = SandboxPolicy::new(&root).unwrap();
Jail(root, policy)
}
impl Drop for Jail {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn with_components(components: Value) -> Vec<Value> {
vec![json!({"version": "1.0", "createSurface": {
"surfaceId": "s", "catalogId": "c", "components": components
}})]
}
fn refused(messages: &[Value], jail: &Jail, remote: bool) -> Vec<String> {
policy(messages, &jail.1, remote)
.into_iter()
.map(|r| format!("{} {}", r.path, r.message))
.collect()
}
#[test]
fn a_password_field_is_refused_with_request_secret_named() {
let jail = jail("obscured");
let got = refused(
&with_components(json!([
{"id": "root", "component": "TextField", "label": "Password", "variant": "obscured"},
{"id": "note", "component": "TextField", "label": "Note", "variant": "longText"}
])),
&jail,
false,
);
assert_eq!(got.len(), 1, "{got:?}");
assert!(got[0].starts_with("/0/createSurface/components/0/variant TextField root"));
assert!(got[0].contains("request_secret"));
}
#[test]
fn media_loads_only_data_urls_and_workspace_files_unless_remote_is_on() {
let jail = jail("media");
let image =
|url: Value| with_components(json!([{"id": "root", "component": "Image", "url": url}]));
let ok = |url: Value, remote| refused(&image(url), &jail, remote).is_empty();
assert!(ok(json!("data:image/png;base64,iVBORw0KGgo="), false));
assert!(ok(json!("img/cat.png"), false));
assert!(!ok(json!("img/dog.png"), false), "missing file");
assert!(!ok(json!("../outside.png"), false), "outside the jail");
assert!(!ok(json!("https://example.com/cat.png"), false));
assert!(ok(json!("https://example.com/cat.png"), true));
assert!(!ok(json!("http://example.com/cat.png"), true), "only https");
assert!(!ok(json!("file:///etc/passwd"), true));
let bound = refused(&image(json!({"@path": "/url"})), &jail, true);
assert!(bound[0].contains("must be a literal string"), "{bound:?}");
let video = with_components(json!([{"id": "root", "component": "Video",
"url": "data:video/mp4;base64,AAAA", "posterUrl": "https://example.com/p.png"}]));
let got = refused(&video, &jail, false);
assert_eq!(got.len(), 1);
assert!(got[0].starts_with("/0/createSurface/components/0/posterUrl"));
}
#[test]
fn open_url_takes_only_http_and_https_literals() {
let jail = jail("open");
let button = |url: Value| {
with_components(json!([
{"id": "root", "component": "Button", "child": "t",
"action": {"functionCall": {"@call": "openUrl", "args": {"url": url}}}},
{"id": "t", "component": "Text", "text": "Go"}
]))
};
assert!(refused(&button(json!("https://example.com")), &jail, false).is_empty());
assert!(refused(&button(json!("http://example.com")), &jail, false).is_empty());
assert!(refused(&button(json!({"@path": "/link"})), &jail, false).is_empty());
let got = refused(&button(json!("javascript:alert(1)")), &jail, false);
assert_eq!(
got,
["/0/createSurface/components/0/action/functionCall/args/url openUrl only opens http and https URLs, not \"javascript:alert(1)\""]
);
}
#[test]
fn renderer_and_agent_functions_are_refused() {
let jail = jail("functions");
let got = refused(
&[
json!({"version": "1.0", "callRendererFunction": {"surfaceId": "s", "functionCallId": "f", "call": {"@call": "x"}}}),
json!({"version": "1.0", "agentFunctionResponse": {"functionCallId": "f", "value": 1}}),
],
&jail,
false,
);
assert!(got[0].starts_with("/0/callRendererFunction renderer functions are not available"));
assert!(got[1].starts_with("/1/agentFunctionResponse agent functions are not available"));
}
#[test]
fn a_drive_letter_is_not_a_scheme() {
assert_eq!(scheme("C:\\img\\cat.png"), None);
assert_eq!(scheme("HTTPS://x"), Some("https".into()));
assert_eq!(scheme("img/cat.png"), None);
}
#[test]
fn sanitize_redacts_secrets_and_with_egress_redact_what_the_guardrail_finds() {
let vault = crate::vault::SecretVault::default();
vault.set("API_TOKEN", "tok-abcdef-123456".into());
let message =
json!({"text": "use tok-abcdef-123456", "aws": "AKIAABCDEFGHIJKLMNOP", "n": 3});
let kept = sanitize(&message, &vault, EgressMode::Warn);
assert_eq!(kept["text"], "use ${secret:API_TOKEN}");
assert_eq!(kept["aws"], "AKIAABCDEFGHIJKLMNOP");
assert_eq!(kept["n"], 3);
let redacted = sanitize(&message, &vault, EgressMode::Redact);
assert_ne!(redacted["aws"], "AKIAABCDEFGHIJKLMNOP");
assert!(!redacted.to_string().contains("AKIA"), "{redacted}");
}
#[test]
fn the_basic_catalog_reference_names_components_and_functions() {
let reference = reference(Catalog::basic());
assert!(
reference.contains(
"- Button { child: Child, variant?: \"default\"|\"primary\"|\"borderless\", action: Action, weight?: number } (accepts @checks)"
),
"{reference}"
);
assert!(reference.contains("- TextField {"), "{reference}");
assert!(
reference.contains("- formatString(value: DynamicString) -> string"),
"{reference}"
);
assert!(!reference.contains("component:"), "{reference}");
}
#[test]
fn the_prompt_section_carries_the_catalog_instructions() {
let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
let section = session.prompt_section();
assert!(section.starts_with("## agent86UI: drawing UI with render_ui"));
assert!(section.contains(&format!("### Catalog `{}`", agent86_ui::BASIC_CATALOG_ID)));
assert!(section.contains("## Catalog Guidelines"));
assert!(section.contains("[ui action] submit on <surfaceId>"));
}
#[test]
fn fields_beside_the_kind_are_moved_inside_it() {
let (tidied, moved) = tidy(&serde_json::json!({
"version": "1.0",
"createSurface": {"catalogId": "c", "components": []},
"surfaceId": "plan"
}));
assert_eq!(
tidied,
serde_json::json!({"version": "1.0",
"createSurface": {"catalogId": "c", "components": [], "surfaceId": "plan"}})
);
assert_eq!(moved, ["surfaceId into createSurface"]);
for message in [
serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}, "surfaceId": "b"}),
serde_json::json!({"version": "1.0", "surfaceId": "b"}),
serde_json::json!({"version": "1.0", "deleteSurface": {}, "updateDataModel": {}, "x": 1}),
serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}}),
] {
assert_eq!(tidy(&message), (message.clone(), Vec::new()), "{message}");
}
}
#[test]
fn the_prompt_s_example_is_valid() {
let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
let call: Value =
serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, true)).unwrap();
let messages = call["messages"].as_array().unwrap();
let report = session.apply(messages);
assert!(report.is_ok(), "{:?}", report.errors);
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
let section = session.prompt_section();
assert!(section.contains("surfaceId` goes inside createSurface"));
assert!(
!section.contains("\"wait\":true"),
"no waiter, no wait in the example"
);
}
#[test]
fn a_waiter_set_later_offers_wait_from_then_on() {
let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
let request = UiWait {
surface_ids: vec!["s".into()],
};
assert!(!session.can_wait());
assert!(!session.prompt_section().contains("\"wait\": true"));
assert_eq!(session.wait(&request), None);
session.set_waiter(Some(std::sync::Arc::new(|wait: &UiWait| {
Some(Action::new(
"ok",
wait.surface_ids[0].clone(),
"root",
"2026-11-22T00:00:00Z",
Map::new(),
))
})));
assert!(session.can_wait());
assert!(session.prompt_section().contains("\"wait\": true"));
assert_eq!(session.wait(&request).map(|a| a.name), Some("ok".into()));
session.set_waiter(None);
assert!(!session.can_wait());
}
#[test]
fn orphans_are_warnings_and_dangling_references_errors() {
let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
let create = |components: Value| {
serde_json::json!({"version": "1.0", "createSurface": {
"surfaceId": "s",
"catalogId": agent86_ui::BASIC_CATALOG_ID,
"components": components,
}})
};
let report = session.apply(&[create(serde_json::json!([
{"id": "root", "component": "Column", "children": ["missing"]}
]))]);
assert!(report.errors[0].message.starts_with("Dangling reference"));
let report = session.apply(&[create(serde_json::json!([
{"id": "root", "component": "Text", "text": "hi"},
{"id": "spare", "component": "Text", "text": "nobody shows me"}
]))]);
assert!(report.is_ok(), "{:?}", report.errors);
assert!(report.warnings[0].message.contains("not reachable"));
assert_eq!(session.surface_ids(), ["s"]);
}
fn create_with(components: Value, data_model: Option<Value>) -> Value {
let mut body = json!({
"surfaceId": "s",
"catalogId": agent86_ui::BASIC_CATALOG_ID,
"components": components,
});
if let Some(model) = data_model {
body["dataModel"] = model;
}
json!({"version": "1.0", "createSurface": body})
}
fn submit_button() -> Value {
json!({"id": "go", "component": "Button", "child": "go_label",
"action": {"event": {"name": "submit"}}})
}
#[test]
fn a_button_without_context_sends_every_top_level_value() {
let message = create_with(
json!([
{"id": "root", "component": "Column", "children": ["plan", "note", "go"]},
{"id": "plan", "component": "ChoicePicker", "value": {"@path": "/plan"},
"options": [{"label": "A", "value": "a"}]},
{"id": "note", "component": "TextField", "label": "Note",
"value": {"@path": "/extra/note"}},
submit_button(),
]),
Some(json!({"plan": [], "size": 1})),
);
let (messages, notes) = complete(&[message], |_| Vec::new());
assert!(notes.is_empty(), "{notes:?}");
assert_eq!(
messages[0].pointer("/createSurface/components/3/action/event/context"),
Some(&json!({
"plan": {"@path": "/plan"},
"size": {"@path": "/size"},
"extra": {"@path": "/extra"}
}))
);
}
#[test]
fn a_context_the_model_gave_is_kept() {
let mut button = submit_button();
button["action"]["event"]["context"] = json!({"choice": "pro"});
let message = create_with(
json!([{"id": "root", "component": "Column", "children": ["go"]}, button]),
Some(json!({"plan": []})),
);
let (messages, _) = complete(&[message], |_| Vec::new());
assert_eq!(
messages[0].pointer("/createSurface/components/1/action/event/context"),
Some(&json!({"choice": "pro"}))
);
}
#[test]
fn a_button_added_later_sends_the_values_of_the_surface_already_up() {
let update = json!({"version": "1.0", "updateComponents": {
"surfaceId": "s",
"components": [submit_button()],
}});
let (messages, _) = complete(&[update], |id| {
assert_eq!(id, "s");
vec!["name".to_owned(), "a/b".to_owned()]
});
assert_eq!(
messages[0].pointer("/updateComponents/components/0/action/event/context"),
Some(&json!({"name": {"@path": "/name"}, "a/b": {"@path": "/a~1b"}}))
);
}
#[test]
fn a_lone_path_is_read_as_a_binding_and_noted() {
let mut button = submit_button();
button["action"]["event"]["context"] = json!({"plan": {"path": "/plan"}});
let message = create_with(
json!([
{"id": "root", "component": "Column",
"children": {"path": "/items", "componentId": "row"}},
{"id": "row", "component": "Text", "text": {"path": "/label"}},
button,
]),
Some(json!({"items": []})),
);
let (messages, notes) = complete(&[message], |_| Vec::new());
let components = &messages[0]["createSurface"]["components"];
assert_eq!(
components[0]["children"],
json!({"path": "/items", "componentId": "row"})
);
assert_eq!(components[1]["text"], json!({"@path": "/label"}));
assert_eq!(
components[2]["action"]["event"]["context"],
json!({"plan": {"@path": "/plan"}})
);
assert_eq!(
notes,
[
"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.",
"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.",
]
);
}
#[test]
fn the_completed_example_validates_and_its_button_sends_the_choice() {
let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
let call: Value =
serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, false)).unwrap();
let messages = call["messages"].as_array().unwrap().clone();
let (messages, _) = complete(&messages, |id| session.surface_keys(id));
assert!(session.apply(&messages).is_ok());
let submit = messages[0]["createSurface"]["components"]
.as_array()
.unwrap()
.iter()
.find(|component| component["id"] == "submit")
.unwrap();
assert_eq!(
submit["action"]["event"]["context"],
json!({"plan": {"@path": "/plan"}})
);
}
#[test]
fn a_surface_as_text_shows_each_component_as_the_user_reads_it() {
let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
let report = session.apply(&[serde_json::json!({"version": "1.0", "createSurface": {
"surfaceId": "order",
"catalogId": agent86_ui::BASIC_CATALOG_ID,
"components": [
{"id": "root", "component": "Column",
"children": ["title", "name", "note", "plan", "extras", "receipt", "seats",
"line", "logo", "tabs", "row"]},
{"id": "title", "component": "Text", "text": "Your order\u{1b}[31m"},
{"id": "name", "component": "TextField", "label": "Name", "value": {"@path": "/name"}},
{"id": "note", "component": "TextField", "label": "Note", "value": {"@path": "/note"}},
{"id": "plan", "component": "ChoicePicker", "label": "Plan",
"options": [{"label": "Free", "value": "free"}, {"label": "Pro", "value": "pro"}],
"value": {"@path": "/plan"}},
{"id": "extras", "component": "ChoicePicker", "variant": "multipleSelection",
"options": [{"label": "Gift wrap", "value": "wrap"}, {"label": "Card", "value": "card"}],
"value": {"@path": "/extras"}},
{"id": "receipt", "component": "CheckBox", "label": "Email me the receipt",
"value": {"@path": "/receipt"}},
{"id": "seats", "component": "Slider", "label": "Seats", "min": 1, "max": 10,
"value": {"@path": "/seats"}},
{"id": "line", "component": "Divider"},
{"id": "logo", "component": "Image", "description": "Our logo",
"url": "https://example.com/logo.png"},
{"id": "tabs", "component": "Tabs", "tabs": [{"title": "One", "child": "one"}]},
{"id": "one", "component": "Text", "text": "inside a tab"},
{"id": "row", "component": "Row", "children": ["ok", "cancel"]},
{"id": "ok", "component": "Button", "child": "ok_label",
"action": {"event": {"name": "submit"}}},
{"id": "ok_label", "component": "Text", "text": "OK"},
{"id": "cancel", "component": "Button", "child": "cancel_label",
"action": {"event": {"name": "cancel"}}},
{"id": "cancel_label", "component": "Text", "text": "Cancel"}
],
"dataModel": {"name": "Ada", "note": "", "plan": ["pro"], "extras": ["wrap", "card"],
"receipt": true, "seats": 3}
}})]);
assert!(report.is_ok(), "{:?}", report.errors);
assert_eq!(
session.surface_texts(),
[concat!(
"[agent86UI surface \"order\": this client cannot draw it, so it is shown as ",
"text; answer in your reply]\n",
"Your order\u{241b}[31m\n",
"Name: Ada\n",
"Note: (empty)\n",
"Plan: a) Free b) Pro (chosen)\n",
"a) Gift wrap (chosen) b) Card (chosen)\n",
"[x] Email me the receipt\n",
"Seats: 3 (1 to 10)\n",
"---\n",
"[image] Our logo https://example.com/logo.png\n",
"(a Tabs is not shown as text)\n",
"[OK]\n",
"[Cancel]"
)]
);
}
}