tauri-hasgard-cli 0.1.0

CLI and MCP server for Tauri Hasgard automation
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
mod cli;
mod client;
mod mcp;
mod output;
mod protocol;
mod scenario;
mod style;

use std::fmt::Write as _;

use anyhow::{Context, Result};
use base64::Engine;
use clap::Parser;
use serde_json::{Value, json};
use std::io::IsTerminal;
#[cfg(unix)]
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;

use cli::{AssertKind, Cli, Command, FormsArgs, RecordAction, StorageAction, StorageArgs, Target, parse_target};
use client::Client;

#[tokio::main]
async fn main() -> Result<()> {
    let args = Cli::parse();
    let is_mcp = matches!(args.command, Command::Mcp);
    let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn"));

    // CLI tools must keep stdout reserved for data so callers can pipe into
    // `jq`, `python -c 'json.load(...)'`, etc. without log noise corrupting the
    // payload (see #80).
    tracing_subscriber::fmt().with_env_filter(env_filter).with_writer(std::io::stderr).init();

    if is_mcp {
        return mcp::run_mcp_server(args.socket, args.window).await;
    }

    if let Command::Run { ref scenario, ref junit, no_fail_fast } = args.command {
        return run_scenario_command(scenario, junit.as_deref(), no_fail_fast, args.socket, args.window.as_deref())
            .await;
    }

    let socket = resolve_socket(args.socket)?;
    let mut client = Client::connect(&socket).await?;

    // Handle --follow mode: loop forever polling for new entries
    if let Command::Logs { follow: true, ref level, ref last, .. } = args.command {
        follow_logs(&mut client, args.json, level.as_deref(), *last, args.window.as_deref()).await?;
    } else if let Command::Network { follow: true, ref filter, ref last, failed, .. } = args.command {
        follow_network(&mut client, args.json, filter.as_deref(), *last, failed, args.window.as_deref()).await?;
    }

    let screenshot_path = if let Command::Screenshot { ref path, .. } = args.command { path.clone() } else { None };
    let is_screenshot = matches!(args.command, Command::Screenshot { .. });
    let is_ping = matches!(args.command, Command::Ping);
    // Capture output kind before command is consumed by run_command
    let output_kind = OutputKind::from(&args.command);
    let result = if is_screenshot && !args.json && std::io::stdout().is_terminal() {
        let spinner = indicatif::ProgressBar::new_spinner();
        spinner.enable_steady_tick(Duration::from_millis(80));
        spinner.set_message("Taking screenshot...");
        let res = run_command(&mut client, args.command, args.window.as_deref()).await;
        spinner.finish_and_clear();
        res?
    } else {
        run_command(&mut client, args.command, args.window.as_deref()).await?
    };

    // Screenshot save-to-file: decode base64 data URL and write PNG
    if let Some(path) = screenshot_path {
        save_screenshot(&result, &path)?;
        if args.json {
            output::format_json(&serde_json::json!({"path": path.display().to_string()}))?;
        } else {
            println!("{}", crate::style::success(&format!("Saved to {}", path.display())));
        }
        return Ok(());
    }

    // `ping` doubles as a version handshake: surface the plugin version baked
    // into the running app alongside the CLI version and warn on drift, the
    // signal that was missing when issue #135 was diagnosed. JSON output keeps
    // the raw `plugin_version` field instead.
    if is_ping && !args.json {
        report_ping(&result);
        return Ok(());
    }

    format_result(output_kind, &result, args.json)?;
    Ok(())
}

#[derive(Copy, Clone)]
enum OutputKind {
    Snapshot,
    Diff,
    Logs,
    Network,
    Watch,
    Storage,
    Forms,
    Windows,
    Record,
    Replay,
    Text,
}

impl From<&Command> for OutputKind {
    fn from(cmd: &Command) -> Self {
        match cmd {
            Command::Snapshot { .. } => OutputKind::Snapshot,
            Command::Diff { .. } => OutputKind::Diff,
            Command::Logs { .. } => OutputKind::Logs,
            Command::Network { .. } => OutputKind::Network,
            Command::Watch { .. } => OutputKind::Watch,
            Command::Storage(..) => OutputKind::Storage,
            Command::Forms(..) => OutputKind::Forms,
            Command::Windows => OutputKind::Windows,
            Command::Record { .. } => OutputKind::Record,
            Command::Replay { .. } => OutputKind::Replay,
            _ => OutputKind::Text,
        }
    }
}

fn format_result(kind: OutputKind, result: &serde_json::Value, emit_json: bool) -> Result<()> {
    if emit_json {
        return output::format_json(result);
    }
    match kind {
        OutputKind::Snapshot => output::format_snapshot(result),
        OutputKind::Diff => output::format_diff(result),
        OutputKind::Logs => {
            if result.get("cleared").is_some() {
                output::format_text(result);
            } else {
                print!("{}", output::format_logs(result));
            }
        }
        OutputKind::Network => {
            if result.get("cleared").is_some() {
                output::format_text(result);
            } else {
                print!("{}", output::format_network(result));
            }
        }
        OutputKind::Watch => output::format_watch(result),
        OutputKind::Storage => {
            if result.get("cleared").is_some() {
                output::format_text(result);
            } else if result.get("entries").is_some() {
                output::format_storage(result);
            } else if result.get("found").is_some() {
                output::format_storage_value(result);
            } else {
                output::format_text(result);
            }
        }
        OutputKind::Forms => output::format_forms(result),
        OutputKind::Windows => output::format_windows(result),
        OutputKind::Record => {
            let formatted = output::format_record(result);
            if !formatted.is_empty() {
                println!("{formatted}");
            }
        }
        OutputKind::Replay | OutputKind::Text => output::format_text(result),
    }
    Ok(())
}

/// Print the `ping` version handshake: the plugin version embedded in the
/// running app, the CLI version, and a drift warning when they disagree.
fn report_ping(result: &Value) {
    let (summary, warning) =
        diagnose_versions(env!("CARGO_PKG_VERSION"), result.get("plugin_version").and_then(Value::as_str));
    println!("{}", crate::style::success(&summary));
    if let Some(warning) = warning {
        eprintln!("{}", crate::style::warn(&warning));
    }
}

/// Build the human-facing `ping` summary line and an optional version-drift
/// warning.
///
/// Since 0.7.1 the plugin reports its own compile-time version in the ping
/// response. A response without that field comes from a plugin <= 0.7.0, which
/// predates the macOS native-eval fix (issue #135), so the CLI points the user
/// at an upgrade.
fn diagnose_versions(cli: &str, plugin: Option<&str>) -> (String, Option<String>) {
    match plugin {
        Some(p) if p == cli => (format!("Connected. Plugin and CLI both {p}."), None),
        Some(p) => (
            format!("Connected. Plugin {p}, CLI {cli}."),
            Some(format!(
                "Plugin {p} and CLI {cli} differ. Rebuild your app against \
                 tauri-plugin-hasgard {cli} (or match the CLI) so they stay in sync."
            )),
        ),
        None => (
            format!("Connected. Plugin <= 0.7.0, CLI {cli}."),
            Some(format!(
                "This plugin predates version reporting (<= 0.7.0). If eval fails \
                 on macOS, bump tauri-plugin-hasgard to >= {cli} and rebuild the app \
                 (issue #135)."
            )),
        ),
    }
}

async fn follow_logs(
    client: &mut Client, emit_json: bool, level: Option<&str>, last: Option<usize>, window: Option<&str>,
) -> Result<()> {
    let mut last_seen_id: u64 = 0;
    let mut first_poll = true;
    loop {
        let mut params = serde_json::Map::new();
        if last_seen_id > 0 {
            params.insert("sinceId".into(), json!(last_seen_id));
        }
        if let Some(l) = level {
            params.insert("level".into(), json!(l));
        }
        if first_poll && let Some(n) = last {
            params.insert("last".into(), json!(n));
            first_poll = false;
        }
        let result = client.call("console.getLogs", with_window(Some(Value::Object(params)), window)).await?;
        if let Some(entries) = result.as_array()
            && !entries.is_empty()
        {
            if emit_json {
                // Emit NDJSON: one JSON object per entry for jq compatibility
                for entry in entries {
                    println!("{entry}");
                }
            } else {
                print!("{}", output::format_logs(&result));
            }
            last_seen_id =
                entries.last().and_then(|e| e.get("id")).and_then(serde_json::Value::as_u64).unwrap_or(last_seen_id);
        }
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

async fn follow_network(
    client: &mut Client, emit_json: bool, filter: Option<&str>, last: Option<usize>, failed: bool, window: Option<&str>,
) -> Result<()> {
    let mut last_seen_id: u64 = 0;
    let mut first_poll = true;
    loop {
        let mut params = serde_json::Map::new();
        if last_seen_id > 0 {
            params.insert("sinceId".into(), json!(last_seen_id));
        }
        if let Some(f) = filter {
            params.insert("filter".into(), json!(f));
        }
        if failed {
            params.insert("failedOnly".into(), json!(true));
        }
        if first_poll && let Some(n) = last {
            params.insert("last".into(), json!(n));
            first_poll = false;
        }
        let result = client.call("network.getRequests", with_window(Some(Value::Object(params)), window)).await?;
        if let Some(entries) = result.as_array()
            && !entries.is_empty()
        {
            if emit_json {
                for entry in entries {
                    println!("{entry}");
                }
            } else {
                print!("{}", output::format_network(&result));
            }
            last_seen_id =
                entries.last().and_then(|e| e.get("id")).and_then(serde_json::Value::as_u64).unwrap_or(last_seen_id);
        }
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

pub(crate) fn with_window(params: Option<Value>, window: Option<&str>) -> Option<Value> {
    match (params, window) {
        (Some(Value::Object(mut map)), Some(w)) => {
            map.insert("window".to_string(), json!(w));
            Some(Value::Object(map))
        }
        (None, Some(w)) => Some(json!({"window": w})),
        (params, _) => params,
    }
}

async fn run_command(client: &mut Client, command: Command, window: Option<&str>) -> Result<serde_json::Value> {
    match command {
        Command::Mcp => anyhow::bail!("mcp must be handled before run_command"),
        Command::Run { .. } => anyhow::bail!("run must be handled before run_command"),
        Command::Windows => client.call("windows.list", None).await,
        Command::Ping => client.call("ping", with_window(None, window)).await,
        Command::State => client.call("state", with_window(None, window)).await,
        Command::Snapshot { interactive, selector, depth, save } => {
            run_snapshot_command(client, interactive, selector, depth, save, window).await
        }
        Command::Diff { r#ref: ref_path, interactive, selector, depth } => {
            run_diff_command(client, ref_path, interactive, selector, depth, window).await
        }
        Command::Ipc { command, args } => run_ipc_command(client, &command, args.as_deref(), window).await,
        Command::Screenshot { path, selector } => {
            client.call("screenshot", with_window(Some(json!({"path": path, "selector": selector})), window)).await
        }
        Command::ScreenshotNative { window_id, output, format } => {
            client
                .call(
                    "screenshot_native",
                    with_window(
                        Some(json!({
                            "window_id": window_id,
                            "output_path": output.display().to_string(),
                            "format": format,
                        })),
                        window,
                    ),
                )
                .await
        }
        Command::Navigate { url } => client.call("navigate", with_window(Some(json!({"url": url})), window)).await,
        Command::Url => client.call("url", with_window(None, window)).await,
        Command::Title => client.call("title", with_window(None, window)).await,
        Command::Wait { target, selector, gone, timeout } => {
            let params = build_wait_params(target.as_deref(), selector.as_deref(), gone, timeout);
            client.call("wait", with_window(Some(params), window)).await
        }
        Command::Watch { selector, timeout, stable, require_mutation } => {
            run_watch_command(client, selector, timeout, stable, require_mutation, window).await
        }
        Command::Logs { level, last, clear, follow } => {
            run_logs_command(client, level, last, clear, follow, window).await
        }
        Command::Network { filter, failed, last, clear, follow } => {
            run_network_command(client, filter, failed, last, clear, follow, window).await
        }
        Command::Assert(kind) => run_assert_command(client, kind, window).await,
        Command::Storage(storage_args) => run_storage_command(client, storage_args, window).await,
        Command::Forms(args) => run_forms_command(client, args, window).await,
        Command::Drop { target, file } => run_drop_command(client, &target, file, window).await,
        Command::Record { action } => run_record_command(client, action, window).await,
        Command::Replay { path, export } => run_replay_command(client, &path, export.as_deref(), window).await,
        cmd => run_dom_command(client, cmd, window).await,
    }
}

async fn run_snapshot_command(
    client: &mut Client, interactive: bool, selector: Option<String>, depth: Option<u8>,
    save: Option<std::path::PathBuf>, window: Option<&str>,
) -> Result<serde_json::Value> {
    tracing::info!(
        interactive,
        selector = selector.as_deref(),
        depth,
        save = save.as_ref().map(|p| p.display().to_string()),
        "running snapshot"
    );
    let params = with_window(
        Some(json!({
            "interactive": interactive,
            "selector": selector,
            "depth": depth,
        })),
        window,
    );
    let mut result = client.call("snapshot", params).await?;
    if let Some(ref path) = save {
        // The on-disk file holds the unmodified RPC payload; the `"path"` key
        // below is added to the in-memory result *after* the write so consumers
        // who later re-load the file still see the original `{"elements": …}`
        // shape that `diff --ref` and the plugin expect.
        let json = serde_json::to_string_pretty(&result)?;
        std::fs::write(path, &json).with_context(|| format!("Failed to save snapshot to {}", path.display()))?;
        // Embed the saved path in the JSON result so `--json` consumers can
        // recover it without parsing stderr (matches `record stop --output`
        // and `screenshot` conventions; see #80).
        if let serde_json::Value::Object(ref mut obj) = result {
            obj.insert("path".into(), json!(path.display().to_string()));
        } else {
            tracing::warn!("snapshot RPC returned a non-object result; skipping `path` injection");
        }
        eprintln!("Snapshot saved to {}", path.display());
    }
    Ok(result)
}

async fn run_watch_command(
    client: &mut Client, selector: Option<String>, timeout: u64, stable: u64, require_mutation: bool,
    window: Option<&str>,
) -> Result<serde_json::Value> {
    let mut params = serde_json::Map::new();
    params.insert("timeout".into(), json!(timeout));
    params.insert("stable".into(), json!(stable));
    if require_mutation {
        params.insert("requireMutation".into(), json!(true));
    }
    if let Some(sel) = selector {
        params.insert("selector".into(), json!(sel));
    }
    client.call("watch", with_window(Some(serde_json::Value::Object(params)), window)).await
}

async fn run_diff_command(
    client: &mut Client, ref_path: Option<std::path::PathBuf>, interactive: bool, selector: Option<String>,
    depth: Option<u8>, window: Option<&str>,
) -> Result<serde_json::Value> {
    let mut params = json!({
        "interactive": interactive,
        "selector": selector,
        "depth": depth,
    });
    if let Some(path) = ref_path {
        let meta =
            std::fs::metadata(&path).with_context(|| format!("Failed to stat snapshot file: {}", path.display()))?;
        anyhow::ensure!(meta.len() < 50 * 1024 * 1024, "Snapshot file too large (>50 MB): {}", path.display());
        let content = std::fs::read_to_string(&path)
            .with_context(|| format!("Failed to read snapshot file: {}", path.display()))?;
        let reference: serde_json::Value = serde_json::from_str(&content).context("Invalid snapshot file format")?;
        anyhow::ensure!(
            reference.get("elements").is_some(),
            "Snapshot file missing \"elements\" key — not a valid snapshot"
        );
        params["reference"] = reference;
    }
    client.call("diff", with_window(Some(params), window)).await
}

fn read_script(reader: &mut impl std::io::Read) -> Result<String> {
    let mut s = String::new();
    reader.read_to_string(&mut s).context("reading script from stdin")?;
    anyhow::ensure!(!s.trim().is_empty(), "script read from stdin is empty or blank");
    Ok(s)
}

async fn handle_eval(client: &mut Client, script: Option<String>, window: Option<&str>) -> Result<Value> {
    let script = match script.as_deref() {
        None | Some("-") => {
            anyhow::ensure!(
                !std::io::stdin().is_terminal(),
                "stdin is a terminal: pass a script as argument or pipe it in"
            );
            read_script(&mut std::io::stdin())?
        }
        Some(s) => s.to_owned(),
    };
    client.call("eval", with_window(Some(json!({"script": script})), window)).await
}

async fn run_dom_command(client: &mut Client, command: Command, window: Option<&str>) -> Result<serde_json::Value> {
    match command {
        Command::Click { target } => client.call("click", with_window(Some(target_params(&target)), window)).await,
        Command::Fill { target, value } => {
            let mut p = target_params(&target);
            p["value"] = json!(value);
            client.call("fill", with_window(Some(p), window)).await
        }
        Command::Type { target, text } => {
            let mut p = target_params(&target);
            p["text"] = json!(text);
            client.call("type", with_window(Some(p), window)).await
        }
        Command::Press { key } => client.call("press", with_window(Some(json!({"key": key})), window)).await,
        Command::Select { target, value } => {
            let mut p = target_params(&target);
            p["value"] = json!(value);
            client.call("select", with_window(Some(p), window)).await
        }
        Command::Check { target } => client.call("check", with_window(Some(target_params(&target)), window)).await,
        Command::Scroll { direction, amount, r#ref } => {
            client
                .call(
                    "scroll",
                    with_window(Some(json!({"direction": direction, "amount": amount, "ref": r#ref})), window),
                )
                .await
        }
        Command::Text { target } => client.call("text", with_window(Some(target_params(&target)), window)).await,
        Command::Html { target } => {
            let params = target.map(|t| target_params(&t));
            client.call("html", with_window(params, window)).await
        }
        Command::Value { target } => client.call("value", with_window(Some(target_params(&target)), window)).await,
        Command::Attrs { target } => client.call("attrs", with_window(Some(target_params(&target)), window)).await,
        Command::Eval { script } => handle_eval(client, script, window).await,
        Command::Drag { source, target, offset } => {
            let mut p = json!({"source": target_params(&source)});
            if let Some(t) = target {
                p["target"] = target_params(&t);
            } else if let Some(off) = offset {
                let parts: Vec<&str> = off.split(',').collect();
                anyhow::ensure!(parts.len() == 2, "offset must be X,Y (e.g., '0,100')");
                let x: f64 = parts[0].trim().parse().context("invalid offset X value")?;
                let y: f64 = parts[1].trim().parse().context("invalid offset Y value")?;
                p["offset"] = json!({"x": x, "y": y});
            } else {
                anyhow::bail!("drag requires either a target element or --offset");
            }
            client.call("drag", with_window(Some(p), window)).await
        }
        _ => anyhow::bail!("unexpected command in run_dom_command"),
    }
}

/// Extract a string from a JSON value, bailing if not a string.
fn require_str(val: &serde_json::Value) -> Result<&str> {
    val.as_str().ok_or_else(|| anyhow::anyhow!("expected string response from server"))
}

/// Extract a bool field from a JSON object, bailing if missing.
fn require_bool_field(val: &serde_json::Value, field: &str) -> Result<bool> {
    val.get(field)
        .and_then(serde_json::Value::as_bool)
        .ok_or_else(|| anyhow::anyhow!("missing '{field}' field in server response"))
}

/// Print assertion failure and exit with code 1.
fn assert_fail(msg: &str) -> ! {
    output::format_assert_fail(msg);
    std::process::exit(1)
}

async fn run_assert_command(client: &mut Client, kind: AssertKind, window: Option<&str>) -> Result<serde_json::Value> {
    match kind {
        AssertKind::Text { target, expected } => {
            let result = client.call("text", with_window(Some(target_params(&target)), window)).await?;
            let actual = require_str(&result)?;
            if actual != expected {
                assert_fail(&format!("expected text \"{expected}\", got \"{actual}\""));
            }
        }
        AssertKind::Visible { target } => {
            let visible = require_bool_field(
                &client.call("visible", with_window(Some(target_params(&target)), window)).await?,
                "visible",
            )?;
            if !visible {
                assert_fail("element is not visible");
            }
        }
        AssertKind::Hidden { target } => {
            let visible = require_bool_field(
                &client.call("visible", with_window(Some(target_params(&target)), window)).await?,
                "visible",
            )?;
            if visible {
                assert_fail("element is visible");
            }
        }
        AssertKind::Value { target, expected } => {
            let result = client.call("value", with_window(Some(target_params(&target)), window)).await?;
            let actual = require_str(&result)?;
            if actual != expected {
                assert_fail(&format!("expected value \"{expected}\", got \"{actual}\""));
            }
        }
        AssertKind::Count { selector, expected } => {
            let result = client.call("count", with_window(Some(json!({"selector": selector})), window)).await?;
            let actual = result
                .get("count")
                .and_then(serde_json::Value::as_u64)
                .ok_or_else(|| anyhow::anyhow!("missing 'count' field in server response"))?;
            if actual != expected {
                assert_fail(&format!("expected {expected} elements, found {actual}"));
            }
        }
        AssertKind::Checked { target } => {
            let checked = require_bool_field(
                &client.call("checked", with_window(Some(target_params(&target)), window)).await?,
                "checked",
            )?;
            if !checked {
                assert_fail("element is not checked");
            }
        }
        AssertKind::Contains { target, expected } => {
            let result = client.call("text", with_window(Some(target_params(&target)), window)).await?;
            let actual = require_str(&result)?;
            if !actual.contains(&expected) {
                assert_fail(&format!("text does not contain \"{expected}\", got \"{actual}\""));
            }
        }
        AssertKind::Url { expected } => {
            let result = client.call("url", with_window(None, window)).await?;
            let actual = require_str(&result)?;
            if !actual.contains(&expected) {
                assert_fail(&format!("URL does not contain \"{expected}\", got \"{actual}\""));
            }
        }
    }
    Ok(json!({"ok": true}))
}

async fn run_ipc_command(
    client: &mut Client, command: &str, args: Option<&str>, window: Option<&str>,
) -> Result<serde_json::Value> {
    let parsed_args: Option<serde_json::Value> = args.map(serde_json::from_str).transpose()?;
    client.call("ipc", with_window(Some(json!({"command": command, "args": parsed_args})), window)).await
}

async fn run_logs_command(
    client: &mut Client, level: Option<String>, last: Option<usize>, clear: bool, follow: bool, window: Option<&str>,
) -> Result<serde_json::Value> {
    if follow {
        anyhow::bail!("follow mode must be handled before run_command");
    }
    if clear {
        return client.call("console.clear", with_window(None, window)).await;
    }
    let mut params = serde_json::Map::new();
    if let Some(l) = level {
        params.insert("level".into(), json!(l));
    }
    if let Some(n) = last {
        params.insert("last".into(), json!(n));
    }
    client.call("console.getLogs", with_window(Some(serde_json::Value::Object(params)), window)).await
}

async fn run_network_command(
    client: &mut Client, filter: Option<String>, failed: bool, last: Option<usize>, clear: bool, follow: bool,
    window: Option<&str>,
) -> Result<serde_json::Value> {
    if follow {
        anyhow::bail!("follow mode must be handled before run_command");
    }
    if clear {
        return client.call("network.clear", with_window(None, window)).await;
    }
    let mut params = serde_json::Map::new();
    if let Some(f) = filter {
        params.insert("filter".into(), json!(f));
    }
    if failed {
        params.insert("failedOnly".into(), json!(true));
    }
    if let Some(n) = last {
        params.insert("last".into(), json!(n));
    }
    client.call("network.getRequests", with_window(Some(serde_json::Value::Object(params)), window)).await
}

async fn run_forms_command(client: &mut Client, args: FormsArgs, window: Option<&str>) -> Result<serde_json::Value> {
    let params = args.selector.map(|s| json!({"selector": s}));
    client.call("forms.dump", with_window(params, window)).await
}

async fn run_storage_command(
    client: &mut Client, args: StorageArgs, window: Option<&str>,
) -> Result<serde_json::Value> {
    let session = args.session;
    match args.action {
        StorageAction::Get { key } => {
            client.call("storage.get", with_window(Some(json!({"key": key, "session": session})), window)).await
        }
        StorageAction::Set { key, value } => {
            client
                .call("storage.set", with_window(Some(json!({"key": key, "value": value, "session": session})), window))
                .await
        }
        StorageAction::List => {
            client.call("storage.list", with_window(Some(json!({"session": session})), window)).await
        }
        StorageAction::Clear => {
            client.call("storage.clear", with_window(Some(json!({"session": session})), window)).await
        }
    }
}

const MAX_DROP_FILE_SIZE: u64 = 50 * 1024 * 1024; // 50 MB per file
const MAX_TOTAL_DROP_SIZE: usize = 100 * 1024 * 1024; // 100 MB total base64 payload

pub(crate) async fn run_drop_command(
    client: &mut Client, target: &str, file: Vec<std::path::PathBuf>, window: Option<&str>,
) -> Result<serde_json::Value> {
    let mut p = target_params(target);
    let mut files = Vec::new();
    let mut total_encoded = 0usize;
    for path in &file {
        let meta = std::fs::metadata(path).with_context(|| format!("Failed to stat file: {}", path.display()))?;
        anyhow::ensure!(meta.is_file(), "Not a regular file: {}", path.display());
        anyhow::ensure!(meta.len() <= MAX_DROP_FILE_SIZE, "File too large (>50 MB): {}", path.display());
        let data = std::fs::read(path).with_context(|| format!("Failed to read file: {}", path.display()))?;
        let encoded = base64::engine::general_purpose::STANDARD.encode(&data);
        total_encoded += encoded.len();
        anyhow::ensure!(total_encoded <= MAX_TOTAL_DROP_SIZE, "Total drop payload exceeds 100 MB limit");
        let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
        let mime = mime_from_ext(path);
        files.push(json!({"name": name, "type": mime, "data": encoded}));
    }
    p["files"] = json!(files);
    client.call("drop", with_window(Some(p), window)).await
}

pub(crate) fn target_params(raw: &str) -> serde_json::Value {
    match parse_target(raw) {
        Target::Ref(r) => json!({"ref": r}),
        Target::Selector(s) => json!({"selector": s}),
        Target::Coords(x, y) => json!({"x": x, "y": y}),
    }
}

/// Build params for the `wait` RPC call.
///
/// Routing precedence:
/// - `--selector` flag wins over positional target.
/// - Positional target is parsed via [`parse_target`] (`@x` ref, else selector).
///   Coords are not meaningful for `wait`, so they pass through as a selector
///   so the bridge surfaces a `SyntaxError` from `document.querySelector`
///   instead of silently timing out.
/// - With neither target nor selector, only `gone`/`timeout` are sent and the
///   bridge `waitFor` rejects up-front (issue #74).
pub(crate) fn build_wait_params(
    target: Option<&str>, selector: Option<&str>, gone: bool, timeout: u64,
) -> serde_json::Value {
    match (selector, target) {
        (Some(s), _) => json!({ "selector": s, "gone": gone, "timeout": timeout }),
        (None, Some(t)) => match parse_target(t) {
            // `@` alone strips to an empty ref. Drop it so the bridge's
            // `waitFor` rejects up-front instead of hanging on a
            // `MutationObserver` until the timeout fires.
            Target::Ref(r) if r.is_empty() => json!({ "gone": gone, "timeout": timeout }),
            Target::Ref(r) => json!({ "ref": r, "gone": gone, "timeout": timeout }),
            Target::Selector(s) => json!({ "selector": s, "gone": gone, "timeout": timeout }),
            Target::Coords(..) => json!({ "selector": t, "gone": gone, "timeout": timeout }),
        },
        (None, None) => json!({ "gone": gone, "timeout": timeout }),
    }
}

fn mime_from_ext(path: &std::path::Path) -> &'static str {
    let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase);
    match ext.as_deref() {
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("svg") => "image/svg+xml",
        Some("webp") => "image/webp",
        Some("pdf") => "application/pdf",
        Some("json") => "application/json",
        Some("txt") => "text/plain",
        Some("html" | "htm") => "text/html",
        Some("css") => "text/css",
        Some("js") => "application/javascript",
        Some("csv") => "text/csv",
        Some("xml") => "application/xml",
        Some("zip") => "application/zip",
        _ => "application/octet-stream",
    }
}

/// Decode a base64 data URL and write the PNG file.
fn save_screenshot(result: &serde_json::Value, path: &std::path::Path) -> Result<()> {
    let data_url = result.as_str().ok_or_else(|| anyhow::anyhow!("Screenshot result is not a string"))?;

    let base64_data = data_url.strip_prefix("data:image/png;base64,").unwrap_or(data_url);

    let bytes = base64::engine::general_purpose::STANDARD
        .decode(base64_data)
        .map_err(|e| anyhow::anyhow!("Failed to decode base64: {e}"))?;

    std::fs::write(path, bytes)?;
    Ok(())
}

async fn run_record_command(client: &mut Client, action: RecordAction, window: Option<&str>) -> Result<Value> {
    match action {
        RecordAction::Start => client.call("record.start", with_window(None, window)).await,
        RecordAction::Stop { output } => {
            let result = client.call("record.stop", with_window(None, window)).await?;
            let entries = result
                .get("entries")
                .and_then(|e| e.as_array())
                .ok_or_else(|| anyhow::anyhow!("no entries in response"))?;
            let json = serde_json::to_string_pretty(entries)?;
            std::fs::write(&output, &json)
                .with_context(|| format!("Failed to write recording to {}", output.display()))?;
            Ok(serde_json::json!({
                "status": "saved",
                "path": output.display().to_string(),
                "count": entries.len()
            }))
        }
        RecordAction::Status => client.call("record.status", with_window(None, window)).await,
    }
}

pub(crate) async fn run_replay_command(
    client: &mut Client, path: &std::path::Path, export: Option<&str>, window: Option<&str>,
) -> Result<Value> {
    let entries = read_replay_entries(path)?;

    if let Some(fmt) = export {
        return export_replay_command(&entries, fmt);
    }

    let total = entries.len();
    let mut prev_ts: u64 = 0;
    let mut passed = 0;
    let mut skipped = 0;

    for (i, entry) in entries.iter().enumerate() {
        let action = entry.get("action").and_then(|a| a.as_str()).unwrap_or("unknown");
        let timestamp = entry.get("timestamp").and_then(serde_json::Value::as_u64).unwrap_or(0);

        let delta = timestamp.saturating_sub(prev_ts);
        if delta > 0 && i > 0 {
            tokio::time::sleep(std::time::Duration::from_millis(delta)).await;
        }
        prev_ts = timestamp;

        if !is_replayable(action) {
            skipped += 1;
            eprintln!("{}", crate::output::format_replay_step(i + 1, total, action, "SKIP"));
            continue;
        }

        let mut params = serde_json::Map::new();
        if let Some(obj) = entry.as_object() {
            for (k, v) in obj {
                if k != "action" && k != "timestamp" {
                    params.insert(k.clone(), v.clone());
                }
            }
        }

        if let Some(w) = window {
            params.insert("window".to_string(), Value::String(w.to_string()));
        }

        let result = client.call(action, Some(Value::Object(params))).await;

        let status = if result.is_ok() {
            passed += 1;
            "ok"
        } else {
            "FAIL"
        };
        eprintln!("{}", crate::output::format_replay_step(i + 1, total, action, status));
    }

    let executed = total - skipped;
    let status = if passed == executed { "ok" } else { "failed" };
    Ok(serde_json::json!({
        "status": status,
        "total": total,
        "passed": passed,
        "skipped": skipped,
        "failed": executed - passed
    }))
}

fn read_replay_entries(path: &std::path::Path) -> Result<Vec<serde_json::Value>> {
    let content =
        std::fs::read_to_string(path).with_context(|| format!("Failed to read recording file: {}", path.display()))?;
    serde_json::from_str(&content).context("Invalid recording file format")
}

pub(crate) fn export_replay_file(path: &std::path::Path, export: &str) -> Result<Value> {
    let entries = read_replay_entries(path)?;
    export_replay_command(&entries, export)
}

fn export_replay_command(entries: &[Value], export: &str) -> Result<Value> {
    if export == "sh" {
        return Ok(Value::String(export_shell_script(entries)));
    }
    anyhow::bail!("unsupported export format: {export}; supported: sh")
}

fn export_shell_script(entries: &[Value]) -> String {
    let mut script = String::from("#!/bin/bash\n# Generated by tauri-hasgard record/replay\n\n");
    let mut prev_ts: u64 = 0;

    for (i, entry) in entries.iter().enumerate() {
        let action = entry.get("action").and_then(|a| a.as_str()).unwrap_or("unknown");
        let timestamp = entry.get("timestamp").and_then(serde_json::Value::as_u64).unwrap_or(0);

        let delta = timestamp.saturating_sub(prev_ts);
        if delta > 0 && i > 0 {
            let secs = std::time::Duration::from_millis(delta).as_secs_f64();
            let _ = writeln!(script, "sleep {secs:.1}");
        }
        prev_ts = timestamp;

        script.push_str(&entry_to_cli_command(action, entry));
        script.push('\n');
    }

    script
}

/// Wrap a string in single quotes with proper escaping for shell safety.
fn shell_escape(s: &str) -> String {
    let mut escaped = String::with_capacity(s.len() + 2);
    escaped.push('\'');
    for c in s.chars() {
        if c == '\'' {
            escaped.push_str("'\\''");
        } else {
            escaped.push(c);
        }
    }
    escaped.push('\'');
    escaped
}

/// Build a shell-safe CLI target for element refs (e.g. `@e1`).
fn shell_escape_ref_target(ref_id: &str) -> String {
    shell_escape(&format!("@{ref_id}"))
}

/// Returns `true` for actions that are safe to replay.
fn is_replayable(action: &str) -> bool {
    matches!(
        action,
        "click"
            | "fill"
            | "type"
            | "press"
            | "select"
            | "check"
            | "scroll"
            | "drag"
            | "drop"
            | "navigate"
            | "snapshot"
            | "wait"
            | "eval"
    )
}

/// Extract a CLI target string from a nested source/target object.
/// Handles `{"ref": "e3"}`, `{"selector": ".foo"}`, and `{"x": N, "y": N}`.
fn resolve_export_target(val: Option<&Value>) -> Option<String> {
    let obj = val?;
    if let Some(r) = obj.get("ref").and_then(|r| r.as_str()) {
        return Some(shell_escape_ref_target(r));
    }
    if let Some(s) = obj.get("selector").and_then(|s| s.as_str()) {
        return Some(shell_escape(s));
    }
    if let (Some(x), Some(y)) =
        (obj.get("x").and_then(serde_json::Value::as_i64), obj.get("y").and_then(serde_json::Value::as_i64))
    {
        return Some(format!("{x},{y}"));
    }
    None
}

fn entry_to_cli_command(action: &str, entry: &Value) -> String {
    let ref_id = entry.get("ref").and_then(|r| r.as_str());
    let selector = entry.get("selector").and_then(|s| s.as_str());
    let target = if let Some(r) = ref_id {
        shell_escape_ref_target(r)
    } else if let Some(s) = selector {
        shell_escape(s)
    } else {
        String::new()
    };

    match action {
        "click" => format!("tauri-hasgard click {target}"),
        "fill" => {
            let value = entry.get("value").and_then(|v| v.as_str()).unwrap_or("");
            format!("tauri-hasgard fill {target} {}", shell_escape(value))
        }
        "type" => {
            let text = entry.get("text").and_then(|v| v.as_str()).unwrap_or("");
            format!("tauri-hasgard type {target} {}", shell_escape(text))
        }
        "press" => {
            let key = entry.get("key").and_then(|k| k.as_str()).unwrap_or("");
            format!("tauri-hasgard press {}", shell_escape(key))
        }
        "select" => {
            let value = entry.get("value").and_then(|v| v.as_str()).unwrap_or("");
            format!("tauri-hasgard select {target} {}", shell_escape(value))
        }
        "check" => format!("tauri-hasgard check {target}"),
        "scroll" => {
            let dir = entry.get("direction").and_then(|d| d.as_str()).unwrap_or("down");
            let mut cmd = format!("tauri-hasgard scroll {}", shell_escape(dir));
            if let Some(amt) = entry.get("amount").and_then(serde_json::Value::as_i64) {
                let _ = write!(cmd, " {amt}");
            }
            if let Some(r) = entry.get("ref").and_then(|r| r.as_str()) {
                let _ = write!(cmd, " --ref {}", shell_escape_ref_target(r));
            }
            cmd
        }
        "drag" => {
            let src = resolve_export_target(entry.get("source"));
            let dst = resolve_export_target(entry.get("target"));
            // Offsets may be stored as floats (browser getBoundingClientRect
            // returns fractional pixels). The CLI --offset parser accepts
            // f64 values, so pass them through without truncation.
            let offset = entry.get("offset").and_then(|o| {
                let x = o.get("x").and_then(serde_json::Value::as_f64)?;
                let y = o.get("y").and_then(serde_json::Value::as_f64)?;
                Some(format!("{x},{y}"))
            });
            match (src, dst, offset) {
                (Some(s), Some(d), _) => format!("tauri-hasgard drag {s} {d}"),
                (Some(s), None, Some(off)) => format!("tauri-hasgard drag {s} --offset {off}"),
                (Some(s), None, None) => format!("tauri-hasgard drag {s}"),
                _ => "# drag: missing source ref/selector".to_string(),
            }
        }
        "drop" => {
            // drop requires --file with file data; cannot be fully exported
            // as a shell command since recordings store base64 file contents.
            format!("# drop {target} (requires --file; not exportable)")
        }
        "navigate" => {
            let url = entry.get("url").and_then(|u| u.as_str()).unwrap_or("");
            format!("tauri-hasgard navigate {}", shell_escape(url))
        }
        _ => {
            let safe = action.replace(['\n', '\r'], " ");
            format!("# unknown action: {safe}")
        }
    }
}

async fn run_scenario_command(
    scenario_path: &std::path::Path, junit: Option<&std::path::Path>, no_fail_fast: bool,
    explicit_socket: Option<PathBuf>, window: Option<&str>,
) -> Result<()> {
    let loaded = scenario::load_scenario(scenario_path)?;

    // Socket resolution: CLI flag > TOML [connect].socket > auto-detect
    let socket = explicit_socket
        .or_else(|| loaded.connect.as_ref().and_then(|c| c.socket.clone()))
        .map_or_else(|| resolve_socket(None), Ok)?;

    let connect_timeout = loaded.connect.as_ref().and_then(|c| c.timeout_ms).map(std::time::Duration::from_millis);
    let mut client = match connect_timeout {
        Some(t) => tokio::time::timeout(t, Client::connect(&socket))
            .await
            .map_err(|_| anyhow::anyhow!("connection timed out after {}ms", t.as_millis()))??,
        None => Client::connect(&socket).await?,
    };

    let fail_fast_override = if no_fail_fast { Some(false) } else { None };
    let global_ms = loaded.scenario.global_timeout_ms;
    let report = match global_ms {
        Some(ms) => {
            let t = std::time::Duration::from_millis(ms);
            tokio::time::timeout(t, scenario::run_scenario(&mut client, &loaded, window, fail_fast_override))
                .await
                .map_err(|_| anyhow::anyhow!("scenario exceeded global timeout of {ms}ms"))??
        }
        None => scenario::run_scenario(&mut client, &loaded, window, fail_fast_override).await?,
    };

    scenario::print_report(&report);

    if let Some(xml_path) = junit {
        scenario::write_junit_xml(&report, xml_path)?;
        eprintln!("JUnit XML written to {}", xml_path.display());
    }

    if !report.all_passed() {
        std::process::exit(1);
    }
    Ok(())
}

/// Resolve the socket path from explicit arg, env var, or auto-detection.
pub(crate) fn resolve_socket(explicit: Option<PathBuf>) -> Result<PathBuf> {
    if let Some(path) = explicit {
        return Ok(path);
    }

    #[cfg(unix)]
    {
        if let Some(xdg) = std::env::var_os("XDG_RUNTIME_DIR").filter(|v| !v.is_empty()) {
            let xdg = PathBuf::from(xdg);
            if let Some(socket) = newest_socket_in_dir(&xdg) {
                return Ok(socket);
            }
        }

        newest_socket_in_dir(Path::new("/tmp"))
            .ok_or_else(|| anyhow::anyhow!("No tauri-hasgard socket found. Is a Tauri app running?"))
    }

    #[cfg(windows)]
    {
        resolve_socket_windows()
    }
}

#[cfg(windows)]
fn resolve_socket_windows() -> Result<PathBuf> {
    use windows::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
    use windows::Win32::System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION};

    fn is_pid_alive(pid: u32) -> bool {
        let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) };
        match handle {
            Ok(h) => {
                let alive = unsafe {
                    let mut exit_code: u32 = 0;
                    GetExitCodeProcess(h, &raw mut exit_code).is_ok() && exit_code == STILL_ACTIVE.0 as u32
                };
                unsafe {
                    let _ = CloseHandle(h);
                }
                alive
            }
            Err(_) => false,
        }
    }

    #[derive(serde::Deserialize)]
    struct InstanceEntry {
        pid: u32,
        pipe: String,
        created_at: u64,
    }

    let local_app_data = std::env::var_os("LOCALAPPDATA").filter(|v| !v.is_empty()).ok_or_else(|| {
        anyhow::anyhow!(
            "LOCALAPPDATA environment variable is not set or empty. \
                 Is a Tauri app running?"
        )
    })?;

    let instances_dir = PathBuf::from(local_app_data).join("tauri-hasgard").join("instances");

    if !instances_dir.exists() {
        anyhow::bail!(
            "No tauri-hasgard instances directory found at {}. \
             Is a Tauri app running?",
            instances_dir.display()
        );
    }

    let mut newest: Option<(u64, PathBuf)> = None;
    for entry in std::fs::read_dir(&instances_dir)?.filter_map(Result::ok) {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "skipping corrupted instance file");
                continue;
            }
        };
        let info: InstanceEntry = match serde_json::from_str(&content) {
            Ok(i) => i,
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "skipping malformed instance file");
                continue;
            }
        };
        if !is_pid_alive(info.pid) {
            tracing::debug!(pid = info.pid, path = %path.display(), "skipping stale instance");
            continue;
        }
        let should_update = match newest {
            None => true,
            Some((current_max, _)) => info.created_at > current_max,
        };
        if should_update {
            newest = Some((info.created_at, PathBuf::from(info.pipe)));
        }
    }

    newest
        .map(|(_, pipe)| pipe)
        .ok_or_else(|| anyhow::anyhow!("No active tauri-hasgard instance found. Is a Tauri app running?"))
}

#[cfg(not(windows))]
fn newest_socket_in_dir(dir: &Path) -> Option<PathBuf> {
    let mut candidates: Vec<PathBuf> = std::fs::read_dir(dir)
        .ok()?
        .filter_map(Result::ok)
        .map(|e| e.path())
        .filter(|p| {
            p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
                n.starts_with("tauri-hasgard-")
                    && std::path::Path::new(n).extension().is_some_and(|ext| ext.eq_ignore_ascii_case("sock"))
            })
        })
        .filter(|p| {
            use std::os::unix::fs::MetadataExt;
            // SAFETY: getuid() has no preconditions.
            let my_uid = unsafe { libc::getuid() };
            std::fs::metadata(p).is_ok_and(|m| m.uid() == my_uid)
        })
        .collect();

    candidates
        .sort_by_key(|p| std::fs::metadata(p).and_then(|m| m.modified()).unwrap_or(std::time::SystemTime::UNIX_EPOCH));

    candidates.pop()
}

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

    #[test]
    fn test_diagnose_versions_match_has_no_warning() {
        let (line, warning) = diagnose_versions("0.7.1", Some("0.7.1"));
        assert!(line.contains("0.7.1"));
        assert!(warning.is_none());
    }

    #[test]
    fn test_diagnose_versions_mismatch_warns() {
        let (line, warning) = diagnose_versions("0.7.1", Some("0.7.0"));
        assert!(line.contains("0.7.0"));
        assert!(line.contains("0.7.1"));
        let warning = warning.expect("a version mismatch must warn");
        assert!(warning.contains("0.7.0"));
        assert!(warning.contains("0.7.1"));
    }

    #[test]
    fn test_diagnose_versions_absent_plugin_warns_pre_introspection() {
        let (line, warning) = diagnose_versions("0.7.1", None);
        assert!(line.contains("0.7.1"));
        let warning = warning.expect("an absent plugin version must warn");
        assert!(warning.contains("135"));
    }

    #[test]
    fn test_mime_from_ext_png() {
        assert_eq!(mime_from_ext(std::path::Path::new("photo.png")), "image/png");
    }

    #[test]
    fn test_mime_from_ext_jpeg_variants() {
        assert_eq!(mime_from_ext(std::path::Path::new("a.jpg")), "image/jpeg");
        assert_eq!(mime_from_ext(std::path::Path::new("b.jpeg")), "image/jpeg");
    }

    #[test]
    fn test_mime_from_ext_unknown_defaults_to_octet_stream() {
        assert_eq!(mime_from_ext(std::path::Path::new("data.bin")), "application/octet-stream");
    }

    #[test]
    fn test_mime_from_ext_no_extension() {
        assert_eq!(mime_from_ext(std::path::Path::new("Makefile")), "application/octet-stream");
    }

    #[test]
    fn test_mime_from_ext_case_insensitive() {
        assert_eq!(mime_from_ext(std::path::Path::new("PHOTO.PNG")), "image/png");
        assert_eq!(mime_from_ext(std::path::Path::new("file.PnG")), "image/png");
        assert_eq!(mime_from_ext(std::path::Path::new("doc.PDF")), "application/pdf");
    }

    #[test]
    fn test_with_window_no_window_returns_params_unchanged() {
        let params = Some(json!({"selector": "#btn"}));
        let result = with_window(params.clone(), None);
        assert_eq!(result, params);
    }

    #[test]
    fn test_with_window_none_params_none_window_returns_none() {
        let result = with_window(None, None);
        assert_eq!(result, None);
    }

    #[test]
    fn test_with_window_injects_into_existing_object() {
        let params = Some(json!({"selector": "#btn"}));
        let result = with_window(params, Some("settings"));
        assert_eq!(result, Some(json!({"selector": "#btn", "window": "settings"})));
    }

    #[test]
    fn test_with_window_none_params_creates_object() {
        let result = with_window(None, Some("main"));
        assert_eq!(result, Some(json!({"window": "main"})));
    }

    #[test]
    #[cfg(unix)]
    #[serial]
    fn test_resolve_socket_finds_socket_in_xdg_runtime_dir() {
        let dir = std::env::temp_dir().join(format!("tauri-hasgard-xdg-cli-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create xdg test dir");
        let sock = dir.join("tauri-hasgard-myapp.sock");
        // Create a dummy file that looks like a socket name.
        std::fs::write(&sock, b"").expect("create dummy socket file");

        // SAFETY: serial attribute serializes tests that touch XDG_RUNTIME_DIR.
        unsafe { std::env::set_var("XDG_RUNTIME_DIR", &dir) };
        let result = resolve_socket(None);
        unsafe { std::env::remove_var("XDG_RUNTIME_DIR") };

        let _ = std::fs::remove_file(&sock);
        let _ = std::fs::remove_dir(&dir);

        assert_eq!(result.expect("socket found"), sock);
    }

    #[test]
    #[cfg(unix)]
    #[serial]
    fn test_resolve_socket_prefers_xdg_runtime_dir_over_tmp() {
        let dir = std::env::temp_dir().join(format!("tauri-hasgard-xdg-precedence-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("create xdg test dir");
        let xdg_sock = dir.join("tauri-hasgard-xdg.sock");
        let tmp_sock =
            std::path::PathBuf::from(format!("/tmp/tauri-hasgard-newer-tmp-test-{}.sock", std::process::id()));
        let _ = std::fs::remove_file(&tmp_sock);
        std::fs::write(&xdg_sock, b"").expect("create xdg socket file");
        std::fs::write(&tmp_sock, b"").expect("create newer tmp socket file");

        // SAFETY: serial attribute serializes tests that touch XDG_RUNTIME_DIR.
        unsafe { std::env::set_var("XDG_RUNTIME_DIR", &dir) };
        let result = resolve_socket(None);
        unsafe { std::env::remove_var("XDG_RUNTIME_DIR") };

        let _ = std::fs::remove_file(&xdg_sock);
        let _ = std::fs::remove_file(&tmp_sock);
        let _ = std::fs::remove_dir(&dir);

        assert_eq!(result.expect("socket found"), xdg_sock);
    }

    #[test]
    #[cfg(unix)]
    #[serial]
    fn test_resolve_socket_falls_back_to_tmp_when_xdg_unset() {
        let tmp_sock =
            std::path::PathBuf::from(format!("/tmp/tauri-hasgard-fallback-test-{}.sock", std::process::id()));
        // Remove then recreate to ensure this file has the newest mtime.
        let _ = std::fs::remove_file(&tmp_sock);
        std::fs::write(&tmp_sock, b"").expect("create dummy socket in /tmp");

        unsafe { std::env::remove_var("XDG_RUNTIME_DIR") };
        let result = resolve_socket(None);

        let _ = std::fs::remove_file(&tmp_sock);

        // Assert the result is a valid tauri-hasgard socket path, not an exact path,
        // to avoid flakiness if other sockets exist in /tmp with newer mtime.
        let found = result.expect("socket found in /tmp");
        let name = found.file_name().and_then(|n| n.to_str()).expect("socket has a filename");
        assert!(
            name.starts_with("tauri-hasgard-")
                && std::path::Path::new(name).extension().is_some_and(|ext| ext.eq_ignore_ascii_case("sock")),
            "expected a tauri-hasgard-*.sock path, got: {found:?}"
        );
    }

    #[test]
    fn test_resolve_socket_returns_explicit_path() {
        let explicit = std::path::PathBuf::from("/tmp/my-explicit.sock");
        let result = resolve_socket(Some(explicit.clone()));
        assert_eq!(result.expect("explicit path returned"), explicit);
    }

    #[test]
    #[cfg(windows)]
    #[serial]
    fn test_resolve_socket_windows_reads_registry() {
        let dir = std::env::temp_dir().join(format!("tauri-hasgard-reg-test-{}", std::process::id()));
        let instances_dir = dir.join("tauri-hasgard").join("instances");
        std::fs::create_dir_all(&instances_dir).expect("create reg test dir");

        let pipe = r"\\.\pipe\tauri-hasgard-testapp";
        // Use the current process id so the liveness check in
        // `resolve_socket_windows` doesn't skip this mock entry as stale.
        std::fs::write(
            instances_dir.join("testapp.json"),
            serde_json::to_string_pretty(&serde_json::json!({
                "pid": std::process::id(),
                "pipe": pipe,
                "created_at": 1_745_200_000_u64
            }))
            .expect("serialize mock entry"),
        )
        .expect("write mock registry file");

        unsafe { std::env::set_var("LOCALAPPDATA", &dir) };
        let result = resolve_socket(None);
        unsafe { std::env::remove_var("LOCALAPPDATA") };

        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(result.expect("pipe found"), std::path::PathBuf::from(pipe));
    }

    #[test]
    #[cfg(windows)]
    fn test_resolve_socket_windows_returns_explicit() {
        let explicit = std::path::PathBuf::from(r"\\.\pipe\my-explicit");
        let result = resolve_socket(Some(explicit.clone()));
        assert_eq!(result.expect("explicit path returned"), explicit);
    }

    #[test]
    #[cfg(windows)]
    #[serial]
    fn test_resolve_socket_windows_picks_newest_instance() {
        let dir = std::env::temp_dir().join(format!("tauri-hasgard-reg-newest-test-{}", std::process::id()));
        let instances_dir = dir.join("tauri-hasgard").join("instances");
        std::fs::create_dir_all(&instances_dir).expect("create reg test dir");

        // Both entries must use live PIDs — otherwise the liveness filter in
        // `resolve_socket_windows` would skip them as stale and the test
        // would flake. Using the current process id keeps both "alive".
        let live_pid = std::process::id();
        let old_entry = serde_json::json!({
            "pid": live_pid,
            "pipe": r"\\.\pipe\tauri-hasgard-old",
            "created_at": 1000
        });
        let new_entry = serde_json::json!({
            "pid": live_pid,
            "pipe": r"\\.\pipe\tauri-hasgard-new",
            "created_at": 2000
        });
        std::fs::write(
            instances_dir.join("old_app.json"),
            serde_json::to_string(&old_entry).expect("serialize old entry"),
        )
        .expect("write mock old instance");
        std::fs::write(
            instances_dir.join("new_app.json"),
            serde_json::to_string(&new_entry).expect("serialize new entry"),
        )
        .expect("write mock new instance");

        unsafe { std::env::set_var("LOCALAPPDATA", &dir) };
        let result = resolve_socket(None);
        unsafe { std::env::remove_var("LOCALAPPDATA") };

        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(result.expect("pipe found"), std::path::PathBuf::from(r"\\.\pipe\tauri-hasgard-new"));
    }

    #[test]
    fn test_read_script_valid() {
        let mut reader = std::io::Cursor::new(b"document.title");
        assert_eq!(read_script(&mut reader).expect("read_script succeeds"), "document.title");
    }

    #[test]
    fn test_read_script_empty_errors() {
        let mut reader = std::io::Cursor::new(b"");
        let err = read_script(&mut reader).expect_err("empty input rejected");
        assert!(err.to_string().contains("empty or blank"), "got: {err}");
    }

    #[test]
    fn test_read_script_blank_errors() {
        let mut reader = std::io::Cursor::new(b"   \n  ");
        let err = read_script(&mut reader).expect_err("blank input rejected");
        assert!(err.to_string().contains("empty or blank"), "got: {err}");
    }

    // ─── build_wait_params (issue #74) ────────────────────────────────────────

    #[test]
    fn test_build_wait_params_positional_css_selector_routes_to_selector() {
        let p = build_wait_params(Some("#trigger"), None, false, 1000);
        assert_eq!(p, json!({"selector": "#trigger", "gone": false, "timeout": 1000}));
    }

    #[test]
    fn test_build_wait_params_positional_class_selector_routes_to_selector() {
        let p = build_wait_params(Some(".btn-primary"), None, false, 5000);
        assert_eq!(p, json!({"selector": ".btn-primary", "gone": false, "timeout": 5000}));
    }

    #[test]
    fn test_build_wait_params_positional_attr_selector_routes_to_selector() {
        let p = build_wait_params(Some("[data-test=foo]"), None, false, 1000);
        assert_eq!(p, json!({"selector": "[data-test=foo]", "gone": false, "timeout": 1000}));
    }

    #[test]
    fn test_build_wait_params_at_prefix_routes_to_ref() {
        let p = build_wait_params(Some("@e1"), None, false, 1000);
        assert_eq!(p, json!({"ref": "e1", "gone": false, "timeout": 1000}));
    }

    #[test]
    fn test_build_wait_params_explicit_selector_flag_wins_over_positional() {
        let p = build_wait_params(Some("@e1"), Some("#real"), false, 1000);
        assert_eq!(p, json!({"selector": "#real", "gone": false, "timeout": 1000}));
    }

    #[test]
    fn test_build_wait_params_no_target_no_selector_yields_empty_payload() {
        let p = build_wait_params(None, None, true, 2000);
        assert_eq!(p, json!({"gone": true, "timeout": 2000}));
    }

    #[test]
    fn test_build_wait_params_coords_fall_back_to_selector_for_syntax_error() {
        // wait does not act on coordinates; pass through verbatim so
        // `document.querySelector("100,200")` raises a `SyntaxError`
        // instead of the bridge silently waiting on a `MutationObserver`.
        let p = build_wait_params(Some("100,200"), None, false, 1000);
        assert_eq!(p, json!({"selector": "100,200", "gone": false, "timeout": 1000}));
    }

    #[test]
    fn test_build_wait_params_propagates_gone_flag() {
        let p = build_wait_params(Some("#x"), None, true, 500);
        assert_eq!(p, json!({"selector": "#x", "gone": true, "timeout": 500}));
    }

    #[test]
    fn test_build_wait_params_empty_ref_at_alone_drops_to_no_target() {
        // `@` strips to an empty ref. We omit it so the bridge `waitFor`
        // rejects immediately instead of hanging on `MutationObserver`.
        let p = build_wait_params(Some("@"), None, false, 1000);
        assert_eq!(p, json!({"gone": false, "timeout": 1000}));
    }
}