1use 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
17pub const RENDER_UI: &str = "render_ui";
19
20pub const MESSAGES_KEY: &str = "agent86ui_messages";
24
25pub const TRACE_KEY: &str = "agent86ui_trace";
28
29pub const WAIT_KEY: &str = "agent86ui_wait";
33
34#[derive(Debug, Clone, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct UiWait {
40 pub surface_ids: Vec<String>,
42}
43
44pub type UiWaiter = std::sync::Arc<dyn Fn(&UiWait) -> Option<Action> + Send + Sync>;
46
47pub const RULES: Rules = Rules::STRICT.allowing_orphans(true);
52
53pub struct UiSession {
55 catalogs: Vec<Catalog>,
56 runtime: Mutex<Runtime>,
57 egress: EgressMode,
60 remote_media: bool,
63 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 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 pub fn with_egress(mut self, mode: EgressMode) -> Self {
97 self.egress = mode;
98 self
99 }
100
101 pub fn with_remote_media(mut self, allow: bool) -> Self {
104 self.remote_media = allow;
105 self
106 }
107
108 pub fn with_waiter(self, waiter: Option<UiWaiter>) -> Self {
110 self.set_waiter(waiter);
111 self
112 }
113
114 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 pub fn can_wait(&self) -> bool {
130 self.waiter().is_some()
131 }
132
133 pub fn wait(&self, request: &UiWait) -> Option<Action> {
136 self.waiter().and_then(|waiter| waiter(request))
137 }
138
139 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 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 pub fn surface_keys(&self, surface_id: &str) -> Vec<String> {
193 surface_keys(&self.runtime(), surface_id)
194 }
195
196 pub fn apply(&self, messages: &[Value]) -> Report {
198 self.runtime().apply(messages)
199 }
200
201 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 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 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 pub fn surface_ids(&self) -> Vec<String> {
269 self.runtime().surface_ids().map(String::from).collect()
270 }
271
272 pub fn surface_texts(&self) -> Vec<String> {
276 let runtime = self.runtime();
277 let ids: Vec<String> = runtime.surface_ids().map(String::from).collect();
278 ids.iter()
279 .filter_map(|id| runtime.tree(id).map(|tree| surface_text(id, &tree)))
280 .collect()
281 }
282
283 pub fn prompt_section(&self) -> String {
287 let mut section = String::from(PROMPT);
288 let media = if self.remote_media {
289 "a data: URL, an https URL, or the path of a file in the workspace"
290 } else {
291 "a data: URL or the path of a file in the workspace (remote URLs are not loaded)"
292 };
293 if self.can_wait() {
294 section.push_str(
295 "\n- With `\"wait\": true` the call waits for the user's first action on \
296 the surface and returns it as its result (`[ui action] ...`). Use it for a \
297 form you need answered before you can go on; otherwise leave it out and \
298 carry on.",
299 );
300 }
301 section.push_str(&format!(
302 "\n- Never ask for a password, key, or token in a surface (no TextField with \
303 variant \"obscured\"): call request_secret, which asks through a masked prompt \
304 and never shows you the value.\n- The url (and a Video's posterUrl) of Image, \
305 Video, and AudioPlayer must be a literal string: {media}.\n- openUrl opens only \
306 http and https URLs."
307 ));
308 if let Some(catalog) = self.catalogs.first() {
309 section.push_str(&format!(
310 "\n\nA complete call, a choice with a Submit button (`surfaceId` goes \
311 inside createSurface, never beside it):\n{}",
312 example(catalog.id(), self.can_wait())
313 ));
314 }
315 for catalog in &self.catalogs {
316 section.push_str(&format!("\n\n### Catalog `{}`\n", catalog.id()));
317 if let Some(instructions) = catalog.instructions() {
318 section.push('\n');
319 section.push_str(instructions.trim());
320 section.push('\n');
321 }
322 section.push_str(&reference(catalog));
323 }
324 section
325 }
326}
327
328const KINDS: &[&str] = &[
331 "createSurface",
332 "updateComponents",
333 "updateDataModel",
334 "deleteSurface",
335 "callRendererFunction",
336 "agentFunctionResponse",
337];
338
339pub fn tidy(message: &Value) -> (Value, Vec<String>) {
347 let Some(envelope) = message.as_object() else {
348 return (message.clone(), Vec::new());
349 };
350 let kinds: Vec<&String> = envelope
351 .keys()
352 .filter(|key| KINDS.contains(&key.as_str()))
353 .collect();
354 let [kind] = kinds.as_slice() else {
355 return (message.clone(), Vec::new());
356 };
357 let kind = (*kind).clone();
358 let Some(body) = envelope.get(&kind).and_then(Value::as_object) else {
359 return (message.clone(), Vec::new());
360 };
361 let strays: Vec<String> = envelope
362 .keys()
363 .filter(|key| *key != "version" && **key != kind && !body.contains_key(*key))
364 .cloned()
365 .collect();
366 if strays.is_empty() {
367 return (message.clone(), Vec::new());
368 }
369 let mut envelope = envelope.clone();
370 let mut body = body.clone();
371 for key in &strays {
372 if let Some(value) = envelope.remove(key) {
373 body.insert(key.clone(), value);
374 }
375 }
376 envelope.insert(kind.clone(), Value::Object(body));
377 let moved = strays
378 .into_iter()
379 .map(|key| format!("{key} into {kind}"))
380 .collect();
381 (Value::Object(envelope), moved)
382}
383
384pub fn complete(
404 messages: &[Value],
405 existing: impl Fn(&str) -> Vec<String>,
406) -> (Vec<Value>, Vec<String>) {
407 let mut keys: std::collections::HashMap<String, Vec<String>> = Default::default();
408 let mut notes = Vec::new();
409 let mut out = Vec::with_capacity(messages.len());
410 for (index, message) in messages.iter().enumerate() {
411 let mut message = message.clone();
412 if let Some(create) = message.get_mut("createSurface") {
413 let id = surface_of(create);
414 let mut known = Vec::new();
415 if let Some(Value::Object(model)) = create.get("dataModel") {
416 extend_unique(&mut known, model.keys().cloned());
417 }
418 rebind(
419 create,
420 &format!("messages/{index}/createSurface"),
421 &mut notes,
422 );
423 extend_unique(&mut known, bound_keys(create.get("components")));
424 fill_contexts(create, &known);
425 keys.insert(id, known);
426 } else if let Some(update) = message.get_mut("updateComponents") {
427 let id = surface_of(update);
428 let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
429 rebind(
430 update,
431 &format!("messages/{index}/updateComponents"),
432 &mut notes,
433 );
434 extend_unique(known, bound_keys(update.get("components")));
435 fill_contexts(update, known);
436 } else if let Some(update) = message.get("updateDataModel") {
437 let id = surface_of(update);
438 let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
439 match update.get("path").and_then(Value::as_str) {
440 None | Some("" | "/") => {
441 if let Some(Value::Object(model)) = update.get("value") {
442 extend_unique(known, model.keys().cloned());
443 }
444 }
445 Some(path) => extend_unique(known, top_segment(path)),
446 }
447 }
448 out.push(message);
449 }
450 (out, notes)
451}
452
453pub fn surface_keys(runtime: &Runtime, surface_id: &str) -> Vec<String> {
456 let mut keys = Vec::new();
457 if let Some(Value::Object(model)) = runtime.data_model(surface_id) {
458 extend_unique(&mut keys, model.keys().cloned());
459 }
460 if let Some(components) = runtime.components(surface_id) {
461 let components = Value::Array(components.cloned().collect());
462 extend_unique(&mut keys, bound_keys(Some(&components)));
463 }
464 keys
465}
466
467fn surface_of(body: &Value) -> String {
468 body.get("surfaceId")
469 .and_then(Value::as_str)
470 .unwrap_or_default()
471 .to_owned()
472}
473
474fn extend_unique(keys: &mut Vec<String>, more: impl IntoIterator<Item = String>) {
475 for key in more {
476 if !keys.contains(&key) {
477 keys.push(key);
478 }
479 }
480}
481
482fn top_segment(path: &str) -> Option<String> {
484 let rest = path.strip_prefix('/')?;
485 let segment = rest.split('/').next().unwrap_or_default();
486 (!segment.is_empty()).then(|| segment.replace("~1", "/").replace("~0", "~"))
487}
488
489fn bound_keys(value: Option<&Value>) -> Vec<String> {
491 fn walk(value: &Value, keys: &mut Vec<String>) {
492 match value {
493 Value::Object(map) => {
494 if let Some(Value::String(path)) = map.get("@path") {
495 extend_unique(keys, top_segment(path));
496 }
497 map.values().for_each(|value| walk(value, keys));
498 }
499 Value::Array(items) => items.iter().for_each(|value| walk(value, keys)),
500 _ => {}
501 }
502 }
503 let mut keys = Vec::new();
504 if let Some(value) = value {
505 walk(value, &mut keys);
506 }
507 keys
508}
509
510fn rebind(body: &mut Value, at: &str, notes: &mut Vec<String>) {
513 fn walk(value: &mut Value) -> bool {
514 match value {
515 Value::Object(map) => {
516 let lone_path = map.len() == 1
517 && map
518 .get("path")
519 .and_then(Value::as_str)
520 .is_some_and(|path| path.starts_with('/'));
521 if lone_path {
522 let path = map.remove("path").expect("checked above");
523 map.insert("@path".to_owned(), path);
524 return true;
525 }
526 let mut changed = false;
527 for value in map.values_mut() {
528 changed |= walk(value);
529 }
530 changed
531 }
532 Value::Array(items) => items
533 .iter_mut()
534 .fold(false, |changed, item| walk(item) | changed),
535 _ => false,
536 }
537 }
538 let Some(Value::Array(components)) = body.get_mut("components") else {
539 return;
540 };
541 for (index, component) in components.iter_mut().enumerate() {
542 let Value::Object(fields) = component else {
543 continue;
544 };
545 let mut changed = false;
546 for (key, value) in fields.iter_mut() {
547 if key != "id" && key != "component" {
548 changed |= walk(value);
549 }
550 }
551 if changed {
552 let id = fields.get("id").and_then(Value::as_str).unwrap_or("?");
553 notes.push(format!(
554 "Note: read {{\"path\": ...}} as {{\"@path\": ...}} in {at}/components/{index} \
555 ({id}); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal."
556 ));
557 }
558 }
559}
560
561fn fill_contexts(body: &mut Value, keys: &[String]) {
564 let Some(Value::Array(components)) = body.get_mut("components") else {
565 return;
566 };
567 for component in components.iter_mut() {
568 if component.get("component").and_then(Value::as_str) != Some("Button") {
569 continue;
570 }
571 let Some(Value::Object(event)) = component.pointer_mut("/action/event") else {
572 continue;
573 };
574 if event.contains_key("context") {
575 continue;
576 }
577 let context: Map<String, Value> = keys
578 .iter()
579 .map(|key| {
580 let pointer = format!("/{}", key.replace('~', "~0").replace('/', "~1"));
581 (key.clone(), serde_json::json!({"@path": pointer}))
582 })
583 .collect();
584 event.insert("context".to_owned(), Value::Object(context));
585 }
586}
587
588pub fn is_event_button(component: &Value) -> bool {
591 component.get("component").and_then(Value::as_str) == Some("Button")
592 && component.pointer("/action/event").is_some()
593}
594
595fn example(catalog_id: &str, wait: bool) -> String {
597 let mut call = serde_json::json!({"messages": [{"version": "1.0", "createSurface": {
598 "surfaceId": "plan",
599 "catalogId": catalog_id,
600 "components": [
601 {"id": "root", "component": "Column", "children": ["choice", "submit"]},
602 {"id": "choice", "component": "ChoicePicker", "label": "Which plan?",
603 "variant": "mutuallyExclusive", "value": {"@path": "/plan"},
604 "options": [{"label": "Basic", "value": "basic"}, {"label": "Pro", "value": "pro"}]},
605 {"id": "submit", "component": "Button", "child": "submit_label",
606 "action": {"event": {"name": "submit"}}},
607 {"id": "submit_label", "component": "Text", "text": "Submit"}
608 ],
609 "dataModel": {"plan": []}
610 }}]});
611 if wait {
612 call["wait"] = Value::Bool(true);
613 }
614 call.to_string()
615}
616
617const PROMPT: &str = "## agent86UI: drawing UI with render_ui
619
620You can show the user interactive UI (forms, choices, confirmations, small \
621dashboards) by calling render_ui with A2UI 1.0 messages; the user's screen draws \
622them with its own widgets. Use it when you need a structured answer (pick one of \
623several options, fill in a few fields, confirm a plan) or when a layout says more \
624than prose. Otherwise answer in plain text.
625
626- `messages` is a list of A2UI messages, each `{\"version\": \"1.0\", ...}` with \
627exactly one of `createSurface`, `updateComponents`, `updateDataModel`, or \
628`deleteSurface`. Create a surface once with createSurface (a new `surfaceId`, a \
629`catalogId` from below, and usually its `components` and `dataModel` inline), \
630change it later with updateComponents (a component replaces the one with the same \
631id) and updateDataModel (`path` and `value`), and remove it with deleteSurface.
632- Components are a flat list linked by id, and exactly one has the id \"root\". \
633Every child id must be defined in the same call or an earlier one. An id is an \
634identifier: letters, digits, and `_`, starting with a letter or `_` (`submit_label`, \
635never `submit-label`).
636- A value is a literal, a binding to the surface's data model (`{\"@path\": \
637\"/form/name\"}`), or a function call (`{\"@call\": \"formatString\", \"args\": \
638{...}}`). Input components write what the user enters back to the path they are \
639bound to. A `ChildList` is an array of ids, or a template over a list in the data \
640model (`{\"path\": \"/items\", \"componentId\": \"row\"}`) whose bindings are \
641relative to each item.
642- A button's action is `{\"event\": {\"name\": \"submit\"}}`, and it sends every \
643top-level value of the surface's data model. To send something else, give the \
644event a `context` beside `name` (`{\"event\": {\"name\": \"pick\", \"context\": \
645{\"plan\": \"pro\"}}}`), never beside `event`. When the user presses it, a later \
646user message reads `[ui action] submit on <surfaceId>: <values as JSON>`; the \
647surface stays up meanwhile.
648- Only a Button whose action is an event sends the user's answer: choosing an \
649option or typing only changes the data model. So every form needs a Button (for \
650example Submit).
651- Keep each call short: a surface's JSON breaks most often when it is large. For \
652a form of more than about four inputs, send createSurface with the root and the \
653first few components, then add the rest in further calls with updateComponents, \
654sending the root again with its longer `children`; put `wait` only on the last call.
655- render_ui's result is the validator's verdict. If it lists problems, nothing \
656was drawn: fix them and send the corrected messages again.
657- Renderer functions (`callRendererFunction`) and agent functions are not \
658available.";
659
660pub fn reference(catalog: &Catalog) -> String {
664 let document = catalog.document();
665 let mut out = String::from("\nComponents:\n");
666 for (name, schema) in document
667 .get("components")
668 .and_then(Value::as_object)
669 .into_iter()
670 .flatten()
671 {
672 let (properties, required, checkable) = gather(schema);
673 let fields: Vec<String> = properties
674 .iter()
675 .filter(|(key, _)| *key != "component" && *key != "id")
676 .map(|(key, property)| {
677 let optional = if required.iter().any(|r| r == key) {
678 ""
679 } else {
680 "?"
681 };
682 format!("{key}{optional}: {}", type_of(property, document))
683 })
684 .collect();
685 let checks = if checkable { " (accepts @checks)" } else { "" };
686 out.push_str(&format!("- {name} {{ {} }}{checks}\n", fields.join(", ")));
687 }
688 let functions: Vec<String> = document
689 .get("functions")
690 .and_then(Value::as_object)
691 .into_iter()
692 .flatten()
693 .filter(|(name, _)| {
694 catalog
695 .function(name)
696 .is_none_or(|def| def.callers != agent86_ui::Callers::AgentOnly)
697 })
698 .map(|(name, schema)| {
699 let args = schema.pointer("/properties/args");
700 let required: Vec<&str> = args
701 .and_then(|a| a.get("required"))
702 .and_then(Value::as_array)
703 .into_iter()
704 .flatten()
705 .filter_map(Value::as_str)
706 .collect();
707 let params: Vec<String> = args
708 .and_then(|a| a.get("properties"))
709 .and_then(Value::as_object)
710 .into_iter()
711 .flatten()
712 .map(|(key, property)| {
713 let optional = if required.contains(&key.as_str()) {
714 ""
715 } else {
716 "?"
717 };
718 format!("{key}{optional}: {}", type_of(property, document))
719 })
720 .collect();
721 let returns = schema
722 .get("returnType")
723 .and_then(Value::as_str)
724 .unwrap_or("any");
725 format!("- {name}({}) -> {returns}\n", params.join(", "))
726 })
727 .collect();
728 if !functions.is_empty() {
729 out.push_str("\nFunctions:\n");
730 out.extend(functions);
731 }
732 out
733}
734
735fn gather(schema: &Value) -> (Map<String, Value>, Vec<String>, bool) {
738 let mut properties = Map::new();
739 let mut required = Vec::new();
740 let mut checkable = false;
741 let mut parts = vec![schema];
742 if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
743 parts.extend(all);
744 }
745 for part in parts {
746 if part
747 .get("$ref")
748 .and_then(Value::as_str)
749 .is_some_and(|r| r.ends_with("/Checkable"))
750 {
751 checkable = true;
752 }
753 if let Some(own) = part.get("properties").and_then(Value::as_object) {
754 for (key, value) in own {
755 properties.insert(key.clone(), value.clone());
756 }
757 }
758 required.extend(
759 part.get("required")
760 .and_then(Value::as_array)
761 .into_iter()
762 .flatten()
763 .filter_map(Value::as_str)
764 .map(String::from),
765 );
766 }
767 (properties, required, checkable)
768}
769
770fn type_of(property: &Value, document: &Value) -> String {
774 if let Some(target) = property.get("$ref").and_then(Value::as_str) {
775 if let Some(local) = target.strip_prefix("#/$defs/") {
776 if let Some(def) = document.pointer(&format!("/$defs/{local}")) {
777 if def.get("$ref").is_none() {
778 return type_of(def, document);
779 }
780 }
781 }
782 return target.rsplit('/').next().unwrap_or(target).to_string();
783 }
784 if let Some(values) = property.get("enum").and_then(Value::as_array) {
785 return values
786 .iter()
787 .map(|v| v.to_string())
788 .collect::<Vec<_>>()
789 .join("|");
790 }
791 match property.get("type").and_then(Value::as_str) {
792 Some("array") => match property.get("items") {
793 Some(items) => format!("array of {}", type_of(items, document)),
794 None => "array".into(),
795 },
796 Some(kind) => kind.to_string(),
797 None => "any".into(),
798 }
799}
800
801pub fn take_drawn(metadata: &mut Map<String, Value>) -> (Vec<AgentMessage>, Option<Value>) {
805 let messages = match metadata.remove(MESSAGES_KEY) {
806 Some(Value::Array(items)) => items
807 .into_iter()
808 .filter_map(|item| serde_json::from_value(item).ok())
809 .collect(),
810 _ => Vec::new(),
811 };
812 (messages, metadata.remove(TRACE_KEY))
813}
814
815const DREW: &[&str] = &["Rendered surface ", "Deleted surface ", "Applied."];
817
818fn drew(result: &crate::types::ToolResult) -> bool {
822 let text = if result.ok {
823 result.content.as_str()
824 } else {
825 result.error.as_deref().unwrap_or_default()
826 };
827 result.ok
828 || text
829 .lines()
830 .any(|line| DREW.iter().any(|opening| line.starts_with(opening)))
831}
832
833pub fn take_wait(metadata: &mut Map<String, Value>) -> Option<Vec<String>> {
835 match metadata.remove(WAIT_KEY)? {
836 Value::Array(ids) => Some(
837 ids.into_iter()
838 .filter_map(|id| id.as_str().map(String::from))
839 .collect(),
840 ),
841 _ => None,
842 }
843}
844
845pub fn action_text(action: &Action) -> String {
849 let context = crate::pyjson::python_json_dumps(&Value::Object(action.context.clone()), false);
850 let mut text = format!(
851 "[ui action] {} on {}: {context}",
852 action.name, action.surface_id
853 );
854 if let Some(message) = action.user_message.as_deref().filter(|m| !m.is_empty()) {
855 text.push('\n');
856 text.push_str(message);
857 }
858 text
859}
860
861impl crate::agent::Harness {
862 pub fn attach_ui(&mut self, session: UiSession) -> Result<(), String> {
867 self.registry
868 .register(Box::new(crate::tools::render_ui::RenderUiTool))?;
869 self.context.ui = Some(std::sync::Arc::new(session));
870 Ok(())
871 }
872
873 pub fn accept_ui_action(&self, sid: &str, action: &Action) -> Result<String, String> {
881 let ui = self
882 .context
883 .ui
884 .as_deref()
885 .ok_or_else(|| String::from("this agent has no renderer"))?;
886 ui.check_action(action, None)?;
887 self.recorder.event(
888 sid,
889 "ui_action",
890 vec![
891 ("surface", serde_json::json!(action.surface_id)),
892 ("name", serde_json::json!(action.name)),
893 ("component", serde_json::json!(action.source_component_id)),
894 ("waited", serde_json::json!(false)),
895 ],
896 );
897 Ok(action_text(action))
898 }
899
900 pub(crate) fn ui_wait(
906 &self,
907 call: &crate::types::ToolCall,
908 drawn: crate::types::ToolResult,
909 surfaces: Vec<String>,
910 sid: &str,
911 ) -> crate::types::ToolResult {
912 use crate::tools::{failure, success};
913 let Some(ui) = self.context.ui.as_deref() else {
914 return drawn;
915 };
916 if surfaces.is_empty() {
917 return drawn;
918 }
919 let request = UiWait {
920 surface_ids: surfaces.clone(),
921 };
922 let question = crate::approval::Question {
923 tool: Some(RENDER_UI.into()),
924 call: Some(call.id.clone()),
925 ..crate::approval::Question::new(crate::approval::QuestionKind::Ui)
926 };
927 let shown = drawn.content.clone();
928 let answered = |result: crate::types::ToolResult| crate::types::ToolResult {
929 call_id: drawn.call_id.clone(),
930 ..result
931 };
932 let action = match self.gate.queue.ask(question, || ui.wait(&request)) {
933 None => {
934 return answered(failure(
935 RENDER_UI,
936 format!(
937 "The turn was cancelled before the user answered. The surface stays \
938 up; an action on it later comes as a user message.\n{shown}"
939 ),
940 ))
941 }
942 Some(None) => {
943 return answered(failure(
944 RENDER_UI,
945 format!(
946 "The user did not answer (they dismissed it). The surface stays up; an \
947 action on it later comes as a user message.\n{shown}"
948 ),
949 ))
950 }
951 Some(Some(action)) => action,
952 };
953 if let Err(why) = ui.check_action(&action, Some(&surfaces)) {
954 return answered(failure(
955 RENDER_UI,
956 format!("The screen's answer could not be used: {why}.\n{shown}"),
957 ));
958 }
959 let text = self.context.secrets.redact(&action_text(&action));
960 let report = self.guardrails.inspect_ingress(&text);
961 if report.flagged() {
962 self.recorder.event(
963 sid,
964 "guardrail",
965 vec![
966 ("stage", serde_json::json!("ingress")),
967 ("source", serde_json::json!("ui_action")),
968 ("findings", serde_json::json!(report.summary())),
969 ],
970 );
971 }
972 self.recorder.event(
973 sid,
974 "ui_action",
975 vec![
976 ("surface", serde_json::json!(action.surface_id)),
977 ("name", serde_json::json!(action.name)),
978 ("component", serde_json::json!(action.source_component_id)),
979 ("waited", serde_json::json!(true)),
980 ],
981 );
982 if self.guardrails.should_block(&report) {
983 return answered(failure(
984 RENDER_UI,
985 format!(
986 "The user's answer was refused by the input guardrail ({}).\n{shown}",
987 report.summary()
988 ),
989 ));
990 }
991 answered(success(RENDER_UI, format!("{shown}\n{text}")))
992 }
993}
994
995pub fn sanitize(value: &Value, vault: &crate::vault::SecretVault, egress: EgressMode) -> Value {
999 match value {
1000 Value::String(text) => {
1001 let text = vault.redact(text);
1002 Value::String(if egress == EgressMode::Redact {
1003 crate::guardrails::redact(&text).0
1004 } else {
1005 text
1006 })
1007 }
1008 Value::Array(items) => Value::Array(
1009 items
1010 .iter()
1011 .map(|item| sanitize(item, vault, egress))
1012 .collect(),
1013 ),
1014 Value::Object(map) => Value::Object(
1015 map.iter()
1016 .map(|(key, item)| (key.clone(), sanitize(item, vault, egress)))
1017 .collect(),
1018 ),
1019 other => other.clone(),
1020 }
1021}
1022
1023#[derive(Debug, Clone, PartialEq, Eq)]
1026pub struct Refusal {
1027 pub path: String,
1028 pub message: String,
1029}
1030
1031impl std::fmt::Display for Refusal {
1032 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1033 write!(f, "REFUSED at {}: {}", self.path, self.message)
1034 }
1035}
1036
1037const MEDIA: &[(&str, &[&str])] = &[
1040 ("Image", &["url"]),
1041 ("Video", &["url", "posterUrl"]),
1042 ("AudioPlayer", &["url"]),
1043];
1044
1045pub fn policy(
1055 messages: &[Value],
1056 jail: &crate::tools::SandboxPolicy,
1057 remote_media: bool,
1058) -> Vec<Refusal> {
1059 let mut refusals = Vec::new();
1060 let mut refuse = |path: String, message: String| refusals.push(Refusal { path, message });
1061 for (index, message) in messages.iter().enumerate() {
1062 if message.get("callRendererFunction").is_some() {
1063 refuse(
1064 format!("/{index}/callRendererFunction"),
1065 "renderer functions are not available here; draw with components and change \
1066 them with updateComponents and updateDataModel instead"
1067 .into(),
1068 );
1069 }
1070 if message.get("agentFunctionResponse").is_some() {
1071 refuse(
1072 format!("/{index}/agentFunctionResponse"),
1073 "agent functions are not available here".into(),
1074 );
1075 }
1076 for kind in ["createSurface", "updateComponents"] {
1077 let Some(components) = message
1078 .get(kind)
1079 .and_then(|body| body.get("components"))
1080 .and_then(Value::as_array)
1081 else {
1082 continue;
1083 };
1084 for (number, component) in components.iter().enumerate() {
1085 let at = format!("/{index}/{kind}/components/{number}");
1086 let type_name = component.get("component").and_then(Value::as_str);
1087 let id = component
1088 .get("id")
1089 .and_then(Value::as_str)
1090 .unwrap_or("this component");
1091 if type_name == Some("TextField")
1092 && component.get("variant").and_then(Value::as_str) == Some("obscured")
1093 {
1094 refuse(
1095 format!("{at}/variant"),
1096 format!(
1097 "TextField {id} is \"obscured\", a password field, but a surface never \
1098 collects secrets: call request_secret instead, which asks the user \
1099 through a masked prompt and never shows you the value"
1100 ),
1101 );
1102 }
1103 if let Some((_, properties)) =
1104 MEDIA.iter().find(|(name, _)| Some(*name) == type_name)
1105 {
1106 for property in *properties {
1107 let Some(value) = component.get(*property) else {
1108 continue;
1109 };
1110 let path = format!("{at}/{property}");
1111 match value.as_str() {
1112 Some(url) => {
1113 if let Some(why) = media_problem(url, jail, remote_media) {
1114 refuse(path, format!("{id}'s {property} {why}"));
1115 }
1116 }
1117 None => refuse(
1118 path,
1119 format!(
1120 "{id}'s {property} must be a literal string: what a surface \
1121 loads is checked before it is drawn, so it cannot come from a \
1122 binding or a function call"
1123 ),
1124 ),
1125 }
1126 }
1127 }
1128 open_urls(component, &at, &mut refuse);
1129 }
1130 }
1131 }
1132 refusals
1133}
1134
1135fn media_problem(
1137 url: &str,
1138 jail: &crate::tools::SandboxPolicy,
1139 remote_media: bool,
1140) -> Option<String> {
1141 match scheme(url) {
1142 Some(scheme) if scheme == "data" => None,
1143 Some(scheme) if scheme == "https" && remote_media => None,
1144 Some(scheme) if scheme == "https" || scheme == "http" => Some(format!(
1145 "{url:?} is a remote URL, and remote media is off here (a fetch can track the user \
1146 or carry data out in its URL): use a data: URL or a file in the workspace"
1147 )),
1148 Some(scheme) => Some(format!(
1149 "{url:?} uses {scheme}:, which a surface may not load: use a data: URL or a file in \
1150 the workspace"
1151 )),
1152 None => match jail.resolve_within(url) {
1153 Err(_) => Some(format!("{url:?} is outside the workspace")),
1154 Ok(path) if !path.is_file() => Some(format!("{url:?} is not a file in the workspace")),
1155 Ok(_) => None,
1156 },
1157 }
1158}
1159
1160fn scheme(url: &str) -> Option<String> {
1163 let (scheme, _) = url.split_once(':')?;
1164 let valid = scheme.len() > 1
1165 && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
1166 && scheme
1167 .chars()
1168 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
1169 valid.then(|| scheme.to_ascii_lowercase())
1170}
1171
1172fn open_urls(value: &Value, at: &str, refuse: &mut impl FnMut(String, String)) {
1175 match value {
1176 Value::Object(map) => {
1177 if map.get("@call").and_then(Value::as_str) == Some("openUrl") {
1178 if let Some(url) = value.pointer("/args/url").and_then(Value::as_str) {
1179 let scheme = scheme(url);
1180 if !matches!(scheme.as_deref(), Some("http" | "https")) {
1181 refuse(
1182 format!("{at}/args/url"),
1183 format!("openUrl only opens http and https URLs, not {url:?}"),
1184 );
1185 }
1186 }
1187 }
1188 for (key, item) in map {
1189 let segment = key.replace('~', "~0").replace('/', "~1");
1190 open_urls(item, &format!("{at}/{segment}"), refuse);
1191 }
1192 }
1193 Value::Array(items) => {
1194 for (index, item) in items.iter().enumerate() {
1195 open_urls(item, &format!("{at}/{index}"), refuse);
1196 }
1197 }
1198 _ => {}
1199 }
1200}
1201
1202pub fn surface_text(surface_id: &str, tree: &agent86_ui::runtime::Node) -> String {
1210 let mut lines = vec![format!(
1211 "[agent86UI surface {:?}: this client cannot draw it, so it is shown as text; \
1212 answer in your reply]",
1213 crate::escape::show_controls(surface_id)
1214 )];
1215 node_text(tree, &mut lines);
1216 lines.join("\n")
1217}
1218
1219fn prop(node: &agent86_ui::runtime::Node, key: &str) -> String {
1222 let text = match node.properties.get(key) {
1223 Some(Value::String(text)) => text.clone(),
1224 Some(Value::Null) | None => String::new(),
1225 Some(Value::Number(number)) => number.to_string(),
1226 Some(Value::Bool(flag)) => flag.to_string(),
1227 Some(other) => other.to_string(),
1228 };
1229 crate::escape::show_controls(&text)
1230}
1231
1232fn kids<'a>(node: &'a agent86_ui::runtime::Node, key: &str) -> &'a [agent86_ui::runtime::Node] {
1233 node.children
1234 .iter()
1235 .find(|(name, _)| name == key)
1236 .map(|(_, nodes)| nodes.as_slice())
1237 .unwrap_or_default()
1238}
1239
1240fn labeled(label: &str, rest: &str) -> String {
1242 if label.is_empty() {
1243 rest.to_owned()
1244 } else {
1245 format!("{label}: {rest}")
1246 }
1247}
1248
1249fn node_text(node: &agent86_ui::runtime::Node, out: &mut Vec<String>) {
1250 if node.placeholder {
1251 out.push("…".into());
1252 return;
1253 }
1254 match node.component.as_str() {
1255 "Text" => {
1256 let text = prop(node, "text");
1257 if !text.is_empty() {
1258 out.push(text);
1259 }
1260 }
1261 "Column" | "List" | "Row" => {
1262 for child in kids(node, "children") {
1263 node_text(child, out);
1264 }
1265 }
1266 "Card" => {
1267 for child in kids(node, "child") {
1268 node_text(child, out);
1269 }
1270 }
1271 "Divider" => out.push("---".into()),
1272 "Button" => {
1273 let label: Vec<String> = kids(node, "child")
1274 .iter()
1275 .flat_map(|child| child.walk())
1276 .filter(|n| n.component == "Text")
1277 .map(|n| prop(n, "text"))
1278 .filter(|text| !text.is_empty())
1279 .collect();
1280 let label = if label.is_empty() {
1281 crate::escape::show_controls(&node.id)
1282 } else {
1283 label.join(" ").replace('\n', " ")
1284 };
1285 out.push(format!("[{label}]"));
1286 }
1287 "TextField" | "DateTimeInput" => {
1288 let value = prop(node, "value");
1289 let shown = if value.is_empty() {
1290 "(empty)".to_owned()
1291 } else {
1292 value
1293 };
1294 out.push(labeled(&prop(node, "label"), &shown));
1295 }
1296 "CheckBox" => {
1297 let checked = node.properties.get("value").and_then(Value::as_bool) == Some(true);
1298 let mark = if checked { "[x]" } else { "[ ]" };
1299 out.push(format!("{mark} {}", prop(node, "label")));
1300 }
1301 "ChoicePicker" => {
1302 let chosen: Vec<String> = match node.properties.get("value") {
1303 Some(Value::Array(items)) => items
1304 .iter()
1305 .filter_map(|item| item.as_str().map(String::from))
1306 .collect(),
1307 Some(Value::String(one)) => vec![one.clone()],
1308 _ => Vec::new(),
1309 };
1310 let options = node
1311 .properties
1312 .get("options")
1313 .and_then(Value::as_array)
1314 .cloned()
1315 .unwrap_or_default();
1316 let lettered: Vec<String> = options
1317 .iter()
1318 .enumerate()
1319 .map(|(index, option)| {
1320 let value = option.get("value").and_then(Value::as_str).unwrap_or("");
1321 let label = match option.get("label") {
1322 Some(Value::String(text)) => text.clone(),
1323 Some(other) if !other.is_null() => other.to_string(),
1324 _ => value.to_owned(),
1325 };
1326 let letter = char::from(b'a' + (index % 26) as u8);
1327 let on = if chosen.iter().any(|c| c == value) {
1328 " (chosen)"
1329 } else {
1330 ""
1331 };
1332 format!("{letter}) {}{on}", crate::escape::show_controls(&label))
1333 })
1334 .collect();
1335 out.push(labeled(&prop(node, "label"), &lettered.join(" ")));
1336 }
1337 "Slider" => {
1338 let number = |key: &str| node.properties.get(key).and_then(Value::as_f64);
1339 let show = |value: f64| {
1340 if value.fract() == 0.0 && value.abs() < 1e15 {
1341 format!("{}", value as i64)
1342 } else {
1343 format!("{value}")
1344 }
1345 };
1346 let (min, max) = (number("min").unwrap_or(0.0), number("max").unwrap_or(100.0));
1347 let value = number("value").unwrap_or(min);
1348 out.push(labeled(
1349 &prop(node, "label"),
1350 &format!("{} ({} to {})", show(value), show(min), show(max)),
1351 ));
1352 }
1353 kind @ ("Image" | "Video" | "AudioPlayer") => {
1354 let what = match kind {
1355 "Image" => "image",
1356 "Video" => "video",
1357 _ => "audio",
1358 };
1359 let mut text = format!("[{what}]");
1360 let description = prop(node, "description");
1361 if !description.is_empty() {
1362 text.push(' ');
1363 text.push_str(&description);
1364 }
1365 let url = prop(node, "url");
1366 if !url.is_empty() && !url.starts_with("data:") {
1367 text.push(' ');
1368 text.push_str(&url);
1369 }
1370 out.push(text);
1371 }
1372 "Icon" => out.push(format!("[{}]", prop(node, "name"))),
1373 other => {
1374 let name = if other.is_empty() { "?" } else { other };
1375 out.push(format!(
1376 "(a {} is not shown as text)",
1377 crate::escape::show_controls(name)
1378 ));
1379 }
1380 }
1381 for message in node.validation_errors() {
1382 out.push(format!(" ! {}", crate::escape::show_controls(&message)));
1383 }
1384 for error in &node.errors {
1385 out.push(format!("! {}", crate::escape::show_controls(error)));
1386 }
1387}
1388
1389#[cfg(test)]
1390mod tests {
1391 use super::*;
1392
1393 use crate::tools::SandboxPolicy;
1394 use serde_json::json;
1395
1396 struct Jail(std::path::PathBuf, SandboxPolicy);
1397
1398 fn jail(name: &str) -> Jail {
1399 let root = std::env::temp_dir().join(format!("agent86-ui-{name}-{}", std::process::id()));
1400 let _ = std::fs::remove_dir_all(&root);
1401 std::fs::create_dir_all(root.join("img")).unwrap();
1402 std::fs::write(root.join("img/cat.png"), b"png").unwrap();
1403 let policy = SandboxPolicy::new(&root).unwrap();
1404 Jail(root, policy)
1405 }
1406
1407 impl Drop for Jail {
1408 fn drop(&mut self) {
1409 let _ = std::fs::remove_dir_all(&self.0);
1410 }
1411 }
1412
1413 fn with_components(components: Value) -> Vec<Value> {
1414 vec![json!({"version": "1.0", "createSurface": {
1415 "surfaceId": "s", "catalogId": "c", "components": components
1416 }})]
1417 }
1418
1419 fn refused(messages: &[Value], jail: &Jail, remote: bool) -> Vec<String> {
1420 policy(messages, &jail.1, remote)
1421 .into_iter()
1422 .map(|r| format!("{} {}", r.path, r.message))
1423 .collect()
1424 }
1425
1426 #[test]
1427 fn a_password_field_is_refused_with_request_secret_named() {
1428 let jail = jail("obscured");
1429 let got = refused(
1430 &with_components(json!([
1431 {"id": "root", "component": "TextField", "label": "Password", "variant": "obscured"},
1432 {"id": "note", "component": "TextField", "label": "Note", "variant": "longText"}
1433 ])),
1434 &jail,
1435 false,
1436 );
1437 assert_eq!(got.len(), 1, "{got:?}");
1438 assert!(got[0].starts_with("/0/createSurface/components/0/variant TextField root"));
1439 assert!(got[0].contains("request_secret"));
1440 }
1441
1442 #[test]
1443 fn media_loads_only_data_urls_and_workspace_files_unless_remote_is_on() {
1444 let jail = jail("media");
1445 let image =
1446 |url: Value| with_components(json!([{"id": "root", "component": "Image", "url": url}]));
1447 let ok = |url: Value, remote| refused(&image(url), &jail, remote).is_empty();
1448 assert!(ok(json!("data:image/png;base64,iVBORw0KGgo="), false));
1449 assert!(ok(json!("img/cat.png"), false));
1450 assert!(!ok(json!("img/dog.png"), false), "missing file");
1451 assert!(!ok(json!("../outside.png"), false), "outside the jail");
1452 assert!(!ok(json!("https://example.com/cat.png"), false));
1453 assert!(ok(json!("https://example.com/cat.png"), true));
1454 assert!(!ok(json!("http://example.com/cat.png"), true), "only https");
1455 assert!(!ok(json!("file:///etc/passwd"), true));
1456 let bound = refused(&image(json!({"@path": "/url"})), &jail, true);
1457 assert!(bound[0].contains("must be a literal string"), "{bound:?}");
1458 let video = with_components(json!([{"id": "root", "component": "Video",
1460 "url": "data:video/mp4;base64,AAAA", "posterUrl": "https://example.com/p.png"}]));
1461 let got = refused(&video, &jail, false);
1462 assert_eq!(got.len(), 1);
1463 assert!(got[0].starts_with("/0/createSurface/components/0/posterUrl"));
1464 }
1465
1466 #[test]
1467 fn open_url_takes_only_http_and_https_literals() {
1468 let jail = jail("open");
1469 let button = |url: Value| {
1470 with_components(json!([
1471 {"id": "root", "component": "Button", "child": "t",
1472 "action": {"functionCall": {"@call": "openUrl", "args": {"url": url}}}},
1473 {"id": "t", "component": "Text", "text": "Go"}
1474 ]))
1475 };
1476 assert!(refused(&button(json!("https://example.com")), &jail, false).is_empty());
1477 assert!(refused(&button(json!("http://example.com")), &jail, false).is_empty());
1478 assert!(refused(&button(json!({"@path": "/link"})), &jail, false).is_empty());
1480 let got = refused(&button(json!("javascript:alert(1)")), &jail, false);
1481 assert_eq!(
1482 got,
1483 ["/0/createSurface/components/0/action/functionCall/args/url openUrl only opens http and https URLs, not \"javascript:alert(1)\""]
1484 );
1485 }
1486
1487 #[test]
1488 fn renderer_and_agent_functions_are_refused() {
1489 let jail = jail("functions");
1490 let got = refused(
1491 &[
1492 json!({"version": "1.0", "callRendererFunction": {"surfaceId": "s", "functionCallId": "f", "call": {"@call": "x"}}}),
1493 json!({"version": "1.0", "agentFunctionResponse": {"functionCallId": "f", "value": 1}}),
1494 ],
1495 &jail,
1496 false,
1497 );
1498 assert!(got[0].starts_with("/0/callRendererFunction renderer functions are not available"));
1499 assert!(got[1].starts_with("/1/agentFunctionResponse agent functions are not available"));
1500 }
1501
1502 #[test]
1503 fn a_drive_letter_is_not_a_scheme() {
1504 assert_eq!(scheme("C:\\img\\cat.png"), None);
1505 assert_eq!(scheme("HTTPS://x"), Some("https".into()));
1506 assert_eq!(scheme("img/cat.png"), None);
1507 }
1508
1509 #[test]
1510 fn sanitize_redacts_secrets_and_with_egress_redact_what_the_guardrail_finds() {
1511 let vault = crate::vault::SecretVault::default();
1512 vault.set("API_TOKEN", "tok-abcdef-123456".into());
1513 let message =
1514 json!({"text": "use tok-abcdef-123456", "aws": "AKIAABCDEFGHIJKLMNOP", "n": 3});
1515 let kept = sanitize(&message, &vault, EgressMode::Warn);
1516 assert_eq!(kept["text"], "use ${secret:API_TOKEN}");
1517 assert_eq!(kept["aws"], "AKIAABCDEFGHIJKLMNOP");
1518 assert_eq!(kept["n"], 3);
1519 let redacted = sanitize(&message, &vault, EgressMode::Redact);
1520 assert_ne!(redacted["aws"], "AKIAABCDEFGHIJKLMNOP");
1521 assert!(!redacted.to_string().contains("AKIA"), "{redacted}");
1522 }
1523
1524 #[test]
1525 fn the_basic_catalog_reference_names_components_and_functions() {
1526 let reference = reference(Catalog::basic());
1527 assert!(
1528 reference.contains(
1529 "- Button { child: Child, variant?: \"default\"|\"primary\"|\"borderless\", action: Action, weight?: number } (accepts @checks)"
1530 ),
1531 "{reference}"
1532 );
1533 assert!(reference.contains("- TextField {"), "{reference}");
1534 assert!(
1535 reference.contains("- formatString(value: DynamicString) -> string"),
1536 "{reference}"
1537 );
1538 assert!(!reference.contains("component:"), "{reference}");
1539 }
1540
1541 #[test]
1542 fn the_prompt_section_carries_the_catalog_instructions() {
1543 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1544 let section = session.prompt_section();
1545 assert!(section.starts_with("## agent86UI: drawing UI with render_ui"));
1546 assert!(section.contains(&format!("### Catalog `{}`", agent86_ui::BASIC_CATALOG_ID)));
1547 assert!(section.contains("## Catalog Guidelines"));
1548 assert!(section.contains("[ui action] submit on <surfaceId>"));
1549 }
1550
1551 #[test]
1552 fn fields_beside_the_kind_are_moved_inside_it() {
1553 let (tidied, moved) = tidy(&serde_json::json!({
1554 "version": "1.0",
1555 "createSurface": {"catalogId": "c", "components": []},
1556 "surfaceId": "plan"
1557 }));
1558 assert_eq!(
1559 tidied,
1560 serde_json::json!({"version": "1.0",
1561 "createSurface": {"catalogId": "c", "components": [], "surfaceId": "plan"}})
1562 );
1563 assert_eq!(moved, ["surfaceId into createSurface"]);
1564
1565 for message in [
1567 serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}, "surfaceId": "b"}),
1568 serde_json::json!({"version": "1.0", "surfaceId": "b"}),
1569 serde_json::json!({"version": "1.0", "deleteSurface": {}, "updateDataModel": {}, "x": 1}),
1570 serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}}),
1571 ] {
1572 assert_eq!(tidy(&message), (message.clone(), Vec::new()), "{message}");
1573 }
1574 }
1575
1576 #[test]
1577 fn the_prompt_s_example_is_valid() {
1578 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1579 let call: Value =
1580 serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, true)).unwrap();
1581 let messages = call["messages"].as_array().unwrap();
1582 let report = session.apply(messages);
1583 assert!(report.is_ok(), "{:?}", report.errors);
1584 assert!(report.warnings.is_empty(), "{:?}", report.warnings);
1585 let section = session.prompt_section();
1586 assert!(section.contains("surfaceId` goes inside createSurface"));
1587 assert!(
1588 !section.contains("\"wait\":true"),
1589 "no waiter, no wait in the example"
1590 );
1591 }
1592
1593 #[test]
1594 fn a_waiter_set_later_offers_wait_from_then_on() {
1595 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1596 let request = UiWait {
1597 surface_ids: vec!["s".into()],
1598 };
1599 assert!(!session.can_wait());
1600 assert!(!session.prompt_section().contains("\"wait\": true"));
1601 assert_eq!(session.wait(&request), None);
1602
1603 session.set_waiter(Some(std::sync::Arc::new(|wait: &UiWait| {
1604 Some(Action::new(
1605 "ok",
1606 wait.surface_ids[0].clone(),
1607 "root",
1608 "2026-11-22T00:00:00Z",
1609 Map::new(),
1610 ))
1611 })));
1612 assert!(session.can_wait());
1613 assert!(session.prompt_section().contains("\"wait\": true"));
1614 assert_eq!(session.wait(&request).map(|a| a.name), Some("ok".into()));
1615
1616 session.set_waiter(None);
1617 assert!(!session.can_wait());
1618 }
1619
1620 #[test]
1621 fn orphans_are_warnings_and_dangling_references_errors() {
1622 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1623 let create = |components: Value| {
1624 serde_json::json!({"version": "1.0", "createSurface": {
1625 "surfaceId": "s",
1626 "catalogId": agent86_ui::BASIC_CATALOG_ID,
1627 "components": components,
1628 }})
1629 };
1630 let report = session.apply(&[create(serde_json::json!([
1631 {"id": "root", "component": "Column", "children": ["missing"]}
1632 ]))]);
1633 assert!(report.errors[0].message.starts_with("Dangling reference"));
1634 let report = session.apply(&[create(serde_json::json!([
1635 {"id": "root", "component": "Text", "text": "hi"},
1636 {"id": "spare", "component": "Text", "text": "nobody shows me"}
1637 ]))]);
1638 assert!(report.is_ok(), "{:?}", report.errors);
1639 assert!(report.warnings[0].message.contains("not reachable"));
1640 assert_eq!(session.surface_ids(), ["s"]);
1641 }
1642
1643 fn create_with(components: Value, data_model: Option<Value>) -> Value {
1644 let mut body = json!({
1645 "surfaceId": "s",
1646 "catalogId": agent86_ui::BASIC_CATALOG_ID,
1647 "components": components,
1648 });
1649 if let Some(model) = data_model {
1650 body["dataModel"] = model;
1651 }
1652 json!({"version": "1.0", "createSurface": body})
1653 }
1654
1655 fn submit_button() -> Value {
1656 json!({"id": "go", "component": "Button", "child": "go_label",
1657 "action": {"event": {"name": "submit"}}})
1658 }
1659
1660 #[test]
1661 fn a_button_without_context_sends_every_top_level_value() {
1662 let message = create_with(
1665 json!([
1666 {"id": "root", "component": "Column", "children": ["plan", "note", "go"]},
1667 {"id": "plan", "component": "ChoicePicker", "value": {"@path": "/plan"},
1668 "options": [{"label": "A", "value": "a"}]},
1669 {"id": "note", "component": "TextField", "label": "Note",
1670 "value": {"@path": "/extra/note"}},
1671 submit_button(),
1672 ]),
1673 Some(json!({"plan": [], "size": 1})),
1674 );
1675 let (messages, notes) = complete(&[message], |_| Vec::new());
1676 assert!(notes.is_empty(), "{notes:?}");
1677 assert_eq!(
1678 messages[0].pointer("/createSurface/components/3/action/event/context"),
1679 Some(&json!({
1680 "plan": {"@path": "/plan"},
1681 "size": {"@path": "/size"},
1682 "extra": {"@path": "/extra"}
1683 }))
1684 );
1685 }
1686
1687 #[test]
1688 fn a_context_the_model_gave_is_kept() {
1689 let mut button = submit_button();
1690 button["action"]["event"]["context"] = json!({"choice": "pro"});
1691 let message = create_with(
1692 json!([{"id": "root", "component": "Column", "children": ["go"]}, button]),
1693 Some(json!({"plan": []})),
1694 );
1695 let (messages, _) = complete(&[message], |_| Vec::new());
1696 assert_eq!(
1697 messages[0].pointer("/createSurface/components/1/action/event/context"),
1698 Some(&json!({"choice": "pro"}))
1699 );
1700 }
1701
1702 #[test]
1703 fn a_button_added_later_sends_the_values_of_the_surface_already_up() {
1704 let update = json!({"version": "1.0", "updateComponents": {
1705 "surfaceId": "s",
1706 "components": [submit_button()],
1707 }});
1708 let (messages, _) = complete(&[update], |id| {
1709 assert_eq!(id, "s");
1710 vec!["name".to_owned(), "a/b".to_owned()]
1711 });
1712 assert_eq!(
1713 messages[0].pointer("/updateComponents/components/0/action/event/context"),
1714 Some(&json!({"name": {"@path": "/name"}, "a/b": {"@path": "/a~1b"}}))
1715 );
1716 }
1717
1718 #[test]
1719 fn a_lone_path_is_read_as_a_binding_and_noted() {
1720 let mut button = submit_button();
1721 button["action"]["event"]["context"] = json!({"plan": {"path": "/plan"}});
1722 let message = create_with(
1723 json!([
1724 {"id": "root", "component": "Column",
1725 "children": {"path": "/items", "componentId": "row"}},
1726 {"id": "row", "component": "Text", "text": {"path": "/label"}},
1727 button,
1728 ]),
1729 Some(json!({"items": []})),
1730 );
1731 let (messages, notes) = complete(&[message], |_| Vec::new());
1732 let components = &messages[0]["createSurface"]["components"];
1733 assert_eq!(
1735 components[0]["children"],
1736 json!({"path": "/items", "componentId": "row"})
1737 );
1738 assert_eq!(components[1]["text"], json!({"@path": "/label"}));
1739 assert_eq!(
1740 components[2]["action"]["event"]["context"],
1741 json!({"plan": {"@path": "/plan"}})
1742 );
1743 assert_eq!(
1744 notes,
1745 [
1746 "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.",
1747 "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.",
1748 ]
1749 );
1750 }
1751
1752 #[test]
1753 fn the_completed_example_validates_and_its_button_sends_the_choice() {
1754 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1755 let call: Value =
1756 serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, false)).unwrap();
1757 let messages = call["messages"].as_array().unwrap().clone();
1758 let (messages, _) = complete(&messages, |id| session.surface_keys(id));
1759 assert!(session.apply(&messages).is_ok());
1760 let submit = messages[0]["createSurface"]["components"]
1761 .as_array()
1762 .unwrap()
1763 .iter()
1764 .find(|component| component["id"] == "submit")
1765 .unwrap();
1766 assert_eq!(
1767 submit["action"]["event"]["context"],
1768 json!({"plan": {"@path": "/plan"}})
1769 );
1770 }
1771
1772 #[test]
1773 fn a_surface_as_text_shows_each_component_as_the_user_reads_it() {
1774 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1775 let report = session.apply(&[serde_json::json!({"version": "1.0", "createSurface": {
1776 "surfaceId": "order",
1777 "catalogId": agent86_ui::BASIC_CATALOG_ID,
1778 "components": [
1779 {"id": "root", "component": "Column",
1780 "children": ["title", "name", "note", "plan", "extras", "receipt", "seats",
1781 "line", "logo", "tabs", "row"]},
1782 {"id": "title", "component": "Text", "text": "Your order\u{1b}[31m"},
1783 {"id": "name", "component": "TextField", "label": "Name", "value": {"@path": "/name"}},
1784 {"id": "note", "component": "TextField", "label": "Note", "value": {"@path": "/note"}},
1785 {"id": "plan", "component": "ChoicePicker", "label": "Plan",
1786 "options": [{"label": "Free", "value": "free"}, {"label": "Pro", "value": "pro"}],
1787 "value": {"@path": "/plan"}},
1788 {"id": "extras", "component": "ChoicePicker", "variant": "multipleSelection",
1789 "options": [{"label": "Gift wrap", "value": "wrap"}, {"label": "Card", "value": "card"}],
1790 "value": {"@path": "/extras"}},
1791 {"id": "receipt", "component": "CheckBox", "label": "Email me the receipt",
1792 "value": {"@path": "/receipt"}},
1793 {"id": "seats", "component": "Slider", "label": "Seats", "min": 1, "max": 10,
1794 "value": {"@path": "/seats"}},
1795 {"id": "line", "component": "Divider"},
1796 {"id": "logo", "component": "Image", "description": "Our logo",
1797 "url": "https://example.com/logo.png"},
1798 {"id": "tabs", "component": "Tabs", "tabs": [{"title": "One", "child": "one"}]},
1799 {"id": "one", "component": "Text", "text": "inside a tab"},
1800 {"id": "row", "component": "Row", "children": ["ok", "cancel"]},
1801 {"id": "ok", "component": "Button", "child": "ok_label",
1802 "action": {"event": {"name": "submit"}}},
1803 {"id": "ok_label", "component": "Text", "text": "OK"},
1804 {"id": "cancel", "component": "Button", "child": "cancel_label",
1805 "action": {"event": {"name": "cancel"}}},
1806 {"id": "cancel_label", "component": "Text", "text": "Cancel"}
1807 ],
1808 "dataModel": {"name": "Ada", "note": "", "plan": ["pro"], "extras": ["wrap", "card"],
1809 "receipt": true, "seats": 3}
1810 }})]);
1811 assert!(report.is_ok(), "{:?}", report.errors);
1812 assert_eq!(
1813 session.surface_texts(),
1814 [concat!(
1815 "[agent86UI surface \"order\": this client cannot draw it, so it is shown as ",
1816 "text; answer in your reply]\n",
1817 "Your order\u{241b}[31m\n",
1819 "Name: Ada\n",
1820 "Note: (empty)\n",
1821 "Plan: a) Free b) Pro (chosen)\n",
1822 "a) Gift wrap (chosen) b) Card (chosen)\n",
1823 "[x] Email me the receipt\n",
1824 "Seats: 3 (1 to 10)\n",
1825 "---\n",
1826 "[image] Our logo https://example.com/logo.png\n",
1827 "(a Tabs is not shown as text)\n",
1828 "[OK]\n",
1829 "[Cancel]"
1830 )]
1831 );
1832 }
1833}