aster-completion 0.2.0

Natural shell completion
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
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use tempfile::tempdir;

#[test]
fn popup_preserves_highlights_and_shell_bindings() {
    if !command_exists("tmux") || !command_exists("zsh") {
        eprintln!("skipping ZLE integration test because tmux or zsh is unavailable");
        return;
    }

    let aster = Path::new(env!("CARGO_BIN_EXE_aster"));
    let binary_directory = aster.parent().unwrap();
    let temporary = tempdir().unwrap();
    let state = temporary.path().join("state");
    let zdotdir = temporary.path().join("zsh");
    let helper_bin = temporary.path().join("bin");
    fs::create_dir(&state).unwrap();
    fs::create_dir(&zdotdir).unwrap();
    fs::create_dir(&helper_bin).unwrap();
    fs::set_permissions(&state, fs::Permissions::from_mode(0o700)).unwrap();
    fs::set_permissions(&zdotdir, fs::Permissions::from_mode(0o700)).unwrap();

    let config = temporary.path().join("aster.toml");
    let socket = state.join("aster.sock");
    let state_dump = temporary.path().join("zle-state");
    let sync_file = temporary.path().join("zle-sync");
    let preview_file = temporary.path().join("preview-target.txt");
    let preview_file_two = temporary.path().join("preview-target.zzz.txt");
    fs::write(&preview_file, "preview-first-line\npreview-second-line\n").unwrap();
    fs::write(&preview_file_two, "preview-other-candidate\n").unwrap();
    fs::write(temporary.path().join("filesystem-alpha"), "alpha").unwrap();
    fs::write(temporary.path().join("filesystem-beta"), "beta").unwrap();
    fs::write(
        temporary.path().join("kitty.conf"),
        "font_family monospace\n",
    )
    .unwrap();
    fs::write(temporary.path().join("kitty.conf.bak"), "backup\n").unwrap();
    let fake_eza = helper_bin.join("eza");
    fs::write(
        &fake_eza,
        "#!/bin/sh\nprintf '\\033[31meza-alias-preview\\033[0m\\npreview-target.txt\\n'\n",
    )
    .unwrap();
    fs::set_permissions(&fake_eza, fs::Permissions::from_mode(0o755)).unwrap();
    let path = format!(
        "{}:{}:{}",
        helper_bin.display(),
        binary_directory.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let zshrc = format!(
        r#"export PATH={helper_bin}:$PATH
autoload -Uz add-zle-hook-widget compinit
compinit -u
autoload -Uz bracketed-paste-magic
zle -N bracketed-paste bracketed-paste-magic
_aster_test_history_up() {{
  BUFFER=history-arrow-up
  CURSOR=${{#BUFFER}}
}}
_aster_test_history_down() {{
  BUFFER=history-arrow-down
  CURSOR=${{#BUFFER}}
}}
zle -N _aster_test_history_up
zle -N _aster_test_history_down
bindkey '^[[A' _aster_test_history_up
bindkey '^[OA' _aster_test_history_up
bindkey '^[[B' _aster_test_history_down
bindkey '^[OB' _aster_test_history_down
_aster_test_highlight() {{
  region_highlight=( "${{(@)region_highlight:#*memo=foreign-test*}}" )
  [[ -n "$BUFFER" ]] && region_highlight+=("0 ${{#BUFFER}} fg=green memo=foreign-test")
}}
add-zle-hook-widget line-pre-redraw _aster_test_highlight
_aster_test_native() {{
  sleep 0.12
  if (( CURRENT > 2 )); then
    compadd next-value
  else
    compadd native/path/file native/second/file native/third/file
  fi
}}
compdef _aster_test_native aster-native-fixture
_aster_test_file() {{
  compadd {preview_file} {preview_file_two}
}}
compdef _aster_test_file aster-preview-fixture
_aster_test_scp() {{
  if [[ "$PREFIX" == zz* ]]; then
    compadd 'zzuser@example.com:/srv/app/file'
  else
    compadd file-alpha file-beta
  fi
}}
compdef _aster_test_scp scp
_aster_test_ssh() {{
  compadd alice@example.com
}}
compdef _aster_test_ssh ssh
_aster_test_long() {{
  compadd visible-first-option visible-second-option
}}
compdef _aster_test_long aster-command-with-a-very-long-name
alias ls=eza
eval "$({aster} init zsh)"
_aster_test_dump_state() {{
  print -r -- "$_ASTER_MENU_ACTIVE|${{#_ASTER_MENU_ACCEPTS}}|$_ASTER_MENU_BUFFER|$BUFFER|${{_ASTER_MENU_ACCEPTS[1]}}|$_ASTER_MENU_INDEX|${{_ASTER_MENU_DISPLAYS[$_ASTER_MENU_INDEX]}}|$_ASTER_FUZZY_ACTIVE|$_ASTER_FUZZY_BASE|$_ASTER_FUZZY_QUERY|$_ASTER_PREVIEW_FD|$_ASTER_PREVIEW_TICKS|$_ASTER_PREVIEW_PATH|${{(j:;:)_ASTER_PREVIEW_LINES}}|${{(j:;:)_ASTER_MENU_DISPLAYS}}|${{POSTDISPLAY%%$'\n'*}}|${{(j:;:)_ASTER_MENU_SOURCES}}" > {state_dump}
}}
_aster_test_sync() {{
  : > {sync_file}
}}
zle -N _aster_test_dump_state
zle -N _aster_test_sync
bindkey '^X^D' _aster_test_dump_state
bindkey '^G' _aster_test_sync
bindkey -M aster-fuzzy '^X^D' _aster_test_dump_state
bindkey -M aster-fuzzy '^G' _aster_test_sync
PROMPT='%# '
"#,
        aster = shell_quote(aster.to_str().unwrap()),
        helper_bin = shell_quote(helper_bin.to_str().unwrap()),
        preview_file = shell_quote(preview_file.to_str().unwrap()),
        preview_file_two = shell_quote(preview_file_two.to_str().unwrap()),
        state_dump = shell_quote(state_dump.to_str().unwrap()),
        sync_file = shell_quote(sync_file.to_str().unwrap())
    );
    fs::write(zdotdir.join(".zshrc"), zshrc).unwrap();
    let shell_environment = format!(
        "PATH={} ZDOTDIR={} ASTER_CONFIG={} ASTER_STATE_DIR={} ASTER_SOCKET={}",
        shell_quote(&path),
        shell_quote(zdotdir.to_str().unwrap()),
        shell_quote(config.to_str().unwrap()),
        shell_quote(state.to_str().unwrap()),
        shell_quote(socket.to_str().unwrap()),
    );

    let unique = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let server = format!("aster-ui-{}-{unique}", std::process::id());
    let mut guard = ServerGuard {
        server: server.clone(),
        aster: aster.to_owned(),
        config: config.clone(),
        state: state.clone(),
        socket: socket.clone(),
        started: false,
    };

    let status = Command::new("tmux")
        .args([
            "-L",
            &server,
            "-f",
            "/dev/null",
            "new-session",
            "-d",
            "-s",
            "test",
        ])
        .arg(format!("env {shell_environment} zsh -l"))
        .status()
        .unwrap();
    assert!(status.success(), "failed to start isolated tmux server");
    guard.started = true;

    thread::sleep(Duration::from_millis(300));
    let status = Command::new("tmux")
        .args([
            "-L",
            &server,
            "select-pane",
            "-t",
            "test:0.0",
            "-T",
            "user-title",
        ])
        .status()
        .unwrap();
    assert!(status.success(), "failed to set the test pane title");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", ":"])
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Enter"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(100));
    let pane_title = Command::new("tmux")
        .args([
            "-L",
            &server,
            "display-message",
            "-p",
            "-t",
            "test:0.0",
            "#{pane_title}",
        ])
        .output()
        .unwrap();
    assert_eq!(
        String::from_utf8(pane_title.stdout).unwrap().trim(),
        "user-title",
        "Aster overwrote a user-owned tmux pane title"
    );
    let status = Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", "aste"])
        .status()
        .unwrap();
    assert!(status.success(), "failed to type into isolated Zsh");

    let deadline = Instant::now() + Duration::from_secs(4);
    let mut capture = String::new();
    while Instant::now() < deadline {
        let output = Command::new("tmux")
            .args(["-L", &server, "capture-pane", "-p", "-e", "-t", "test:0.0"])
            .output()
            .unwrap();
        capture = String::from_utf8(output.stdout).unwrap();
        if capture.contains('â•­') {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }

    assert!(
        capture.contains('â•­'),
        "Aster popup did not appear:\n{capture}"
    );
    assert!(
        capture.contains("\u{1b}[32maste"),
        "existing syntax highlight was lost after popup rendering:\n{capture:?}"
    );

    let status = Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-Space"])
        .status()
        .unwrap();
    assert!(status.success(), "failed to accept the selected candidate");

    let deadline = Instant::now() + Duration::from_secs(2);
    let mut accepted_capture = String::new();
    while Instant::now() < deadline {
        accepted_capture = capture_pane(&server, true);
        if accepted_capture.contains("\u{1b}[32master") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        accepted_capture.contains("\u{1b}[32master"),
        "accepted command was not fully highlighted:\n{accepted_capture:?}"
    );

    let binding_file = temporary.path().join("enter-binding");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    let binding_command = format!(
        "{{ bindkey '^M'; bindkey '^I'; bindkey '^[[Z'; }} > {}",
        shell_quote(binding_file.to_str().unwrap())
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg(binding_command)
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Enter"])
        .status()
        .unwrap();

    let deadline = Instant::now() + Duration::from_secs(2);
    while Instant::now() < deadline && !binding_file.exists() {
        thread::sleep(Duration::from_millis(50));
    }
    let binding = fs::read_to_string(&binding_file).unwrap_or_else(|error| {
        panic!(
            "Enter did not execute bindkey: {error}\n{}",
            capture_pane(&server, false)
        )
    });
    assert!(binding.contains(r#""^M" accept-line"#));
    assert!(binding.contains(r#""^I" aster-tab"#));
    assert!(binding.contains("aster-shift-tab"));

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", "cd "])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(500));
    dump_zle_state(&server);
    let reordered_state = fs::read_to_string(&state_dump).unwrap();
    let reordered_fields: Vec<_> = reordered_state.trim_end().split('|').collect();
    assert_eq!(reordered_fields[0], "1", "cd path menu was not active");
    assert!(
        reordered_fields[1].parse::<usize>().unwrap() > 1,
        "cd path menu did not contain multiple candidates: {reordered_state:?}"
    );
    assert_eq!(
        reordered_fields[5], "1",
        "async provider merging moved the menu away from row 1: {reordered_state:?}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Up"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(350));
    dump_zle_state(&server);
    let history_up_state = fs::read_to_string(&state_dump).unwrap();
    let history_up_fields: Vec<_> = history_up_state.trim_end().split('|').collect();
    assert_eq!(history_up_fields[0], "0");
    assert_eq!(history_up_fields[3], "history-arrow-up");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Down"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let history_down_state = fs::read_to_string(&state_dump).unwrap();
    let history_down_fields: Vec<_> = history_down_state.trim_end().split('|').collect();
    assert_eq!(history_down_fields[0], "0");
    assert_eq!(history_down_fields[3], "history-arrow-down");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);

    let status = Command::new(aster)
        .args([
            "record",
            "--command",
            "cargo release patch --execute",
            "--cwd",
            temporary.path().to_str().unwrap(),
            "--exit-code",
            "0",
            "--session",
            "history-priority-test",
        ])
        .env("ASTER_CONFIG", &config)
        .env("ASTER_STATE_DIR", &state)
        .env("ASTER_SOCKET", &socket)
        .status()
        .unwrap();
    assert!(status.success(), "failed to seed priority history");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg("cargo release patch ")
        .status()
        .unwrap();
    wait_for_pane(&server, "cargo release patch --execute");
    dump_zle_state(&server);
    let history_priority_state = fs::read_to_string(&state_dump).unwrap();
    let history_priority_fields: Vec<_> = history_priority_state.trim_end().split('|').collect();
    assert_eq!(history_priority_fields[6], "cargo release patch --execute");
    assert!(
        history_priority_fields[16]
            .split(';')
            .any(|source| source == "filesystem"),
        "filesystem fixture did not compete with history: {history_priority_state:?}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg("aster-command-with-a-very-long-name v")
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(4);
    let mut long_candidate_capture = String::new();
    while Instant::now() < deadline {
        long_candidate_capture = capture_pane(&server, false);
        if long_candidate_capture.contains("… isible-first-option")
            && long_candidate_capture.contains("… isible-second-option")
        {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        long_candidate_capture.contains("… isible-first-option")
            && long_candidate_capture.contains("… isible-second-option"),
        "long completion rows did not preserve their distinguishing suffixes:\n{long_candidate_capture}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);

    Command::new("tmux")
        .args([
            "-L",
            &server,
            "send-keys",
            "-l",
            "-t",
            "test:0.0",
            "echo before",
        ])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(100));
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg("\u{1b}[200~ pasted\u{1b}[201~")
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", " after"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(500));
    dump_zle_state(&server);
    let typed_after_paste = fs::read_to_string(&state_dump).unwrap();
    let typed_after_paste_fields: Vec<_> = typed_after_paste.trim_end().split('|').collect();
    assert_eq!(
        typed_after_paste_fields[3], "echo before pasted after",
        "typing after bracketed paste replaced the existing line"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg("aster-native-fixture na")
        .status()
        .unwrap();
    let immediate_capture = capture_pane(&server, false);
    assert!(
        !immediate_capture.contains("native/path/file"),
        "native completion ran synchronously instead of waiting for the debounce"
    );
    let deadline = Instant::now() + Duration::from_secs(4);
    let mut native_capture = String::new();
    while Instant::now() < deadline {
        native_capture = capture_pane(&server, false);
        if native_capture.contains("aster-native-fixture native/path/file") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        native_capture.contains("aster-native-fixture native/path/file")
            && native_capture.contains("Zsh completion"),
        "debounced native Zsh candidate was absent:\n{native_capture}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", "t"])
        .status()
        .unwrap();
    let retained_capture = capture_pane(&server, false);
    assert!(
        retained_capture.contains('â•­')
            && retained_capture.contains("aster-native-fixture native/path/file"),
        "matching candidates flashed off while the next request was pending:\n{retained_capture}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-n", "C-n"])
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "BTab"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let shifted_state = fs::read_to_string(&state_dump).unwrap();
    assert!(
        shifted_state.contains("|2|aster-native-fixture native/second/file"),
        "Shift-Tab did not select the next candidate: {shifted_state:?}"
    );
    let shifted_fields: Vec<_> = shifted_state.trim_end().split('|').collect();
    assert_eq!(
        shifted_fields[15], "ive/second/file",
        "selected candidate was not reflected in ghost text"
    );

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", "i"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let typed_state = fs::read_to_string(&state_dump).unwrap();
    assert!(
        typed_state.contains("|aster-native-fixture nati|aster-native-fixture nati|"),
        "ordinary typing did not update the buffer after selection: {typed_state:?}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "BSpace"])
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(4);
    while Instant::now() < deadline {
        native_capture = capture_pane(&server, false);
        if native_capture.contains("aster-native-fixture native/path/file") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        native_capture.contains("aster-native-fixture native/path/file"),
        "Backspace did not resume completion from the edited buffer:\n{native_capture}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-n"])
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-x", "C-d"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(20));
    let segment_capture = capture_pane(&server, false);
    let state_after_tab = fs::read_to_string(&state_dump).unwrap();
    assert!(
        state_after_tab
            .contains("|aster-native-fixture native/|aster-native-fixture native/|path/file")
            && state_after_tab.contains("|1|aster-native-fixture native/path/file"),
        "Tab did not accept the next path segment and reset selection; state was {state_after_tab:?}:\n{segment_capture}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-x", "C-d"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(20));
    let second_segment_capture = capture_pane(&server, false);
    let state_after_second_tab = fs::read_to_string(&state_dump).unwrap();
    assert!(
        state_after_second_tab
            .contains("|aster-native-fixture native/path/|aster-native-fixture native/path/|file"),
        "a repeated Tab did not accept the next path segment; state was {state_after_second_tab:?}:\n{second_segment_capture}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(4);
    let mut follow_up_capture = String::new();
    let mut follow_up_state = String::new();
    while Instant::now() < deadline {
        follow_up_capture = capture_pane(&server, false);
        dump_zle_state(&server);
        follow_up_state = fs::read_to_string(&state_dump).unwrap();
        if follow_up_state.contains("next-value") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        follow_up_state.contains("next-value"),
        "native completion did not continue after accepting a complete match; state was {follow_up_state:?}:\n{follow_up_capture}"
    );

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    Command::new("tmux")
        .args([
            "-L",
            &server,
            "send-keys",
            "-l",
            "-t",
            "test:0.0",
            "ssh ali",
        ])
        .status()
        .unwrap();
    wait_for_pane(&server, "ssh alice@example.com");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let ssh_user_state = fs::read_to_string(&state_dump).unwrap();
    assert!(
        ssh_user_state.contains("|ssh alice@|ssh alice@|example.com"),
        "Tab did not stop after the SSH user boundary: {ssh_user_state:?}"
    );

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    Command::new("tmux")
        .args([
            "-L",
            &server,
            "send-keys",
            "-l",
            "-t",
            "test:0.0",
            "scp zzu",
        ])
        .status()
        .unwrap();
    wait_for_pane(&server, "scp zzuser@example.com:/srv/app/file");
    for expected in [
        "|scp zzuser@|scp zzuser@|example.com:/srv/app/file",
        "|scp zzuser@example.com:/|scp zzuser@example.com:/|srv/app/file",
        "|scp zzuser@example.com:/srv/|scp zzuser@example.com:/srv/|app/file",
    ] {
        Command::new("tmux")
            .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
            .status()
            .unwrap();
        dump_zle_state(&server);
        let remote_path_state = fs::read_to_string(&state_dump).unwrap();
        assert!(
            remote_path_state.contains(expected),
            "Tab did not stop at remote path boundary {expected:?}: {remote_path_state:?}"
        );
    }

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg("aster-native-fixture na")
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(350));
    let tab_capture = capture_pane(&server, false);
    assert!(
        !tab_capture.contains("completion cannot be used recursively"),
        "ticker entered completion recursively during native Tab:\n{tab_capture}"
    );

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    let scp_path_prefix = format!("scp -r {}/filesystem-", temporary.path().display());
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg(&scp_path_prefix)
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(4);
    let mut scp_capture = String::new();
    while Instant::now() < deadline {
        scp_capture = capture_pane(&server, false);
        if scp_capture.contains("1/2") && scp_capture.matches("File").count() >= 2 {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        scp_capture.contains("1/2") && scp_capture.matches("File").count() >= 2,
        "generic filesystem candidates were absent for scp:\n{scp_capture}"
    );
    dump_zle_state(&server);
    let scp_before_tab = fs::read_to_string(&state_dump).unwrap();
    assert!(
        scp_before_tab.contains(&format!("|{scp_path_prefix}|{scp_path_prefix}|")),
        "Aster did not retain the scp path prefix: {scp_before_tab:?}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(50));
    dump_zle_state(&server);
    let scp_after_tab = fs::read_to_string(&state_dump).unwrap();
    assert!(
        scp_after_tab.contains(&format!("|{scp_path_prefix}|{scp_path_prefix}|")),
        "ambiguous path Tab selected an arbitrary file: {scp_after_tab:?}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", "a"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(100));
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let scp_unique_path = fs::read_to_string(&state_dump).unwrap();
    assert!(
        scp_unique_path.contains(&format!(
            "|{}filesystem-alpha |{}filesystem-alpha |",
            &scp_path_prefix[..scp_path_prefix.len() - "filesystem-".len()],
            &scp_path_prefix[..scp_path_prefix.len() - "filesystem-".len()]
        )),
        "Tab did not accept the unique filesystem candidate: {scp_unique_path:?}"
    );

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    let kitty_prefix = format!("nv {}/kitty.con", temporary.path().display());
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg(&kitty_prefix)
        .status()
        .unwrap();
    wait_for_pane(&server, "f.bak");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let common_path_state = fs::read_to_string(&state_dump).unwrap();
    let common_path_fields: Vec<_> = common_path_state.trim_end().split('|').collect();
    assert_eq!(common_path_fields[3], format!("{kitty_prefix}f"));
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let exact_path_state = fs::read_to_string(&state_dump).unwrap();
    let exact_path_fields: Vec<_> = exact_path_state.trim_end().split('|').collect();
    assert_eq!(exact_path_fields[3], format!("{kitty_prefix}f "));

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    let source_command = format!(
        "zle -D _aster-native-space; source {}",
        shell_quote(zdotdir.join(".zshrc").to_str().unwrap())
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg(source_command)
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Enter"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(300));
    let rebound_file = temporary.path().join("reloaded-bindings");
    let rebound_command = format!(
        "{{ bindkey '^I'; bindkey '^[[Z'; bindkey '^@'; }} > {}",
        shell_quote(rebound_file.to_str().unwrap())
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg(rebound_command)
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Enter"])
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(2);
    while Instant::now() < deadline && !rebound_file.exists() {
        thread::sleep(Duration::from_millis(20));
    }
    let rebound = fs::read_to_string(&rebound_file).unwrap();
    assert!(rebound.contains(r#""^I" aster-tab"#));
    assert!(rebound.contains("aster-shift-tab"));
    assert!(rebound.contains(r#""^@" aster-complete"#));

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", "aste"])
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(4);
    let mut reloaded_capture = String::new();
    while Instant::now() < deadline {
        reloaded_capture = capture_pane(&server, false);
        if reloaded_capture.contains('â•­') {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        reloaded_capture.contains('â•­'),
        "Aster did not restart its ticker after .zshrc was sourced:\n{reloaded_capture}"
    );

    for command in [
        "echo fuzzy-history-target",
        "echo fuzzy-history-target-secondary",
    ] {
        let status = Command::new(aster)
            .args([
                "record",
                "--command",
                command,
                "--cwd",
                temporary.path().to_str().unwrap(),
                "--exit-code",
                "0",
                "--session",
                "fuzzy-test",
            ])
            .env("ASTER_CONFIG", &config)
            .env("ASTER_STATE_DIR", &state)
            .env("ASTER_SOCKET", &socket)
            .status()
            .unwrap();
        assert!(status.success(), "failed to seed fuzzy history");
    }
    let ls_history = format!("ls {}", temporary.path().display());
    let status = Command::new(aster)
        .args([
            "record",
            "--command",
            &ls_history,
            "--cwd",
            temporary.path().to_str().unwrap(),
            "--exit-code",
            "0",
            "--session",
            "preview-test",
        ])
        .env("ASTER_CONFIG", &config)
        .env("ASTER_STATE_DIR", &state)
        .env("ASTER_SOCKET", &socket)
        .status()
        .unwrap();
    assert!(status.success(), "failed to seed ls preview history");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", "  fzht"])
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(4);
    let mut fuzzy_capture = String::new();
    while Instant::now() < deadline {
        fuzzy_capture = capture_pane(&server, false);
        if fuzzy_capture.contains("echo fuzzy-history-target") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        fuzzy_capture.contains("echo fuzzy-history-target"),
        "inline fuzzy history result was absent:\n{fuzzy_capture}"
    );
    dump_zle_state(&server);
    let fuzzy_state = fs::read_to_string(&state_dump).unwrap();
    let fuzzy_fields: Vec<_> = fuzzy_state.trim_end().split('|').collect();
    assert_eq!(fuzzy_fields[3], " fzht");
    assert_eq!(fuzzy_fields[7], "1");
    assert_eq!(fuzzy_fields[8], " ");
    assert_eq!(fuzzy_fields[9], "fzht");
    assert_eq!(
        fuzzy_fields[15],
        format!("  → {}", fuzzy_fields[6]),
        "selected fuzzy candidate was not reflected in ghost text"
    );
    assert_eq!(
        cursor_x(&server, "test:0.0"),
        7,
        "fuzzy query did not retain ZLE's real cursor"
    );
    assert!(
        fuzzy_fields[1].parse::<usize>().unwrap() >= 2,
        "fuzzy fixture did not produce scrollable candidates: {fuzzy_state:?}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-n"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let scrolled_fuzzy_state = fs::read_to_string(&state_dump).unwrap();
    let scrolled_fuzzy_fields: Vec<_> = scrolled_fuzzy_state.trim_end().split('|').collect();
    assert_ne!(scrolled_fuzzy_fields[6], fuzzy_fields[6]);
    assert_eq!(
        scrolled_fuzzy_fields[15],
        format!("  → {}", scrolled_fuzzy_fields[6]),
        "scrolling did not update fuzzy ghost text"
    );

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Escape"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let escaped_state = fs::read_to_string(&state_dump).unwrap();
    let escaped_fields: Vec<_> = escaped_state.trim_end().split('|').collect();
    assert_eq!(escaped_fields[3], " ");
    assert_eq!(escaped_fields[7], "0");
    assert_eq!(escaped_fields[9], "");

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", " fzht"])
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(4);
    while Instant::now() < deadline {
        fuzzy_capture = capture_pane(&server, false);
        if fuzzy_capture.contains("echo fuzzy-history-target") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Tab"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let accepted_fuzzy_state = fs::read_to_string(&state_dump).unwrap();
    let accepted_fields: Vec<_> = accepted_fuzzy_state.trim_end().split('|').collect();
    assert!(accepted_fields[3].starts_with("echo fuzzy-history-target"));
    assert_eq!(accepted_fields[7], "0");

    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);

    Command::new("tmux")
        .args([
            "-L",
            &server,
            "send-keys",
            "-l",
            "-t",
            "test:0.0",
            "echo first  stale",
        ])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let first_interrupted_fuzzy = fs::read_to_string(&state_dump).unwrap();
    let first_interrupted_fields: Vec<_> = first_interrupted_fuzzy.trim_end().split('|').collect();
    assert_eq!(first_interrupted_fields[7], "1");
    assert_eq!(first_interrupted_fields[8], "echo first ");
    assert_eq!(first_interrupted_fields[9], "stale");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);

    Command::new("tmux")
        .args([
            "-L",
            &server,
            "send-keys",
            "-l",
            "-t",
            "test:0.0",
            "echo second  fresh",
        ])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let second_fuzzy = fs::read_to_string(&state_dump).unwrap();
    let second_fuzzy_fields: Vec<_> = second_fuzzy.trim_end().split('|').collect();
    assert_eq!(second_fuzzy_fields[7], "1");
    assert_eq!(second_fuzzy_fields[8], "echo second ");
    assert_eq!(second_fuzzy_fields[9], "fresh");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "Escape"])
        .status()
        .unwrap();
    dump_zle_state(&server);
    let escaped_second_fuzzy = fs::read_to_string(&state_dump).unwrap();
    let escaped_second_fields: Vec<_> = escaped_second_fuzzy.trim_end().split('|').collect();
    assert_eq!(escaped_second_fields[3], "echo second ");
    assert_eq!(escaped_second_fields[7], "0");
    assert_eq!(escaped_second_fields[8], "");
    assert_eq!(escaped_second_fields[9], "");
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    Command::new("tmux")
        .args([
            "-L",
            &server,
            "resize-window",
            "-t",
            "test:0",
            "-x",
            "140",
            "-y",
            "40",
        ])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(50));
    Command::new("tmux")
        .args([
            "-L",
            &server,
            "send-keys",
            "-l",
            "-t",
            "test:0.0",
            "echo fuzzy",
        ])
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(4);
    let mut history_capture = String::new();
    while Instant::now() < deadline {
        history_capture = capture_pane(&server, false);
        if history_capture.contains("echo fuzzy-history-target") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(history_capture.contains("echo fuzzy-history-target"));
    assert!(
        !history_capture.contains("Preview:"),
        "history-only suggestions opened an unnecessary preview:\n{history_capture}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0", "ls "])
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(5);
    let mut command_preview_capture = String::new();
    while Instant::now() < deadline {
        command_preview_capture = capture_pane(&server, true);
        if command_preview_capture.contains("eza-alias-preview")
            && command_preview_capture.contains("\u{1b}[31meza-alias-preview")
            && command_preview_capture.contains("preview-target.txt")
            && command_preview_capture.contains("Preview:")
        {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        command_preview_capture.contains("eza-alias-preview")
            && command_preview_capture.contains("\u{1b}[31meza-alias-preview")
            && command_preview_capture.contains("preview-target.txt")
            && command_preview_capture.contains("Preview:"),
        "safe eza-backed ls command preview was absent:\n{command_preview_capture}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-c"])
        .status()
        .unwrap();
    wait_for_zle(&server, &sync_file);
    let preview_prefix = preview_file.to_str().unwrap().strip_suffix("txt").unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-l", "-t", "test:0.0"])
        .arg(format!("aster-preview-fixture {preview_prefix}"))
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(5);
    let mut preview_capture = String::new();
    while Instant::now() < deadline {
        preview_capture = capture_pane(&server, false);
        if preview_capture.contains("preview-first-line") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    dump_zle_state(&server);
    let preview_state = fs::read_to_string(&state_dump).unwrap();
    assert!(
        preview_capture.contains("preview-first-line") && preview_capture.contains("Preview:"),
        "lazy wide-terminal file preview was absent; state was {preview_state:?}:\n{preview_capture}"
    );
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:0.0", "C-n"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(20));
    let switching_preview = capture_pane(&server, false);
    assert!(
        !switching_preview.contains("preview-first-line"),
        "the previous preview remained visible while switching rows:\n{switching_preview}"
    );
    let deadline = Instant::now() + Duration::from_secs(5);
    let mut second_preview = String::new();
    while Instant::now() < deadline {
        second_preview = capture_pane(&server, false);
        if second_preview.contains("preview-other-candidate") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        second_preview.contains("preview-other-candidate")
            && !second_preview.contains("preview-first-line"),
        "the second preview did not replace the first cleanly:\n{second_preview}"
    );
    Command::new("tmux")
        .args([
            "-L",
            &server,
            "resize-window",
            "-t",
            "test:0",
            "-x",
            "80",
            "-y",
            "24",
        ])
        .status()
        .unwrap();

    let ascii_shell = format!("env LC_ALL=C LANG=C {shell_environment} zsh -l");
    let status = Command::new("tmux")
        .args([
            "-L",
            &server,
            "new-window",
            "-d",
            "-t",
            "test",
            "-n",
            "ascii",
        ])
        .arg(ascii_shell)
        .status()
        .unwrap();
    assert!(
        status.success(),
        "failed to start the non-UTF-8 Zsh fixture"
    );
    wait_for_zle_target(&server, "test:ascii.0", &sync_file);
    Command::new("tmux")
        .args([
            "-L",
            &server,
            "send-keys",
            "-l",
            "-t",
            "test:ascii.0",
            "aste",
        ])
        .status()
        .unwrap();
    let deadline = Instant::now() + Duration::from_secs(4);
    let mut ascii_capture = String::new();
    while Instant::now() < deadline {
        ascii_capture = capture_target(&server, "test:ascii.0", false);
        if ascii_capture.contains("+-") && ascii_capture.contains("aster") {
            break;
        }
        thread::sleep(Duration::from_millis(50));
    }
    assert!(
        ascii_capture.contains("+-") && ascii_capture.contains("| > "),
        "ASCII fallback menu was absent:\n{ascii_capture}"
    );
    assert!(
        !ascii_capture.contains("<e2>") && !ascii_capture.contains('â•­'),
        "non-UTF-8 menu still contained Unicode rendering:\n{ascii_capture}"
    );
    assert_eq!(cursor_x(&server, "test:ascii.0"), 6);
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:ascii.0", "BSpace"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(50));
    assert_eq!(cursor_x(&server, "test:ascii.0"), 5);
    Command::new("tmux")
        .args([
            "-L",
            &server,
            "send-keys",
            "-t",
            "test:ascii.0",
            "C-x",
            "C-d",
        ])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(20));
    let ascii_state = fs::read_to_string(&state_dump).unwrap();
    let ascii_fields: Vec<_> = ascii_state.trim_end().split('|').collect();
    assert_eq!(ascii_fields[3], "ast");
    Command::new("tmux")
        .args([
            "-L",
            &server,
            "resize-window",
            "-t",
            "test:ascii",
            "-x",
            "20",
            "-y",
            "15",
        ])
        .status()
        .unwrap();
    Command::new("tmux")
        .args(["-L", &server, "send-keys", "-t", "test:ascii.0", "C-l"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(100));
    let narrow_capture = capture_target(&server, "test:ascii.0", false);
    assert!(
        narrow_capture.contains("aster") && !narrow_capture.contains("+-"),
        "narrow terminal did not retain a compact suggestion:\n{narrow_capture}"
    );
    assert_eq!(cursor_x(&server, "test:ascii.0"), 5);
}

fn dump_zle_state(server: &str) {
    Command::new("tmux")
        .args(["-L", server, "send-keys", "-t", "test:0.0", "C-x", "C-d"])
        .status()
        .unwrap();
    thread::sleep(Duration::from_millis(20));
}

fn wait_for_zle(server: &str, sync_file: &Path) {
    wait_for_zle_target(server, "test:0.0", sync_file);
}

fn wait_for_zle_target(server: &str, target: &str, sync_file: &Path) {
    let _ = fs::remove_file(sync_file);
    let deadline = Instant::now() + Duration::from_secs(4);
    while Instant::now() < deadline {
        Command::new("tmux")
            .args(["-L", server, "send-keys", "-t", target, "C-g"])
            .status()
            .unwrap();
        thread::sleep(Duration::from_millis(50));
        if sync_file.exists() {
            return;
        }
    }
    panic!(
        "ZLE did not become ready in {target}:\n{}",
        capture_target(server, target, false)
    );
}

fn capture_pane(server: &str, include_escape_sequences: bool) -> String {
    capture_target(server, "test:0.0", include_escape_sequences)
}

fn wait_for_pane(server: &str, expected: &str) {
    let deadline = Instant::now() + Duration::from_secs(4);
    let mut capture = String::new();
    while Instant::now() < deadline {
        capture = capture_pane(server, false);
        if capture.contains(expected) {
            return;
        }
        thread::sleep(Duration::from_millis(50));
    }
    panic!("pane did not contain {expected:?}:\n{capture}");
}

fn cursor_x(server: &str, target: &str) -> usize {
    let output = Command::new("tmux")
        .args([
            "-L",
            server,
            "display-message",
            "-p",
            "-t",
            target,
            "#{cursor_x}",
        ])
        .output()
        .unwrap();
    String::from_utf8(output.stdout)
        .unwrap()
        .trim()
        .parse()
        .unwrap()
}

fn capture_target(server: &str, target: &str, include_escape_sequences: bool) -> String {
    let mut command = Command::new("tmux");
    command.args(["-L", server, "capture-pane", "-p"]);
    if include_escape_sequences {
        command.arg("-e");
    }
    let output = command.args(["-t", target]).output().unwrap();
    String::from_utf8(output.stdout).unwrap()
}

fn command_exists(name: &str) -> bool {
    Command::new(name)
        .arg("-V")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .is_ok()
}

fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

struct ServerGuard {
    server: String,
    aster: std::path::PathBuf,
    config: std::path::PathBuf,
    state: std::path::PathBuf,
    socket: std::path::PathBuf,
    started: bool,
}

impl Drop for ServerGuard {
    fn drop(&mut self) {
        if self.started {
            let _ = Command::new("tmux")
                .args(["-L", &self.server, "kill-server"])
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();
        }
        let _ = Command::new(&self.aster)
            .arg("stop")
            .env("ASTER_CONFIG", &self.config)
            .env("ASTER_STATE_DIR", &self.state)
            .env("ASTER_SOCKET", &self.socket)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}