crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 浏览器自动下载管理器
//!
//! 提供 Chrome/Chromium 浏览器的自动下载功能,降低用户使用门槛。
//!
//! 注意:当前版本使用系统浏览器检测,chromiumoxide_fetcher 的完整支持将在后续版本中添加。

use log::info;

use crate::i18n::{tr_log, tr_log_args};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use thiserror::Error;
use tokio::sync::RwLock;

/// 下载状态
#[derive(Debug, Clone, PartialEq)]
pub enum DownloadStatus {
    NotDownloaded,
    Downloading,
    Downloaded,
    Failed(String),
}

/// 浏览器下载错误
#[derive(Error, Debug)]
pub enum BrowserDownloadError {
    #[error("Download failed: {0}")]
    DownloadFailed(String),

    #[error("Browser directory creation failed: {0}")]
    DirectoryCreationFailed(String),

    #[error("Browser executable not found: {0}")]
    ExecutableNotFound(PathBuf),

    #[error("Permission denied: {0}")]
    PermissionDenied(String),
}

/// 浏览器下载配置
#[derive(Clone, Debug)]
pub struct BrowserDownloadConfig {
    /// 下载目录
    pub download_dir: PathBuf,
    /// 下载超时时间(秒)
    pub timeout_seconds: u64,
    /// 是否在启动时自动下载
    pub auto_download: bool,
}

impl Default for BrowserDownloadConfig {
    fn default() -> Self {
        Self {
            download_dir: get_default_browser_path(),
            timeout_seconds: 300, // 5分钟
            auto_download: true,
        }
    }
}

/// 获取默认浏览器路径
fn get_default_browser_path() -> PathBuf {
    let mut path = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
    path.push(".cache");
    path.push("crawlrs");
    path.push("chromium");
    path
}

/// 获取浏览器可执行文件路径
pub fn get_browser_executable_path(cache_dir: &Path) -> PathBuf {
    let mut path = cache_dir.to_path_buf();
    // 根据平台选择可执行文件名
    #[cfg(target_os = "windows")]
    {
        path.push("chrome-win");
        path.push("chrome.exe");
    }
    #[cfg(target_os = "macos")]
    {
        path.push("chrome-mac");
        path.push("Chromium.app");
        path.push("Contents");
        path.push("MacOS");
        path.push("Chromium");
    }
    #[cfg(target_os = "linux")]
    {
        path.push("chrome-linux");
        path.push("chrome");
    }
    path
}

/// 浏览器下载管理器
///
/// 管理 Chrome/Chromium 浏览器的自动下载和缓存
#[derive(Clone, Debug)]
pub struct BrowserDownloadManager {
    /// 配置
    config: Arc<BrowserDownloadConfig>,
    /// 下载状态
    status: Arc<RwLock<DownloadStatus>>,
}

impl BrowserDownloadManager {
    /// 创建新的下载管理器
    pub fn new(config: BrowserDownloadConfig) -> Self {
        Self {
            config: Arc::new(config),
            status: Arc::new(RwLock::new(DownloadStatus::NotDownloaded)),
        }
    }

    /// 创建使用默认配置的下载管理器
    pub fn with_defaults() -> Self {
        Self::new(BrowserDownloadConfig::default())
    }

    /// 获取当前下载状态
    pub async fn get_status(&self) -> DownloadStatus {
        let status = self.status.read().await;
        status.clone()
    }

    /// 检查浏览器是否已下载
    pub async fn is_browser_downloaded(&self) -> bool {
        let executable_path = get_browser_executable_path(&self.config.download_dir);
        executable_path.exists() && executable_path.is_file()
    }

    /// 浏览器自动下载(简化实现)
    ///
    /// 当前版本检测系统浏览器并提示用户。
    /// 完整的自动下载功能需要 chromiumoxide_fetcher 的稳定支持。
    pub async fn download_browser(&self) -> Result<PathBuf, BrowserDownloadError> {
        info!("{}", tr_log("browser-check-started"));

        {
            let mut status = self.status.write().await;
            *status = DownloadStatus::Downloading;
        }

        // 首先检查系统浏览器
        if let Some(path) = find_system_browser().await {
            let mut status = self.status.write().await;
            *status = DownloadStatus::Downloaded;
            return Ok(path);
        }

        if self.is_browser_downloaded().await {
            let path = get_browser_executable_path(&self.config.download_dir);
            let mut status = self.status.write().await;
            *status = DownloadStatus::Downloaded;
            return Ok(path);
        }

        if let Err(e) = tokio::fs::create_dir_all(&self.config.download_dir).await {
            let err_msg = format!("Failed to create download directory: {}", e);
            let mut status = self.status.write().await;
            *status = DownloadStatus::Failed(err_msg.clone());
            return Err(BrowserDownloadError::DirectoryCreationFailed(err_msg));
        }

        // 尝试使用 chromiumoxide_fetcher 下载
        if let Ok(path) = self.try_fetcher_download().await {
            let mut status = self.status.write().await;
            *status = DownloadStatus::Downloaded;
            return Ok(path);
        }

        // 如果自动下载失败,返回错误提示
        // 运维人员可见的安装提示(错误载荷):i18n 初始化前即可能触发,
        // 保持英文规范串以保证回退可读性。
        let err_msg = String::from(
            "Chrome/Chromium browser not found. Install one of the following and retry:\n\
             - Google Chrome (https: // www.google.com/chrome)\n\
             - Chromium (https: // www.chromium.org/getting-involved/download-chromium)\n\
             or make sure the browser is available on PATH.",
        );
        let mut status = self.status.write().await;
        *status = DownloadStatus::Failed(err_msg.clone());
        Err(BrowserDownloadError::DownloadFailed(err_msg))
    }

    /// 尝试使用 chromiumoxide_fetcher 下载
    async fn try_fetcher_download(&self) -> Result<PathBuf, BrowserDownloadError> {
        // 动态检测是否可以使用 fetcher
        // 如果 browser-download 特性启用,尝试下载
        #[cfg(feature = "engine-playwright")]
        {
            match self.do_fetcher_download().await {
                Ok(path) => return Ok(path),
                Err(e) => {
                    log::warn!(
                        "{}",
                        tr_log_args(
                            "browser-fetcher-download-failed",
                            &[("error", e.to_string())],
                        )
                    );
                }
            }
        }

        Err(BrowserDownloadError::DownloadFailed(
            "automatic browser download is unavailable in this build (chromiumoxide_fetcher was removed for RUSTSEC advisories); install Chrome/Chromium or set CRAWLRS__ENGINES__PLAYWRIGHT__BROWSER_PATH"
                .to_string(),
        ))
    }

    /// 实际的 fetcher 下载实现(仅在 browser-download 特性启用时编译)
    #[cfg(feature = "engine-playwright")]
    async fn do_fetcher_download(&self) -> Result<PathBuf, BrowserDownloadError> {
        // chromiumoxide_fetcher API 需要正确的使用方式
        // 完整实现需要参考 crates.io 上的最新文档
        Err(BrowserDownloadError::DownloadFailed(
            "Browser download feature requires full implementation".to_string(),
        ))
    }

    /// 下载并返回浏览器路径(如果需要的话)
    pub async fn get_or_download_browser(&self) -> Result<PathBuf, BrowserDownloadError> {
        self.download_browser().await
    }

    /// 清理下载的浏览器
    pub async fn cleanup(&self) -> Result<(), BrowserDownloadError> {
        if self.config.download_dir.exists() {
            tokio::fs::remove_dir_all(&self.config.download_dir)
                .await
                .map_err(|e| {
                    BrowserDownloadError::DownloadFailed(format!("Cleanup failed: {}", e))
                })?;
            let mut status = self.status.write().await;
            *status = DownloadStatus::NotDownloaded;
            info!("{}", tr_log("browser-cleaned-up"));
        }
        Ok(())
    }

    /// 获取浏览器缓存目录
    pub fn get_cache_dir(&self) -> &PathBuf {
        &self.config.download_dir
    }
}

/// 浏览器路径环境变量名(显式路径优先于系统探测与内置下载)。
pub const BROWSER_PATH_ENV: &str = "CRAWLRS__ENGINES__PLAYWRIGHT__BROWSER_PATH";

/// 解析环境变量指定的浏览器可执行文件。
///
/// 统一两个启动路径(直连 playwright / 浏览器池)的读取与校验逻辑;
/// 日志只记录"已设置/无效",不输出路径值(审查 L2:路径可能包含用户名)。
pub fn browser_path_from_env() -> Option<PathBuf> {
    let raw = std::env::var(BROWSER_PATH_ENV).ok()?;
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    let path = PathBuf::from(trimmed);
    if path.is_file() {
        log::info!("{BROWSER_PATH_ENV} is set and points to an existing file");
        Some(path)
    } else {
        log::warn!("{BROWSER_PATH_ENV} is set but the path does not exist; ignoring");
        None
    }
}

/// 检查系统是否有可用的 Chrome/Chromium
pub async fn find_system_browser() -> Option<PathBuf> {
    // 检查常见路径
    let common_paths = [
        // Linux
        PathBuf::from("/usr/bin/google-chrome"),
        PathBuf::from("/usr/bin/chromium"),
        PathBuf::from("/usr/bin/chromium-browser"),
        // macOS
        PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
        PathBuf::from("/Applications/Chromium.app/Contents/MacOS/Chromium"),
        // Windows
        PathBuf::from(r"C:\Program Files\Google\Chrome\Application\chrome.exe"),
        PathBuf::from(r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"),
    ];

    for path in &common_paths {
        if path.is_file() {
            log::info!(
                "{}",
                tr_log_args("browser-system-found", &[("path", format!("{:?}", path))],)
            );
            return Some(path.clone());
        }
    }

    None
}

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

    // === DownloadStatus tests ===

    #[test]
    fn test_download_status_not_downloaded() {
        let status = DownloadStatus::NotDownloaded;
        assert_eq!(status, DownloadStatus::NotDownloaded);
        assert_ne!(status, DownloadStatus::Downloading);
    }

    #[test]
    fn test_download_status_downloading() {
        let status = DownloadStatus::Downloading;
        assert_eq!(status, DownloadStatus::Downloading);
        assert_ne!(status, DownloadStatus::Downloaded);
    }

    #[test]
    fn test_download_status_downloaded() {
        let status = DownloadStatus::Downloaded;
        assert_eq!(status, DownloadStatus::Downloaded);
        assert_ne!(status, DownloadStatus::NotDownloaded);
    }

    #[test]
    fn test_download_status_failed_with_message() {
        let status = DownloadStatus::Failed("network error".to_string());
        match status {
            DownloadStatus::Failed(msg) => assert_eq!(msg, "network error"),
            other => panic!("Expected Failed, got {:?}", other),
        }
    }

    #[test]
    fn test_download_status_clone() {
        let status = DownloadStatus::Failed("error".to_string());
        let cloned = status.clone();
        assert_eq!(status, cloned);
    }

    #[test]
    fn test_download_status_debug() {
        let status = DownloadStatus::Downloaded;
        let debug_str = format!("{:?}", status);
        assert_eq!(debug_str, "Downloaded");
    }

    // === BrowserDownloadError tests ===

    #[test]
    fn test_browser_download_error_download_failed() {
        let err = BrowserDownloadError::DownloadFailed("timeout".to_string());
        assert_eq!(err.to_string(), "Download failed: timeout");
    }

    #[test]
    fn test_browser_download_error_directory_creation_failed() {
        let err = BrowserDownloadError::DirectoryCreationFailed("permission denied".to_string());
        assert_eq!(
            err.to_string(),
            "Browser directory creation failed: permission denied"
        );
    }

    #[test]
    fn test_browser_download_error_executable_not_found() {
        let path = PathBuf::from("/usr/bin/chrome");
        let err = BrowserDownloadError::ExecutableNotFound(path.clone());
        assert_eq!(
            err.to_string(),
            format!("Browser executable not found: {}", path.display())
        );
    }

    #[test]
    fn test_browser_download_error_permission_denied() {
        let err = BrowserDownloadError::PermissionDenied("/root/.cache".to_string());
        assert_eq!(err.to_string(), "Permission denied: /root/.cache");
    }

    // === BrowserDownloadConfig tests ===

    #[test]
    fn test_browser_download_config_default() {
        let config = BrowserDownloadConfig::default();
        assert_eq!(config.timeout_seconds, 300);
        assert!(config.auto_download);
        // download_dir should end with .cache/crawlrs/chromium
        assert!(config.download_dir.ends_with("chromium"));
    }

    #[test]
    fn test_browser_download_config_custom() {
        let config = BrowserDownloadConfig {
            download_dir: PathBuf::from("/tmp/custom-browser"),
            timeout_seconds: 600,
            auto_download: false,
        };
        assert_eq!(config.download_dir, PathBuf::from("/tmp/custom-browser"));
        assert_eq!(config.timeout_seconds, 600);
        assert!(!config.auto_download);
    }

    #[test]
    fn test_browser_download_config_clone() {
        let config = BrowserDownloadConfig {
            download_dir: PathBuf::from("/tmp/test"),
            timeout_seconds: 100,
            auto_download: true,
        };
        let cloned = config.clone();
        assert_eq!(config.download_dir, cloned.download_dir);
        assert_eq!(config.timeout_seconds, cloned.timeout_seconds);
        assert_eq!(config.auto_download, cloned.auto_download);
    }

    // === get_browser_executable_path tests ===

    #[test]
    fn test_get_browser_executable_path_returns_path_under_cache() {
        let cache_dir = PathBuf::from("/tmp/some-cache");
        let exe_path = get_browser_executable_path(&cache_dir);

        // The path should start with the cache directory
        assert!(exe_path.starts_with(&cache_dir));

        // Platform-specific assertions
        #[cfg(target_os = "linux")]
        {
            assert!(exe_path.ends_with("chrome"));
            assert!(exe_path.to_string_lossy().contains("chrome-linux"));
        }
        #[cfg(target_os = "windows")]
        {
            assert!(exe_path.ends_with("chrome.exe"));
            assert!(exe_path.to_string_lossy().contains("chrome-win"));
        }
        #[cfg(target_os = "macos")]
        {
            assert!(exe_path.ends_with("Chromium"));
            assert!(exe_path.to_string_lossy().contains("chrome-mac"));
        }
    }

    #[test]
    fn test_get_browser_executable_path_with_empty_dir() {
        let cache_dir = PathBuf::new();
        let exe_path = get_browser_executable_path(&cache_dir);
        // Should still produce a valid relative path(断言仅 linux 有意义:
        // 其它平台的可执行名不同,故该绑定在非 linux 下不参与使用)
        #[cfg(target_os = "linux")]
        assert!(exe_path.ends_with("chrome"));
        #[cfg(not(target_os = "linux"))]
        let _ = &exe_path;
    }

    // === BrowserDownloadManager creation tests ===

    #[test]
    fn test_browser_download_manager_new() {
        let config = BrowserDownloadConfig {
            download_dir: PathBuf::from("/tmp/test-browser"),
            timeout_seconds: 60,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);
        // Verify the manager is created (get_cache_dir confirms config is stored)
        assert_eq!(manager.get_cache_dir(), &PathBuf::from("/tmp/test-browser"));
    }

    #[test]
    fn test_browser_download_manager_with_defaults() {
        let manager = BrowserDownloadManager::with_defaults();
        let cache_dir = manager.get_cache_dir();
        assert!(cache_dir.ends_with("chromium"));
    }

    // === get_status tests ===

    #[tokio::test]
    async fn test_get_status_initial_not_downloaded() {
        let manager = BrowserDownloadManager::with_defaults();
        let status = manager.get_status().await;
        assert_eq!(status, DownloadStatus::NotDownloaded);
    }

    #[tokio::test]
    async fn test_get_status_initial_after_custom_config() {
        let config = BrowserDownloadConfig {
            download_dir: PathBuf::from("/nonexistent/path/test"),
            timeout_seconds: 60,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);
        let status = manager.get_status().await;
        assert_eq!(status, DownloadStatus::NotDownloaded);
    }

    // === is_browser_downloaded tests ===

    #[tokio::test]
    async fn test_is_browser_downloaded_nonexistent_path() {
        let config = BrowserDownloadConfig {
            download_dir: PathBuf::from("/nonexistent/path/that/does/not/exist"),
            timeout_seconds: 60,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);
        assert!(!manager.is_browser_downloaded().await);
    }

    #[tokio::test]
    async fn test_is_browser_downloaded_temp_empty_dir() {
        let temp_dir = tempfile::tempdir().unwrap();
        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 60,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);
        // No executable in empty temp dir
        assert!(!manager.is_browser_downloaded().await);
    }

    // === get_cache_dir tests ===

    #[test]
    fn test_get_cache_dir_custom() {
        let custom_path = PathBuf::from("/custom/cache/dir");
        let config = BrowserDownloadConfig {
            download_dir: custom_path.clone(),
            timeout_seconds: 60,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);
        assert_eq!(manager.get_cache_dir(), &custom_path);
    }

    // === cleanup tests ===

    #[tokio::test]
    async fn test_cleanup_nonexistent_dir() {
        let config = BrowserDownloadConfig {
            download_dir: PathBuf::from("/nonexistent/path/for/cleanup/test"),
            timeout_seconds: 60,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);
        // cleanup on nonexistent dir should succeed (no-op)
        let result = manager.cleanup().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_cleanup_existing_temp_dir() {
        let temp_dir = tempfile::tempdir().unwrap();
        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 60,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        // Create a file inside the dir to verify it exists
        let test_file = temp_dir.path().join("test_file.txt");
        tokio::fs::write(&test_file, "test").await.unwrap();
        assert!(test_file.exists());

        // Cleanup should remove the directory
        let result = manager.cleanup().await;
        assert!(result.is_ok());
        assert!(!temp_dir.path().exists());

        // Status should be reset to NotDownloaded
        let status = manager.get_status().await;
        assert_eq!(status, DownloadStatus::NotDownloaded);
    }

    #[tokio::test]
    async fn test_cleanup_then_status_is_not_downloaded() {
        let temp_dir = tempfile::tempdir().unwrap();
        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 60,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        manager.cleanup().await.unwrap();
        let status = manager.get_status().await;
        assert_eq!(status, DownloadStatus::NotDownloaded);
    }

    // === find_system_browser tests ===

    #[tokio::test]
    async fn test_find_system_browser_returns_option() {
        let result = find_system_browser().await;
        // We can't assert specific result since it depends on the system
        // Just verify it doesn't panic
        let _ = result;
    }

    // === download_browser tests (using temp dir) ===

    #[tokio::test]
    async fn test_download_browser_no_system_browser_returns_error_or_path() {
        // Use a temp directory that definitely doesn't have a browser
        let temp_dir = tempfile::tempdir().unwrap();
        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 5,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        let result = manager.download_browser().await;

        // The result depends on whether a system browser is found:
        // - If system browser found: Ok(path)
        // - If no system browser: Err (fetcher not available without browser-download feature)
        match result {
            Ok(path) => {
                // System browser was found, path should exist
                assert!(path.exists());
                let status = manager.get_status().await;
                assert_eq!(status, DownloadStatus::Downloaded);
            }
            Err(e) => {
                // No system browser found, fetcher not available
                let status = manager.get_status().await;
                match status {
                    DownloadStatus::Failed(msg) => {
                        assert!(!msg.is_empty());
                    }
                    _ => panic!("Expected Failed status, got {:?}", status),
                }
                // Verify the error is DownloadFailed
                assert!(matches!(e, BrowserDownloadError::DownloadFailed(_)));
            }
        }
    }

    #[tokio::test]
    async fn test_download_browser_sets_status_downloading() {
        // This test verifies that after calling download_browser, status is not
        // NotDownloaded (it should be Downloaded or Failed)
        let temp_dir = tempfile::tempdir().unwrap();
        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 5,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        let _ = manager.download_browser().await;
        let status = manager.get_status().await;
        assert_ne!(status, DownloadStatus::NotDownloaded);
        assert_ne!(status, DownloadStatus::Downloading);
    }

    // === get_or_download_browser tests ===

    #[tokio::test]
    async fn test_get_or_download_browser_calls_download() {
        let temp_dir = tempfile::tempdir().unwrap();
        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 5,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        let result = manager.get_or_download_browser().await;
        // Should behave same as download_browser
        if let Ok(path) = result {
            assert!(path.exists());
        }
    }

    // === Manager clone tests ===

    #[test]
    fn test_browser_download_manager_clone() {
        let config = BrowserDownloadConfig {
            download_dir: PathBuf::from("/tmp/clone-test"),
            timeout_seconds: 120,
            auto_download: true,
        };
        let manager = BrowserDownloadManager::new(config);
        let cloned = manager.clone();

        // Both should point to the same cache dir
        assert_eq!(manager.get_cache_dir(), cloned.get_cache_dir());
    }

    #[test]
    fn test_browser_download_manager_debug() {
        let manager = BrowserDownloadManager::with_defaults();
        let debug_str = format!("{:?}", manager);
        // Should contain "BrowserDownloadManager"
        assert!(debug_str.contains("BrowserDownloadManager"));
    }

    // === download_browser: is_browser_downloaded early-return path ===
    // Covers the branch where the browser executable already exists in the download dir
    // (line 156-161): is_browser_downloaded() returns true, download_browser returns the
    // cached path without attempting to download.

    #[tokio::test]
    async fn test_download_browser_returns_cached_executable() {
        // Create the expected executable path under the download dir so that
        // is_browser_downloaded() returns true.
        let temp_dir = tempfile::tempdir().unwrap();
        let exe_path = get_browser_executable_path(temp_dir.path());
        if let Some(parent) = exe_path.parent() {
            tokio::fs::create_dir_all(parent).await.unwrap();
        }
        tokio::fs::write(&exe_path, "fake browser binary")
            .await
            .unwrap();

        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 5,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        let result = manager.download_browser().await;
        assert!(result.is_ok());
        let status = manager.get_status().await;
        assert_eq!(status, DownloadStatus::Downloaded);
    }

    #[tokio::test]
    async fn test_is_browser_downloaded_true_when_executable_exists() {
        // Directly verify is_browser_downloaded returns true when the executable file exists.
        let temp_dir = tempfile::tempdir().unwrap();
        let exe_path = get_browser_executable_path(temp_dir.path());
        if let Some(parent) = exe_path.parent() {
            tokio::fs::create_dir_all(parent).await.unwrap();
        }
        tokio::fs::write(&exe_path, "binary").await.unwrap();

        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 5,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);
        assert!(manager.is_browser_downloaded().await);
    }

    // === download_browser: create_dir_all failure path ===
    // Covers the branch where tokio::fs::create_dir_all fails (line 164-169).
    // We make the download_dir a child of a regular file, which causes create_dir_all to
    // return an error (NotADirectory).

    #[tokio::test]
    async fn test_download_browser_create_dir_failure() {
        // Create a regular file, then set download_dir to a sub-path of it.
        // create_dir_all will fail because the parent is a file, not a directory.
        let temp_dir = tempfile::tempdir().unwrap();
        let blocking_file = temp_dir.path().join("blocking_file");
        tokio::fs::write(&blocking_file, "block").await.unwrap();

        let impossible_dir = blocking_file.join("subdir");
        let config = BrowserDownloadConfig {
            download_dir: impossible_dir,
            timeout_seconds: 5,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        let result = manager.download_browser().await;
        match result {
            Ok(_) => {
                // find_system_browser() found a system browser before create_dir_all was
                // reached. The status should be Downloaded.
                let status = manager.get_status().await;
                assert_eq!(status, DownloadStatus::Downloaded);
            }
            Err(BrowserDownloadError::DirectoryCreationFailed(msg)) => {
                // create_dir_all failed as expected
                assert!(msg.contains("Failed to create download directory"));
                let status = manager.get_status().await;
                match status {
                    DownloadStatus::Failed(s) => assert!(!s.is_empty()),
                    other => panic!("Expected Failed status, got {:?}", other),
                }
            }
            Err(other) => panic!("Expected DirectoryCreationFailed or Ok, got {:?}", other),
        }
    }

    // === download_browser: status transitions ===
    // Verify the Downloading status is set at the start of download_browser.

    #[tokio::test]
    async fn test_download_browser_sets_downloading_then_terminal_status() {
        let temp_dir = tempfile::tempdir().unwrap();
        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 5,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        let _ = manager.download_browser().await;
        let status = manager.get_status().await;
        // After download_browser completes, status should be Downloaded or Failed,
        // never NotDownloaded or Downloading.
        assert_ne!(status, DownloadStatus::NotDownloaded);
        assert_ne!(status, DownloadStatus::Downloading);
    }

    // === try_fetcher_download: returns error when browser-download feature is disabled ===
    // When the browser-download feature is not enabled, try_fetcher_download always returns
    // Err(DownloadFailed("Fetcher 不可用")). This is the default configuration.

    #[tokio::test]
    async fn test_download_browser_fetcher_unavailable_falls_through_to_error() {
        // With no system browser, no cached executable, and no browser-download feature,
        // download_browser should return DownloadFailed with an instructional message.
        // We use a temp dir with no executable to ensure is_browser_downloaded is false.
        let temp_dir = tempfile::tempdir().unwrap();
        let config = BrowserDownloadConfig {
            download_dir: temp_dir.path().to_path_buf(),
            timeout_seconds: 5,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        let result = manager.download_browser().await;
        match result {
            Ok(path) => {
                // System browser was found
                assert!(path.exists());
                let status = manager.get_status().await;
                assert_eq!(status, DownloadStatus::Downloaded);
            }
            Err(BrowserDownloadError::DownloadFailed(msg)) => {
                // No system browser, fetcher unavailable
                assert!(msg.contains("Chrome") || msg.contains("Chromium"));
                let status = manager.get_status().await;
                match status {
                    DownloadStatus::Failed(s) => assert!(!s.is_empty()),
                    other => panic!("Expected Failed status, got {:?}", other),
                }
            }
            Err(other) => panic!("Expected DownloadFailed or Ok, got {:?}", other),
        }
    }

    // === cleanup: error when removal fails ===
    // Covers the error path in cleanup() when remove_dir_all fails.

    #[tokio::test]
    async fn test_cleanup_error_on_non_directory_path() {
        // If download_dir is a file (not a directory), remove_dir_all will fail.
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("not_a_dir");
        tokio::fs::write(&file_path, "file").await.unwrap();

        let config = BrowserDownloadConfig {
            download_dir: file_path,
            timeout_seconds: 5,
            auto_download: false,
        };
        let manager = BrowserDownloadManager::new(config);

        let result = manager.cleanup().await;
        // remove_dir_all on a file should return an error
        assert!(result.is_err());
        match result.unwrap_err() {
            BrowserDownloadError::DownloadFailed(msg) => {
                assert!(msg.contains("Cleanup failed"));
            }
            other => panic!("Expected DownloadFailed, got {:?}", other),
        }
    }
}