fetchkit 0.2.0

AI-friendly web content fetching and HTML-to-Markdown conversion library
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
//! Safety and robustness tests for FileSaver and save_to_file
//!
//! Covers: error handling, path traversal, hung servers, malformed responses,
//! concurrent saves, empty/huge payloads, special filenames, and edge cases.

use fetchkit::{FetchError, FetchRequest, LocalFileSaver, Tool};
use std::time::Duration;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn tool_with_save() -> Tool {
    Tool::builder()
        .block_private_ips(false)
        .enable_save_to_file(true)
        .build()
}

fn saver_in(dir: &std::path::Path) -> LocalFileSaver {
    LocalFileSaver::new(Some(dir.to_path_buf()))
}

// ---------------------------------------------------------------------------
// Path traversal attacks
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_path_traversal_dotdot() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("pwned"))
        .mount(&mock)
        .await;

    for attack_path in &[
        "../../etc/passwd",
        "../../../etc/shadow",
        "foo/../../bar",
        "a/b/c/../../../../outside",
        "../.ssh/authorized_keys",
    ] {
        let req =
            FetchRequest::new(format!("{}/", mock.uri())).save_to_file(attack_path.to_string());
        let result = tool.execute_with_saver(req, Some(&saver)).await;
        assert!(
            result.is_err(),
            "Path traversal should be rejected: {}",
            attack_path
        );
    }
}

#[tokio::test]
async fn test_path_traversal_absolute_escape() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("pwned"))
        .mount(&mock)
        .await;

    // Absolute path outside base_dir
    let req = FetchRequest::new(format!("{}/", mock.uri())).save_to_file("/tmp/evil.txt");
    let result = tool.execute_with_saver(req, Some(&saver)).await;
    assert!(result.is_err(), "Absolute path outside base should fail");
}

#[tokio::test]
async fn test_path_traversal_null_bytes() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("data"))
        .mount(&mock)
        .await;

    // Null byte in path — should either fail or be sanitized
    let req = FetchRequest::new(format!("{}/", mock.uri())).save_to_file("file\x00.txt");
    let result = tool.execute_with_saver(req, Some(&saver)).await;
    // On most OSes, null bytes in filenames cause IO errors
    assert!(result.is_err(), "Null byte path should fail");
}

#[tokio::test]
async fn test_no_base_dir_requires_absolute() {
    let saver = LocalFileSaver::new(None);
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("data"))
        .mount(&mock)
        .await;

    let req = FetchRequest::new(format!("{}/", mock.uri())).save_to_file("relative.txt");
    let result = tool.execute_with_saver(req, Some(&saver)).await;
    assert!(
        result.is_err(),
        "Relative path without base_dir should fail"
    );
}

// ---------------------------------------------------------------------------
// Server errors and edge cases
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_http_404() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/missing"))
        .respond_with(
            ResponseTemplate::new(404)
                .set_body_string("Not Found")
                .insert_header("content-type", "text/plain"),
        )
        .mount(&mock)
        .await;

    let req = FetchRequest::new(format!("{}/missing", mock.uri())).save_to_file("not_found.txt");
    let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();

    // 404 body is still saved — caller decides what to do with status
    assert_eq!(resp.status_code, 404);
    assert!(resp.saved_path.is_some());
    let content = std::fs::read_to_string(dir.path().join("not_found.txt")).unwrap();
    assert_eq!(content, "Not Found");
}

#[tokio::test]
async fn test_save_http_500() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/error"))
        .respond_with(
            ResponseTemplate::new(500)
                .set_body_string("Internal Error")
                .insert_header("content-type", "text/plain"),
        )
        .mount(&mock)
        .await;

    let req = FetchRequest::new(format!("{}/error", mock.uri())).save_to_file("error.txt");
    let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();
    assert_eq!(resp.status_code, 500);
    assert!(resp.saved_path.is_some());
}

#[tokio::test]
async fn test_save_empty_body() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/empty"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_bytes(vec![])
                .insert_header("content-type", "application/octet-stream"),
        )
        .mount(&mock)
        .await;

    let req = FetchRequest::new(format!("{}/empty", mock.uri())).save_to_file("empty.bin");
    let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();

    assert_eq!(resp.status_code, 200);
    assert_eq!(resp.bytes_written, Some(0));
    assert!(dir.path().join("empty.bin").exists());
    assert_eq!(
        std::fs::read(dir.path().join("empty.bin")).unwrap().len(),
        0
    );
}

// ---------------------------------------------------------------------------
// Slow/hung server — must not hang forever
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_slow_server_does_not_hang() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/slow"))
        .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(60)))
        .mount(&mock)
        .await;

    // Wrap in a tokio timeout to ensure we don't hang
    let result = tokio::time::timeout(Duration::from_secs(10), async {
        let req = FetchRequest::new(format!("{}/slow", mock.uri())).save_to_file("slow.txt");
        tool.execute_with_saver(req, Some(&saver)).await
    })
    .await;

    // Should complete within timeout — either with timeout error or partial content
    assert!(
        result.is_ok(),
        "Should not hang — must complete within 10 seconds"
    );
    // The inner result may be an error (timeout) or a truncated response, both are fine
}

#[tokio::test]
async fn test_save_connect_timeout_does_not_hang() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());

    // Use a non-routable IP to trigger connect timeout
    let result = tokio::time::timeout(Duration::from_secs(10), async {
        let req = FetchRequest::new("http://192.0.2.1:12345/file").save_to_file("timeout.txt");
        // Need to allow this IP for the test (it's a documentation range, normally blocked)
        let tool = Tool::builder()
            .block_private_ips(false)
            .enable_save_to_file(true)
            .build();
        tool.execute_with_saver(req, Some(&saver)).await
    })
    .await;

    assert!(
        result.is_ok(),
        "Connect timeout should not hang the process"
    );
    assert!(result.unwrap().is_err(), "Should return error on timeout");
}

// ---------------------------------------------------------------------------
// Feature gating / authorization
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_disabled_by_default() {
    let tool = Tool::default();
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());

    let req = FetchRequest::new("https://example.com").save_to_file("file.txt");
    let result = tool.execute_with_saver(req, Some(&saver)).await;

    assert!(matches!(result, Err(FetchError::SaverNotAvailable)));
}

#[tokio::test]
async fn test_save_no_saver_errors() {
    let tool = tool_with_save();

    let req = FetchRequest::new("https://example.com").save_to_file("file.txt");
    let result = tool.execute_with_saver(req, None).await;

    assert!(matches!(result, Err(FetchError::SaverNotAvailable)));
}

#[tokio::test]
async fn test_save_schema_gating_default_hidden() {
    let tool = Tool::default();
    let schema = tool.input_schema();
    let props = schema["properties"].as_object().unwrap();
    assert!(
        !props.contains_key("save_to_file"),
        "save_to_file should be hidden in default schema"
    );
}

#[tokio::test]
async fn test_save_schema_gating_enabled_visible() {
    let tool = tool_with_save();
    let schema = tool.input_schema();
    let props = schema["properties"].as_object().unwrap();
    assert!(
        props.contains_key("save_to_file"),
        "save_to_file should be visible when enabled"
    );
}

// ---------------------------------------------------------------------------
// Concurrent saves
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_concurrent_saves_dont_corrupt() {
    let dir = tempfile::tempdir().unwrap();

    let mock = MockServer::start().await;
    for i in 0..5 {
        Mock::given(method("GET"))
            .and(path(format!("/file{}", i)))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(format!("content-{}", i))
                    .insert_header("content-type", "text/plain"),
            )
            .mount(&mock)
            .await;
    }

    let mut handles = vec![];
    for i in 0..5 {
        let url = format!("{}/file{}", mock.uri(), i);
        let save_path = format!("concurrent/file{}.txt", i);
        let dir_path = dir.path().to_path_buf();

        let handle = tokio::spawn(async move {
            let saver = LocalFileSaver::new(Some(dir_path));
            let tool = Tool::builder()
                .block_private_ips(false)
                .enable_save_to_file(true)
                .build();
            let req = FetchRequest::new(url).save_to_file(save_path);
            tool.execute_with_saver(req, Some(&saver)).await
        });
        handles.push(handle);
    }

    for (i, handle) in handles.into_iter().enumerate() {
        let result = handle.await.unwrap();
        assert!(result.is_ok(), "Concurrent save {} failed: {:?}", i, result);
    }

    // Verify each file has correct content
    for i in 0..5 {
        let content =
            std::fs::read_to_string(dir.path().join(format!("concurrent/file{}.txt", i))).unwrap();
        assert_eq!(content, format!("content-{}", i));
    }
}

// ---------------------------------------------------------------------------
// Special filenames
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_filename_with_spaces() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("data"))
        .mount(&mock)
        .await;

    let req = FetchRequest::new(format!("{}/", mock.uri())).save_to_file("my file (1).txt");
    let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();
    assert!(resp.saved_path.is_some());
    assert!(dir.path().join("my file (1).txt").exists());
}

#[tokio::test]
async fn test_save_filename_unicode() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("data"))
        .mount(&mock)
        .await;

    let req = FetchRequest::new(format!("{}/", mock.uri())).save_to_file("datos_ñ.txt");
    let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();
    assert!(resp.saved_path.is_some());
}

#[tokio::test]
async fn test_save_deeply_nested_path() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("deep"))
        .mount(&mock)
        .await;

    let req =
        FetchRequest::new(format!("{}/", mock.uri())).save_to_file("a/b/c/d/e/f/g/h/deep.txt");
    let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();
    assert!(resp.saved_path.is_some());
    assert!(dir.path().join("a/b/c/d/e/f/g/h/deep.txt").exists());
}

// ---------------------------------------------------------------------------
// Overwrite behavior
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_overwrites_existing_file() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    // Create existing file
    std::fs::write(dir.path().join("existing.txt"), "old content").unwrap();

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("new content"))
        .mount(&mock)
        .await;

    let req = FetchRequest::new(format!("{}/", mock.uri())).save_to_file("existing.txt");
    let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();
    assert!(resp.saved_path.is_some());

    let content = std::fs::read_to_string(dir.path().join("existing.txt")).unwrap();
    assert_eq!(content, "new content");
}

// ---------------------------------------------------------------------------
// Various binary content types
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_various_binary_types() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();
    let mock = MockServer::start().await;

    let cases = vec![
        ("image.jpg", "image/jpeg", vec![0xFF, 0xD8, 0xFF, 0xE0]),
        ("doc.pdf", "application/pdf", b"%PDF-1.4".to_vec()),
        (
            "archive.zip",
            "application/zip",
            vec![0x50, 0x4B, 0x03, 0x04],
        ),
        (
            "data.bin",
            "application/octet-stream",
            (0..=255u8).collect::<Vec<u8>>(),
        ),
    ];

    for (filename, content_type, data) in &cases {
        let url_path = format!("/{}", filename);
        Mock::given(method("GET"))
            .and(path(&url_path))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_bytes(data.clone())
                    .insert_header("content-type", *content_type),
            )
            .mount(&mock)
            .await;

        let req = FetchRequest::new(format!("{}{}", mock.uri(), url_path))
            .save_to_file(filename.to_string());
        let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();

        assert_eq!(resp.status_code, 200, "Failed for {}", filename);
        assert!(resp.saved_path.is_some(), "No saved_path for {}", filename);
        assert!(resp.error.is_none(), "Unexpected error for {}", filename);

        let saved = std::fs::read(dir.path().join(filename)).unwrap();
        assert_eq!(saved, *data, "Content mismatch for {}", filename);
    }
}

// ---------------------------------------------------------------------------
// URL allow/block list interaction with save_to_file
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_respects_block_list() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("blocked"))
        .mount(&mock)
        .await;

    let tool = Tool::builder()
        .block_private_ips(false)
        .enable_save_to_file(true)
        .block_prefix("http://127.0.0.1")
        .build();

    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());

    let req = FetchRequest::new(format!("{}/", mock.uri())).save_to_file("blocked.txt");
    let result = tool.execute_with_saver(req, Some(&saver)).await;
    assert!(
        matches!(result, Err(FetchError::BlockedUrl)),
        "Blocked URLs should still be rejected for save_to_file"
    );
}

#[tokio::test]
async fn test_save_respects_allow_list() {
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/"))
        .respond_with(ResponseTemplate::new(200).set_body_string("denied"))
        .mount(&mock)
        .await;

    let tool = Tool::builder()
        .block_private_ips(false)
        .enable_save_to_file(true)
        .allow_prefix("https://allowed.example.com")
        .build();

    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());

    let req = FetchRequest::new(format!("{}/", mock.uri())).save_to_file("denied.txt");
    let result = tool.execute_with_saver(req, Some(&saver)).await;
    assert!(result.is_err(), "Non-allowed URLs should be rejected");
}

// ---------------------------------------------------------------------------
// HEAD request with save_to_file
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_head_request_no_body() {
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    Mock::given(method("HEAD"))
        .and(path("/file"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/pdf")
                .insert_header("content-length", "1000"),
        )
        .mount(&mock)
        .await;

    let req = FetchRequest::new(format!("{}/file", mock.uri()))
        .method(fetchkit::HttpMethod::Head)
        .save_to_file("metadata.txt");
    let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();

    // HEAD returns metadata, no body to save
    assert_eq!(resp.status_code, 200);
    assert_eq!(resp.method, Some("HEAD".to_string()));
}

// ---------------------------------------------------------------------------
// LocalFileSaver unit tests (edge cases)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_local_file_saver_validate_then_save() {
    use fetchkit::file_saver::FileSaver;

    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());

    // Validate first, then save
    saver.validate_path("valid.txt").await.unwrap();
    let result = saver.save("valid.txt", b"validated content").await.unwrap();
    assert_eq!(result.bytes_written, 17);
}

#[tokio::test]
async fn test_local_file_saver_empty_filename() {
    use fetchkit::file_saver::FileSaver;

    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());

    // Empty filename — resolves to base dir itself, which is a directory
    let result = saver.save("", b"data").await;
    // This should fail because we're trying to write to a directory
    assert!(result.is_err());
}

#[tokio::test]
async fn test_local_file_saver_large_write() {
    use fetchkit::file_saver::FileSaver;

    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());

    // 1MB write
    let data = vec![0xABu8; 1_000_000];
    let result = saver.save("large.bin", &data).await.unwrap();
    assert_eq!(result.bytes_written, 1_000_000);

    let saved = std::fs::read(dir.path().join("large.bin")).unwrap();
    assert_eq!(saved.len(), 1_000_000);
    assert!(saved.iter().all(|&b| b == 0xAB));
}

// ---------------------------------------------------------------------------
// Default Fetcher::fetch_to_file (used by non-DefaultFetcher fetchers)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_via_default_fetch_to_file_trait_method() {
    // Tests the default Fetcher::fetch_to_file implementation, which calls
    // fetch() then saves the string content. This path is used by fetchers
    // that don't override fetch_to_file (e.g. GitHubRepoFetcher).
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());

    let mock = MockServer::start().await;
    // Return HTML that will be converted to markdown by DefaultFetcher
    Mock::given(method("GET"))
        .and(path("/page"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string("<html><body><h1>Title</h1><p>Body text</p></body></html>")
                .insert_header("content-type", "text/html"),
        )
        .mount(&mock)
        .await;

    let tool = Tool::builder()
        .block_private_ips(false)
        .enable_save_to_file(true)
        .enable_markdown(true)
        .build();

    // save_to_file with HTML content: DefaultFetcher::fetch_to_file handles
    // this directly (binary-aware path), but confirms the full save pipeline
    let req = FetchRequest::new(format!("{}/page", mock.uri())).save_to_file("page_content.txt");
    let resp = tool.execute_with_saver(req, Some(&saver)).await.unwrap();

    assert_eq!(resp.status_code, 200);
    assert!(resp.saved_path.is_some());
    assert!(resp.bytes_written.unwrap() > 0);
    assert!(resp.content.is_none());

    // File should exist with some content
    let content = std::fs::read_to_string(dir.path().join("page_content.txt")).unwrap();
    assert!(!content.is_empty());
}

// ---------------------------------------------------------------------------
// Truncated binary save (slow binary download)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_save_binary_with_slow_response_truncated() {
    // Verifies that a binary download with a delayed response times out
    // gracefully and either saves partial content or returns an error
    let dir = tempfile::tempdir().unwrap();
    let saver = saver_in(dir.path());
    let tool = tool_with_save();

    let mock = MockServer::start().await;
    // Respond with binary content-type but delay the response
    Mock::given(method("GET"))
        .and(path("/big.bin"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_bytes(vec![0xDE, 0xAD, 0xBE, 0xEF])
                .insert_header("content-type", "application/octet-stream")
                .set_delay(Duration::from_secs(45)),
        )
        .mount(&mock)
        .await;

    let result = tokio::time::timeout(Duration::from_secs(10), async {
        let req = FetchRequest::new(format!("{}/big.bin", mock.uri())).save_to_file("big.bin");
        tool.execute_with_saver(req, Some(&saver)).await
    })
    .await;

    // Must not hang
    assert!(result.is_ok(), "Binary save with slow server must not hang");
    // Inner result is expected to be an error (connect/first-byte timeout)
}

// ---------------------------------------------------------------------------
// Description/llmtxt reflects enabled state
// ---------------------------------------------------------------------------

#[test]
fn test_description_reflects_save_enabled() {
    let default_tool = Tool::default();
    assert!(!default_tool.description().contains("save_to_file"));
    assert!(!default_tool.llmtxt().contains("save_to_file"));

    let save_tool = tool_with_save();
    assert!(save_tool.description().contains("save_to_file"));
    assert!(save_tool.llmtxt().contains("save_to_file"));
}