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
use clap::{Parser, Subcommand};
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "tauri-hasgard", version, about = "Interactive testing CLI for Tauri apps")]
pub(crate) struct Cli {
    /// Socket path (auto-detected if omitted).
    #[arg(long, env = "TAURI_HASGARD_SOCKET")]
    pub socket: Option<PathBuf>,

    /// Output JSON instead of text.
    #[arg(long, global = true)]
    pub json: bool,

    /// Target a specific window by label
    #[arg(long, env = "TAURI_HASGARD_WINDOW", global = true)]
    pub window: Option<String>,

    #[command(subcommand)]
    pub command: Command,
}

#[derive(Subcommand)]
pub(crate) enum Command {
    /// Start a Model Context Protocol server over stdio.
    Mcp,
    /// List all open windows
    Windows,
    /// Check connectivity with a running Tauri app.
    Ping,
    /// Get app state (url, title, ready).
    State,
    /// Capture an accessibility snapshot of the UI.
    Snapshot {
        #[arg(short, long)]
        interactive: bool,
        #[arg(short, long)]
        selector: Option<String>,
        #[arg(short, long)]
        depth: Option<u8>,
        #[arg(long, value_name = "FILE")]
        save: Option<std::path::PathBuf>,
    },
    /// Compare the current webview with a previous snapshot, showing only differences.
    Diff {
        /// Path to a saved snapshot file to compare against
        #[arg(long, value_name = "FILE")]
        r#ref: Option<std::path::PathBuf>,
        /// Only include interactive elements
        #[arg(short, long)]
        interactive: bool,
        /// CSS selector to scope the snapshot
        #[arg(short, long)]
        selector: Option<String>,
        /// Maximum depth to traverse
        #[arg(short, long)]
        depth: Option<u8>,
    },
    /// Click an element.
    Click { target: String },
    /// Clear and fill an input with a value.
    Fill { target: String, value: String },
    /// Type text character by character.
    Type { target: String, text: String },
    /// Press a keyboard key.
    Press { key: String },
    /// Select an option in a <select>.
    Select { target: String, value: String },
    /// Toggle a checkbox.
    Check { target: String },
    /// Scroll the webview document or an element.
    Scroll {
        direction: String,
        amount: Option<i32>,
        #[arg(long)]
        r#ref: Option<String>,
    },
    /// Drag an element to another element or by offset.
    Drag {
        source: String,
        #[arg(conflicts_with = "offset")]
        target: Option<String>,
        /// Pixel offset as X,Y (e.g., "0,100").
        #[arg(long, value_name = "X,Y", conflicts_with = "target")]
        offset: Option<String>,
    },
    /// Simulate a file drop on an element.
    Drop {
        target: String,
        /// File(s) to drop. Can be repeated.
        #[arg(long, required = true)]
        file: Vec<std::path::PathBuf>,
    },
    /// Get text content of an element.
    Text { target: String },
    /// Get inner HTML of an element or the full webview document.
    Html { target: Option<String> },
    /// Get the value of an input/select/textarea.
    Value { target: String },
    /// Get all attributes of an element.
    Attrs { target: String },
    /// Evaluate arbitrary JavaScript.
    /// Pass `-` as the script or omit it to read from stdin.
    Eval {
        /// JavaScript to evaluate. Use `-` or omit to read from stdin.
        script: Option<String>,
    },
    /// Invoke a Tauri IPC command.
    Ipc {
        command: String,
        #[arg(long)]
        args: Option<String>,
    },
    /// Capture the full webview document as a PNG.
    Screenshot {
        path: Option<PathBuf>,
        #[arg(long)]
        selector: Option<String>,
    },
    /// Capture a native window screenshot (PNG) by platform window id.
    #[command(name = "screenshot_native", visible_alias = "screenshot-native")]
    ScreenshotNative {
        #[arg(long)]
        window_id: u32,
        #[arg(long)]
        output: PathBuf,
        #[arg(long, default_value = "png")]
        format: String,
    },
    /// Navigate to a URL.
    Navigate { url: String },
    /// Get current URL.
    Url,
    /// Get the current webview title.
    Title,
    /// Wait for an element or condition.
    Wait {
        target: Option<String>,
        #[arg(long)]
        selector: Option<String>,
        #[arg(long)]
        gone: bool,
        #[arg(long, default_value = "10000")]
        timeout: u64,
    },
    /// Watch for DOM mutations and report changes.
    Watch {
        /// CSS selector to scope observation to a subtree.
        #[arg(long)]
        selector: Option<String>,
        /// Maximum wait time in ms. With `--require-mutation`, rejects on timeout
        /// if no mutation occurred; otherwise resolves after `--stable` ms of quiet.
        #[arg(long, default_value = "10000")]
        timeout: u64,
        /// Wait until DOM is stable for N ms (no new mutations).
        #[arg(long, default_value = "300")]
        stable: u64,
        /// Defer the stability timer until at least one mutation occurs.
        /// Use after IPC calls that trigger async re-renders (e.g., React state updates).
        #[arg(long)]
        require_mutation: bool,
    },
    /// Display or stream captured console logs.
    Logs {
        /// Filter by log level (log, info, warn, error).
        #[arg(long, value_parser = ["log", "info", "warn", "error"])]
        level: Option<String>,

        /// Show last N log entries.
        #[arg(long)]
        last: Option<usize>,

        /// Clear the log buffer.
        #[arg(long, conflicts_with = "follow")]
        clear: bool,

        /// Continuously poll for new logs.
        #[arg(long, short = 'f')]
        follow: bool,
    },
    /// Display or stream captured network requests.
    Network {
        /// Filter by URL pattern (substring match).
        #[arg(long)]
        filter: Option<String>,

        /// Show only failed requests (4xx/5xx and network errors).
        #[arg(long)]
        failed: bool,

        /// Show last N requests.
        #[arg(long)]
        last: Option<usize>,

        /// Clear the request buffer.
        #[arg(long, conflicts_with = "follow")]
        clear: bool,

        /// Continuously poll for new requests.
        #[arg(long, short = 'f')]
        follow: bool,
    },
    /// Assert element state
    #[command(subcommand)]
    Assert(AssertKind),
    /// Read and write browser storage (localStorage/sessionStorage).
    Storage(StorageArgs),
    /// Dump all form fields in the webview document.
    Forms(FormsArgs),
    /// Record interactions for replay
    Record {
        #[command(subcommand)]
        action: RecordAction,
    },
    /// Replay a recorded session
    Replay {
        /// Path to recording file (JSON)
        path: PathBuf,
        /// Export format instead of replaying (e.g., "sh")
        #[arg(long)]
        export: Option<String>,
    },
    /// Execute a declarative scenario from a TOML file.
    Run {
        /// Path to scenario TOML file.
        scenario: PathBuf,
        /// Write `JUnit` XML report to this path.
        #[arg(long, value_name = "FILE")]
        junit: Option<PathBuf>,
        /// Override `fail_fast` setting from the scenario file.
        #[arg(long)]
        no_fail_fast: bool,
    },
}

#[derive(Subcommand, Debug)]
pub(crate) enum AssertKind {
    /// Assert exact text content
    Text { target: String, expected: String },
    /// Assert element is visible
    Visible { target: String },
    /// Assert element is hidden
    Hidden { target: String },
    /// Assert input value
    Value { target: String, expected: String },
    /// Assert element count matching selector
    Count { selector: String, expected: u64 },
    /// Assert checkbox is checked
    Checked { target: String },
    /// Assert text contains substring
    Contains { target: String, expected: String },
    /// Assert current URL contains string
    Url { expected: String },
}

#[derive(clap::Args, Debug)]
pub(crate) struct StorageArgs {
    /// Use sessionStorage instead of localStorage.
    #[arg(long)]
    pub session: bool,
    #[command(subcommand)]
    pub action: StorageAction,
}

#[derive(clap::Args, Debug)]
pub(crate) struct FormsArgs {
    /// Target a specific form by CSS selector.
    #[arg(long)]
    pub selector: Option<String>,
}

#[derive(Subcommand, Debug)]
pub(crate) enum StorageAction {
    /// Get a value by key.
    Get { key: String },
    /// Set a key-value pair.
    Set { key: String, value: String },
    /// List all key-value pairs.
    List,
    /// Clear all storage.
    Clear,
}

#[derive(Subcommand, Debug)]
pub(crate) enum RecordAction {
    /// Start recording interactions
    Start,
    /// Stop recording and save to file
    Stop {
        /// Output file path (JSON)
        #[arg(short, long)]
        output: PathBuf,
    },
    /// Show recording status
    Status,
}

/// Parsed target for element-targeting commands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Target {
    Ref(String),
    Selector(String),
    Coords(i32, i32),
}

/// Parse a target string into a `Target` variant.
pub(crate) fn parse_target(s: &str) -> Target {
    if let Some(r) = s.strip_prefix('@') {
        return Target::Ref(r.to_owned());
    }

    if let Some((x_str, y_str)) = s.split_once(',')
        && let (Ok(x), Ok(y)) = (x_str.trim().parse::<i32>(), y_str.trim().parse::<i32>())
    {
        return Target::Coords(x, y);
    }

    Target::Selector(s.to_owned())
}

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

    #[test]
    fn test_parse_target_ref() {
        assert_eq!(parse_target("@e1"), Target::Ref("e1".to_owned()));
        assert_eq!(parse_target("@e42"), Target::Ref("e42".to_owned()));
    }

    #[test]
    fn test_parse_target_selector() {
        assert_eq!(parse_target("#submit-btn"), Target::Selector("#submit-btn".to_owned()));
        assert_eq!(parse_target(".class"), Target::Selector(".class".to_owned()));
    }

    #[test]
    fn test_parse_target_coords() {
        assert_eq!(parse_target("100,200"), Target::Coords(100, 200));
        assert_eq!(parse_target("0, 0"), Target::Coords(0, 0));
    }

    #[test]
    fn test_parse_target_invalid_coords_as_selector() {
        assert_eq!(parse_target("abc,def"), Target::Selector("abc,def".to_owned()));
    }

    #[test]
    fn test_parse_diff_command() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "diff"]);
        assert!(matches!(cli.command, Command::Diff { r#ref: None, interactive: false, selector: None, depth: None }));
    }

    #[test]
    fn test_parse_diff_with_ref() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "diff", "--ref", "/tmp/snap.json"]);
        if let Command::Diff { r#ref: Some(path), .. } = cli.command {
            assert_eq!(path, std::path::PathBuf::from("/tmp/snap.json"));
        } else {
            panic!("Expected Diff command with ref");
        }
    }

    #[test]
    fn test_parse_assert_text() {
        let cli =
            Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "assert", "text", "@e1", "Dashboard"]);
        if let Command::Assert(AssertKind::Text { target, expected }) = cli.command {
            assert_eq!(target, "@e1");
            assert_eq!(expected, "Dashboard");
        } else {
            panic!("Expected Assert Text command");
        }
    }

    #[test]
    fn test_parse_assert_visible() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "assert", "visible", "#submit"]);
        if let Command::Assert(AssertKind::Visible { target }) = cli.command {
            assert_eq!(target, "#submit");
        } else {
            panic!("Expected Assert Visible command");
        }
    }

    #[test]
    fn test_parse_assert_count() {
        let cli =
            Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "assert", "count", ".list-item", "5"]);
        if let Command::Assert(AssertKind::Count { selector, expected }) = cli.command {
            assert_eq!(selector, ".list-item");
            assert_eq!(expected, 5);
        } else {
            panic!("Expected Assert Count command");
        }
    }

    #[test]
    fn test_parse_assert_url() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "assert", "url", "/dashboard"]);
        if let Command::Assert(AssertKind::Url { expected }) = cli.command {
            assert_eq!(expected, "/dashboard");
        } else {
            panic!("Expected Assert Url command");
        }
    }

    #[test]
    fn test_parse_watch_command() {
        let cli = Cli::parse_from([
            "tauri-hasgard",
            "--socket",
            "/tmp/test.sock",
            "watch",
            "--selector",
            ".results",
            "--timeout",
            "5000",
            "--stable",
            "500",
        ]);
        if let Command::Watch { selector, timeout, stable, require_mutation } = cli.command {
            assert_eq!(selector, Some(".results".to_owned()));
            assert_eq!(timeout, 5000);
            assert_eq!(stable, 500);
            assert!(!require_mutation);
        } else {
            panic!("Expected Watch command");
        }
    }

    #[test]
    fn test_parse_watch_defaults() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "watch"]);
        if let Command::Watch { selector, timeout, stable, require_mutation } = cli.command {
            assert_eq!(selector, None);
            assert_eq!(timeout, 10000);
            assert_eq!(stable, 300);
            assert!(!require_mutation);
        } else {
            panic!("Expected Watch command");
        }
    }

    #[test]
    fn test_parse_watch_require_mutation() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "watch", "--require-mutation"]);
        if let Command::Watch { require_mutation, .. } = cli.command {
            assert!(require_mutation);
        } else {
            panic!("Expected Watch command");
        }
    }

    #[test]
    fn test_parse_watch_require_mutation_with_selector() {
        let cli = Cli::parse_from([
            "tauri-hasgard",
            "--socket",
            "/tmp/test.sock",
            "watch",
            "--selector",
            "#root",
            "--require-mutation",
            "--stable",
            "500",
        ]);
        if let Command::Watch { selector, stable, require_mutation, .. } = cli.command {
            assert_eq!(selector, Some("#root".to_owned()));
            assert_eq!(stable, 500);
            assert!(require_mutation);
        } else {
            panic!("Expected Watch command");
        }
    }

    #[test]
    fn test_parse_drag_to_element() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/t.sock", "drag", "@e5", "@e6"]);
        assert!(matches!(cli.command, Command::Drag { ref source, target: Some(_), .. } if source == "@e5"));
    }

    #[test]
    fn test_parse_drag_with_offset() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/t.sock", "drag", "@e5", "--offset", "0,100"]);
        assert!(
            matches!(cli.command, Command::Drag { ref source, offset: Some(ref off), .. } if source == "@e5" && off == "0,100")
        );
    }

    #[test]
    fn test_parse_drop_with_file() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/t.sock", "drop", "@e3", "--file", "test.png"]);
        assert!(matches!(cli.command, Command::Drop { ref target, .. } if target == "@e3"));
    }

    #[test]
    fn test_parse_drop_multiple_files() {
        let cli = Cli::parse_from([
            "tauri-hasgard",
            "--socket",
            "/tmp/t.sock",
            "drop",
            "@e3",
            "--file",
            "a.png",
            "--file",
            "b.txt",
        ]);
        if let Command::Drop { file, .. } = cli.command {
            assert_eq!(file.len(), 2);
        } else {
            panic!("expected Drop command");
        }
    }

    #[test]
    fn test_parse_drag_rejects_both_target_and_offset() {
        let result = Cli::try_parse_from([
            "tauri-hasgard",
            "--socket",
            "/tmp/t.sock",
            "drag",
            "@e5",
            "@e6",
            "--offset",
            "0,100",
        ]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_drop_requires_file() {
        let result = Cli::try_parse_from(["tauri-hasgard", "--socket", "/tmp/t.sock", "drop", "@e3"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_storage_get() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/t.sock", "storage", "get", "auth_token"]);
        if let Command::Storage(StorageArgs { session, action: StorageAction::Get { key } }) = cli.command {
            assert!(!session);
            assert_eq!(key, "auth_token");
        } else {
            panic!("Expected Storage Get command");
        }
    }

    #[test]
    fn test_parse_storage_set() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/t.sock", "storage", "set", "theme", "dark"]);
        if let Command::Storage(StorageArgs { session, action: StorageAction::Set { key, value } }) = cli.command {
            assert!(!session);
            assert_eq!(key, "theme");
            assert_eq!(value, "dark");
        } else {
            panic!("Expected Storage Set command");
        }
    }

    #[test]
    fn test_parse_storage_list_session() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/t.sock", "storage", "--session", "list"]);
        if let Command::Storage(StorageArgs { session, action: StorageAction::List }) = cli.command {
            assert!(session);
        } else {
            panic!("Expected Storage List command with session flag");
        }
    }

    #[test]
    fn test_parse_storage_clear() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/t.sock", "storage", "clear"]);
        assert!(matches!(cli.command, Command::Storage(StorageArgs { action: StorageAction::Clear, .. })));
    }

    #[test]
    fn test_parse_forms_command() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "forms"]);
        if let Command::Forms(FormsArgs { selector }) = cli.command {
            assert_eq!(selector, None);
        } else {
            panic!("Expected Forms command");
        }
    }

    #[test]
    fn test_parse_forms_with_selector() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "forms", "--selector", "#login"]);
        if let Command::Forms(FormsArgs { selector }) = cli.command {
            assert_eq!(selector, Some("#login".to_owned()));
        } else {
            panic!("Expected Forms command with selector");
        }
    }

    #[test]
    fn test_parse_record_start() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "record", "start"]);
        assert!(matches!(cli.command, Command::Record { action: RecordAction::Start }));
    }

    #[test]
    fn test_parse_record_stop_with_output() {
        let cli =
            Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "record", "stop", "--output", "test.json"]);
        if let Command::Record { action: RecordAction::Stop { output } } = cli.command {
            assert_eq!(output, std::path::PathBuf::from("test.json"));
        } else {
            panic!("Expected Record Stop command with output");
        }
    }

    #[test]
    fn test_parse_record_stop_requires_output() {
        let result = Cli::try_parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "record", "stop"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_replay_with_export() {
        let cli =
            Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "replay", "test.json", "--export", "sh"]);
        if let Command::Replay { path, export } = cli.command {
            assert_eq!(path, std::path::PathBuf::from("test.json"));
            assert_eq!(export, Some("sh".to_owned()));
        } else {
            panic!("Expected Replay command with export");
        }
    }

    #[test]
    fn test_windows_command() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "windows"]);
        assert!(matches!(cli.command, Command::Windows));
    }

    #[test]
    fn test_parse_screenshot_native_command() {
        let cli = Cli::parse_from([
            "tauri-hasgard",
            "--socket",
            "/tmp/test.sock",
            "screenshot_native",
            "--window-id",
            "42",
            "--output",
            "/tmp/out.png",
        ]);
        if let Command::ScreenshotNative { window_id, output, format } = cli.command {
            assert_eq!(window_id, 42);
            assert_eq!(output, std::path::PathBuf::from("/tmp/out.png"));
            assert_eq!(format, "png");
        } else {
            panic!("Expected ScreenshotNative command");
        }
    }

    #[test]
    fn test_mcp_command() {
        let cli = Cli::parse_from(["tauri-hasgard", "mcp"]);
        assert!(matches!(cli.command, Command::Mcp));
    }

    #[test]
    fn test_window_flag_with_command() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "--window", "settings", "snapshot"]);
        assert_eq!(cli.window, Some("settings".to_owned()));
        assert!(matches!(cli.command, Command::Snapshot { .. }));
    }

    #[test]
    #[serial_test::serial]
    fn test_window_flag_env() {
        // SAFETY: test is serialized via #[serial] to prevent parallel env access
        unsafe {
            std::env::set_var("TAURI_HASGARD_WINDOW", "main");
        }
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "ping"]);
        assert_eq!(cli.window, Some("main".to_owned()));
        unsafe {
            std::env::remove_var("TAURI_HASGARD_WINDOW");
        }
    }

    #[test]
    fn test_parse_eval_with_script_containing_quotes() {
        // Scripts with double quotes are the primary motivation for stdin support —
        // the shell would mangle them if passed as a CLI argument.
        let script = r#"document.querySelector('[data-id="main"]').textContent"#;
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "eval", script]);
        if let Command::Eval { script: parsed } = cli.command {
            assert_eq!(parsed, Some(script.to_owned()));
        } else {
            panic!("Expected Eval command");
        }
    }

    #[test]
    fn test_parse_eval_dash_reads_stdin() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "eval", "-"]);
        if let Command::Eval { script } = cli.command {
            assert_eq!(script, Some("-".to_owned()));
        } else {
            panic!("Expected Eval command with dash");
        }
    }

    #[test]
    fn test_parse_eval_no_arg_reads_stdin() {
        let cli = Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "eval"]);
        if let Command::Eval { script } = cli.command {
            assert_eq!(script, None);
        } else {
            panic!("Expected Eval command with no script");
        }
    }

    #[test]
    fn test_parse_snapshot_with_save() {
        let cli =
            Cli::parse_from(["tauri-hasgard", "--socket", "/tmp/test.sock", "snapshot", "--save", "/tmp/snap.json"]);
        if let Command::Snapshot { save: Some(path), .. } = cli.command {
            assert_eq!(path, std::path::PathBuf::from("/tmp/snap.json"));
        } else {
            panic!("Expected Snapshot command with save");
        }
    }
}