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 prompt_section(&self) -> String {
276 let mut section = String::from(PROMPT);
277 let media = if self.remote_media {
278 "a data: URL, an https URL, or the path of a file in the workspace"
279 } else {
280 "a data: URL or the path of a file in the workspace (remote URLs are not loaded)"
281 };
282 if self.can_wait() {
283 section.push_str(
284 "\n- With `\"wait\": true` the call waits for the user's first action on \
285 the surface and returns it as its result (`[ui action] ...`). Use it for a \
286 form you need answered before you can go on; otherwise leave it out and \
287 carry on.",
288 );
289 }
290 section.push_str(&format!(
291 "\n- Never ask for a password, key, or token in a surface (no TextField with \
292 variant \"obscured\"): call request_secret, which asks through a masked prompt \
293 and never shows you the value.\n- The url (and a Video's posterUrl) of Image, \
294 Video, and AudioPlayer must be a literal string: {media}.\n- openUrl opens only \
295 http and https URLs."
296 ));
297 if let Some(catalog) = self.catalogs.first() {
298 section.push_str(&format!(
299 "\n\nA complete call, a choice with a Submit button (`surfaceId` goes \
300 inside createSurface, never beside it):\n{}",
301 example(catalog.id(), self.can_wait())
302 ));
303 }
304 for catalog in &self.catalogs {
305 section.push_str(&format!("\n\n### Catalog `{}`\n", catalog.id()));
306 if let Some(instructions) = catalog.instructions() {
307 section.push('\n');
308 section.push_str(instructions.trim());
309 section.push('\n');
310 }
311 section.push_str(&reference(catalog));
312 }
313 section
314 }
315}
316
317const KINDS: &[&str] = &[
320 "createSurface",
321 "updateComponents",
322 "updateDataModel",
323 "deleteSurface",
324 "callRendererFunction",
325 "agentFunctionResponse",
326];
327
328pub fn tidy(message: &Value) -> (Value, Vec<String>) {
336 let Some(envelope) = message.as_object() else {
337 return (message.clone(), Vec::new());
338 };
339 let kinds: Vec<&String> = envelope
340 .keys()
341 .filter(|key| KINDS.contains(&key.as_str()))
342 .collect();
343 let [kind] = kinds.as_slice() else {
344 return (message.clone(), Vec::new());
345 };
346 let kind = (*kind).clone();
347 let Some(body) = envelope.get(&kind).and_then(Value::as_object) else {
348 return (message.clone(), Vec::new());
349 };
350 let strays: Vec<String> = envelope
351 .keys()
352 .filter(|key| *key != "version" && **key != kind && !body.contains_key(*key))
353 .cloned()
354 .collect();
355 if strays.is_empty() {
356 return (message.clone(), Vec::new());
357 }
358 let mut envelope = envelope.clone();
359 let mut body = body.clone();
360 for key in &strays {
361 if let Some(value) = envelope.remove(key) {
362 body.insert(key.clone(), value);
363 }
364 }
365 envelope.insert(kind.clone(), Value::Object(body));
366 let moved = strays
367 .into_iter()
368 .map(|key| format!("{key} into {kind}"))
369 .collect();
370 (Value::Object(envelope), moved)
371}
372
373pub fn complete(
393 messages: &[Value],
394 existing: impl Fn(&str) -> Vec<String>,
395) -> (Vec<Value>, Vec<String>) {
396 let mut keys: std::collections::HashMap<String, Vec<String>> = Default::default();
397 let mut notes = Vec::new();
398 let mut out = Vec::with_capacity(messages.len());
399 for (index, message) in messages.iter().enumerate() {
400 let mut message = message.clone();
401 if let Some(create) = message.get_mut("createSurface") {
402 let id = surface_of(create);
403 let mut known = Vec::new();
404 if let Some(Value::Object(model)) = create.get("dataModel") {
405 extend_unique(&mut known, model.keys().cloned());
406 }
407 rebind(
408 create,
409 &format!("messages/{index}/createSurface"),
410 &mut notes,
411 );
412 extend_unique(&mut known, bound_keys(create.get("components")));
413 fill_contexts(create, &known);
414 keys.insert(id, known);
415 } else if let Some(update) = message.get_mut("updateComponents") {
416 let id = surface_of(update);
417 let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
418 rebind(
419 update,
420 &format!("messages/{index}/updateComponents"),
421 &mut notes,
422 );
423 extend_unique(known, bound_keys(update.get("components")));
424 fill_contexts(update, known);
425 } else if let Some(update) = message.get("updateDataModel") {
426 let id = surface_of(update);
427 let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
428 match update.get("path").and_then(Value::as_str) {
429 None | Some("" | "/") => {
430 if let Some(Value::Object(model)) = update.get("value") {
431 extend_unique(known, model.keys().cloned());
432 }
433 }
434 Some(path) => extend_unique(known, top_segment(path)),
435 }
436 }
437 out.push(message);
438 }
439 (out, notes)
440}
441
442pub fn surface_keys(runtime: &Runtime, surface_id: &str) -> Vec<String> {
445 let mut keys = Vec::new();
446 if let Some(Value::Object(model)) = runtime.data_model(surface_id) {
447 extend_unique(&mut keys, model.keys().cloned());
448 }
449 if let Some(components) = runtime.components(surface_id) {
450 let components = Value::Array(components.cloned().collect());
451 extend_unique(&mut keys, bound_keys(Some(&components)));
452 }
453 keys
454}
455
456fn surface_of(body: &Value) -> String {
457 body.get("surfaceId")
458 .and_then(Value::as_str)
459 .unwrap_or_default()
460 .to_owned()
461}
462
463fn extend_unique(keys: &mut Vec<String>, more: impl IntoIterator<Item = String>) {
464 for key in more {
465 if !keys.contains(&key) {
466 keys.push(key);
467 }
468 }
469}
470
471fn top_segment(path: &str) -> Option<String> {
473 let rest = path.strip_prefix('/')?;
474 let segment = rest.split('/').next().unwrap_or_default();
475 (!segment.is_empty()).then(|| segment.replace("~1", "/").replace("~0", "~"))
476}
477
478fn bound_keys(value: Option<&Value>) -> Vec<String> {
480 fn walk(value: &Value, keys: &mut Vec<String>) {
481 match value {
482 Value::Object(map) => {
483 if let Some(Value::String(path)) = map.get("@path") {
484 extend_unique(keys, top_segment(path));
485 }
486 map.values().for_each(|value| walk(value, keys));
487 }
488 Value::Array(items) => items.iter().for_each(|value| walk(value, keys)),
489 _ => {}
490 }
491 }
492 let mut keys = Vec::new();
493 if let Some(value) = value {
494 walk(value, &mut keys);
495 }
496 keys
497}
498
499fn rebind(body: &mut Value, at: &str, notes: &mut Vec<String>) {
502 fn walk(value: &mut Value) -> bool {
503 match value {
504 Value::Object(map) => {
505 let lone_path = map.len() == 1
506 && map
507 .get("path")
508 .and_then(Value::as_str)
509 .is_some_and(|path| path.starts_with('/'));
510 if lone_path {
511 let path = map.remove("path").expect("checked above");
512 map.insert("@path".to_owned(), path);
513 return true;
514 }
515 let mut changed = false;
516 for value in map.values_mut() {
517 changed |= walk(value);
518 }
519 changed
520 }
521 Value::Array(items) => items
522 .iter_mut()
523 .fold(false, |changed, item| walk(item) | changed),
524 _ => false,
525 }
526 }
527 let Some(Value::Array(components)) = body.get_mut("components") else {
528 return;
529 };
530 for (index, component) in components.iter_mut().enumerate() {
531 let Value::Object(fields) = component else {
532 continue;
533 };
534 let mut changed = false;
535 for (key, value) in fields.iter_mut() {
536 if key != "id" && key != "component" {
537 changed |= walk(value);
538 }
539 }
540 if changed {
541 let id = fields.get("id").and_then(Value::as_str).unwrap_or("?");
542 notes.push(format!(
543 "Note: read {{\"path\": ...}} as {{\"@path\": ...}} in {at}/components/{index} \
544 ({id}); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal."
545 ));
546 }
547 }
548}
549
550fn fill_contexts(body: &mut Value, keys: &[String]) {
553 let Some(Value::Array(components)) = body.get_mut("components") else {
554 return;
555 };
556 for component in components.iter_mut() {
557 if component.get("component").and_then(Value::as_str) != Some("Button") {
558 continue;
559 }
560 let Some(Value::Object(event)) = component.pointer_mut("/action/event") else {
561 continue;
562 };
563 if event.contains_key("context") {
564 continue;
565 }
566 let context: Map<String, Value> = keys
567 .iter()
568 .map(|key| {
569 let pointer = format!("/{}", key.replace('~', "~0").replace('/', "~1"));
570 (key.clone(), serde_json::json!({"@path": pointer}))
571 })
572 .collect();
573 event.insert("context".to_owned(), Value::Object(context));
574 }
575}
576
577pub fn is_event_button(component: &Value) -> bool {
580 component.get("component").and_then(Value::as_str) == Some("Button")
581 && component.pointer("/action/event").is_some()
582}
583
584fn example(catalog_id: &str, wait: bool) -> String {
586 let mut call = serde_json::json!({"messages": [{"version": "1.0", "createSurface": {
587 "surfaceId": "plan",
588 "catalogId": catalog_id,
589 "components": [
590 {"id": "root", "component": "Column", "children": ["choice", "submit"]},
591 {"id": "choice", "component": "ChoicePicker", "label": "Which plan?",
592 "variant": "mutuallyExclusive", "value": {"@path": "/plan"},
593 "options": [{"label": "Basic", "value": "basic"}, {"label": "Pro", "value": "pro"}]},
594 {"id": "submit", "component": "Button", "child": "submit_label",
595 "action": {"event": {"name": "submit"}}},
596 {"id": "submit_label", "component": "Text", "text": "Submit"}
597 ],
598 "dataModel": {"plan": []}
599 }}]});
600 if wait {
601 call["wait"] = Value::Bool(true);
602 }
603 call.to_string()
604}
605
606const PROMPT: &str = "## agent86UI: drawing UI with render_ui
608
609You can show the user interactive UI (forms, choices, confirmations, small \
610dashboards) by calling render_ui with A2UI 1.0 messages; the user's screen draws \
611them with its own widgets. Use it when you need a structured answer (pick one of \
612several options, fill in a few fields, confirm a plan) or when a layout says more \
613than prose. Otherwise answer in plain text.
614
615- `messages` is a list of A2UI messages, each `{\"version\": \"1.0\", ...}` with \
616exactly one of `createSurface`, `updateComponents`, `updateDataModel`, or \
617`deleteSurface`. Create a surface once with createSurface (a new `surfaceId`, a \
618`catalogId` from below, and usually its `components` and `dataModel` inline), \
619change it later with updateComponents (a component replaces the one with the same \
620id) and updateDataModel (`path` and `value`), and remove it with deleteSurface.
621- Components are a flat list linked by id, and exactly one has the id \"root\". \
622Every child id must be defined in the same call or an earlier one. An id is an \
623identifier: letters, digits, and `_`, starting with a letter or `_` (`submit_label`, \
624never `submit-label`).
625- A value is a literal, a binding to the surface's data model (`{\"@path\": \
626\"/form/name\"}`), or a function call (`{\"@call\": \"formatString\", \"args\": \
627{...}}`). Input components write what the user enters back to the path they are \
628bound to. A `ChildList` is an array of ids, or a template over a list in the data \
629model (`{\"path\": \"/items\", \"componentId\": \"row\"}`) whose bindings are \
630relative to each item.
631- A button's action is `{\"event\": {\"name\": \"submit\"}}`, and it sends every \
632top-level value of the surface's data model. To send something else, give the \
633event a `context` beside `name` (`{\"event\": {\"name\": \"pick\", \"context\": \
634{\"plan\": \"pro\"}}}`), never beside `event`. When the user presses it, a later \
635user message reads `[ui action] submit on <surfaceId>: <values as JSON>`; the \
636surface stays up meanwhile.
637- Only a Button whose action is an event sends the user's answer: choosing an \
638option or typing only changes the data model. So every form needs a Button (for \
639example Submit).
640- Keep each call short: a surface's JSON breaks most often when it is large. For \
641a form of more than about four inputs, send createSurface with the root and the \
642first few components, then add the rest in further calls with updateComponents, \
643sending the root again with its longer `children`; put `wait` only on the last call.
644- render_ui's result is the validator's verdict. If it lists problems, nothing \
645was drawn: fix them and send the corrected messages again.
646- Renderer functions (`callRendererFunction`) and agent functions are not \
647available.";
648
649pub fn reference(catalog: &Catalog) -> String {
653 let document = catalog.document();
654 let mut out = String::from("\nComponents:\n");
655 for (name, schema) in document
656 .get("components")
657 .and_then(Value::as_object)
658 .into_iter()
659 .flatten()
660 {
661 let (properties, required, checkable) = gather(schema);
662 let fields: Vec<String> = properties
663 .iter()
664 .filter(|(key, _)| *key != "component" && *key != "id")
665 .map(|(key, property)| {
666 let optional = if required.iter().any(|r| r == key) {
667 ""
668 } else {
669 "?"
670 };
671 format!("{key}{optional}: {}", type_of(property, document))
672 })
673 .collect();
674 let checks = if checkable { " (accepts @checks)" } else { "" };
675 out.push_str(&format!("- {name} {{ {} }}{checks}\n", fields.join(", ")));
676 }
677 let functions: Vec<String> = document
678 .get("functions")
679 .and_then(Value::as_object)
680 .into_iter()
681 .flatten()
682 .filter(|(name, _)| {
683 catalog
684 .function(name)
685 .is_none_or(|def| def.callers != agent86_ui::Callers::AgentOnly)
686 })
687 .map(|(name, schema)| {
688 let args = schema.pointer("/properties/args");
689 let required: Vec<&str> = args
690 .and_then(|a| a.get("required"))
691 .and_then(Value::as_array)
692 .into_iter()
693 .flatten()
694 .filter_map(Value::as_str)
695 .collect();
696 let params: Vec<String> = args
697 .and_then(|a| a.get("properties"))
698 .and_then(Value::as_object)
699 .into_iter()
700 .flatten()
701 .map(|(key, property)| {
702 let optional = if required.contains(&key.as_str()) {
703 ""
704 } else {
705 "?"
706 };
707 format!("{key}{optional}: {}", type_of(property, document))
708 })
709 .collect();
710 let returns = schema
711 .get("returnType")
712 .and_then(Value::as_str)
713 .unwrap_or("any");
714 format!("- {name}({}) -> {returns}\n", params.join(", "))
715 })
716 .collect();
717 if !functions.is_empty() {
718 out.push_str("\nFunctions:\n");
719 out.extend(functions);
720 }
721 out
722}
723
724fn gather(schema: &Value) -> (Map<String, Value>, Vec<String>, bool) {
727 let mut properties = Map::new();
728 let mut required = Vec::new();
729 let mut checkable = false;
730 let mut parts = vec![schema];
731 if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
732 parts.extend(all);
733 }
734 for part in parts {
735 if part
736 .get("$ref")
737 .and_then(Value::as_str)
738 .is_some_and(|r| r.ends_with("/Checkable"))
739 {
740 checkable = true;
741 }
742 if let Some(own) = part.get("properties").and_then(Value::as_object) {
743 for (key, value) in own {
744 properties.insert(key.clone(), value.clone());
745 }
746 }
747 required.extend(
748 part.get("required")
749 .and_then(Value::as_array)
750 .into_iter()
751 .flatten()
752 .filter_map(Value::as_str)
753 .map(String::from),
754 );
755 }
756 (properties, required, checkable)
757}
758
759fn type_of(property: &Value, document: &Value) -> String {
763 if let Some(target) = property.get("$ref").and_then(Value::as_str) {
764 if let Some(local) = target.strip_prefix("#/$defs/") {
765 if let Some(def) = document.pointer(&format!("/$defs/{local}")) {
766 if def.get("$ref").is_none() {
767 return type_of(def, document);
768 }
769 }
770 }
771 return target.rsplit('/').next().unwrap_or(target).to_string();
772 }
773 if let Some(values) = property.get("enum").and_then(Value::as_array) {
774 return values
775 .iter()
776 .map(|v| v.to_string())
777 .collect::<Vec<_>>()
778 .join("|");
779 }
780 match property.get("type").and_then(Value::as_str) {
781 Some("array") => match property.get("items") {
782 Some(items) => format!("array of {}", type_of(items, document)),
783 None => "array".into(),
784 },
785 Some(kind) => kind.to_string(),
786 None => "any".into(),
787 }
788}
789
790pub fn take_drawn(metadata: &mut Map<String, Value>) -> (Vec<AgentMessage>, Option<Value>) {
794 let messages = match metadata.remove(MESSAGES_KEY) {
795 Some(Value::Array(items)) => items
796 .into_iter()
797 .filter_map(|item| serde_json::from_value(item).ok())
798 .collect(),
799 _ => Vec::new(),
800 };
801 (messages, metadata.remove(TRACE_KEY))
802}
803
804const DREW: &[&str] = &["Rendered surface ", "Deleted surface ", "Applied."];
806
807fn drew(result: &crate::types::ToolResult) -> bool {
811 let text = if result.ok {
812 result.content.as_str()
813 } else {
814 result.error.as_deref().unwrap_or_default()
815 };
816 result.ok
817 || text
818 .lines()
819 .any(|line| DREW.iter().any(|opening| line.starts_with(opening)))
820}
821
822pub fn take_wait(metadata: &mut Map<String, Value>) -> Option<Vec<String>> {
824 match metadata.remove(WAIT_KEY)? {
825 Value::Array(ids) => Some(
826 ids.into_iter()
827 .filter_map(|id| id.as_str().map(String::from))
828 .collect(),
829 ),
830 _ => None,
831 }
832}
833
834pub fn action_text(action: &Action) -> String {
838 let context = crate::pyjson::python_json_dumps(&Value::Object(action.context.clone()), false);
839 let mut text = format!(
840 "[ui action] {} on {}: {context}",
841 action.name, action.surface_id
842 );
843 if let Some(message) = action.user_message.as_deref().filter(|m| !m.is_empty()) {
844 text.push('\n');
845 text.push_str(message);
846 }
847 text
848}
849
850impl crate::agent::Harness {
851 pub fn attach_ui(&mut self, session: UiSession) -> Result<(), String> {
856 self.registry
857 .register(Box::new(crate::tools::render_ui::RenderUiTool))?;
858 self.context.ui = Some(std::sync::Arc::new(session));
859 Ok(())
860 }
861
862 pub fn accept_ui_action(&self, sid: &str, action: &Action) -> Result<String, String> {
870 let ui = self
871 .context
872 .ui
873 .as_deref()
874 .ok_or_else(|| String::from("this agent has no renderer"))?;
875 ui.check_action(action, None)?;
876 self.recorder.event(
877 sid,
878 "ui_action",
879 vec![
880 ("surface", serde_json::json!(action.surface_id)),
881 ("name", serde_json::json!(action.name)),
882 ("component", serde_json::json!(action.source_component_id)),
883 ("waited", serde_json::json!(false)),
884 ],
885 );
886 Ok(action_text(action))
887 }
888
889 pub(crate) fn ui_wait(
895 &self,
896 call: &crate::types::ToolCall,
897 drawn: crate::types::ToolResult,
898 surfaces: Vec<String>,
899 sid: &str,
900 ) -> crate::types::ToolResult {
901 use crate::tools::{failure, success};
902 let Some(ui) = self.context.ui.as_deref() else {
903 return drawn;
904 };
905 if surfaces.is_empty() {
906 return drawn;
907 }
908 let request = UiWait {
909 surface_ids: surfaces.clone(),
910 };
911 let question = crate::approval::Question {
912 tool: Some(RENDER_UI.into()),
913 call: Some(call.id.clone()),
914 ..crate::approval::Question::new(crate::approval::QuestionKind::Ui)
915 };
916 let shown = drawn.content.clone();
917 let answered = |result: crate::types::ToolResult| crate::types::ToolResult {
918 call_id: drawn.call_id.clone(),
919 ..result
920 };
921 let action = match self.gate.queue.ask(question, || ui.wait(&request)) {
922 None => {
923 return answered(failure(
924 RENDER_UI,
925 format!(
926 "The turn was cancelled before the user answered. The surface stays \
927 up; an action on it later comes as a user message.\n{shown}"
928 ),
929 ))
930 }
931 Some(None) => {
932 return answered(failure(
933 RENDER_UI,
934 format!(
935 "The user did not answer (they dismissed it). The surface stays up; an \
936 action on it later comes as a user message.\n{shown}"
937 ),
938 ))
939 }
940 Some(Some(action)) => action,
941 };
942 if let Err(why) = ui.check_action(&action, Some(&surfaces)) {
943 return answered(failure(
944 RENDER_UI,
945 format!("The screen's answer could not be used: {why}.\n{shown}"),
946 ));
947 }
948 let text = self.context.secrets.redact(&action_text(&action));
949 let report = self.guardrails.inspect_ingress(&text);
950 if report.flagged() {
951 self.recorder.event(
952 sid,
953 "guardrail",
954 vec![
955 ("stage", serde_json::json!("ingress")),
956 ("source", serde_json::json!("ui_action")),
957 ("findings", serde_json::json!(report.summary())),
958 ],
959 );
960 }
961 self.recorder.event(
962 sid,
963 "ui_action",
964 vec![
965 ("surface", serde_json::json!(action.surface_id)),
966 ("name", serde_json::json!(action.name)),
967 ("component", serde_json::json!(action.source_component_id)),
968 ("waited", serde_json::json!(true)),
969 ],
970 );
971 if self.guardrails.should_block(&report) {
972 return answered(failure(
973 RENDER_UI,
974 format!(
975 "The user's answer was refused by the input guardrail ({}).\n{shown}",
976 report.summary()
977 ),
978 ));
979 }
980 answered(success(RENDER_UI, format!("{shown}\n{text}")))
981 }
982}
983
984pub fn sanitize(value: &Value, vault: &crate::vault::SecretVault, egress: EgressMode) -> Value {
988 match value {
989 Value::String(text) => {
990 let text = vault.redact(text);
991 Value::String(if egress == EgressMode::Redact {
992 crate::guardrails::redact(&text).0
993 } else {
994 text
995 })
996 }
997 Value::Array(items) => Value::Array(
998 items
999 .iter()
1000 .map(|item| sanitize(item, vault, egress))
1001 .collect(),
1002 ),
1003 Value::Object(map) => Value::Object(
1004 map.iter()
1005 .map(|(key, item)| (key.clone(), sanitize(item, vault, egress)))
1006 .collect(),
1007 ),
1008 other => other.clone(),
1009 }
1010}
1011
1012#[derive(Debug, Clone, PartialEq, Eq)]
1015pub struct Refusal {
1016 pub path: String,
1017 pub message: String,
1018}
1019
1020impl std::fmt::Display for Refusal {
1021 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1022 write!(f, "REFUSED at {}: {}", self.path, self.message)
1023 }
1024}
1025
1026const MEDIA: &[(&str, &[&str])] = &[
1029 ("Image", &["url"]),
1030 ("Video", &["url", "posterUrl"]),
1031 ("AudioPlayer", &["url"]),
1032];
1033
1034pub fn policy(
1044 messages: &[Value],
1045 jail: &crate::tools::SandboxPolicy,
1046 remote_media: bool,
1047) -> Vec<Refusal> {
1048 let mut refusals = Vec::new();
1049 let mut refuse = |path: String, message: String| refusals.push(Refusal { path, message });
1050 for (index, message) in messages.iter().enumerate() {
1051 if message.get("callRendererFunction").is_some() {
1052 refuse(
1053 format!("/{index}/callRendererFunction"),
1054 "renderer functions are not available here; draw with components and change \
1055 them with updateComponents and updateDataModel instead"
1056 .into(),
1057 );
1058 }
1059 if message.get("agentFunctionResponse").is_some() {
1060 refuse(
1061 format!("/{index}/agentFunctionResponse"),
1062 "agent functions are not available here".into(),
1063 );
1064 }
1065 for kind in ["createSurface", "updateComponents"] {
1066 let Some(components) = message
1067 .get(kind)
1068 .and_then(|body| body.get("components"))
1069 .and_then(Value::as_array)
1070 else {
1071 continue;
1072 };
1073 for (number, component) in components.iter().enumerate() {
1074 let at = format!("/{index}/{kind}/components/{number}");
1075 let type_name = component.get("component").and_then(Value::as_str);
1076 let id = component
1077 .get("id")
1078 .and_then(Value::as_str)
1079 .unwrap_or("this component");
1080 if type_name == Some("TextField")
1081 && component.get("variant").and_then(Value::as_str) == Some("obscured")
1082 {
1083 refuse(
1084 format!("{at}/variant"),
1085 format!(
1086 "TextField {id} is \"obscured\", a password field, but a surface never \
1087 collects secrets: call request_secret instead, which asks the user \
1088 through a masked prompt and never shows you the value"
1089 ),
1090 );
1091 }
1092 if let Some((_, properties)) =
1093 MEDIA.iter().find(|(name, _)| Some(*name) == type_name)
1094 {
1095 for property in *properties {
1096 let Some(value) = component.get(*property) else {
1097 continue;
1098 };
1099 let path = format!("{at}/{property}");
1100 match value.as_str() {
1101 Some(url) => {
1102 if let Some(why) = media_problem(url, jail, remote_media) {
1103 refuse(path, format!("{id}'s {property} {why}"));
1104 }
1105 }
1106 None => refuse(
1107 path,
1108 format!(
1109 "{id}'s {property} must be a literal string: what a surface \
1110 loads is checked before it is drawn, so it cannot come from a \
1111 binding or a function call"
1112 ),
1113 ),
1114 }
1115 }
1116 }
1117 open_urls(component, &at, &mut refuse);
1118 }
1119 }
1120 }
1121 refusals
1122}
1123
1124fn media_problem(
1126 url: &str,
1127 jail: &crate::tools::SandboxPolicy,
1128 remote_media: bool,
1129) -> Option<String> {
1130 match scheme(url) {
1131 Some(scheme) if scheme == "data" => None,
1132 Some(scheme) if scheme == "https" && remote_media => None,
1133 Some(scheme) if scheme == "https" || scheme == "http" => Some(format!(
1134 "{url:?} is a remote URL, and remote media is off here (a fetch can track the user \
1135 or carry data out in its URL): use a data: URL or a file in the workspace"
1136 )),
1137 Some(scheme) => Some(format!(
1138 "{url:?} uses {scheme}:, which a surface may not load: use a data: URL or a file in \
1139 the workspace"
1140 )),
1141 None => match jail.resolve_within(url) {
1142 Err(_) => Some(format!("{url:?} is outside the workspace")),
1143 Ok(path) if !path.is_file() => Some(format!("{url:?} is not a file in the workspace")),
1144 Ok(_) => None,
1145 },
1146 }
1147}
1148
1149fn scheme(url: &str) -> Option<String> {
1152 let (scheme, _) = url.split_once(':')?;
1153 let valid = scheme.len() > 1
1154 && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
1155 && scheme
1156 .chars()
1157 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
1158 valid.then(|| scheme.to_ascii_lowercase())
1159}
1160
1161fn open_urls(value: &Value, at: &str, refuse: &mut impl FnMut(String, String)) {
1164 match value {
1165 Value::Object(map) => {
1166 if map.get("@call").and_then(Value::as_str) == Some("openUrl") {
1167 if let Some(url) = value.pointer("/args/url").and_then(Value::as_str) {
1168 let scheme = scheme(url);
1169 if !matches!(scheme.as_deref(), Some("http" | "https")) {
1170 refuse(
1171 format!("{at}/args/url"),
1172 format!("openUrl only opens http and https URLs, not {url:?}"),
1173 );
1174 }
1175 }
1176 }
1177 for (key, item) in map {
1178 let segment = key.replace('~', "~0").replace('/', "~1");
1179 open_urls(item, &format!("{at}/{segment}"), refuse);
1180 }
1181 }
1182 Value::Array(items) => {
1183 for (index, item) in items.iter().enumerate() {
1184 open_urls(item, &format!("{at}/{index}"), refuse);
1185 }
1186 }
1187 _ => {}
1188 }
1189}
1190
1191#[cfg(test)]
1192mod tests {
1193 use super::*;
1194
1195 use crate::tools::SandboxPolicy;
1196 use serde_json::json;
1197
1198 struct Jail(std::path::PathBuf, SandboxPolicy);
1199
1200 fn jail(name: &str) -> Jail {
1201 let root = std::env::temp_dir().join(format!("agent86-ui-{name}-{}", std::process::id()));
1202 let _ = std::fs::remove_dir_all(&root);
1203 std::fs::create_dir_all(root.join("img")).unwrap();
1204 std::fs::write(root.join("img/cat.png"), b"png").unwrap();
1205 let policy = SandboxPolicy::new(&root).unwrap();
1206 Jail(root, policy)
1207 }
1208
1209 impl Drop for Jail {
1210 fn drop(&mut self) {
1211 let _ = std::fs::remove_dir_all(&self.0);
1212 }
1213 }
1214
1215 fn with_components(components: Value) -> Vec<Value> {
1216 vec![json!({"version": "1.0", "createSurface": {
1217 "surfaceId": "s", "catalogId": "c", "components": components
1218 }})]
1219 }
1220
1221 fn refused(messages: &[Value], jail: &Jail, remote: bool) -> Vec<String> {
1222 policy(messages, &jail.1, remote)
1223 .into_iter()
1224 .map(|r| format!("{} {}", r.path, r.message))
1225 .collect()
1226 }
1227
1228 #[test]
1229 fn a_password_field_is_refused_with_request_secret_named() {
1230 let jail = jail("obscured");
1231 let got = refused(
1232 &with_components(json!([
1233 {"id": "root", "component": "TextField", "label": "Password", "variant": "obscured"},
1234 {"id": "note", "component": "TextField", "label": "Note", "variant": "longText"}
1235 ])),
1236 &jail,
1237 false,
1238 );
1239 assert_eq!(got.len(), 1, "{got:?}");
1240 assert!(got[0].starts_with("/0/createSurface/components/0/variant TextField root"));
1241 assert!(got[0].contains("request_secret"));
1242 }
1243
1244 #[test]
1245 fn media_loads_only_data_urls_and_workspace_files_unless_remote_is_on() {
1246 let jail = jail("media");
1247 let image =
1248 |url: Value| with_components(json!([{"id": "root", "component": "Image", "url": url}]));
1249 let ok = |url: Value, remote| refused(&image(url), &jail, remote).is_empty();
1250 assert!(ok(json!("data:image/png;base64,iVBORw0KGgo="), false));
1251 assert!(ok(json!("img/cat.png"), false));
1252 assert!(!ok(json!("img/dog.png"), false), "missing file");
1253 assert!(!ok(json!("../outside.png"), false), "outside the jail");
1254 assert!(!ok(json!("https://example.com/cat.png"), false));
1255 assert!(ok(json!("https://example.com/cat.png"), true));
1256 assert!(!ok(json!("http://example.com/cat.png"), true), "only https");
1257 assert!(!ok(json!("file:///etc/passwd"), true));
1258 let bound = refused(&image(json!({"@path": "/url"})), &jail, true);
1259 assert!(bound[0].contains("must be a literal string"), "{bound:?}");
1260 let video = with_components(json!([{"id": "root", "component": "Video",
1262 "url": "data:video/mp4;base64,AAAA", "posterUrl": "https://example.com/p.png"}]));
1263 let got = refused(&video, &jail, false);
1264 assert_eq!(got.len(), 1);
1265 assert!(got[0].starts_with("/0/createSurface/components/0/posterUrl"));
1266 }
1267
1268 #[test]
1269 fn open_url_takes_only_http_and_https_literals() {
1270 let jail = jail("open");
1271 let button = |url: Value| {
1272 with_components(json!([
1273 {"id": "root", "component": "Button", "child": "t",
1274 "action": {"functionCall": {"@call": "openUrl", "args": {"url": url}}}},
1275 {"id": "t", "component": "Text", "text": "Go"}
1276 ]))
1277 };
1278 assert!(refused(&button(json!("https://example.com")), &jail, false).is_empty());
1279 assert!(refused(&button(json!("http://example.com")), &jail, false).is_empty());
1280 assert!(refused(&button(json!({"@path": "/link"})), &jail, false).is_empty());
1282 let got = refused(&button(json!("javascript:alert(1)")), &jail, false);
1283 assert_eq!(
1284 got,
1285 ["/0/createSurface/components/0/action/functionCall/args/url openUrl only opens http and https URLs, not \"javascript:alert(1)\""]
1286 );
1287 }
1288
1289 #[test]
1290 fn renderer_and_agent_functions_are_refused() {
1291 let jail = jail("functions");
1292 let got = refused(
1293 &[
1294 json!({"version": "1.0", "callRendererFunction": {"surfaceId": "s", "functionCallId": "f", "call": {"@call": "x"}}}),
1295 json!({"version": "1.0", "agentFunctionResponse": {"functionCallId": "f", "value": 1}}),
1296 ],
1297 &jail,
1298 false,
1299 );
1300 assert!(got[0].starts_with("/0/callRendererFunction renderer functions are not available"));
1301 assert!(got[1].starts_with("/1/agentFunctionResponse agent functions are not available"));
1302 }
1303
1304 #[test]
1305 fn a_drive_letter_is_not_a_scheme() {
1306 assert_eq!(scheme("C:\\img\\cat.png"), None);
1307 assert_eq!(scheme("HTTPS://x"), Some("https".into()));
1308 assert_eq!(scheme("img/cat.png"), None);
1309 }
1310
1311 #[test]
1312 fn sanitize_redacts_secrets_and_with_egress_redact_what_the_guardrail_finds() {
1313 let vault = crate::vault::SecretVault::default();
1314 vault.set("API_TOKEN", "tok-abcdef-123456".into());
1315 let message =
1316 json!({"text": "use tok-abcdef-123456", "aws": "AKIAABCDEFGHIJKLMNOP", "n": 3});
1317 let kept = sanitize(&message, &vault, EgressMode::Warn);
1318 assert_eq!(kept["text"], "use ${secret:API_TOKEN}");
1319 assert_eq!(kept["aws"], "AKIAABCDEFGHIJKLMNOP");
1320 assert_eq!(kept["n"], 3);
1321 let redacted = sanitize(&message, &vault, EgressMode::Redact);
1322 assert_ne!(redacted["aws"], "AKIAABCDEFGHIJKLMNOP");
1323 assert!(!redacted.to_string().contains("AKIA"), "{redacted}");
1324 }
1325
1326 #[test]
1327 fn the_basic_catalog_reference_names_components_and_functions() {
1328 let reference = reference(Catalog::basic());
1329 assert!(
1330 reference.contains(
1331 "- Button { child: Child, variant?: \"default\"|\"primary\"|\"borderless\", action: Action, weight?: number } (accepts @checks)"
1332 ),
1333 "{reference}"
1334 );
1335 assert!(reference.contains("- TextField {"), "{reference}");
1336 assert!(
1337 reference.contains("- formatString(value: DynamicString) -> string"),
1338 "{reference}"
1339 );
1340 assert!(!reference.contains("component:"), "{reference}");
1341 }
1342
1343 #[test]
1344 fn the_prompt_section_carries_the_catalog_instructions() {
1345 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1346 let section = session.prompt_section();
1347 assert!(section.starts_with("## agent86UI: drawing UI with render_ui"));
1348 assert!(section.contains(&format!("### Catalog `{}`", agent86_ui::BASIC_CATALOG_ID)));
1349 assert!(section.contains("## Catalog Guidelines"));
1350 assert!(section.contains("[ui action] submit on <surfaceId>"));
1351 }
1352
1353 #[test]
1354 fn fields_beside_the_kind_are_moved_inside_it() {
1355 let (tidied, moved) = tidy(&serde_json::json!({
1356 "version": "1.0",
1357 "createSurface": {"catalogId": "c", "components": []},
1358 "surfaceId": "plan"
1359 }));
1360 assert_eq!(
1361 tidied,
1362 serde_json::json!({"version": "1.0",
1363 "createSurface": {"catalogId": "c", "components": [], "surfaceId": "plan"}})
1364 );
1365 assert_eq!(moved, ["surfaceId into createSurface"]);
1366
1367 for message in [
1369 serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}, "surfaceId": "b"}),
1370 serde_json::json!({"version": "1.0", "surfaceId": "b"}),
1371 serde_json::json!({"version": "1.0", "deleteSurface": {}, "updateDataModel": {}, "x": 1}),
1372 serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}}),
1373 ] {
1374 assert_eq!(tidy(&message), (message.clone(), Vec::new()), "{message}");
1375 }
1376 }
1377
1378 #[test]
1379 fn the_prompt_s_example_is_valid() {
1380 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1381 let call: Value =
1382 serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, true)).unwrap();
1383 let messages = call["messages"].as_array().unwrap();
1384 let report = session.apply(messages);
1385 assert!(report.is_ok(), "{:?}", report.errors);
1386 assert!(report.warnings.is_empty(), "{:?}", report.warnings);
1387 let section = session.prompt_section();
1388 assert!(section.contains("surfaceId` goes inside createSurface"));
1389 assert!(
1390 !section.contains("\"wait\":true"),
1391 "no waiter, no wait in the example"
1392 );
1393 }
1394
1395 #[test]
1396 fn a_waiter_set_later_offers_wait_from_then_on() {
1397 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1398 let request = UiWait {
1399 surface_ids: vec!["s".into()],
1400 };
1401 assert!(!session.can_wait());
1402 assert!(!session.prompt_section().contains("\"wait\": true"));
1403 assert_eq!(session.wait(&request), None);
1404
1405 session.set_waiter(Some(std::sync::Arc::new(|wait: &UiWait| {
1406 Some(Action::new(
1407 "ok",
1408 wait.surface_ids[0].clone(),
1409 "root",
1410 "2026-11-22T00:00:00Z",
1411 Map::new(),
1412 ))
1413 })));
1414 assert!(session.can_wait());
1415 assert!(session.prompt_section().contains("\"wait\": true"));
1416 assert_eq!(session.wait(&request).map(|a| a.name), Some("ok".into()));
1417
1418 session.set_waiter(None);
1419 assert!(!session.can_wait());
1420 }
1421
1422 #[test]
1423 fn orphans_are_warnings_and_dangling_references_errors() {
1424 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1425 let create = |components: Value| {
1426 serde_json::json!({"version": "1.0", "createSurface": {
1427 "surfaceId": "s",
1428 "catalogId": agent86_ui::BASIC_CATALOG_ID,
1429 "components": components,
1430 }})
1431 };
1432 let report = session.apply(&[create(serde_json::json!([
1433 {"id": "root", "component": "Column", "children": ["missing"]}
1434 ]))]);
1435 assert!(report.errors[0].message.starts_with("Dangling reference"));
1436 let report = session.apply(&[create(serde_json::json!([
1437 {"id": "root", "component": "Text", "text": "hi"},
1438 {"id": "spare", "component": "Text", "text": "nobody shows me"}
1439 ]))]);
1440 assert!(report.is_ok(), "{:?}", report.errors);
1441 assert!(report.warnings[0].message.contains("not reachable"));
1442 assert_eq!(session.surface_ids(), ["s"]);
1443 }
1444
1445 fn create_with(components: Value, data_model: Option<Value>) -> Value {
1446 let mut body = json!({
1447 "surfaceId": "s",
1448 "catalogId": agent86_ui::BASIC_CATALOG_ID,
1449 "components": components,
1450 });
1451 if let Some(model) = data_model {
1452 body["dataModel"] = model;
1453 }
1454 json!({"version": "1.0", "createSurface": body})
1455 }
1456
1457 fn submit_button() -> Value {
1458 json!({"id": "go", "component": "Button", "child": "go_label",
1459 "action": {"event": {"name": "submit"}}})
1460 }
1461
1462 #[test]
1463 fn a_button_without_context_sends_every_top_level_value() {
1464 let message = create_with(
1467 json!([
1468 {"id": "root", "component": "Column", "children": ["plan", "note", "go"]},
1469 {"id": "plan", "component": "ChoicePicker", "value": {"@path": "/plan"},
1470 "options": [{"label": "A", "value": "a"}]},
1471 {"id": "note", "component": "TextField", "label": "Note",
1472 "value": {"@path": "/extra/note"}},
1473 submit_button(),
1474 ]),
1475 Some(json!({"plan": [], "size": 1})),
1476 );
1477 let (messages, notes) = complete(&[message], |_| Vec::new());
1478 assert!(notes.is_empty(), "{notes:?}");
1479 assert_eq!(
1480 messages[0].pointer("/createSurface/components/3/action/event/context"),
1481 Some(&json!({
1482 "plan": {"@path": "/plan"},
1483 "size": {"@path": "/size"},
1484 "extra": {"@path": "/extra"}
1485 }))
1486 );
1487 }
1488
1489 #[test]
1490 fn a_context_the_model_gave_is_kept() {
1491 let mut button = submit_button();
1492 button["action"]["event"]["context"] = json!({"choice": "pro"});
1493 let message = create_with(
1494 json!([{"id": "root", "component": "Column", "children": ["go"]}, button]),
1495 Some(json!({"plan": []})),
1496 );
1497 let (messages, _) = complete(&[message], |_| Vec::new());
1498 assert_eq!(
1499 messages[0].pointer("/createSurface/components/1/action/event/context"),
1500 Some(&json!({"choice": "pro"}))
1501 );
1502 }
1503
1504 #[test]
1505 fn a_button_added_later_sends_the_values_of_the_surface_already_up() {
1506 let update = json!({"version": "1.0", "updateComponents": {
1507 "surfaceId": "s",
1508 "components": [submit_button()],
1509 }});
1510 let (messages, _) = complete(&[update], |id| {
1511 assert_eq!(id, "s");
1512 vec!["name".to_owned(), "a/b".to_owned()]
1513 });
1514 assert_eq!(
1515 messages[0].pointer("/updateComponents/components/0/action/event/context"),
1516 Some(&json!({"name": {"@path": "/name"}, "a/b": {"@path": "/a~1b"}}))
1517 );
1518 }
1519
1520 #[test]
1521 fn a_lone_path_is_read_as_a_binding_and_noted() {
1522 let mut button = submit_button();
1523 button["action"]["event"]["context"] = json!({"plan": {"path": "/plan"}});
1524 let message = create_with(
1525 json!([
1526 {"id": "root", "component": "Column",
1527 "children": {"path": "/items", "componentId": "row"}},
1528 {"id": "row", "component": "Text", "text": {"path": "/label"}},
1529 button,
1530 ]),
1531 Some(json!({"items": []})),
1532 );
1533 let (messages, notes) = complete(&[message], |_| Vec::new());
1534 let components = &messages[0]["createSurface"]["components"];
1535 assert_eq!(
1537 components[0]["children"],
1538 json!({"path": "/items", "componentId": "row"})
1539 );
1540 assert_eq!(components[1]["text"], json!({"@path": "/label"}));
1541 assert_eq!(
1542 components[2]["action"]["event"]["context"],
1543 json!({"plan": {"@path": "/plan"}})
1544 );
1545 assert_eq!(
1546 notes,
1547 [
1548 "Note: read {\"path\": ...} as {\"@path\": ...} in messages/0/createSurface/components/1 (row); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal.",
1549 "Note: read {\"path\": ...} as {\"@path\": ...} in messages/0/createSurface/components/2 (go); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal.",
1550 ]
1551 );
1552 }
1553
1554 #[test]
1555 fn the_completed_example_validates_and_its_button_sends_the_choice() {
1556 let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
1557 let call: Value =
1558 serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, false)).unwrap();
1559 let messages = call["messages"].as_array().unwrap().clone();
1560 let (messages, _) = complete(&messages, |id| session.surface_keys(id));
1561 assert!(session.apply(&messages).is_ok());
1562 let submit = messages[0]["createSurface"]["components"]
1563 .as_array()
1564 .unwrap()
1565 .iter()
1566 .find(|component| component["id"] == "submit")
1567 .unwrap();
1568 assert_eq!(
1569 submit["action"]["event"]["context"],
1570 json!({"plan": {"@path": "/plan"}})
1571 );
1572 }
1573}