par-term 0.48.0

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
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
//! In-app UI test harness: scripted key injection + overlay assertions.
//!
//! Agents cannot drive the real UI from outside on macOS: TCC refuses
//! synthetic keystrokes and screen capture for ungranted host processes
//! (osascript error 1002; `screencapture` "could not create image from
//! display"), and `--screenshot` captures only the offscreen pane composite,
//! which excludes egui overlays by design. This harness closes the gap from
//! inside the process, where no host permission applies:
//!
//! - `chord` steps reach the real keybinding layer through
//!   [`KeybindingRegistry::lookup_with_key_fields`] — winit's `KeyEvent` has
//!   private fields and cannot be constructed outside winit, so chords enter
//!   as public key fields — and dispatch via `execute_keybinding_action`,
//!   the same entry point real key events use. A chord bound to
//!   `pass_to_terminal`, or one no binding matches, is encoded to the
//!   focused terminal's PTY through the same `KeyInput` path the keyboard
//!   handler's tail uses.
//! - `type_text`/`press` steps push [`egui::Event`]s onto
//!   `EguiState::pending_events`, the channel macOS menu accelerators already
//!   use for synthetic input, so overlay widgets consume them on the next
//!   frame.
//! - `assert*` steps read live overlay/window state. Every step appends an
//!   observation record regardless of assertion, and the run finishes by
//!   writing a JSON report and exiting the app.
//!
//! Scripts are JSON. See `docs/guides/AGENT_UI_VERIFICATION.md` for the
//! format and a worked palette example.

use crate::app::window_manager::WindowManager;
use crate::app::window_state::WindowState;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use winit::event_loop::ActiveEventLoop;
use winit::keyboard::{
    Key, KeyCode, ModifiersState, NamedKey, NativeKey, NativeKeyCode, PhysicalKey,
};

/// Default delay before each step, letting the event loop settle.
fn default_wait_ms() -> u64 {
    250
}

/// A parsed `--ui-test` script.
#[derive(Debug, Clone)]
pub(crate) struct UiTestScript {
    /// Steps in execution order.
    pub(crate) steps: Vec<UiTestStep>,
}

/// One scripted action plus its settle delay.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct UiTestStep {
    /// Milliseconds to wait before executing this step.
    #[serde(default = "default_wait_ms")]
    pub(crate) wait_ms: u64,
    /// What to do.
    #[serde(flatten)]
    pub(crate) action: UiTestAction,
}

/// The step verb. Exactly one field per JSON object (untagged).
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub(crate) enum UiTestAction {
    /// Inject a chord (e.g. `"Ctrl+Alt+Cmd+P"`) through the keybinding layer.
    Chord { chord: String },
    /// Deliver text to the focused egui widget (palette/settings fields).
    TypeText { type_text: String },
    /// Press a named key (`Enter`, `Escape`, `ArrowDown`, `F1`..`F12`, ...) on
    /// the egui side.
    Press { press: String },
    /// Assert a named boolean condition is true.
    Assert { assert: String },
    /// Assert a named boolean condition is false.
    AssertNot { assert_not: String },
    /// Assert a named keyed value: `["top_action", "toggle_fullscreen"]`,
    /// `["file_empty", "/tmp/capture.txt"]`,
    /// `["mux_pane_grid", "97x29"]`.
    AssertEq { assert_eq: (String, String) },
    /// Stash a keyed operand's current value for a later
    /// `assert_eq_captured` step — for values a script cannot know up
    /// front, like a spawned shell's PID.
    Capture { capture: String },
    /// Assert a keyed operand's current value equals the one an earlier
    /// `capture` step stashed for it.
    AssertEqCaptured { assert_eq_captured: String },
    /// Seed one of the B61 modal dialogs open (`close_running_job`,
    /// `mux_last_tab`, `trigger_confirm`, `agent_command_confirm`,
    /// `update_dialog`, `tab_context_menu`, `profile_launcher`,
    /// `demote_chooser`, `profile_drawer`, `quit_confirmation`) — the seam
    /// standing in for the user interaction that opens each dialog, so a
    /// script can prove typed keys stay off the PTY while it is open.
    OpenModal { open_modal: String },
    /// Seed clipboard-history entries into the focused pane's terminal
    /// (B70): in production only selection copies feed that history, which a
    /// script cannot drive — this stands in for the copy, newest last.
    SeedClipboard { seed_clipboard: Vec<String> },
    /// Close a dialog opened by `open_modal` (clears the seeded state; the
    /// dialogs' own button/Escape handling is egui-side, via `press`).
    CloseModal { close_modal: String },
}

/// The env var a run recipe exports with its per-run PTY-sink path. A
/// `file_bytes`/`file_empty` operand may reference it bare
/// (`$PAR_TERM_UI_TEST_SINK`) or braced; the PTY child inherits the same
/// value, so the config's `cat > "$PAR_TERM_UI_TEST_SINK"` lands on the
/// identical path. Referenced but unset fails the load loudly.
const SINK_ENV_VAR: &str = "PAR_TERM_UI_TEST_SINK";

/// Expand `$PAR_TERM_UI_TEST_SINK` in a file operand; operands without the
/// reference come back unchanged.
fn resolve_sink_var(operand: &str) -> anyhow::Result<String> {
    let bare = format!("${SINK_ENV_VAR}");
    let braced = format!("${{{SINK_ENV_VAR}}}");
    if !operand.contains(&bare) && !operand.contains(&braced) {
        return Ok(operand.to_string());
    }
    match std::env::var(SINK_ENV_VAR) {
        Ok(value) => Ok(operand.replace(&braced, &value).replace(&bare, &value)),
        Err(_) => Err(anyhow::anyhow!(
            "--ui-test: ${SINK_ENV_VAR} referenced but not set — export it to this run's sink path"
        )),
    }
}

/// Split a `file_bytes` operand into `(path, hex, exact)`: `<path>:<hex>`
/// matches exactly, `<path>*<hex>` as a suffix. The split runs from the
/// END and a `:` tail must be pure hex, so a Windows drive colon
/// (`C:\...`) stays part of the path instead of being read as a delimiter.
fn split_file_bytes_operand(operand: &str) -> Option<(&str, &str, bool)> {
    if let Some(star) = operand.rfind('*') {
        return Some((&operand[..star], &operand[star + 1..], false));
    }
    let (path, hex) = operand.rsplit_once(':')?;
    if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    Some((path, hex, true))
}

/// The files a script's `file_bytes`/`file_empty` operands name (path
/// portion only, before `:`/`*`).
fn sink_paths(steps: &[UiTestStep]) -> Vec<PathBuf> {
    let mut paths: Vec<PathBuf> = steps
        .iter()
        .filter_map(|step| match &step.action {
            UiTestAction::AssertEq {
                assert_eq: (what, operand),
            } => match (what.as_str(), operand.as_str()) {
                ("file_empty", path) => Some(path),
                ("file_bytes", path) => split_file_bytes_operand(path).map(|(p, _, _)| p),
                _ => None,
            },
            _ => None,
        })
        .filter(|p| !p.is_empty())
        .map(PathBuf::from)
        .collect();
    paths.sort();
    paths.dedup();
    paths
}

/// Delete the sink files the script names, so a file an earlier run left
/// can never satisfy a delivery proof (observed 2026-09-29: a stale /tmp
/// sink answered b64's step 14 a day later while that run's config
/// captured elsewhere). Runs while only `App::run` has executed — before
/// any window or PTY exists — so the app's own shell recreates the sink on
/// first delivery.
fn reset_sink_files(steps: &[UiTestStep]) -> anyhow::Result<()> {
    for path in sink_paths(steps) {
        match std::fs::remove_file(&path) {
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => {
                return Err(anyhow::anyhow!(
                    "--ui-test: cannot reset sink {}: {e}",
                    path.display()
                ));
            }
            Ok(()) => {}
        }
    }
    Ok(())
}

/// Load and parse a script file. Fails loudly on bad JSON so typos never
/// masquerade as a passing run.
pub(crate) fn load_script(path: &Path) -> anyhow::Result<UiTestScript> {
    let raw = std::fs::read_to_string(path)
        .map_err(|e| anyhow::anyhow!("--ui-test: cannot read {}: {}", path.display(), e))?;
    #[derive(Deserialize)]
    struct RawScript {
        steps: Vec<UiTestStep>,
    }
    let raw: RawScript = serde_json::from_str(&raw).map_err(|e| {
        anyhow::anyhow!(
            "--ui-test: invalid script JSON in {}: {}",
            path.display(),
            e
        )
    })?;
    let mut steps = raw.steps;
    // Resolve before resetting so the reset (and the report) see per-run
    // paths, not the placeholder text.
    for step in &mut steps {
        if let UiTestAction::AssertEq {
            assert_eq: (what, operand),
        } = &mut step.action
            && matches!(what.as_str(), "file_bytes" | "file_empty")
        {
            *operand = resolve_sink_var(operand)?;
        }
    }
    reset_sink_files(&steps)?;
    Ok(UiTestScript { steps })
}

/// Accumulated per-step records for the final report.
#[derive(Debug, Default)]
pub(crate) struct UiTestRun {
    /// Where the JSON report is written at finish.
    pub(crate) report_path: Option<PathBuf>,
    /// One record per executed step, in order.
    pub(crate) records: Vec<StepRecord>,
    /// Count of failed assertions (missing assert operands count too).
    pub(crate) failed: usize,
    /// Count of passed assertions.
    pub(crate) passed: usize,
    /// Operand values stashed by `capture` steps, keyed by operand name.
    pub(crate) captured: std::collections::HashMap<String, String>,
}

/// What one step did, with the observation taken after it.
#[derive(Debug, Serialize)]
pub(crate) struct StepRecord {
    /// 1-based step index.
    index: usize,
    /// The settle delay that preceded the step.
    wait_ms: u64,
    /// Human-readable description of the action.
    action: String,
    /// `Some(ok)` for verdict-bearing steps (assertions, and action steps
    /// that could not execute); `None` for performed non-verdict steps.
    ok: Option<bool>,
    /// Outcome detail (matched action, assert value, errors).
    detail: String,
    /// Live UI state sampled right after the step.
    observation: Observation,
}

/// Overlay/window visibility snapshot taken after every step — the script's
/// eyes. Fields are the surfaces `--ui-test` exists to expose.
#[derive(Debug, Serialize, Clone)]
pub(crate) struct Observation {
    /// Command palette overlay visible.
    palette_open: bool,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    agent_usage_panel_open: bool,
    /// Search overlay visible.
    search_open: bool,
    /// Standalone settings window open.
    settings_window_open: bool,
    /// `any_modal_ui_visible()` — the guard that blocks keys from the PTY.
    modal_guard: bool,
    /// egui currently owns keyboard focus (text field focused).
    egui_keyboard: bool,
    /// Window is in fullscreen mode.
    fullscreen: bool,
    /// Top-ranked palette action id for the current query, if the palette
    /// is open.
    top_action: Option<String>,
    /// Names of every modal overlay currently visible — the modal_guard
    /// breakdown, so a surprise guard=true names its cause.
    modals: Vec<String>,
}

/// Names of the overlays `any_modal_ui_visible()` is true for, bottom to
/// top — derived from the overlay stack, so the report can never list a
/// different set than the guard sums over (UX.md MP1: "the harness's modal
/// list is derived from the overlay stack").
fn visible_modal_names(ws: &WindowState) -> Vec<String> {
    ws.overlay_stack().guard_names()
}

/// Prefix that makes a chord step inject the key the way Windows reports
/// Ctrl+Alt+letter: logical key `Key::Unidentified`, physical key carrying the
/// letter (`"Unidentified+Ctrl+Alt+S"`). Without it every character chord is
/// injected as `Key::Character`, which never exercises that matcher path.
const UNIDENTIFIED_PREFIX: &str = "Unidentified+";

/// The physical key a letter or digit occupies on a US layout.
fn physical_code_for_char(c: char) -> Option<KeyCode> {
    Some(match c.to_ascii_uppercase() {
        'A' => KeyCode::KeyA,
        'B' => KeyCode::KeyB,
        'C' => KeyCode::KeyC,
        'D' => KeyCode::KeyD,
        'E' => KeyCode::KeyE,
        'F' => KeyCode::KeyF,
        'G' => KeyCode::KeyG,
        'H' => KeyCode::KeyH,
        'I' => KeyCode::KeyI,
        'J' => KeyCode::KeyJ,
        'K' => KeyCode::KeyK,
        'L' => KeyCode::KeyL,
        'M' => KeyCode::KeyM,
        'N' => KeyCode::KeyN,
        'O' => KeyCode::KeyO,
        'P' => KeyCode::KeyP,
        'Q' => KeyCode::KeyQ,
        'R' => KeyCode::KeyR,
        'S' => KeyCode::KeyS,
        'T' => KeyCode::KeyT,
        'U' => KeyCode::KeyU,
        'V' => KeyCode::KeyV,
        'W' => KeyCode::KeyW,
        'X' => KeyCode::KeyX,
        'Y' => KeyCode::KeyY,
        'Z' => KeyCode::KeyZ,
        '0' => KeyCode::Digit0,
        '1' => KeyCode::Digit1,
        '2' => KeyCode::Digit2,
        '3' => KeyCode::Digit3,
        '4' => KeyCode::Digit4,
        '5' => KeyCode::Digit5,
        '6' => KeyCode::Digit6,
        '7' => KeyCode::Digit7,
        '8' => KeyCode::Digit8,
        '9' => KeyCode::Digit9,
        _ => return None,
    })
}

/// Convert a chord string into the (logical key, physical key, modifiers)
/// triple the keybinding seam consumes.
fn chord_to_fields(chord: &str) -> Result<(Key, PhysicalKey, winit::event::Modifiers), String> {
    use par_term_keybindings::parser::{ParsedKey, parse_key_combo};

    let (unidentified, spec) = match chord.get(..UNIDENTIFIED_PREFIX.len()) {
        Some(head) if head.eq_ignore_ascii_case(UNIDENTIFIED_PREFIX) => {
            (true, &chord[UNIDENTIFIED_PREFIX.len()..])
        }
        _ => (false, chord),
    };
    let combo = parse_key_combo(spec).map_err(|e| format!("cannot parse chord '{chord}': {e}"))?;
    let m = &combo.modifiers;

    let mut state = ModifiersState::empty();
    if m.ctrl {
        state |= ModifiersState::CONTROL;
    }
    if m.alt {
        state |= ModifiersState::ALT;
    }
    if m.shift {
        state |= ModifiersState::SHIFT;
    }
    // CmdOrCtrl resolves platform-side at match time; injected chords must
    // carry the resolved modifier to match what a real event would report.
    if m.super_key || (m.cmd_or_ctrl && cfg!(target_os = "macos")) {
        state |= ModifiersState::SUPER;
    }
    if m.cmd_or_ctrl && !cfg!(target_os = "macos") {
        state |= ModifiersState::CONTROL;
    }
    let modifiers = winit::event::Modifiers::from(state);

    match combo.key {
        ParsedKey::Character(c) if unidentified => {
            let code = physical_code_for_char(c).ok_or_else(|| {
                format!("chord '{chord}': Unidentified+ needs a letter or digit key, got '{c}'")
            })?;
            Ok((
                Key::Unidentified(NativeKey::Windows(c.to_ascii_uppercase() as u16)),
                PhysicalKey::Code(code),
                modifiers,
            ))
        }
        _ if unidentified => Err(format!(
            "chord '{chord}': Unidentified+ applies to letter or digit chords only"
        )),
        ParsedKey::Character(c) => {
            let upper = c.to_ascii_uppercase().to_string();
            Ok((
                Key::Character(upper.into()),
                PhysicalKey::Unidentified(NativeKeyCode::Unidentified),
                modifiers,
            ))
        }
        ParsedKey::Named(named) => Ok((Key::Named(named), named_physical_code(&named), modifiers)),
        ParsedKey::Physical(code) => {
            // Physical bindings name a KeyCode, not a logical key; matching
            // goes by scan code, so the logical slot carries a placeholder.
            Ok((Key::Dead(None), PhysicalKey::Code(code), modifiers))
        }
    }
}

/// Best-effort physical code for named keys, so physical-preference matching
/// works for the common harness chords.
fn named_physical_code(key: &NamedKey) -> PhysicalKey {
    match key {
        NamedKey::F1 => PhysicalKey::Code(KeyCode::F1),
        NamedKey::F2 => PhysicalKey::Code(KeyCode::F2),
        NamedKey::F3 => PhysicalKey::Code(KeyCode::F3),
        NamedKey::F4 => PhysicalKey::Code(KeyCode::F4),
        NamedKey::F5 => PhysicalKey::Code(KeyCode::F5),
        NamedKey::F6 => PhysicalKey::Code(KeyCode::F6),
        NamedKey::F7 => PhysicalKey::Code(KeyCode::F7),
        NamedKey::F8 => PhysicalKey::Code(KeyCode::F8),
        NamedKey::F9 => PhysicalKey::Code(KeyCode::F9),
        NamedKey::F10 => PhysicalKey::Code(KeyCode::F10),
        NamedKey::F11 => PhysicalKey::Code(KeyCode::F11),
        NamedKey::F12 => PhysicalKey::Code(KeyCode::F12),
        NamedKey::Enter => PhysicalKey::Code(KeyCode::Enter),
        NamedKey::Escape => PhysicalKey::Code(KeyCode::Escape),
        NamedKey::Tab => PhysicalKey::Code(KeyCode::Tab),
        NamedKey::Backspace => PhysicalKey::Code(KeyCode::Backspace),
        NamedKey::Delete => PhysicalKey::Code(KeyCode::Delete),
        NamedKey::ArrowUp => PhysicalKey::Code(KeyCode::ArrowUp),
        NamedKey::ArrowDown => PhysicalKey::Code(KeyCode::ArrowDown),
        NamedKey::ArrowLeft => PhysicalKey::Code(KeyCode::ArrowLeft),
        NamedKey::ArrowRight => PhysicalKey::Code(KeyCode::ArrowRight),
        NamedKey::Home => PhysicalKey::Code(KeyCode::Home),
        NamedKey::End => PhysicalKey::Code(KeyCode::End),
        NamedKey::PageUp => PhysicalKey::Code(KeyCode::PageUp),
        NamedKey::PageDown => PhysicalKey::Code(KeyCode::PageDown),
        _ => PhysicalKey::Unidentified(NativeKeyCode::Unidentified),
    }
}

/// Split a `press` name's modifier prefixes (`Shift+`, `Cmd+`, `Ctrl+`, in
/// any order) from its key name. `Cmd+` is egui's platform command
/// modifier (Cmd on macOS, Ctrl elsewhere), the one egui's `COMMAND`
/// shortcuts match.
fn press_modifiers(press: &str) -> (&str, egui::Modifiers) {
    let mut modifiers = egui::Modifiers::NONE;
    let mut rest = press;
    loop {
        if let Some(r) = rest.strip_prefix("Shift+") {
            modifiers.shift = true;
            rest = r;
        } else if let Some(r) = rest.strip_prefix("Cmd+") {
            modifiers |= egui::Modifiers::COMMAND;
            rest = r;
        } else if let Some(r) = rest.strip_prefix("Ctrl+") {
            modifiers.ctrl = true;
            rest = r;
        } else {
            return (rest, modifiers);
        }
    }
}

/// Map a step's `press` name to the egui key it should deliver.
fn press_to_egui_key(name: &str) -> Option<egui::Key> {
    Some(match name.to_ascii_lowercase().as_str() {
        "enter" => egui::Key::Enter,
        "escape" => egui::Key::Escape,
        "tab" => egui::Key::Tab,
        "backspace" => egui::Key::Backspace,
        "delete" => egui::Key::Delete,
        "arrowup" | "up" => egui::Key::ArrowUp,
        "arrowdown" | "down" => egui::Key::ArrowDown,
        "arrowleft" | "left" => egui::Key::ArrowLeft,
        "arrowright" | "right" => egui::Key::ArrowRight,
        "home" => egui::Key::Home,
        "end" => egui::Key::End,
        "pageup" => egui::Key::PageUp,
        "pagedown" => egui::Key::PageDown,
        "f1" => egui::Key::F1,
        "f2" => egui::Key::F2,
        "f3" => egui::Key::F3,
        "f4" => egui::Key::F4,
        "f5" => egui::Key::F5,
        "f6" => egui::Key::F6,
        "f7" => egui::Key::F7,
        "f8" => egui::Key::F8,
        "f9" => egui::Key::F9,
        "f10" => egui::Key::F10,
        "f11" => egui::Key::F11,
        "f12" => egui::Key::F12,
        // Single letters a–z are documented press names
        // (AGENT_UI_VERIFICATION.md) for letter-keyed overlays such as the
        // agent-usage panel's `r` refresh; anything else is unknown.
        s if s.len() == 1 && s.as_bytes()[0].is_ascii_alphabetic() => egui::Key::from_name(s)?,
        _ => return None,
    })
}

/// Fold a step outcome into (action description, verdict, detail).
///
/// `Failed` must carry `Some(false)` — a step that could not execute
/// (unknown press/chord name, no terminal window yet) has to fail the run,
/// or a typo'd script reports `all_passed: true`. `Performed` carries no
/// verdict, including a chord deliberately blocked by the modal guard.
fn step_verdict(outcome: StepOutcome) -> (String, Option<bool>, String) {
    match outcome {
        StepOutcome::Performed(desc) => (desc, None, String::new()),
        StepOutcome::Asserted {
            desc,
            passed,
            detail,
        } => (desc, Some(passed), detail),
        StepOutcome::Failed(desc) => (desc.clone(), Some(false), desc),
    }
}

impl WindowManager {
    /// Execute one scripted step against the first terminal window.
    pub(crate) fn run_ui_test_step(&mut self, step: &UiTestStep) {
        let index = self.ui_test.records.len() + 1;
        let (action_desc, ok, detail) = step_verdict(self.ui_test_step_inner(step));
        let observation = self.ui_test_observe();
        if ok == Some(false) {
            self.ui_test.failed += 1;
            log::warn!("UI TEST step {index} FAILED: {action_desc} — {detail}");
        } else if ok == Some(true) {
            self.ui_test.passed += 1;
        }
        self.ui_test.records.push(StepRecord {
            index,
            wait_ms: step.wait_ms,
            action: action_desc,
            ok,
            detail,
            observation,
        });
    }

    /// The step body, before observation recording.
    fn ui_test_step_inner(&mut self, step: &UiTestStep) -> StepOutcome {
        // Steps act on the first non-settings terminal window; scripts are
        // single-window by design.
        let window_ids: Vec<_> = self.windows.keys().copied().collect();
        let terminal_id = window_ids
            .into_iter()
            .find(|id| !self.is_settings_window(*id));

        match &step.action {
            UiTestAction::Chord { chord } => {
                let Some(id) = terminal_id else {
                    return StepOutcome::Failed("chord: no terminal window yet".into());
                };
                let ws = self.windows.get_mut(&id).expect("id from keys()");
                Self::inject_chord(ws, chord)
            }
            UiTestAction::TypeText { type_text } => {
                let Some(id) = terminal_id else {
                    return StepOutcome::Failed("type_text: no terminal window yet".into());
                };
                let ws = self.windows.get_mut(&id).expect("id from keys()");
                ws.egui
                    .pending_events
                    .push(egui::Event::Text(type_text.clone()));
                Self::render_ui_test_frame(ws);
                StepOutcome::Performed(format!("type_text \"{type_text}\" (egui)"))
            }
            UiTestAction::Press { press } => {
                // "Shift+" / "Cmd+" / "Ctrl+" prefixes (any order, e.g.
                // "Cmd+Shift+d") carry the modifiers on the egui event —
                // panels distinguish plain from modified keys (clipboard
                // history's Enter vs Shift+Enter, Open Profiles' Cmd+D).
                let (key_name, modifiers) = press_modifiers(press);
                let Some(egui_key) = press_to_egui_key(key_name) else {
                    return StepOutcome::Failed(format!(
                        "press: unknown key name '{press}' (see AGENT_UI_VERIFICATION.md)"
                    ));
                };
                let Some(id) = terminal_id else {
                    return StepOutcome::Failed("press: no terminal window yet".into());
                };
                let ws = self.windows.get_mut(&id).expect("id from keys()");
                ws.egui.pending_events.push(egui::Event::Key {
                    key: egui_key,
                    physical_key: None,
                    pressed: true,
                    repeat: false,
                    modifiers,
                });
                Self::render_ui_test_frame(ws);
                StepOutcome::Performed(format!("press {press} (egui)"))
            }
            UiTestAction::SeedClipboard { seed_clipboard } => {
                let Some(id) = terminal_id else {
                    return StepOutcome::Failed("seed_clipboard: no terminal window yet".into());
                };
                let ws = self.windows.get_mut(&id).expect("id from keys()");
                let Some(tab) = ws.tab_manager.active_tab() else {
                    return StepOutcome::Failed("seed_clipboard: no active tab".into());
                };
                let terminal = tab.read_terminal_handle();
                let Ok(term) = terminal.try_read() else {
                    return StepOutcome::Failed("seed_clipboard: terminal lock busy".into());
                };
                for content in seed_clipboard {
                    term.add_to_clipboard_history(
                        par_term_terminal::ClipboardSlot::Clipboard,
                        content.clone(),
                        None,
                    );
                }
                StepOutcome::Performed(format!("seed_clipboard {} entries", seed_clipboard.len()))
            }
            UiTestAction::Assert { assert } => {
                let value = self.ui_test_bool(assert);
                match value {
                    Some(v) => StepOutcome::Asserted {
                        desc: format!("assert {assert}"),
                        passed: v,
                        detail: format!("{assert} = {v}"),
                    },
                    None => StepOutcome::Asserted {
                        desc: format!("assert {assert}"),
                        passed: false,
                        detail: format!("unknown assert operand '{assert}'"),
                    },
                }
            }
            UiTestAction::OpenModal { open_modal } => {
                let Some(id) = terminal_id else {
                    return StepOutcome::Failed("open_modal: no terminal window yet".into());
                };
                let ws = self.windows.get_mut(&id).expect("id from keys()");
                Self::seed_modal_state(ws, open_modal, true)
            }
            UiTestAction::CloseModal { close_modal } => {
                let Some(id) = terminal_id else {
                    return StepOutcome::Failed("close_modal: no terminal window yet".into());
                };
                let ws = self.windows.get_mut(&id).expect("id from keys()");
                Self::seed_modal_state(ws, close_modal, false)
            }
            UiTestAction::AssertNot { assert_not } => {
                let value = self.ui_test_bool(assert_not);
                match value {
                    Some(v) => StepOutcome::Asserted {
                        desc: format!("assert_not {assert_not}"),
                        passed: !v,
                        detail: format!("{assert_not} = {v}"),
                    },
                    None => StepOutcome::Asserted {
                        desc: format!("assert_not {assert_not}"),
                        passed: false,
                        detail: format!("unknown assert operand '{assert_not}'"),
                    },
                }
            }
            UiTestAction::AssertEq { assert_eq } => {
                let (what, expected) = assert_eq;
                match self.ui_test_value(what, expected) {
                    Ok((actual, passed)) => StepOutcome::Asserted {
                        desc: format!("assert_eq {what}"),
                        passed,
                        detail: format!("{what} = {actual:?} (expected {expected:?})"),
                    },
                    Err(err) => StepOutcome::Asserted {
                        desc: format!("assert_eq {what}"),
                        passed: false,
                        detail: err,
                    },
                }
            }
            UiTestAction::Capture { capture } => match self.ui_test_operand(capture) {
                Ok(actual) => {
                    self.ui_test
                        .captured
                        .insert(capture.clone(), actual.clone());
                    StepOutcome::Performed(format!("capture {capture} = {actual}"))
                }
                Err(err) => StepOutcome::Failed(format!("capture {capture}: {err}")),
            },
            UiTestAction::AssertEqCaptured { assert_eq_captured } => {
                let what = assert_eq_captured.as_str();
                let Some(expected) = self.ui_test.captured.get(what).cloned() else {
                    return StepOutcome::Asserted {
                        desc: format!("assert_eq_captured {what}"),
                        passed: false,
                        detail: format!("no captured value for operand '{what}'"),
                    };
                };
                match self.ui_test_operand(what) {
                    Ok(actual) => StepOutcome::Asserted {
                        desc: format!("assert_eq_captured {what}"),
                        passed: actual == expected,
                        detail: format!("{what} = {actual:?} (captured {expected:?})"),
                    },
                    Err(err) => StepOutcome::Asserted {
                        desc: format!("assert_eq_captured {what}"),
                        passed: false,
                        detail: err,
                    },
                }
            }
        }
    }

    /// Seed (`open == true`) or clear (`open == false`) one B61 dialog's
    /// state. Opening uses each dialog's real entry point so the seeded
    /// state is exactly what the user interaction produces; closing restores
    /// the hidden state without driving egui — buttons and Escape are the
    /// egui-side `press` steps' job, this only arms/disarms the modal the
    /// key guard sums over.
    fn seed_modal_state(ws: &mut WindowState, name: &str, open: bool) -> StepOutcome {
        use crate::app::window_state::PendingTriggerAction;
        use par_term_config::agent_commands::CommandAuthor;

        let verb = if open { "open_modal" } else { "close_modal" };
        match name {
            "close_running_job" => {
                if open {
                    let Some(tab_id) = ws.tab_manager.active_tab_id() else {
                        return StepOutcome::Failed(format!("{verb} {name}: no active tab"));
                    };
                    ws.overlay_ui.close_confirmation_ui.show_for_tab(
                        tab_id,
                        "ui-test tab",
                        "sleep 100",
                    );
                } else {
                    ws.overlay_ui.close_confirmation_ui.hide();
                }
            }
            "mux_last_tab" => {
                if open {
                    ws.overlay_ui.mux_last_tab_ui.show_for_session("ui-test");
                } else {
                    ws.overlay_ui.mux_last_tab_ui.hide();
                }
            }
            "trigger_confirm" => {
                if open {
                    ws.trigger_state
                        .pending_trigger_actions
                        .push(PendingTriggerAction {
                            trigger_id: 0,
                            trigger_name: "ui-test trigger".to_string(),
                            action: par_term_emu_core_rust::terminal::ActionResult::RunCommand {
                                trigger_id: 0,
                                command: "echo".to_string(),
                                args: vec!["b61".to_string()],
                            },
                            description: "ui-test pending trigger action".to_string(),
                            target: None,
                        });
                } else {
                    ws.trigger_state.pending_trigger_actions.clear();
                }
            }
            "agent_command_confirm" => {
                if open {
                    let file = par_term_config::agent_commands::AgentCommandFile {
                        created_by: CommandAuthor::User,
                        source_agent: None,
                        created_at: None,
                        action: par_term_config::CustomActionConfig::ShellCommand {
                            id: "ui-test-b61".to_string(),
                            title: "ui-test b61".to_string(),
                            command: "echo".to_string(),
                            args: vec!["b61".to_string()],
                            notify_on_success: false,
                            timeout_secs: 30,
                            capture_output: false,
                            keybinding: None,
                            prefix_char: None,
                            keybinding_enabled: true,
                            description: None,
                        },
                    };
                    ws.agent_commands.request_confirmation(file);
                } else {
                    ws.agent_commands.pending_confirmations.clear();
                }
            }
            "update_dialog" => {
                if open {
                    ws.update_state.show_dialog = true;
                    ws.update_state.last_result = Some(
                        par_term_update::update_checker::UpdateCheckResult::UpdateAvailable(
                            par_term_update::update_checker::UpdateInfo {
                                version: "999.0.0".to_string(),
                                release_notes: None,
                                release_url: "https://example.invalid".to_string(),
                                published_at: None,
                            },
                        ),
                    );
                } else {
                    ws.update_state.show_dialog = false;
                }
            }
            "tab_context_menu" => {
                if open {
                    let Some(tab_id) = ws.tab_manager.active_tab_id() else {
                        return StepOutcome::Failed(format!("{verb} {name}: no active tab"));
                    };
                    ws.tab_bar_ui.test_open_context_menu(tab_id);
                } else {
                    ws.tab_bar_ui.test_close_context_menu();
                }
            }
            "profile_launcher" => {
                if open {
                    ws.open_profile_launcher();
                } else {
                    ws.overlay_ui.profile_launcher_ui.close();
                }
            }
            "demote_chooser" => {
                if open {
                    let Some(tab_id) = ws.tab_manager.active_tab_id() else {
                        return StepOutcome::Failed(format!("{verb} {name}: no active tab"));
                    };
                    // Prefer the direction chooser (the B61 dialog); a
                    // single-pane tab without a focused pane id falls back
                    // to the first pick phase, which the same guard term
                    // covers.
                    let pane_id = ws
                        .tab_manager
                        .active_tab()
                        .and_then(|t| t.focused_pane_id());
                    ws.pane_transfer_state = match pane_id {
                        Some(target_pane_id) => {
                            crate::app::tab_ops::pane_transfer::PaneTransferState::DemoteChooseDirection {
                                source_tab_id: tab_id,
                                target_tab_id: tab_id,
                                target_pane_id,
                            }
                        }
                        None => crate::app::tab_ops::pane_transfer::PaneTransferState::DemotePickTab {
                            source_tab_id: tab_id,
                        },
                    };
                } else {
                    ws.cancel_pane_transfer();
                }
            }
            "profile_drawer" => {
                if ws.overlay_ui.profile_drawer_ui.expanded != open {
                    ws.toggle_profiles_drawer();
                }
            }
            "quit_confirmation" => {
                if open {
                    ws.overlay_ui
                        .quit_confirmation_ui
                        .show_confirmation(1, None);
                } else {
                    ws.overlay_ui.quit_confirmation_ui.hide();
                }
            }
            "tmux_picker" => {
                if open {
                    ws.overlay_ui.tmux_session_picker_ui.show_picker();
                } else {
                    ws.overlay_ui.tmux_session_picker_ui.hide();
                }
            }
            // B70: opened through the real entry points (the registry
            // `toggle_*` actions call these), so a script can drive the
            // panels' egui-side navigation and prove Enter delivers to the
            // PTY sink.
            "command_history" => {
                if ws.overlay_ui.command_history_ui.visible != open {
                    ws.toggle_command_history();
                }
            }
            "clipboard_history" => {
                if ws.overlay_ui.clipboard_history_ui.visible != open {
                    ws.toggle_clipboard_history();
                }
            }
            _ => {
                return StepOutcome::Failed(format!(
                    "{verb}: unknown dialog '{name}' (see UiTestAction::OpenModal docs)"
                ));
            }
        }
        ws.request_redraw();
        StepOutcome::Performed(format!("{verb} {name}"))
    }

    /// Drive one full render frame synchronously after queueing synthetic
    /// egui input.
    ///
    /// The alternative — `request_redraw` and letting the OS deliver
    /// `RedrawRequested` — is neither immediate nor guaranteed: the FPS gate
    /// in `should_render_frame` rejects redraws that arrive close behind a
    /// rendered frame, and an occluded window may not get one at all. Both
    /// were observed as run-to-run flaky `press` delivery (b62/b64 scripts
    /// passing one run and failing the next with the key never reaching the
    /// dialog). Clearing `last_render_time` passes the gate for this one
    /// frame; the frame then flushes `pending_events` through the real
    /// `render()` → egui path, so the next step's asserts read state the
    /// input has already been applied to.
    fn render_ui_test_frame(ws: &mut WindowState) {
        ws.focus_state.last_render_time = None;
        ws.render();
        ws.request_redraw();
    }

    /// Inject a chord through the real keybinding registry + action dispatch.
    fn inject_chord(ws: &mut WindowState, chord: &str) -> StepOutcome {
        let fields = match chord_to_fields(chord) {
            Ok(f) => f,
            Err(err) => return StepOutcome::Failed(format!("chord: {err}")),
        };
        let (logical, physical, modifiers) = fields;

        // The real event path: handle_window_event routes every key press
        // through the overlay stack before terminal dispatch (UX.md OV2).
        // Same function, same facts — this is not a mirror of the guard.
        let facts = ws.overlay_key_facts(&logical, physical, &modifiers);
        let route = ws.route_overlay_key(&facts);
        if ws.apply_overlay_route(&route) {
            return StepOutcome::Performed(format!("chord {chord} -> overlay stack: {route:?}"));
        }
        if !route.continues_to_key_dispatch() {
            return StepOutcome::Performed(format!(
                "chord {chord} -> blocked by modal guard (overlay open): {route:?}"
            ));
        }

        // Mirror the real event path: an armed pane-hint mode captures every
        // key press (any press resolves it — mode-stack contract); a focused
        // plugin overlay swallows everything except Escape. Both checks sit
        // ahead of the keybinding layer in handle_key_event, so the injector
        // must sit them here too or a chord bypasses them.
        if ws.pane_hint_select.is_active() {
            let typed = match &logical {
                Key::Character(ch) => ch.chars().next(),
                _ => None,
            };
            ws.resolve_pane_hint_select(typed);
            return StepOutcome::Performed(format!("chord {chord} -> resolved pane-hint mode"));
        }
        if ws.pane_resize_mode.is_active() {
            let key = crate::app::pane_resize_mode::ResizeModeKey::from_key(
                &logical,
                modifiers.state().shift_key(),
            );
            let cell = ws.resize_mode_cell_size();
            ws.resolve_pane_resize_key(key, cell);
            return StepOutcome::Performed(format!("chord {chord} -> resize mode"));
        }
        if ws.status_bar_ui.plugin_host().focused_overlay().is_some() {
            let is_escape = matches!(&logical, Key::Named(NamedKey::Escape));
            ws.resolve_focused_overlay_key(is_escape);
            return StepOutcome::Performed(format!(
                "chord {chord} -> swallowed by focused overlay{}",
                if is_escape { " (unfocused)" } else { "" }
            ));
        }

        // Mirror the real event path: modifier state is updated before the
        // key press is looked up.
        ws.input_handler.update_modifiers(modifiers);

        // The leader runs ahead of the registry in handle_key_event (UX.md
        // K4); same entry point here, so a script drives the real machine.
        let press = crate::app::leader::LeaderPress {
            logical: &logical,
            physical,
            pressed: true,
            os_repeat: false,
        };
        if let Some(step) = ws.handle_leader_press(press) {
            ws.request_redraw();
            return StepOutcome::Performed(format!("chord {chord} -> leader {step:?}"));
        }

        let config = ws.config.load();
        let action = ws.keybinding_registry.lookup_with_key_fields(
            &logical,
            physical,
            &modifiers,
            &config.input.modifier_remapping,
            config.input.use_physical_keys,
        );
        drop(config);

        match action {
            Some(action) => {
                let action = action.to_string();
                if action == par_term_keybindings::PASS_TO_TERMINAL {
                    // A passthrough row claims the chord for the shell: the
                    // real handler skips every layer and encodes the key to
                    // the PTY, so the injector must too.
                    Self::inject_chord_to_pty(ws, chord, "pass_to_terminal", logical, physical)
                } else {
                    let handled = ws.execute_keybinding_action(&action);
                    ws.request_redraw();
                    StepOutcome::Performed(format!(
                        "chord {chord} -> keybinding '{action}' (handled={handled})"
                    ))
                }
            }
            // An unmatched key falls through every layer to the PTY in the
            // real handler; encode it the same way instead of dropping it.
            None => Self::inject_chord_to_pty(ws, chord, "unbound fallthrough", logical, physical),
        }
    }

    /// Encode a chord's key fields to the focused terminal's PTY — the tail
    /// of the real key handler that a `pass_to_terminal` row or an unmatched
    /// key reaches. Encoding goes through [`par_term_input::KeyInput`], the
    /// sanctioned construction path (a winit `KeyEvent` cannot be fabricated
    /// safely), and the write rides the shared read lock like the keyboard
    /// path so it cannot starve the refresh task.
    fn inject_chord_to_pty(
        ws: &mut WindowState,
        chord: &str,
        via: &str,
        logical: Key,
        physical: PhysicalKey,
    ) -> StepOutcome {
        // B61 mirror: the real key handler consumes any key that survives to
        // its encoding tail while a modal overlay is open (an Escape or
        // F1–F3 that no layer or keybinding claimed). The injector must
        // refuse the PTY write under the same condition, or an Escape chord
        // while a dialog is open would write `1b` the real handler now
        // never writes.
        if ws.any_modal_ui_visible() {
            return StepOutcome::Performed(format!(
                "chord {chord} -> {via} -> consumed by modal guard tail (no PTY write)"
            ));
        }
        // Same mode priority as the keyboard path: focused pane's terminal,
        // else the tab's cached modes. Scoped — the encoder needs &mut
        // input_handler, which cannot alias the tab borrow.
        let (modify_other_keys_mode, application_cursor) = {
            let Some(tab) = ws.tab_manager.active_tab() else {
                return StepOutcome::Failed(format!("chord {chord} -> PTY: no active tab"));
            };
            if let Some(ref pane_manager) = tab.pane_manager
                && let Some(focused_pane) = pane_manager.focused_pane()
                && let Ok(term) = focused_pane.terminal.try_read()
            {
                (term.modify_other_keys_mode(), term.application_cursor())
            } else {
                let (m, a, _) = tab.read_or_cached_modes();
                (m, a)
            }
        };

        let input = par_term_input::KeyInput {
            logical_key: logical,
            physical_key: physical,
            state: winit::event::ElementState::Pressed,
        };
        let Some(bytes) = ws.input_handler.handle_key_input_with_mode(
            &input,
            modify_other_keys_mode,
            application_cursor,
        ) else {
            return StepOutcome::Failed(format!("chord {chord} -> PTY: encoder declined the key"));
        };

        // Same terminal selection as the keyboard path: focused pane's
        // terminal when splits exist, else the tab's main terminal.
        let terminal = {
            let Some(tab) = ws.tab_manager.active_tab() else {
                return StepOutcome::Failed(format!("chord {chord} -> PTY: no active tab"));
            };
            if let Some(ref pane_manager) = tab.pane_manager
                && let Some(focused_pane) = pane_manager.focused_pane()
            {
                std::sync::Arc::clone(&focused_pane.terminal)
            } else {
                std::sync::Arc::clone(&tab.terminal)
            }
        };
        let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
        let byte_count = bytes.len();
        // Write synchronously when the lock is free so the step record's
        // byte claim is true at record time — a spawned write can be
        // starved or dropped at app exit, which a byte-exact sink assert
        // then reports as lost input. The spawn fallback preserves delivery
        // under momentary contention (same shape as the keyboard path).
        // The guard must drop before `terminal`/`bytes` move into the
        // fallback spawn, so the attempt runs in its own block.
        let mut write_result: Result<(), String> = Ok(());
        let mut contended = false;
        {
            match terminal.try_read() {
                Ok(term) => write_result = term.write(&bytes).map_err(|e| e.to_string()),
                Err(_) => contended = true,
            }
        }
        if contended {
            ws.runtime.spawn(async move {
                let term = terminal.read().await;
                if let Err(e) = term.write(&bytes) {
                    crate::debug_error!("INPUT", "PTY write failed (ui-test passthrough): {e}");
                }
            });
        }
        match write_result {
            Ok(()) => StepOutcome::Performed(format!(
                "chord {chord} -> {via} -> PTY ({byte_count} bytes: {hex})"
            )),
            Err(e) => StepOutcome::Failed(format!("chord {chord} -> PTY write failed: {e}")),
        }
    }

    /// Evaluate a named boolean assert operand against live state.
    fn ui_test_bool(&self, name: &str) -> Option<bool> {
        Some(match name {
            "palette_open" => self.ui_test_palette_open(),
            "agent_usage_panel_open" => self.ui_test_agent_usage_panel_open(),
            "settings_window_open" => self.settings_window.is_some(),
            // Manager-level fallbacks when no terminal window exists yet.
            _ => {
                let ws = self.ui_test_window_state()?;
                match name {
                    "search_open" => ws.overlay_ui.search_ui.visible,
                    "agent_usage_ready" => !ws.status_bar_ui.usage_snapshot().records.is_empty(),
                    "plugins_loaded" => ws.status_bar_ui.plugins_discovered_count() >= 1,
                    "plugin_widget_set" => ws.status_bar_ui.any_plugin_widget_text(),
                    "plugin_panel_set" => ws.status_bar_ui.any_plugin_panel_pushed(),
                    "plugin_overlay_set" => !ws.status_bar_ui.plugin_host().overlays().is_empty(),
                    "plugin_overlay_interactive" => ws
                        .status_bar_ui
                        .plugin_host()
                        .overlays()
                        .values()
                        .any(|o| o.interactive),
                    "plugin_overlay_focused" => {
                        ws.status_bar_ui.plugin_host().focused_overlay().is_some()
                    }
                    "plugin_overlay_event" => {
                        ws.status_bar_ui
                            .plugin_host()
                            .overlay_events_dispatched_count()
                            > 0
                    }
                    "plugin_action_dispatched" => ws.status_bar_ui.any_plugin_action_dispatched(),
                    "modal_guard" => ws.any_modal_ui_visible(),
                    "tmux_picker_open" => ws.overlay_ui.tmux_session_picker_ui.visible,
                    "command_history_open" => ws.overlay_ui.command_history_ui.visible,
                    "clipboard_history_open" => ws.overlay_ui.clipboard_history_ui.visible,
                    "paste_special_open" => ws.overlay_ui.paste_special_ui.visible,
                    "palette_selected_visible" => {
                        ws.overlay_ui.command_palette.selected_row_is_visible()
                    }
                    "pane_hint_mode_active" => ws.pane_hint_select.is_active(),
                    // The leader (UX.md K4): armed, and its which-key shown.
                    "leader_armed" => ws.leader.is_armed(),
                    "which_key_open" => ws.overlay_state.which_key.is_some(),
                    "pane_zoomed" => ws
                        .tab_manager
                        .active_tab()
                        .and_then(|t| t.pane_manager())
                        .is_some_and(|pm| pm.is_zoomed()),
                    "egui_keyboard" => ws.is_egui_using_keyboard(),
                    "fullscreen" => ws.window.as_ref().is_some_and(|w| w.fullscreen().is_some()),
                    // `overlay_open:<name>` — any overlay-stack member by
                    // its stack name (`tree_picker_ui`, `help_ui`, …).
                    other => {
                        let name = other.strip_prefix("overlay_open:")?;
                        let id = crate::app::overlay::OverlayId::ALL
                            .iter()
                            .find(|id| id.name() == name)?;
                        ws.overlay_is_open(*id)
                    }
                }
            }
        })
    }

    /// Current value of a capture-capable keyed operand — the ones whose
    /// value a script cannot know up front (a spawned shell's PID). The
    /// literal-comparison operands stay in [`Self::ui_test_value`].
    fn ui_test_operand(&self, what: &str) -> Result<String, String> {
        match what {
            // The focused terminal's PTY child PID: the identity a
            // preserve-shell close/reopen must keep (card 01a0eafef7ee7490a7c9bce3cc52ddcd).
            "tab_shell_pid" => {
                let Some(ws) = self.ui_test_window_state() else {
                    return Err("tab_shell_pid: no terminal window".into());
                };
                let Some(tab) = ws.tab_manager.active_tab() else {
                    return Err("tab_shell_pid: no active tab".into());
                };
                match tab.try_with_read_terminal(|t| t.get_shell_pid()) {
                    Some(Some(pid)) => Ok(pid.to_string()),
                    Some(None) => {
                        Err("tab_shell_pid: PTY child pid unavailable (session exited?)".into())
                    }
                    None => Err("tab_shell_pid: terminal lock contention".into()),
                }
            }
            _ => Err(format!(
                "operand '{what}' has no capturable value (see AGENT_UI_VERIFICATION.md)"
            )),
        }
    }

    /// Evaluate a keyed assert operand, returning (actual, passed).
    fn ui_test_value(&self, what: &str, expected: &str) -> Result<(String, bool), String> {
        match what {
            "top_action" => {
                let Some(ws) = self.ui_test_window_state() else {
                    return Err("top_action: no terminal window".into());
                };
                let actual = ws
                    .overlay_ui
                    .command_palette
                    .top_action()
                    .unwrap_or("<none>")
                    .to_string();
                Ok((actual.clone(), actual == expected))
            }
            // The palette's selected row index into the filtered list — the
            // B62 scroll proof asserts it alongside palette_selected_visible.
            "palette_selected" => {
                let Some(ws) = self.ui_test_window_state() else {
                    return Err("palette_selected: no terminal window".into());
                };
                let actual = ws.overlay_ui.command_palette.selected_index().to_string();
                Ok((actual.clone(), actual == expected))
            }
            // The app's open-window count — the readout a session-restore
            // proof asserts on (TW2: quit must save every window).
            "window_count" => {
                let actual = self.windows.len().to_string();
                Ok((actual.clone(), actual == expected))
            }
            // Visible tab count, the 1-based active tab, and the active
            // tab's pane count — the leader proofs (c, n, p, x).
            "tab_count" | "active_tab" | "pane_count" => {
                let Some(ws) = self.ui_test_window_state() else {
                    return Err(format!("{what}: no terminal window"));
                };
                let tabs = &ws.tab_manager;
                let actual = match what {
                    "tab_count" => tabs.visible_tab_count().to_string(),
                    "active_tab" => tabs
                        .active_tab_index()
                        .map_or("<none>".to_string(), |i| (i + 1).to_string()),
                    _ => tabs.active_tab().map_or(0, |t| t.pane_count()).to_string(),
                };
                Ok((actual.clone(), actual == expected))
            }
            // The selected command's text — the B70 navigation proof pairs
            // it with arrow presses (selection moved to the expected row).
            "command_history_selected" => {
                let Some(ws) = self.ui_test_window_state() else {
                    return Err("command_history_selected: no terminal window".into());
                };
                let actual = ws
                    .overlay_ui
                    .command_history_ui
                    .selected_command()
                    .unwrap_or("<none>".into());
                Ok((actual.clone(), actual == expected))
            }
            // The selected clipboard entry's content — B70, same shape as
            // command_history_selected.
            "clipboard_history_selected" => {
                let Some(ws) = self.ui_test_window_state() else {
                    return Err("clipboard_history_selected: no terminal window".into());
                };
                let actual = ws
                    .overlay_ui
                    .clipboard_history_ui
                    .selected_entry()
                    .map(|e| e.content.clone())
                    .unwrap_or("<none>".into());
                Ok((actual.clone(), actual == expected))
            }
            // Live font size — the B68 reset proof (decrease moves it off
            // the configured value, reset must land back on it, not 14.0).
            "font_size" => {
                let Some(ws) = self.ui_test_window_state() else {
                    return Err("font_size: no terminal window".into());
                };
                let actual = ws.config.load().font_size.to_string();
                Ok((actual.clone(), actual == expected))
            }
            "file_empty" => {
                let meta = std::fs::metadata(expected);
                let actual = match &meta {
                    Ok(m) => format!("{} bytes", m.len()),
                    Err(_) => "missing".to_string(),
                };
                let empty = matches!(&meta, Ok(m) if m.len() == 0)
                    || matches!(&meta, Err(e) if e.kind() == std::io::ErrorKind::NotFound);
                Ok((actual, empty))
            }
            // Byte-exact PTY-sink readout, the delivery half of a
            // pass-to-terminal proof: `["file_bytes", "<path>:<hex>"]`.
            // `"<path>*<hex>"` asserts the sink ENDS with the hex run — for
            // scripts run on a live desktop, where the app window can steal
            // focus mid-run and catch real keystrokes ahead of the scripted
            // ones (observed: stray "cc-" and TAB contaminating the line).
            // Unlike file_empty, a missing file is a failure — a delivery
            // proof must show the bytes arrived.
            "file_bytes" => {
                let (path, expected_hex, exact) = match split_file_bytes_operand(expected) {
                    Some(split) => split,
                    None => {
                        return Err("file_bytes: expected '<path>:<hex>' or '<path>*<hex>'".into());
                    }
                };
                let expected_hex = expected_hex.to_ascii_lowercase();
                let actual = std::fs::read(path)
                    .map(|bytes| bytes.iter().map(|b| format!("{b:02x}")).collect::<String>())
                    .unwrap_or_else(|_| "missing".to_string());
                let ok = actual == expected_hex || (!exact && actual.ends_with(&expected_hex));
                Ok((actual, ok))
            }
            // The rendered grid of every mux-attached pane, the readout a
            // resize proof asserts on: one pane reports bare "WxH", more
            // report "paneid=WxH" joined by commas in ascending pane order.
            "mux_pane_grid" => {
                let Some(ws) = self.ui_test_window_state() else {
                    return Err("mux_pane_grid: no terminal window".into());
                };
                let owners = &ws.tmux_state.tmux_pane_owners;
                if owners.is_empty() {
                    return Err("mux_pane_grid: no par-mux panes attached".into());
                }
                let mut entries: Vec<(u64, String)> = Vec::new();
                for (mux_id, (tab_id, pane_id)) in owners {
                    let Some(tab) = ws.tab_manager.get_tab(*tab_id) else {
                        return Err(format!(
                            "mux_pane_grid: tab {tab_id:?} holding %{mux_id} not found"
                        ));
                    };
                    let Some(pm) = tab.pane_manager() else {
                        return Err(format!(
                            "mux_pane_grid: tab {tab_id:?} holding %{mux_id} has no panes"
                        ));
                    };
                    let Some(pane) = pm.get_pane(*pane_id) else {
                        return Err(format!(
                            "mux_pane_grid: pane {pane_id:?} for %{mux_id} not found"
                        ));
                    };
                    let (cols, rows) = match pane.terminal.try_read() {
                        Ok(term) => term.dimensions(),
                        Err(e) => {
                            return Err(format!("mux_pane_grid: %{mux_id} terminal lock: {e}"));
                        }
                    };
                    entries.push((*mux_id, format!("{cols}x{rows}")));
                }
                entries.sort_by_key(|(id, _)| *id);
                let actual = if entries.len() == 1 {
                    entries
                        .into_iter()
                        .next()
                        .map(|(_, g)| g)
                        .unwrap_or_default()
                } else {
                    entries
                        .into_iter()
                        .map(|(id, g)| format!("%{id}={g}"))
                        .collect::<Vec<_>>()
                        .join(",")
                };
                Ok((actual.clone(), actual == expected))
            }
            _ => Err(format!("unknown assert_eq operand '{what}'")),
        }
    }

    /// Palette visibility is window-level but harmless to probe with no
    /// window (reports false).
    fn ui_test_palette_open(&self) -> bool {
        self.ui_test_window_state()
            .is_some_and(|ws| ws.overlay_ui.command_palette.visible)
    }

    /// Agent-usage panel visibility, same window-level probing contract.
    fn ui_test_agent_usage_panel_open(&self) -> bool {
        self.ui_test_window_state()
            .is_some_and(|ws| ws.overlay_ui.agent_usage_panel.visible)
    }

    /// The first non-settings terminal window's state, if one exists.
    fn ui_test_window_state(&self) -> Option<&WindowState> {
        self.windows
            .iter()
            .find(|(id, _)| !self.is_settings_window(**id))
            .map(|(_, ws)| ws)
    }

    /// Snapshot live overlay/window state — recorded after every step.
    fn ui_test_observe(&self) -> Observation {
        let ws = self.ui_test_window_state();
        Observation {
            palette_open: ws.is_some_and(|w| w.overlay_ui.command_palette.visible),
            agent_usage_panel_open: ws.is_some_and(|w| w.overlay_ui.agent_usage_panel.visible),
            search_open: ws.is_some_and(|w| w.overlay_ui.search_ui.visible),
            settings_window_open: self.settings_window.is_some(),
            modal_guard: ws.is_some_and(|w| w.any_modal_ui_visible()),
            egui_keyboard: ws.is_some_and(|w| w.is_egui_using_keyboard()),
            fullscreen: ws.is_some_and(|w| {
                w.window
                    .as_ref()
                    .is_some_and(|win| win.fullscreen().is_some())
            }),
            top_action: ws
                .and_then(|w| w.overlay_ui.command_palette.top_action())
                .map(str::to_string),
            modals: ws.map(visible_modal_names).unwrap_or_default(),
        }
    }

    /// Write the JSON report, log the summary, and exit the app. Called on
    /// `AppEvent::UiTestFinish`.
    pub(crate) fn ui_test_finish(&mut self, event_loop: &ActiveEventLoop) {
        let all_passed = self.ui_test.failed == 0;
        #[derive(Serialize)]
        struct Report<'a> {
            passed: usize,
            failed: usize,
            all_passed: bool,
            steps: &'a [StepRecord],
        }
        let report = Report {
            passed: self.ui_test.passed,
            failed: self.ui_test.failed,
            all_passed,
            steps: &self.ui_test.records,
        };
        match &self.ui_test.report_path {
            Some(path) => match serde_json::to_string_pretty(&report) {
                Ok(json) => {
                    if let Err(e) = std::fs::write(path, json) {
                        log::error!("UI TEST: cannot write report {}: {e}", path.display());
                    }
                }
                Err(e) => log::error!("UI TEST: cannot serialize report: {e}"),
            },
            None => log::warn!("UI TEST: no report path configured"),
        }
        log::info!(
            "UI TEST finished: {} passed, {} failed — {}",
            self.ui_test.passed,
            self.ui_test.failed,
            if all_passed {
                "ALL PASSED"
            } else {
                "FAILURES PRESENT"
            }
        );
        event_loop.exit();
    }
}

/// Result shape for step bodies.
enum StepOutcome {
    /// Non-asserting step; carried description.
    Performed(String),
    /// Assertion with its verdict.
    Asserted {
        desc: String,
        passed: bool,
        detail: String,
    },
    /// Step could not run (bad operand, no window); recorded as a failure.
    Failed(String),
}

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

    #[test]
    fn chord_to_fields_maps_modifiers() {
        let (logical, physical, modifiers) = chord_to_fields("Ctrl+Alt+Cmd+P").expect("parses");
        assert!(matches!(logical, Key::Character(ref c) if c.as_str() == "P"));
        // Character chords match logically; the physical slot is a documented
        // placeholder (physical-preference configs would need real codes).
        assert!(matches!(physical, PhysicalKey::Unidentified(_)));
        let state = modifiers.state();
        assert!(state.control_key() && state.alt_key() && state.super_key());
        assert!(!state.shift_key());
    }

    #[test]
    fn unidentified_chord_reaches_the_matcher_by_physical_key() {
        use par_term_config::ModifierRemapping;
        use par_term_keybindings::KeybindingRegistry;

        let (logical, physical, modifiers) =
            chord_to_fields("Unidentified+Ctrl+Alt+S").expect("parses");
        assert!(matches!(logical, Key::Unidentified(_)));
        assert_eq!(physical, PhysicalKey::Code(KeyCode::KeyS));
        let state = modifiers.state();
        assert!(state.control_key() && state.alt_key() && !state.shift_key());

        let registry = KeybindingRegistry::from_config(&[par_term_config::KeyBinding {
            key: "Ctrl+Alt+S".into(),
            action: "probe".into(),
        }]);
        let lookup = |l: &Key, p: PhysicalKey, m: &winit::event::Modifiers| {
            registry
                .lookup_with_key_fields(l, p, m, &ModifierRemapping::default(), false)
                .map(str::to_string)
        };
        assert_eq!(
            lookup(&logical, physical, &modifiers).as_deref(),
            Some("probe")
        );
        // The plain spelling injects Key::Character with no physical key, the
        // path Windows never takes; it must not be what this mode exercises.
        let (plain_logical, plain_physical, plain_mods) =
            chord_to_fields("Ctrl+Alt+S").expect("parses");
        assert!(matches!(plain_logical, Key::Character(_)));
        assert!(matches!(plain_physical, PhysicalKey::Unidentified(_)));
        assert_eq!(
            lookup(&plain_logical, plain_physical, &plain_mods).as_deref(),
            Some("probe")
        );
        // A different physical key must not match.
        let (l, p, m) = chord_to_fields("Unidentified+Ctrl+Alt+T").expect("parses");
        assert_eq!(lookup(&l, p, &m), None);
    }

    #[test]
    fn unidentified_chord_rejects_non_character_keys() {
        assert!(chord_to_fields("Unidentified+Ctrl+Alt+F5").is_err());
        assert!(chord_to_fields("Unidentified+Ctrl+Alt+Comma").is_err());
    }

    #[test]
    fn chord_to_fields_rejects_modifier_only_chord() {
        // "Ctrl" ends with a modifier and has no key: a parse error.
        assert!(chord_to_fields("Ctrl").is_err());
    }

    #[test]
    fn named_keys_map_to_egui() {
        assert_eq!(press_to_egui_key("Enter"), Some(egui::Key::Enter));
        assert_eq!(press_to_egui_key("escape"), Some(egui::Key::Escape));
        assert_eq!(press_to_egui_key("Nope"), None);
    }

    #[test]
    fn single_letters_map_to_egui() {
        // The agent-usage panel's `r` refresh drives through this mapping.
        assert_eq!(press_to_egui_key("r"), Some(egui::Key::R));
        assert_eq!(press_to_egui_key("H"), Some(egui::Key::H));
        assert_eq!(press_to_egui_key("rr"), None);
        assert_eq!(press_to_egui_key("1"), None);
    }

    #[test]
    fn failed_steps_carry_a_verdict() {
        // An undrivable step (unknown press name, no terminal window yet)
        // must fail the run: ok=Some(false) feeds the failed counter and
        // all_passed, so a typo'd script cannot report a pass.
        let (_, ok, _) = step_verdict(StepOutcome::Failed("press: unknown key name 'x'".into()));
        assert_eq!(ok, Some(false));
    }

    #[test]
    fn performed_steps_stay_verdict_neutral() {
        // Includes chords deliberately blocked by the modal guard: the
        // injection happened as scripted, the block is the documented
        // behavior, so it must not fail the run.
        let (_, ok, _) = step_verdict(StepOutcome::Performed(
            "chord Ctrl+P -> blocked by modal guard (overlay open)".into(),
        ));
        assert_eq!(ok, None);
    }

    #[test]
    fn ui_test_action_parses_capture_steps() {
        let step: UiTestStep =
            serde_json::from_str(r#"{"capture": "tab_shell_pid"}"#).expect("parses");
        assert!(matches!(
            step.action,
            UiTestAction::Capture { ref capture } if capture == "tab_shell_pid"
        ));

        let step: UiTestStep =
            serde_json::from_str(r#"{"assert_eq_captured": "tab_shell_pid"}"#).expect("parses");
        assert!(matches!(
            step.action,
            UiTestAction::AssertEqCaptured {
                ref assert_eq_captured
            } if assert_eq_captured == "tab_shell_pid"
        ));
    }

    /// Env mutation is process-global; serialize the sink-var tests.
    static SINK_ENV_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn sink_placeholder_resolves_from_the_environment() {
        let _guard = SINK_ENV_LOCK.lock().unwrap();
        let dir = tempfile::tempdir().expect("tempdir");
        let sink = dir.path().join("sink.bin");
        // Process-global env mutation is unsafe in edition 2024; the mutex
        // guard serializes the tests that touch it.
        unsafe { std::env::set_var(SINK_ENV_VAR, &sink) };
        for form in [
            format!(r#"${{{SINK_ENV_VAR}}}:0a"#),
            format!(r#"${SINK_ENV_VAR}:0a"#),
        ] {
            let resolved = resolve_sink_var(&form).expect("resolves");
            assert_eq!(resolved, format!("{}:0a", sink.display()));
        }
        assert_eq!(
            resolve_sink_var("/tmp/literal.bin:0a").expect("literal unchanged"),
            "/tmp/literal.bin:0a"
        );
        unsafe { std::env::remove_var(SINK_ENV_VAR) };
    }

    #[test]
    fn file_bytes_operand_splits_from_the_end() {
        // A Windows drive colon is part of the path, not a delimiter.
        assert_eq!(
            split_file_bytes_operand(r"C:\tmp\sink.bin:0a"),
            Some((r"C:\tmp\sink.bin", "0a", true))
        );
        assert_eq!(
            split_file_bytes_operand("/tmp/sink.bin:0a"),
            Some(("/tmp/sink.bin", "0a", true))
        );
        assert_eq!(
            split_file_bytes_operand(r"C:\tmp\sink*5aa1"),
            Some((r"C:\tmp\sink", "5aa1", false))
        );
        assert_eq!(
            split_file_bytes_operand("/tmp/capture"),
            None,
            "no suffix: the file_bytes caller must reject it"
        );
    }

    #[test]
    fn unset_sink_placeholder_fails_the_load() {
        let _guard = SINK_ENV_LOCK.lock().unwrap();
        unsafe { std::env::remove_var(SINK_ENV_VAR) };
        let dir = tempfile::tempdir().expect("tempdir");
        let script_path = dir.path().join("script.json");
        std::fs::write(
            &script_path,
            format!(r#"{{"steps": [{{"assert_eq": ["file_bytes", "${{{SINK_ENV_VAR}}}:0a"]}}]}}"#),
        )
        .expect("write script");
        let err = load_script(&script_path).expect_err("unset var must fail the load");
        assert!(err.to_string().contains(SINK_ENV_VAR));
    }

    #[test]
    fn load_script_resets_stale_sink_files() {
        let dir = tempfile::tempdir().expect("tempdir");
        // file_bytes: the delivery-proof case from the card — a planted
        // stale sink must be gone before the first step runs.
        let bytes_sink = dir.path().join("sink.bin");
        std::fs::write(&bytes_sink, [0x0a]).expect("plant stale sink");
        let script_path = dir.path().join("bytes.json");
        std::fs::write(
            &script_path,
            format!(
                r#"{{"steps": [{{"assert_eq": ["file_bytes", "{}:0a"]}}]}}"#,
                bytes_sink.display().to_string().replace('\\', "\\\\")
            ),
        )
        .expect("write script");
        load_script(&script_path).expect("loads");
        assert!(!bytes_sink.exists(), "stale delivery sink must be reset");

        // file_empty: same reset, so a prior run's leftover bytes cannot
        // poison the next run either.
        let empty_sink = dir.path().join("capture.txt");
        std::fs::write(&empty_sink, b"leaked").expect("plant stale capture");
        let script_path = dir.path().join("empty.json");
        std::fs::write(
            &script_path,
            format!(
                r#"{{"steps": [{{"assert_eq": ["file_empty", "{}"]}}]}}"#,
                empty_sink.display().to_string().replace('\\', "\\\\")
            ),
        )
        .expect("write script");
        load_script(&script_path).expect("loads");
        assert!(!empty_sink.exists(), "stale file_empty sink must be reset");
    }
}