agent86-core 1.2.3

The agent behind agent86: a safe agent runtime you can embed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
//! agent86UI in the harness (beyond Python; ADR 0005): the model draws A2UI 1.0
//! surfaces through `render_ui` (`crate::tools::render_ui`), checked against
//! the renderer's catalogs by the `agent86-ui` crate, and the loop hands each
//! validated message to the surface as a [`crate::agent::TurnEvent::Ui`].
//!
//! A [`UiSession`] is a surface's renderer as the agent sees it: its catalogs
//! and the surfaces drawn so far (a headless [`Runtime`]), shared by clones of
//! the tool context like the secret vault. It exists only when the embedder
//! declared a renderer; sub-agents never get it.

use crate::config::EgressMode;
use agent86_ui::runtime::Runtime;
use agent86_ui::{Action, AgentMessage, Catalog, CompileError, Report, Rules};
use serde_json::{Map, Value};
use std::sync::{Mutex, PoisonError};

/// The tool's name.
pub const RENDER_UI: &str = "render_ui";

/// Where `render_ui` leaves the validated messages in its result's metadata,
/// for the loop to take out and emit as `TurnEvent::Ui` before the result is
/// recorded (so nothing new reaches the session or the trace).
pub const MESSAGES_KEY: &str = "agent86ui_messages";

/// Where it leaves what the trace's `ui_render` event records (the surfaces,
/// the component count, the verdict), taken out the same way.
pub const TRACE_KEY: &str = "agent86ui_trace";

/// Where it names the surfaces a `wait: true` call waits on, for the loop,
/// which asks once it has emitted the call's messages (so the program has
/// them to draw before it is asked for an answer).
pub const WAIT_KEY: &str = "agent86ui_wait";

/// What a waiting `render_ui` call asks the program (`sdk::Ui::on_wait`): the
/// first action the user takes on one of these surfaces, which the call has
/// just drawn (its `TurnEvent::Ui` messages came first).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UiWait {
    /// The surfaces the call drew that are up, in the order it named them.
    pub surface_ids: Vec<String>,
}

/// Answers a [`UiWait`]: the action, or `None` when the user dismissed it.
pub type UiWaiter = std::sync::Arc<dyn Fn(&UiWait) -> Option<Action> + Send + Sync>;

/// The completeness rules a `render_ui` batch is checked under: strict, but an
/// orphan is a warning, because A2UI 1.0 has no message that removes a
/// component, so one replaced as a child stays behind and the model could not
/// fix the error (ADR 0005, third amendment).
pub const RULES: Rules = Rules::STRICT.allowing_orphans(true);

/// A renderer's catalogs and the surfaces drawn on it so far.
pub struct UiSession {
    catalogs: Vec<Catalog>,
    runtime: Mutex<Runtime>,
    /// The egress guardrail's mode: in `redact`, every string a surface shows
    /// is redacted first.
    egress: EgressMode,
    /// Media may load from `https` URLs, not only `data:` URLs and workspace
    /// files.
    remote_media: bool,
    /// Answers a waiting call, when the program can. Behind a lock, so a
    /// surface that installs its answer after the harness is built (the
    /// interface, once its event channel exists) can set it.
    waiter: Mutex<Option<UiWaiter>>,
}

impl std::fmt::Debug for UiSession {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UiSession")
            .field(
                "catalogs",
                &self.catalogs.iter().map(Catalog::id).collect::<Vec<_>>(),
            )
            .finish_non_exhaustive()
    }
}

impl UiSession {
    /// A renderer that supports `catalogs`, in order of preference.
    pub fn new(catalogs: Vec<Catalog>) -> Result<Self, CompileError> {
        let mut runtime = Runtime::new(catalogs.clone())?;
        runtime.set_rules(RULES);
        Ok(Self {
            catalogs,
            runtime: Mutex::new(runtime),
            egress: EgressMode::Off,
            remote_media: false,
            waiter: Mutex::new(None),
        })
    }

    /// Redact what surfaces show as the egress guardrail in `mode` redacts the
    /// model's text.
    pub fn with_egress(mut self, mode: EgressMode) -> Self {
        self.egress = mode;
        self
    }

    /// Let media load from `https` URLs too (ADR 0005: off by default, since a
    /// fetch can track the user or carry data out in its URL).
    pub fn with_remote_media(mut self, allow: bool) -> Self {
        self.remote_media = allow;
        self
    }

    /// Let a call wait for the user's answer, asking `waiter`.
    pub fn with_waiter(self, waiter: Option<UiWaiter>) -> Self {
        self.set_waiter(waiter);
        self
    }

    /// Install (or, with `None`, remove) the answer to a waiting call. The
    /// prompt section is rebuilt per request, so it offers `wait` from the next
    /// request on.
    pub fn set_waiter(&self, waiter: Option<UiWaiter>) {
        *self.waiter.lock().unwrap_or_else(PoisonError::into_inner) = waiter;
    }

    fn waiter(&self) -> Option<UiWaiter> {
        self.waiter
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Whether a call may wait: someone answers.
    pub fn can_wait(&self) -> bool {
        self.waiter().is_some()
    }

    /// Ask the program for the user's answer (`None`: dismissed, or nobody
    /// answers). The lock is not held while the program answers.
    pub fn wait(&self, request: &UiWait) -> Option<Action> {
        self.waiter().and_then(|waiter| waiter(request))
    }

    /// Whether `action` could have come from a surface up now: its surface
    /// exists (and is one of `among`, when given) and holds the component it
    /// names. What it carries is the user's and is checked as their input is.
    pub fn check_action(&self, action: &Action, among: Option<&[String]>) -> Result<(), String> {
        if action.name.is_empty() {
            return Err("the action has no name".into());
        }
        if among.is_some_and(|ids| !ids.contains(&action.surface_id)) {
            return Err(format!(
                "the action is for surface {:?}, which this call did not draw",
                action.surface_id
            ));
        }
        let runtime = self.runtime();
        let Some(mut components) = runtime.components(&action.surface_id) else {
            return Err(format!("there is no surface {:?}", action.surface_id));
        };
        if !components
            .any(|c| c.get("id").and_then(Value::as_str) == Some(&action.source_component_id))
        {
            return Err(format!(
                "surface {:?} has no component {:?}",
                action.surface_id, action.source_component_id
            ));
        }
        Ok(())
    }

    /// Whether surface `id`, as drawn so far, has a Button whose action sends
    /// an event: something the user can press to answer.
    pub fn has_event_button(&self, id: &str) -> bool {
        self.runtime()
            .components(id)
            .is_some_and(|mut components| components.any(is_event_button))
    }

    pub fn egress(&self) -> EgressMode {
        self.egress
    }

    pub fn remote_media(&self) -> bool {
        self.remote_media
    }

    pub fn catalogs(&self) -> &[Catalog] {
        &self.catalogs
    }

    fn runtime(&self) -> std::sync::MutexGuard<'_, Runtime> {
        self.runtime.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// The top-level keys of surface `surface_id`, if it is up ([`surface_keys`]).
    pub fn surface_keys(&self, surface_id: &str) -> Vec<String> {
        surface_keys(&self.runtime(), surface_id)
    }

    /// Validate a batch and, when it has no errors, apply it to the surfaces.
    pub fn apply(&self, messages: &[Value]) -> Report {
        self.runtime().apply(messages)
    }

    /// Every surface up now as the one `createSurface` that draws it as it is,
    /// for a program that reopens a session (or draws late) to bring its screen
    /// up to date.
    pub fn snapshot(&self) -> Vec<AgentMessage> {
        self.runtime()
            .snapshot()
            .into_iter()
            .filter_map(|message| serde_json::from_value(message).ok())
            .collect()
    }

    /// Rebuild the surfaces from a session's history (ADR 0005: resume replays,
    /// nothing is stored): every `render_ui` call that drew, in order, through
    /// the same redaction, policy, and validation as when it ran. A call that
    /// drew is one whose result is ok or opens with what the tool writes when it
    /// draws (a waiting call the user dismissed reports a failure, yet drew).
    /// Steps keep calls the history's compaction summarized away. Returns how
    /// many calls were replayed.
    pub fn replay(
        &self,
        state: &crate::session::AgentState,
        ctx: &crate::tools::ToolContext,
    ) -> usize {
        let mut runtime = match Runtime::new(self.catalogs.clone()) {
            Ok(runtime) => runtime,
            Err(_) => return 0,
        };
        runtime.set_rules(RULES);
        let mut replayed = 0;
        for step in &state.steps {
            for call in step.tool_calls.iter().filter(|call| call.name == RENDER_UI) {
                let drew = step
                    .results
                    .iter()
                    .find(|result| result.call_id == call.id)
                    .is_some_and(drew);
                if !drew {
                    continue;
                }
                // The history keeps the call as the model sent it, before the
                // registry repaired an array sent as a JSON string.
                let messages = match call.arguments.get("messages") {
                    Some(Value::Array(messages)) => messages.clone(),
                    Some(Value::String(text)) => match serde_json::from_str(text) {
                        Ok(Value::Array(messages)) => messages,
                        _ => continue,
                    },
                    _ => continue,
                };
                let messages: Vec<Value> = messages
                    .iter()
                    .map(|message| tidy(&sanitize(message, &ctx.secrets, self.egress)).0)
                    .collect();
                let (messages, _) = complete(&messages, |id| surface_keys(&runtime, id));
                if !policy(&messages, &ctx.policy, self.remote_media).is_empty() {
                    continue;
                }
                if runtime.apply(&messages).is_ok() {
                    replayed += 1;
                }
            }
        }
        *self.runtime() = runtime;
        replayed
    }

    /// The ids of the surfaces up now.
    pub fn surface_ids(&self) -> Vec<String> {
        self.runtime().surface_ids().map(String::from).collect()
    }

    /// Every surface up now as text, in surface id order, for a client that
    /// cannot draw A2UI (ADR 0005's text fallback): a heading naming the surface,
    /// then its components with every binding resolved ([`surface_text`]).
    pub fn surface_texts(&self) -> Vec<String> {
        let runtime = self.runtime();
        let ids: Vec<String> = runtime.surface_ids().map(String::from).collect();
        ids.iter()
            .filter_map(|id| runtime.tree(id).map(|tree| surface_text(id, &tree)))
            .collect()
    }

    /// The system-prompt section: how to use `render_ui`, then each catalog's
    /// own instructions and a compact reference to its components and
    /// functions. Rebuilt per request, like the MCP section.
    pub fn prompt_section(&self) -> String {
        let mut section = String::from(PROMPT);
        let media = if self.remote_media {
            "a data: URL, an https URL, or the path of a file in the workspace"
        } else {
            "a data: URL or the path of a file in the workspace (remote URLs are not loaded)"
        };
        if self.can_wait() {
            section.push_str(
                "\n- With `\"wait\": true` the call waits for the user's first action on \
                 the surface and returns it as its result (`[ui action] ...`). Use it for a \
                 form you need answered before you can go on; otherwise leave it out and \
                 carry on.",
            );
        }
        section.push_str(&format!(
            "\n- Never ask for a password, key, or token in a surface (no TextField with \
             variant \"obscured\"): call request_secret, which asks through a masked prompt \
             and never shows you the value.\n- The url (and a Video's posterUrl) of Image, \
             Video, and AudioPlayer must be a literal string: {media}.\n- openUrl opens only \
             http and https URLs."
        ));
        if let Some(catalog) = self.catalogs.first() {
            section.push_str(&format!(
                "\n\nA complete call, a choice with a Submit button (`surfaceId` goes \
                 inside createSurface, never beside it):\n{}",
                example(catalog.id(), self.can_wait())
            ));
        }
        for catalog in &self.catalogs {
            section.push_str(&format!("\n\n### Catalog `{}`\n", catalog.id()));
            if let Some(instructions) = catalog.instructions() {
                section.push('\n');
                section.push_str(instructions.trim());
                section.push('\n');
            }
            section.push_str(&reference(catalog));
        }
        section
    }
}

/// The keys that name what an A2UI 1.0 message is; an envelope holds
/// `version` and exactly one of them.
const KINDS: &[&str] = &[
    "createSurface",
    "updateComponents",
    "updateDataModel",
    "deleteSurface",
    "callRendererFunction",
    "agentFunctionResponse",
];

/// Beyond the protocol: a message whose fields sit beside its kind instead of
/// inside it (`{"version": "1.0", "createSurface": {...}, "surfaceId": "x"}`,
/// the mistake models make most often) has them moved in, when the kind's body
/// does not already have them. Such a message is never valid as written, so
/// the move only turns an error into what the model plainly meant. Returns the
/// message and the fields moved, for the result to mention. `render_ui` and
/// replay both apply it, so a session written either way replays the same.
pub fn tidy(message: &Value) -> (Value, Vec<String>) {
    let Some(envelope) = message.as_object() else {
        return (message.clone(), Vec::new());
    };
    let kinds: Vec<&String> = envelope
        .keys()
        .filter(|key| KINDS.contains(&key.as_str()))
        .collect();
    let [kind] = kinds.as_slice() else {
        return (message.clone(), Vec::new());
    };
    let kind = (*kind).clone();
    let Some(body) = envelope.get(&kind).and_then(Value::as_object) else {
        return (message.clone(), Vec::new());
    };
    let strays: Vec<String> = envelope
        .keys()
        .filter(|key| *key != "version" && **key != kind && !body.contains_key(*key))
        .cloned()
        .collect();
    if strays.is_empty() {
        return (message.clone(), Vec::new());
    }
    let mut envelope = envelope.clone();
    let mut body = body.clone();
    for key in &strays {
        if let Some(value) = envelope.remove(key) {
            body.insert(key.clone(), value);
        }
    }
    envelope.insert(kind.clone(), Value::Object(body));
    let moved = strays
        .into_iter()
        .map(|key| format!("{key} into {kind}"))
        .collect();
    (Value::Object(envelope), moved)
}

/// Beyond the protocol (ADR 0006), after [`tidy`]: two shapes A2UI accepts but
/// that do not do what the model meant are completed, so the form works.
///
/// - **A binding written with 0.9.1's key.** Inside components, an object that
///   is exactly `{"path": "/..."}` is a literal object to A2UI 1.0, so a Button
///   would send back `{"path": "/scope"}` instead of the user's choice. It
///   becomes `{"@path": "/..."}`, and the result notes it so the model learns.
///   (A ChildList template has `componentId` beside its `path`, so it is never
///   touched.)
/// - **A Button event with no `context`.** The action would carry nothing, so
///   it gets a context binding every top-level value of its surface: the keys
///   of the data model and the first segment of every absolute path the
///   surface's components bind, from this batch and, for a surface drawn
///   earlier, from `existing`. This is what the prompt promises, which keeps
///   the deepest nesting out of every form the model writes.
///
/// `existing` gives the top-level keys of a surface already up
/// ([`surface_keys`]). `render_ui` and replay both apply it, so a session
/// replays the same. Returns the messages and the notes for the model.
pub fn complete(
    messages: &[Value],
    existing: impl Fn(&str) -> Vec<String>,
) -> (Vec<Value>, Vec<String>) {
    let mut keys: std::collections::HashMap<String, Vec<String>> = Default::default();
    let mut notes = Vec::new();
    let mut out = Vec::with_capacity(messages.len());
    for (index, message) in messages.iter().enumerate() {
        let mut message = message.clone();
        if let Some(create) = message.get_mut("createSurface") {
            let id = surface_of(create);
            let mut known = Vec::new();
            if let Some(Value::Object(model)) = create.get("dataModel") {
                extend_unique(&mut known, model.keys().cloned());
            }
            rebind(
                create,
                &format!("messages/{index}/createSurface"),
                &mut notes,
            );
            extend_unique(&mut known, bound_keys(create.get("components")));
            fill_contexts(create, &known);
            keys.insert(id, known);
        } else if let Some(update) = message.get_mut("updateComponents") {
            let id = surface_of(update);
            let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
            rebind(
                update,
                &format!("messages/{index}/updateComponents"),
                &mut notes,
            );
            extend_unique(known, bound_keys(update.get("components")));
            fill_contexts(update, known);
        } else if let Some(update) = message.get("updateDataModel") {
            let id = surface_of(update);
            let known = keys.entry(id.clone()).or_insert_with(|| existing(&id));
            match update.get("path").and_then(Value::as_str) {
                None | Some("" | "/") => {
                    if let Some(Value::Object(model)) = update.get("value") {
                        extend_unique(known, model.keys().cloned());
                    }
                }
                Some(path) => extend_unique(known, top_segment(path)),
            }
        }
        out.push(message);
    }
    (out, notes)
}

/// The top-level keys of surface `surface_id` in `runtime`: its data model's,
/// then the first segment of every absolute path its components bind.
pub fn surface_keys(runtime: &Runtime, surface_id: &str) -> Vec<String> {
    let mut keys = Vec::new();
    if let Some(Value::Object(model)) = runtime.data_model(surface_id) {
        extend_unique(&mut keys, model.keys().cloned());
    }
    if let Some(components) = runtime.components(surface_id) {
        let components = Value::Array(components.cloned().collect());
        extend_unique(&mut keys, bound_keys(Some(&components)));
    }
    keys
}

fn surface_of(body: &Value) -> String {
    body.get("surfaceId")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_owned()
}

fn extend_unique(keys: &mut Vec<String>, more: impl IntoIterator<Item = String>) {
    for key in more {
        if !keys.contains(&key) {
            keys.push(key);
        }
    }
}

/// The key of an absolute JSON Pointer's first segment, unescaped.
fn top_segment(path: &str) -> Option<String> {
    let rest = path.strip_prefix('/')?;
    let segment = rest.split('/').next().unwrap_or_default();
    (!segment.is_empty()).then(|| segment.replace("~1", "/").replace("~0", "~"))
}

/// The first segment of every absolute `@path` under `value`.
fn bound_keys(value: Option<&Value>) -> Vec<String> {
    fn walk(value: &Value, keys: &mut Vec<String>) {
        match value {
            Value::Object(map) => {
                if let Some(Value::String(path)) = map.get("@path") {
                    extend_unique(keys, top_segment(path));
                }
                map.values().for_each(|value| walk(value, keys));
            }
            Value::Array(items) => items.iter().for_each(|value| walk(value, keys)),
            _ => {}
        }
    }
    let mut keys = Vec::new();
    if let Some(value) = value {
        walk(value, &mut keys);
    }
    keys
}

/// Turn each `{"path": "/..."}` among `body`'s components into a binding,
/// noting each component that had one.
fn rebind(body: &mut Value, at: &str, notes: &mut Vec<String>) {
    fn walk(value: &mut Value) -> bool {
        match value {
            Value::Object(map) => {
                let lone_path = map.len() == 1
                    && map
                        .get("path")
                        .and_then(Value::as_str)
                        .is_some_and(|path| path.starts_with('/'));
                if lone_path {
                    let path = map.remove("path").expect("checked above");
                    map.insert("@path".to_owned(), path);
                    return true;
                }
                let mut changed = false;
                for value in map.values_mut() {
                    changed |= walk(value);
                }
                changed
            }
            Value::Array(items) => items
                .iter_mut()
                .fold(false, |changed, item| walk(item) | changed),
            _ => false,
        }
    }
    let Some(Value::Array(components)) = body.get_mut("components") else {
        return;
    };
    for (index, component) in components.iter_mut().enumerate() {
        let Value::Object(fields) = component else {
            continue;
        };
        let mut changed = false;
        for (key, value) in fields.iter_mut() {
            if key != "id" && key != "component" {
                changed |= walk(value);
            }
        }
        if changed {
            let id = fields.get("id").and_then(Value::as_str).unwrap_or("?");
            notes.push(format!(
                "Note: read {{\"path\": ...}} as {{\"@path\": ...}} in {at}/components/{index} \
                 ({id}); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal."
            ));
        }
    }
}

/// Give every event Button among `body`'s components with no `context` one
/// binding each of `keys`.
fn fill_contexts(body: &mut Value, keys: &[String]) {
    let Some(Value::Array(components)) = body.get_mut("components") else {
        return;
    };
    for component in components.iter_mut() {
        if component.get("component").and_then(Value::as_str) != Some("Button") {
            continue;
        }
        let Some(Value::Object(event)) = component.pointer_mut("/action/event") else {
            continue;
        };
        if event.contains_key("context") {
            continue;
        }
        let context: Map<String, Value> = keys
            .iter()
            .map(|key| {
                let pointer = format!("/{}", key.replace('~', "~0").replace('/', "~1"));
                (key.clone(), serde_json::json!({"@path": pointer}))
            })
            .collect();
        event.insert("context".to_owned(), Value::Object(context));
    }
}

/// Whether a component is a Button whose action sends an event (rather than
/// running a local function such as `openUrl`).
pub fn is_event_button(component: &Value) -> bool {
    component.get("component").and_then(Value::as_str) == Some("Button")
        && component.pointer("/action/event").is_some()
}

/// The prompt's example call, on one line, in `catalog_id`.
fn example(catalog_id: &str, wait: bool) -> String {
    let mut call = serde_json::json!({"messages": [{"version": "1.0", "createSurface": {
        "surfaceId": "plan",
        "catalogId": catalog_id,
        "components": [
            {"id": "root", "component": "Column", "children": ["choice", "submit"]},
            {"id": "choice", "component": "ChoicePicker", "label": "Which plan?",
             "variant": "mutuallyExclusive", "value": {"@path": "/plan"},
             "options": [{"label": "Basic", "value": "basic"}, {"label": "Pro", "value": "pro"}]},
            {"id": "submit", "component": "Button", "child": "submit_label",
             "action": {"event": {"name": "submit"}}},
            {"id": "submit_label", "component": "Text", "text": "Submit"}
        ],
        "dataModel": {"plan": []}
    }}]});
    if wait {
        call["wait"] = Value::Bool(true);
    }
    call.to_string()
}

/// What every `render_ui` prompt says, whatever the catalogs.
const PROMPT: &str = "## agent86UI: drawing UI with render_ui

You can show the user interactive UI (forms, choices, confirmations, small \
dashboards) by calling render_ui with A2UI 1.0 messages; the user's screen draws \
them with its own widgets. Use it when you need a structured answer (pick one of \
several options, fill in a few fields, confirm a plan) or when a layout says more \
than prose. Otherwise answer in plain text.

- `messages` is a list of A2UI messages, each `{\"version\": \"1.0\", ...}` with \
exactly one of `createSurface`, `updateComponents`, `updateDataModel`, or \
`deleteSurface`. Create a surface once with createSurface (a new `surfaceId`, a \
`catalogId` from below, and usually its `components` and `dataModel` inline), \
change it later with updateComponents (a component replaces the one with the same \
id) and updateDataModel (`path` and `value`), and remove it with deleteSurface.
- Components are a flat list linked by id, and exactly one has the id \"root\". \
Every child id must be defined in the same call or an earlier one. An id is an \
identifier: letters, digits, and `_`, starting with a letter or `_` (`submit_label`, \
never `submit-label`).
- A value is a literal, a binding to the surface's data model (`{\"@path\": \
\"/form/name\"}`), or a function call (`{\"@call\": \"formatString\", \"args\": \
{...}}`). Input components write what the user enters back to the path they are \
bound to. A `ChildList` is an array of ids, or a template over a list in the data \
model (`{\"path\": \"/items\", \"componentId\": \"row\"}`) whose bindings are \
relative to each item.
- A button's action is `{\"event\": {\"name\": \"submit\"}}`, and it sends every \
top-level value of the surface's data model. To send something else, give the \
event a `context` beside `name` (`{\"event\": {\"name\": \"pick\", \"context\": \
{\"plan\": \"pro\"}}}`), never beside `event`. When the user presses it, a later \
user message reads `[ui action] submit on <surfaceId>: <values as JSON>`; the \
surface stays up meanwhile.
- Only a Button whose action is an event sends the user's answer: choosing an \
option or typing only changes the data model. So every form needs a Button (for \
example Submit).
- Keep each call short: a surface's JSON breaks most often when it is large. For \
a form of more than about four inputs, send createSurface with the root and the \
first few components, then add the rest in further calls with updateComponents, \
sending the root again with its longer `children`; put `wait` only on the last call.
- render_ui's result is the validator's verdict. If it lists problems, nothing \
was drawn: fix them and send the corrected messages again.
- Renderer functions (`callRendererFunction`) and agent functions are not \
available.";

/// A compact reference to a catalog's components and functions, from their
/// schemas: each component's properties (`?` marks an optional one) with their
/// types, and each function's arguments and return type.
pub fn reference(catalog: &Catalog) -> String {
    let document = catalog.document();
    let mut out = String::from("\nComponents:\n");
    for (name, schema) in document
        .get("components")
        .and_then(Value::as_object)
        .into_iter()
        .flatten()
    {
        let (properties, required, checkable) = gather(schema);
        let fields: Vec<String> = properties
            .iter()
            .filter(|(key, _)| *key != "component" && *key != "id")
            .map(|(key, property)| {
                let optional = if required.iter().any(|r| r == key) {
                    ""
                } else {
                    "?"
                };
                format!("{key}{optional}: {}", type_of(property, document))
            })
            .collect();
        let checks = if checkable { " (accepts @checks)" } else { "" };
        out.push_str(&format!("- {name} {{ {} }}{checks}\n", fields.join(", ")));
    }
    let functions: Vec<String> = document
        .get("functions")
        .and_then(Value::as_object)
        .into_iter()
        .flatten()
        .filter(|(name, _)| {
            catalog
                .function(name)
                .is_none_or(|def| def.callers != agent86_ui::Callers::AgentOnly)
        })
        .map(|(name, schema)| {
            let args = schema.pointer("/properties/args");
            let required: Vec<&str> = args
                .and_then(|a| a.get("required"))
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .filter_map(Value::as_str)
                .collect();
            let params: Vec<String> = args
                .and_then(|a| a.get("properties"))
                .and_then(Value::as_object)
                .into_iter()
                .flatten()
                .map(|(key, property)| {
                    let optional = if required.contains(&key.as_str()) {
                        ""
                    } else {
                        "?"
                    };
                    format!("{key}{optional}: {}", type_of(property, document))
                })
                .collect();
            let returns = schema
                .get("returnType")
                .and_then(Value::as_str)
                .unwrap_or("any");
            format!("- {name}({}) -> {returns}\n", params.join(", "))
        })
        .collect();
    if !functions.is_empty() {
        out.push_str("\nFunctions:\n");
        out.extend(functions);
    }
    out
}

/// A component schema's properties and required names, from its own
/// `properties` and its `allOf` parts, and whether it takes `@checks`.
fn gather(schema: &Value) -> (Map<String, Value>, Vec<String>, bool) {
    let mut properties = Map::new();
    let mut required = Vec::new();
    let mut checkable = false;
    let mut parts = vec![schema];
    if let Some(all) = schema.get("allOf").and_then(Value::as_array) {
        parts.extend(all);
    }
    for part in parts {
        if part
            .get("$ref")
            .and_then(Value::as_str)
            .is_some_and(|r| r.ends_with("/Checkable"))
        {
            checkable = true;
        }
        if let Some(own) = part.get("properties").and_then(Value::as_object) {
            for (key, value) in own {
                properties.insert(key.clone(), value.clone());
            }
        }
        required.extend(
            part.get("required")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .filter_map(Value::as_str)
                .map(String::from),
        );
    }
    (properties, required, checkable)
}

/// A property's type, briefly: a common type by name, a catalog's own
/// definition by what it is (its `Weight` is a number, not a name to guess
/// at), an enum's values, or the JSON type.
fn type_of(property: &Value, document: &Value) -> String {
    if let Some(target) = property.get("$ref").and_then(Value::as_str) {
        if let Some(local) = target.strip_prefix("#/$defs/") {
            if let Some(def) = document.pointer(&format!("/$defs/{local}")) {
                if def.get("$ref").is_none() {
                    return type_of(def, document);
                }
            }
        }
        return target.rsplit('/').next().unwrap_or(target).to_string();
    }
    if let Some(values) = property.get("enum").and_then(Value::as_array) {
        return values
            .iter()
            .map(|v| v.to_string())
            .collect::<Vec<_>>()
            .join("|");
    }
    match property.get("type").and_then(Value::as_str) {
        Some("array") => match property.get("items") {
            Some(items) => format!("array of {}", type_of(items, document)),
            None => "array".into(),
        },
        Some(kind) => kind.to_string(),
        None => "any".into(),
    }
}

/// What a `render_ui` result carries for the loop, taken out of its metadata,
/// so it is emitted and recorded as agent86UI's own and never kept in the
/// session: the validated messages, and the `ui_render` trace fields.
pub fn take_drawn(metadata: &mut Map<String, Value>) -> (Vec<AgentMessage>, Option<Value>) {
    let messages = match metadata.remove(MESSAGES_KEY) {
        Some(Value::Array(items)) => items
            .into_iter()
            .filter_map(|item| serde_json::from_value(item).ok())
            .collect(),
        _ => Vec::new(),
    };
    (messages, metadata.remove(TRACE_KEY))
}

/// What `render_ui`'s result opens with when the call drew.
const DREW: &[&str] = &["Rendered surface ", "Deleted surface ", "Applied."];

/// Whether a `render_ui` result says the call drew. A waiting call that was not
/// answered says so first and what it drew after (earlier versions wrote the
/// drawing first), so every line is looked at.
fn drew(result: &crate::types::ToolResult) -> bool {
    let text = if result.ok {
        result.content.as_str()
    } else {
        result.error.as_deref().unwrap_or_default()
    };
    result.ok
        || text
            .lines()
            .any(|line| DREW.iter().any(|opening| line.starts_with(opening)))
}

/// The surfaces a waiting call waits on, taken out of its result's metadata.
pub fn take_wait(metadata: &mut Map<String, Value>) -> Option<Vec<String>> {
    match metadata.remove(WAIT_KEY)? {
        Value::Array(ids) => Some(
            ids.into_iter()
                .filter_map(|id| id.as_str().map(String::from))
                .collect(),
        ),
        _ => None,
    }
}

/// An action as the model reads it, a waiting call's result or the next user
/// message: `[ui action] <name> on <surfaceId>: <context as JSON>`, then the
/// event's `userMessage` on a line of its own when it has one.
pub fn action_text(action: &Action) -> String {
    let context = crate::pyjson::python_json_dumps(&Value::Object(action.context.clone()), false);
    let mut text = format!(
        "[ui action] {} on {}: {context}",
        action.name, action.surface_id
    );
    if let Some(message) = action.user_message.as_deref().filter(|m| !m.is_empty()) {
        text.push('\n');
        text.push_str(message);
    }
    text
}

impl crate::agent::Harness {
    /// Declare a renderer: put `session` on the tool context and offer the
    /// model `render_ui`. Both assembly paths (`sdk::AgentBuilder::ui` and the
    /// binary's interface, through `setup::attach_renderer`) go through it.
    /// Sub-agents never draw: `ToolContext::fork` drops the session.
    pub fn attach_ui(&mut self, session: UiSession) -> Result<(), String> {
        self.registry
            .register(Box::new(crate::tools::render_ui::RenderUiTool))?;
        self.context.ui = Some(std::sync::Arc::new(session));
        Ok(())
    }

    /// Take an action from a surface no call was waiting on (ADR 0005: it
    /// becomes the next user message): check that it could have come from a
    /// surface up now, record it as `ui_action` (never its values), and give
    /// the text the turn runs on, `[ui action] <name> on <surfaceId>: ...`. The
    /// caller runs that as a plain turn, whose own vault redaction and ingress
    /// guardrail cover it as they cover typed input. `Err` names what was
    /// wrong, never the values, and nothing is recorded.
    pub fn accept_ui_action(&self, sid: &str, action: &Action) -> Result<String, String> {
        let ui = self
            .context
            .ui
            .as_deref()
            .ok_or_else(|| String::from("this agent has no renderer"))?;
        ui.check_action(action, None)?;
        self.recorder.event(
            sid,
            "ui_action",
            vec![
                ("surface", serde_json::json!(action.surface_id)),
                ("name", serde_json::json!(action.name)),
                ("component", serde_json::json!(action.source_component_id)),
                ("waited", serde_json::json!(false)),
            ],
        );
        Ok(action_text(action))
    }

    /// Wait for the user's answer to a `wait: true` call, through the prompt
    /// queue like a secret prompt (one question at a time, declined once the
    /// turn is cancelled), and make it the call's result. The answer goes
    /// through the vault and the ingress guardrail, as typed input does, and is
    /// recorded as `ui_action`, without its values.
    pub(crate) fn ui_wait(
        &self,
        call: &crate::types::ToolCall,
        drawn: crate::types::ToolResult,
        surfaces: Vec<String>,
        sid: &str,
    ) -> crate::types::ToolResult {
        use crate::tools::{failure, success};
        let Some(ui) = self.context.ui.as_deref() else {
            return drawn;
        };
        if surfaces.is_empty() {
            return drawn;
        }
        let request = UiWait {
            surface_ids: surfaces.clone(),
        };
        let question = crate::approval::Question {
            tool: Some(RENDER_UI.into()),
            call: Some(call.id.clone()),
            ..crate::approval::Question::new(crate::approval::QuestionKind::Ui)
        };
        let shown = drawn.content.clone();
        let answered = |result: crate::types::ToolResult| crate::types::ToolResult {
            call_id: drawn.call_id.clone(),
            ..result
        };
        let action = match self.gate.queue.ask(question, || ui.wait(&request)) {
            None => {
                return answered(failure(
                    RENDER_UI,
                    format!(
                        "The turn was cancelled before the user answered. The surface stays \
                         up; an action on it later comes as a user message.\n{shown}"
                    ),
                ))
            }
            Some(None) => {
                return answered(failure(
                    RENDER_UI,
                    format!(
                        "The user did not answer (they dismissed it). The surface stays up; an \
                         action on it later comes as a user message.\n{shown}"
                    ),
                ))
            }
            Some(Some(action)) => action,
        };
        if let Err(why) = ui.check_action(&action, Some(&surfaces)) {
            return answered(failure(
                RENDER_UI,
                format!("The screen's answer could not be used: {why}.\n{shown}"),
            ));
        }
        let text = self.context.secrets.redact(&action_text(&action));
        let report = self.guardrails.inspect_ingress(&text);
        if report.flagged() {
            self.recorder.event(
                sid,
                "guardrail",
                vec![
                    ("stage", serde_json::json!("ingress")),
                    ("source", serde_json::json!("ui_action")),
                    ("findings", serde_json::json!(report.summary())),
                ],
            );
        }
        self.recorder.event(
            sid,
            "ui_action",
            vec![
                ("surface", serde_json::json!(action.surface_id)),
                ("name", serde_json::json!(action.name)),
                ("component", serde_json::json!(action.source_component_id)),
                ("waited", serde_json::json!(true)),
            ],
        );
        if self.guardrails.should_block(&report) {
            return answered(failure(
                RENDER_UI,
                format!(
                    "The user's answer was refused by the input guardrail ({}).\n{shown}",
                    report.summary()
                ),
            ));
        }
        answered(success(RENDER_UI, format!("{shown}\n{text}")))
    }
}

/// Every string in `value`, through the secret vault's redaction and, with the
/// egress guardrail in `redact` mode, its redaction too: what a surface shows
/// reaches the user as the model's text does. Object keys are left alone.
pub fn sanitize(value: &Value, vault: &crate::vault::SecretVault, egress: EgressMode) -> Value {
    match value {
        Value::String(text) => {
            let text = vault.redact(text);
            Value::String(if egress == EgressMode::Redact {
                crate::guardrails::redact(&text).0
            } else {
                text
            })
        }
        Value::Array(items) => Value::Array(
            items
                .iter()
                .map(|item| sanitize(item, vault, egress))
                .collect(),
        ),
        Value::Object(map) => Value::Object(
            map.iter()
                .map(|(key, item)| (key.clone(), sanitize(item, vault, egress)))
                .collect(),
        ),
        other => other.clone(),
    }
}

/// Something agent86's policy refuses in a batch (ADR 0005), where the
/// protocol would allow it: a JSON Pointer into the batch and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
    pub path: String,
    pub message: String,
}

impl std::fmt::Display for Refusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "REFUSED at {}: {}", self.path, self.message)
    }
}

/// The media components of the basic catalog and the properties that load a
/// URL. A custom catalog's component of the same name is held to the same rule.
const MEDIA: &[(&str, &[&str])] = &[
    ("Image", &["url"]),
    ("Video", &["url", "posterUrl"]),
    ("AudioPlayer", &["url"]),
];

/// What agent86 refuses in a batch the protocol allows (ADR 0005):
/// - a `TextField` with `"variant": "obscured"`: secrets are never collected
///   through a surface, so the value never reaches the model;
/// - media from anywhere but a `data:` URL or a file in the workspace (or an
///   `https` URL, with `remote_media`), and from a binding or a call, whose
///   value is not known until the renderer resolves it;
/// - `openUrl` with a literal URL that is not `http` or `https` (a dynamic one
///   is the renderer's to check before it opens it, after showing it);
/// - `callRendererFunction` and agent functions, left out of the first version.
pub fn policy(
    messages: &[Value],
    jail: &crate::tools::SandboxPolicy,
    remote_media: bool,
) -> Vec<Refusal> {
    let mut refusals = Vec::new();
    let mut refuse = |path: String, message: String| refusals.push(Refusal { path, message });
    for (index, message) in messages.iter().enumerate() {
        if message.get("callRendererFunction").is_some() {
            refuse(
                format!("/{index}/callRendererFunction"),
                "renderer functions are not available here; draw with components and change \
                 them with updateComponents and updateDataModel instead"
                    .into(),
            );
        }
        if message.get("agentFunctionResponse").is_some() {
            refuse(
                format!("/{index}/agentFunctionResponse"),
                "agent functions are not available here".into(),
            );
        }
        for kind in ["createSurface", "updateComponents"] {
            let Some(components) = message
                .get(kind)
                .and_then(|body| body.get("components"))
                .and_then(Value::as_array)
            else {
                continue;
            };
            for (number, component) in components.iter().enumerate() {
                let at = format!("/{index}/{kind}/components/{number}");
                let type_name = component.get("component").and_then(Value::as_str);
                let id = component
                    .get("id")
                    .and_then(Value::as_str)
                    .unwrap_or("this component");
                if type_name == Some("TextField")
                    && component.get("variant").and_then(Value::as_str) == Some("obscured")
                {
                    refuse(
                        format!("{at}/variant"),
                        format!(
                            "TextField {id} is \"obscured\", a password field, but a surface never \
                             collects secrets: call request_secret instead, which asks the user \
                             through a masked prompt and never shows you the value"
                        ),
                    );
                }
                if let Some((_, properties)) =
                    MEDIA.iter().find(|(name, _)| Some(*name) == type_name)
                {
                    for property in *properties {
                        let Some(value) = component.get(*property) else {
                            continue;
                        };
                        let path = format!("{at}/{property}");
                        match value.as_str() {
                            Some(url) => {
                                if let Some(why) = media_problem(url, jail, remote_media) {
                                    refuse(path, format!("{id}'s {property} {why}"));
                                }
                            }
                            None => refuse(
                                path,
                                format!(
                                    "{id}'s {property} must be a literal string: what a surface \
                                     loads is checked before it is drawn, so it cannot come from a \
                                     binding or a function call"
                                ),
                            ),
                        }
                    }
                }
                open_urls(component, &at, &mut refuse);
            }
        }
    }
    refusals
}

/// Why a media URL may not load, or `None` when it may.
fn media_problem(
    url: &str,
    jail: &crate::tools::SandboxPolicy,
    remote_media: bool,
) -> Option<String> {
    match scheme(url) {
        Some(scheme) if scheme == "data" => None,
        Some(scheme) if scheme == "https" && remote_media => None,
        Some(scheme) if scheme == "https" || scheme == "http" => Some(format!(
            "{url:?} is a remote URL, and remote media is off here (a fetch can track the user \
             or carry data out in its URL): use a data: URL or a file in the workspace"
        )),
        Some(scheme) => Some(format!(
            "{url:?} uses {scheme}:, which a surface may not load: use a data: URL or a file in \
             the workspace"
        )),
        None => match jail.resolve_within(url) {
            Err(_) => Some(format!("{url:?} is outside the workspace")),
            Ok(path) if !path.is_file() => Some(format!("{url:?} is not a file in the workspace")),
            Ok(_) => None,
        },
    }
}

/// A URL's scheme, lowercased, when it has one. A single letter before the
/// colon is a Windows drive, not a scheme.
fn scheme(url: &str) -> Option<String> {
    let (scheme, _) = url.split_once(':')?;
    let valid = scheme.len() > 1
        && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
        && scheme
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
    valid.then(|| scheme.to_ascii_lowercase())
}

/// Refuse each `openUrl` call in `value` whose literal URL is not `http` or
/// `https`.
fn open_urls(value: &Value, at: &str, refuse: &mut impl FnMut(String, String)) {
    match value {
        Value::Object(map) => {
            if map.get("@call").and_then(Value::as_str) == Some("openUrl") {
                if let Some(url) = value.pointer("/args/url").and_then(Value::as_str) {
                    let scheme = scheme(url);
                    if !matches!(scheme.as_deref(), Some("http" | "https")) {
                        refuse(
                            format!("{at}/args/url"),
                            format!("openUrl only opens http and https URLs, not {url:?}"),
                        );
                    }
                }
            }
            for (key, item) in map {
                let segment = key.replace('~', "~0").replace('/', "~1");
                open_urls(item, &format!("{at}/{segment}"), refuse);
            }
        }
        Value::Array(items) => {
            for (index, item) in items.iter().enumerate() {
                open_urls(item, &format!("{at}/{index}"), refuse);
            }
        }
        _ => {}
    }
}

/// A surface as plain text, for a client that cannot draw it: a heading naming
/// it, then a line or more per component, as the user would read it. Fields show
/// their values (`(empty)` when there are none), choices are lettered with the
/// chosen ones marked, check boxes and buttons are bracketed, media is its
/// description and its URL (never a `data:` one), and what has no text form
/// (Tabs, Modal) is named. Every string goes through
/// [`crate::escape::show_controls`]; the values were redacted when drawn.
pub fn surface_text(surface_id: &str, tree: &agent86_ui::runtime::Node) -> String {
    let mut lines = vec![format!(
        "[agent86UI surface {:?}: this client cannot draw it, so it is shown as text; \
         answer in your reply]",
        crate::escape::show_controls(surface_id)
    )];
    node_text(tree, &mut lines);
    lines.join("\n")
}

/// A property as text: a string as it is, a number or a boolean as JSON writes
/// it, anything else (or nothing) empty.
fn prop(node: &agent86_ui::runtime::Node, key: &str) -> String {
    let text = match node.properties.get(key) {
        Some(Value::String(text)) => text.clone(),
        Some(Value::Null) | None => String::new(),
        Some(Value::Number(number)) => number.to_string(),
        Some(Value::Bool(flag)) => flag.to_string(),
        Some(other) => other.to_string(),
    };
    crate::escape::show_controls(&text)
}

fn kids<'a>(node: &'a agent86_ui::runtime::Node, key: &str) -> &'a [agent86_ui::runtime::Node] {
    node.children
        .iter()
        .find(|(name, _)| name == key)
        .map(|(_, nodes)| nodes.as_slice())
        .unwrap_or_default()
}

/// `label: rest`, or `rest` alone when there is no label.
fn labeled(label: &str, rest: &str) -> String {
    if label.is_empty() {
        rest.to_owned()
    } else {
        format!("{label}: {rest}")
    }
}

fn node_text(node: &agent86_ui::runtime::Node, out: &mut Vec<String>) {
    if node.placeholder {
        out.push("…".into());
        return;
    }
    match node.component.as_str() {
        "Text" => {
            let text = prop(node, "text");
            if !text.is_empty() {
                out.push(text);
            }
        }
        "Column" | "List" | "Row" => {
            for child in kids(node, "children") {
                node_text(child, out);
            }
        }
        "Card" => {
            for child in kids(node, "child") {
                node_text(child, out);
            }
        }
        "Divider" => out.push("---".into()),
        "Button" => {
            let label: Vec<String> = kids(node, "child")
                .iter()
                .flat_map(|child| child.walk())
                .filter(|n| n.component == "Text")
                .map(|n| prop(n, "text"))
                .filter(|text| !text.is_empty())
                .collect();
            let label = if label.is_empty() {
                crate::escape::show_controls(&node.id)
            } else {
                label.join(" ").replace('\n', " ")
            };
            out.push(format!("[{label}]"));
        }
        "TextField" | "DateTimeInput" => {
            let value = prop(node, "value");
            let shown = if value.is_empty() {
                "(empty)".to_owned()
            } else {
                value
            };
            out.push(labeled(&prop(node, "label"), &shown));
        }
        "CheckBox" => {
            let checked = node.properties.get("value").and_then(Value::as_bool) == Some(true);
            let mark = if checked { "[x]" } else { "[ ]" };
            out.push(format!("{mark} {}", prop(node, "label")));
        }
        "ChoicePicker" => {
            let chosen: Vec<String> = match node.properties.get("value") {
                Some(Value::Array(items)) => items
                    .iter()
                    .filter_map(|item| item.as_str().map(String::from))
                    .collect(),
                Some(Value::String(one)) => vec![one.clone()],
                _ => Vec::new(),
            };
            let options = node
                .properties
                .get("options")
                .and_then(Value::as_array)
                .cloned()
                .unwrap_or_default();
            let lettered: Vec<String> = options
                .iter()
                .enumerate()
                .map(|(index, option)| {
                    let value = option.get("value").and_then(Value::as_str).unwrap_or("");
                    let label = match option.get("label") {
                        Some(Value::String(text)) => text.clone(),
                        Some(other) if !other.is_null() => other.to_string(),
                        _ => value.to_owned(),
                    };
                    let letter = char::from(b'a' + (index % 26) as u8);
                    let on = if chosen.iter().any(|c| c == value) {
                        " (chosen)"
                    } else {
                        ""
                    };
                    format!("{letter}) {}{on}", crate::escape::show_controls(&label))
                })
                .collect();
            out.push(labeled(&prop(node, "label"), &lettered.join("  ")));
        }
        "Slider" => {
            let number = |key: &str| node.properties.get(key).and_then(Value::as_f64);
            let show = |value: f64| {
                if value.fract() == 0.0 && value.abs() < 1e15 {
                    format!("{}", value as i64)
                } else {
                    format!("{value}")
                }
            };
            let (min, max) = (number("min").unwrap_or(0.0), number("max").unwrap_or(100.0));
            let value = number("value").unwrap_or(min);
            out.push(labeled(
                &prop(node, "label"),
                &format!("{} ({} to {})", show(value), show(min), show(max)),
            ));
        }
        kind @ ("Image" | "Video" | "AudioPlayer") => {
            let what = match kind {
                "Image" => "image",
                "Video" => "video",
                _ => "audio",
            };
            let mut text = format!("[{what}]");
            let description = prop(node, "description");
            if !description.is_empty() {
                text.push(' ');
                text.push_str(&description);
            }
            let url = prop(node, "url");
            if !url.is_empty() && !url.starts_with("data:") {
                text.push(' ');
                text.push_str(&url);
            }
            out.push(text);
        }
        "Icon" => out.push(format!("[{}]", prop(node, "name"))),
        other => {
            let name = if other.is_empty() { "?" } else { other };
            out.push(format!(
                "(a {} is not shown as text)",
                crate::escape::show_controls(name)
            ));
        }
    }
    for message in node.validation_errors() {
        out.push(format!("  ! {}", crate::escape::show_controls(&message)));
    }
    for error in &node.errors {
        out.push(format!("! {}", crate::escape::show_controls(error)));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::tools::SandboxPolicy;
    use serde_json::json;

    struct Jail(std::path::PathBuf, SandboxPolicy);

    fn jail(name: &str) -> Jail {
        let root = std::env::temp_dir().join(format!("agent86-ui-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("img")).unwrap();
        std::fs::write(root.join("img/cat.png"), b"png").unwrap();
        let policy = SandboxPolicy::new(&root).unwrap();
        Jail(root, policy)
    }

    impl Drop for Jail {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    fn with_components(components: Value) -> Vec<Value> {
        vec![json!({"version": "1.0", "createSurface": {
            "surfaceId": "s", "catalogId": "c", "components": components
        }})]
    }

    fn refused(messages: &[Value], jail: &Jail, remote: bool) -> Vec<String> {
        policy(messages, &jail.1, remote)
            .into_iter()
            .map(|r| format!("{} {}", r.path, r.message))
            .collect()
    }

    #[test]
    fn a_password_field_is_refused_with_request_secret_named() {
        let jail = jail("obscured");
        let got = refused(
            &with_components(json!([
                {"id": "root", "component": "TextField", "label": "Password", "variant": "obscured"},
                {"id": "note", "component": "TextField", "label": "Note", "variant": "longText"}
            ])),
            &jail,
            false,
        );
        assert_eq!(got.len(), 1, "{got:?}");
        assert!(got[0].starts_with("/0/createSurface/components/0/variant TextField root"));
        assert!(got[0].contains("request_secret"));
    }

    #[test]
    fn media_loads_only_data_urls_and_workspace_files_unless_remote_is_on() {
        let jail = jail("media");
        let image =
            |url: Value| with_components(json!([{"id": "root", "component": "Image", "url": url}]));
        let ok = |url: Value, remote| refused(&image(url), &jail, remote).is_empty();
        assert!(ok(json!("data:image/png;base64,iVBORw0KGgo="), false));
        assert!(ok(json!("img/cat.png"), false));
        assert!(!ok(json!("img/dog.png"), false), "missing file");
        assert!(!ok(json!("../outside.png"), false), "outside the jail");
        assert!(!ok(json!("https://example.com/cat.png"), false));
        assert!(ok(json!("https://example.com/cat.png"), true));
        assert!(!ok(json!("http://example.com/cat.png"), true), "only https");
        assert!(!ok(json!("file:///etc/passwd"), true));
        let bound = refused(&image(json!({"@path": "/url"})), &jail, true);
        assert!(bound[0].contains("must be a literal string"), "{bound:?}");
        // A Video's poster is held to the same rule.
        let video = with_components(json!([{"id": "root", "component": "Video",
            "url": "data:video/mp4;base64,AAAA", "posterUrl": "https://example.com/p.png"}]));
        let got = refused(&video, &jail, false);
        assert_eq!(got.len(), 1);
        assert!(got[0].starts_with("/0/createSurface/components/0/posterUrl"));
    }

    #[test]
    fn open_url_takes_only_http_and_https_literals() {
        let jail = jail("open");
        let button = |url: Value| {
            with_components(json!([
                {"id": "root", "component": "Button", "child": "t",
                 "action": {"functionCall": {"@call": "openUrl", "args": {"url": url}}}},
                {"id": "t", "component": "Text", "text": "Go"}
            ]))
        };
        assert!(refused(&button(json!("https://example.com")), &jail, false).is_empty());
        assert!(refused(&button(json!("http://example.com")), &jail, false).is_empty());
        // A dynamic URL is the renderer's to check, after showing it.
        assert!(refused(&button(json!({"@path": "/link"})), &jail, false).is_empty());
        let got = refused(&button(json!("javascript:alert(1)")), &jail, false);
        assert_eq!(
            got,
            ["/0/createSurface/components/0/action/functionCall/args/url openUrl only opens http and https URLs, not \"javascript:alert(1)\""]
        );
    }

    #[test]
    fn renderer_and_agent_functions_are_refused() {
        let jail = jail("functions");
        let got = refused(
            &[
                json!({"version": "1.0", "callRendererFunction": {"surfaceId": "s", "functionCallId": "f", "call": {"@call": "x"}}}),
                json!({"version": "1.0", "agentFunctionResponse": {"functionCallId": "f", "value": 1}}),
            ],
            &jail,
            false,
        );
        assert!(got[0].starts_with("/0/callRendererFunction renderer functions are not available"));
        assert!(got[1].starts_with("/1/agentFunctionResponse agent functions are not available"));
    }

    #[test]
    fn a_drive_letter_is_not_a_scheme() {
        assert_eq!(scheme("C:\\img\\cat.png"), None);
        assert_eq!(scheme("HTTPS://x"), Some("https".into()));
        assert_eq!(scheme("img/cat.png"), None);
    }

    #[test]
    fn sanitize_redacts_secrets_and_with_egress_redact_what_the_guardrail_finds() {
        let vault = crate::vault::SecretVault::default();
        vault.set("API_TOKEN", "tok-abcdef-123456".into());
        let message =
            json!({"text": "use tok-abcdef-123456", "aws": "AKIAABCDEFGHIJKLMNOP", "n": 3});
        let kept = sanitize(&message, &vault, EgressMode::Warn);
        assert_eq!(kept["text"], "use ${secret:API_TOKEN}");
        assert_eq!(kept["aws"], "AKIAABCDEFGHIJKLMNOP");
        assert_eq!(kept["n"], 3);
        let redacted = sanitize(&message, &vault, EgressMode::Redact);
        assert_ne!(redacted["aws"], "AKIAABCDEFGHIJKLMNOP");
        assert!(!redacted.to_string().contains("AKIA"), "{redacted}");
    }

    #[test]
    fn the_basic_catalog_reference_names_components_and_functions() {
        let reference = reference(Catalog::basic());
        assert!(
            reference.contains(
                "- Button { child: Child, variant?: \"default\"|\"primary\"|\"borderless\", action: Action, weight?: number } (accepts @checks)"
            ),
            "{reference}"
        );
        assert!(reference.contains("- TextField {"), "{reference}");
        assert!(
            reference.contains("- formatString(value: DynamicString) -> string"),
            "{reference}"
        );
        assert!(!reference.contains("component:"), "{reference}");
    }

    #[test]
    fn the_prompt_section_carries_the_catalog_instructions() {
        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
        let section = session.prompt_section();
        assert!(section.starts_with("## agent86UI: drawing UI with render_ui"));
        assert!(section.contains(&format!("### Catalog `{}`", agent86_ui::BASIC_CATALOG_ID)));
        assert!(section.contains("## Catalog Guidelines"));
        assert!(section.contains("[ui action] submit on <surfaceId>"));
    }

    #[test]
    fn fields_beside_the_kind_are_moved_inside_it() {
        let (tidied, moved) = tidy(&serde_json::json!({
            "version": "1.0",
            "createSurface": {"catalogId": "c", "components": []},
            "surfaceId": "plan"
        }));
        assert_eq!(
            tidied,
            serde_json::json!({"version": "1.0",
                "createSurface": {"catalogId": "c", "components": [], "surfaceId": "plan"}})
        );
        assert_eq!(moved, ["surfaceId into createSurface"]);

        // Never over a field the body has, and never with no kind or two kinds.
        for message in [
            serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}, "surfaceId": "b"}),
            serde_json::json!({"version": "1.0", "surfaceId": "b"}),
            serde_json::json!({"version": "1.0", "deleteSurface": {}, "updateDataModel": {}, "x": 1}),
            serde_json::json!({"version": "1.0", "deleteSurface": {"surfaceId": "a"}}),
        ] {
            assert_eq!(tidy(&message), (message.clone(), Vec::new()), "{message}");
        }
    }

    #[test]
    fn the_prompt_s_example_is_valid() {
        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
        let call: Value =
            serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, true)).unwrap();
        let messages = call["messages"].as_array().unwrap();
        let report = session.apply(messages);
        assert!(report.is_ok(), "{:?}", report.errors);
        assert!(report.warnings.is_empty(), "{:?}", report.warnings);
        let section = session.prompt_section();
        assert!(section.contains("surfaceId` goes inside createSurface"));
        assert!(
            !section.contains("\"wait\":true"),
            "no waiter, no wait in the example"
        );
    }

    #[test]
    fn a_waiter_set_later_offers_wait_from_then_on() {
        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
        let request = UiWait {
            surface_ids: vec!["s".into()],
        };
        assert!(!session.can_wait());
        assert!(!session.prompt_section().contains("\"wait\": true"));
        assert_eq!(session.wait(&request), None);

        session.set_waiter(Some(std::sync::Arc::new(|wait: &UiWait| {
            Some(Action::new(
                "ok",
                wait.surface_ids[0].clone(),
                "root",
                "2026-11-22T00:00:00Z",
                Map::new(),
            ))
        })));
        assert!(session.can_wait());
        assert!(session.prompt_section().contains("\"wait\": true"));
        assert_eq!(session.wait(&request).map(|a| a.name), Some("ok".into()));

        session.set_waiter(None);
        assert!(!session.can_wait());
    }

    #[test]
    fn orphans_are_warnings_and_dangling_references_errors() {
        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
        let create = |components: Value| {
            serde_json::json!({"version": "1.0", "createSurface": {
                "surfaceId": "s",
                "catalogId": agent86_ui::BASIC_CATALOG_ID,
                "components": components,
            }})
        };
        let report = session.apply(&[create(serde_json::json!([
            {"id": "root", "component": "Column", "children": ["missing"]}
        ]))]);
        assert!(report.errors[0].message.starts_with("Dangling reference"));
        let report = session.apply(&[create(serde_json::json!([
            {"id": "root", "component": "Text", "text": "hi"},
            {"id": "spare", "component": "Text", "text": "nobody shows me"}
        ]))]);
        assert!(report.is_ok(), "{:?}", report.errors);
        assert!(report.warnings[0].message.contains("not reachable"));
        assert_eq!(session.surface_ids(), ["s"]);
    }

    fn create_with(components: Value, data_model: Option<Value>) -> Value {
        let mut body = json!({
            "surfaceId": "s",
            "catalogId": agent86_ui::BASIC_CATALOG_ID,
            "components": components,
        });
        if let Some(model) = data_model {
            body["dataModel"] = model;
        }
        json!({"version": "1.0", "createSurface": body})
    }

    fn submit_button() -> Value {
        json!({"id": "go", "component": "Button", "child": "go_label",
               "action": {"event": {"name": "submit"}}})
    }

    #[test]
    fn a_button_without_context_sends_every_top_level_value() {
        // The data model's keys, then the first segment of every absolute path
        // the components bind (here one with no data model entry yet).
        let message = create_with(
            json!([
                {"id": "root", "component": "Column", "children": ["plan", "note", "go"]},
                {"id": "plan", "component": "ChoicePicker", "value": {"@path": "/plan"},
                 "options": [{"label": "A", "value": "a"}]},
                {"id": "note", "component": "TextField", "label": "Note",
                 "value": {"@path": "/extra/note"}},
                submit_button(),
            ]),
            Some(json!({"plan": [], "size": 1})),
        );
        let (messages, notes) = complete(&[message], |_| Vec::new());
        assert!(notes.is_empty(), "{notes:?}");
        assert_eq!(
            messages[0].pointer("/createSurface/components/3/action/event/context"),
            Some(&json!({
                "plan": {"@path": "/plan"},
                "size": {"@path": "/size"},
                "extra": {"@path": "/extra"}
            }))
        );
    }

    #[test]
    fn a_context_the_model_gave_is_kept() {
        let mut button = submit_button();
        button["action"]["event"]["context"] = json!({"choice": "pro"});
        let message = create_with(
            json!([{"id": "root", "component": "Column", "children": ["go"]}, button]),
            Some(json!({"plan": []})),
        );
        let (messages, _) = complete(&[message], |_| Vec::new());
        assert_eq!(
            messages[0].pointer("/createSurface/components/1/action/event/context"),
            Some(&json!({"choice": "pro"}))
        );
    }

    #[test]
    fn a_button_added_later_sends_the_values_of_the_surface_already_up() {
        let update = json!({"version": "1.0", "updateComponents": {
            "surfaceId": "s",
            "components": [submit_button()],
        }});
        let (messages, _) = complete(&[update], |id| {
            assert_eq!(id, "s");
            vec!["name".to_owned(), "a/b".to_owned()]
        });
        assert_eq!(
            messages[0].pointer("/updateComponents/components/0/action/event/context"),
            Some(&json!({"name": {"@path": "/name"}, "a/b": {"@path": "/a~1b"}}))
        );
    }

    #[test]
    fn a_lone_path_is_read_as_a_binding_and_noted() {
        let mut button = submit_button();
        button["action"]["event"]["context"] = json!({"plan": {"path": "/plan"}});
        let message = create_with(
            json!([
                {"id": "root", "component": "Column",
                 "children": {"path": "/items", "componentId": "row"}},
                {"id": "row", "component": "Text", "text": {"path": "/label"}},
                button,
            ]),
            Some(json!({"items": []})),
        );
        let (messages, notes) = complete(&[message], |_| Vec::new());
        let components = &messages[0]["createSurface"]["components"];
        // A template keeps its `path`, which has a componentId beside it.
        assert_eq!(
            components[0]["children"],
            json!({"path": "/items", "componentId": "row"})
        );
        assert_eq!(components[1]["text"], json!({"@path": "/label"}));
        assert_eq!(
            components[2]["action"]["event"]["context"],
            json!({"plan": {"@path": "/plan"}})
        );
        assert_eq!(
            notes,
            [
                "Note: read {\"path\": ...} as {\"@path\": ...} in messages/0/createSurface/components/1 (row); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal.",
                "Note: read {\"path\": ...} as {\"@path\": ...} in messages/0/createSurface/components/2 (go); A2UI 1.0 binds a value with \"@path\", and a plain \"path\" is a literal.",
            ]
        );
    }

    #[test]
    fn the_completed_example_validates_and_its_button_sends_the_choice() {
        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
        let call: Value =
            serde_json::from_str(&example(agent86_ui::BASIC_CATALOG_ID, false)).unwrap();
        let messages = call["messages"].as_array().unwrap().clone();
        let (messages, _) = complete(&messages, |id| session.surface_keys(id));
        assert!(session.apply(&messages).is_ok());
        let submit = messages[0]["createSurface"]["components"]
            .as_array()
            .unwrap()
            .iter()
            .find(|component| component["id"] == "submit")
            .unwrap();
        assert_eq!(
            submit["action"]["event"]["context"],
            json!({"plan": {"@path": "/plan"}})
        );
    }

    #[test]
    fn a_surface_as_text_shows_each_component_as_the_user_reads_it() {
        let session = UiSession::new(vec![Catalog::basic().clone()]).unwrap();
        let report = session.apply(&[serde_json::json!({"version": "1.0", "createSurface": {
            "surfaceId": "order",
            "catalogId": agent86_ui::BASIC_CATALOG_ID,
            "components": [
                {"id": "root", "component": "Column",
                 "children": ["title", "name", "note", "plan", "extras", "receipt", "seats",
                              "line", "logo", "tabs", "row"]},
                {"id": "title", "component": "Text", "text": "Your order\u{1b}[31m"},
                {"id": "name", "component": "TextField", "label": "Name", "value": {"@path": "/name"}},
                {"id": "note", "component": "TextField", "label": "Note", "value": {"@path": "/note"}},
                {"id": "plan", "component": "ChoicePicker", "label": "Plan",
                 "options": [{"label": "Free", "value": "free"}, {"label": "Pro", "value": "pro"}],
                 "value": {"@path": "/plan"}},
                {"id": "extras", "component": "ChoicePicker", "variant": "multipleSelection",
                 "options": [{"label": "Gift wrap", "value": "wrap"}, {"label": "Card", "value": "card"}],
                 "value": {"@path": "/extras"}},
                {"id": "receipt", "component": "CheckBox", "label": "Email me the receipt",
                 "value": {"@path": "/receipt"}},
                {"id": "seats", "component": "Slider", "label": "Seats", "min": 1, "max": 10,
                 "value": {"@path": "/seats"}},
                {"id": "line", "component": "Divider"},
                {"id": "logo", "component": "Image", "description": "Our logo",
                 "url": "https://example.com/logo.png"},
                {"id": "tabs", "component": "Tabs", "tabs": [{"title": "One", "child": "one"}]},
                {"id": "one", "component": "Text", "text": "inside a tab"},
                {"id": "row", "component": "Row", "children": ["ok", "cancel"]},
                {"id": "ok", "component": "Button", "child": "ok_label",
                 "action": {"event": {"name": "submit"}}},
                {"id": "ok_label", "component": "Text", "text": "OK"},
                {"id": "cancel", "component": "Button", "child": "cancel_label",
                 "action": {"event": {"name": "cancel"}}},
                {"id": "cancel_label", "component": "Text", "text": "Cancel"}
            ],
            "dataModel": {"name": "Ada", "note": "", "plan": ["pro"], "extras": ["wrap", "card"],
                          "receipt": true, "seats": 3}
        }})]);
        assert!(report.is_ok(), "{:?}", report.errors);
        assert_eq!(
            session.surface_texts(),
            [concat!(
                "[agent86UI surface \"order\": this client cannot draw it, so it is shown as ",
                "text; answer in your reply]\n",
                // The escape is shown, never sent through.
                "Your order\u{241b}[31m\n",
                "Name: Ada\n",
                "Note: (empty)\n",
                "Plan: a) Free  b) Pro (chosen)\n",
                "a) Gift wrap (chosen)  b) Card (chosen)\n",
                "[x] Email me the receipt\n",
                "Seats: 3 (1 to 10)\n",
                "---\n",
                "[image] Our logo https://example.com/logo.png\n",
                "(a Tabs is not shown as text)\n",
                "[OK]\n",
                "[Cancel]"
            )]
        );
    }
}