winx-code-agent 0.2.312

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

use std::sync::Arc;
use tempfile::TempDir;
use tokio::sync::Mutex;

use winx_code_agent::errors::{Result, WinxError};
use winx_code_agent::state::bash_state::BashState;
use winx_code_agent::types::{FileWriteOrEdit, Initialize, InitializeType, ModeName, ReadFiles};

const TEST_THREAD_ID: &str = "i2238";

/// Helper function to create an initialized bash state with a specific thread ID
async fn create_initialized_state(
    temp_dir: &TempDir,
    thread_id: &str,
) -> Result<Arc<Mutex<Option<BashState>>>> {
    let bash_state_arc: Arc<Mutex<Option<BashState>>> = Arc::new(Mutex::new(None));

    let init = Initialize {
        init_type: InitializeType::FirstCall,
        mode_name: ModeName::Wcgw,
        any_workspace_path: std::fs::canonicalize(temp_dir.path())?.to_string_lossy().to_string(),
        thread_id: thread_id.to_string(),
        code_writer_config: None,
        initial_files_to_read: vec![],
        task_id_to_resume: String::new(),
    };

    winx_code_agent::tools::initialize::handle_tool_call(&bash_state_arc, init).await?;

    Ok(bash_state_arc)
}

async fn read_file_before_edit(
    bash_state_arc: &Arc<Mutex<Option<BashState>>>,
    file_path: &std::path::Path,
) -> Result<()> {
    let read_files = ReadFiles {
        file_paths: vec![file_path.to_string_lossy().to_string()],
        start_line_nums: vec![None],
        end_line_nums: vec![None],
    };

    winx_code_agent::tools::read_files::handle_tool_call(bash_state_arc, read_files).await?;
    Ok(())
}

// ==================== Test 1: Create New File (percentage > 50) ====================

#[tokio::test(flavor = "multi_thread")]
async fn test_create_new_file_full_write() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, TEST_THREAD_ID).await?;

    let file_path = temp_dir.path().join("new_file.py");
    let content = r#"#!/usr/bin/env python3
"""A simple test module."""

def greet(name: str) -> str:
    """Return a greeting message."""
    return f"Hello, {name}!"

def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

if __name__ == "__main__":
    print(greet("World"))
    print(add(2, 3))
"#;

    let file_write = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: content.to_string(),
        thread_id: TEST_THREAD_ID.to_string(),
    };

    let response =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write)
            .await?;

    // Verify response indicates success
    assert!(
        response.contains("Successfully") || response.contains("wrote"),
        "Expected success message, got: {response}"
    );

    // Verify file exists and content matches
    assert!(file_path.exists(), "File was not created");

    let actual_content = std::fs::read_to_string(&file_path)?;
    assert_eq!(actual_content, content, "File content does not match");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_create_new_rust_file() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "test-rust-create").await?;

    let file_path = temp_dir.path().join("lib.rs");
    let content = r"//! A test library module.

/// Add two numbers together.
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// Subtract b from a.
pub fn subtract(a: i32, b: i32) -> i32 {
    a - b
}

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

    #[test]
    fn test_add() {
        assert_eq!(add(2, 3), 5);
    }

    #[test]
    fn test_subtract() {
        assert_eq!(subtract(5, 3), 2);
    }
}
";

    let file_write = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: content.to_string(),
        thread_id: "test-rust-create".to_string(),
    };

    let response =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write)
            .await?;

    assert!(
        response.contains("Successfully") || response.contains("wrote"),
        "Expected success message, got: {response}"
    );

    // Verify file content
    let actual = std::fs::read_to_string(&file_path)?;
    assert!(actual.contains("pub fn add"));
    assert!(actual.contains("pub fn subtract"));
    assert!(actual.contains("#[cfg(test)]"));

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_full_write_reports_syntax_warning() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "syntax-warning").await?;

    let file_path = temp_dir.path().join("bad.json");
    let file_write = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: "{".to_string(),
        thread_id: "syntaxwarning".to_string(),
    };

    let response =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write)
            .await?;

    assert!(response.contains("Successfully wrote"));
    assert!(response.contains("Syntax warning"));

    Ok(())
}

// ==================== Test 2: Edit with SEARCH/REPLACE (percentage <= 50) ====================

#[tokio::test(flavor = "multi_thread")]
async fn test_edit_with_search_replace() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "test-search-replace").await?;

    // First create a file
    let file_path = temp_dir.path().join("edit_test.py");
    let initial_content = r#"#!/usr/bin/env python3
"""A simple test module."""

def greet(name: str) -> str:
    """Return a greeting message."""
    return f"Hello, {name}!"

def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b
"#;

    // Write the initial file
    let file_write = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: initial_content.to_string(),
        thread_id: "test-search-replace".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write)
        .await?;

    // Read the file to add it to whitelist
    let read_files = ReadFiles {
        file_paths: vec![file_path.to_string_lossy().to_string()],
        start_line_nums: vec![None],
        end_line_nums: vec![None],
    };

    winx_code_agent::tools::read_files::handle_tool_call(&bash_state_arc, read_files).await?;

    // Now edit with SEARCH/REPLACE
    let search_replace = r#"<<<<<<< SEARCH
def greet(name: str) -> str:
    """Return a greeting message."""
    return f"Hello, {name}!"
=======
def greet(name: str, formal: bool = False) -> str:
    """Return a greeting message."""
    if formal:
        return f"Good day, {name}!"
    return f"Hello, {name}!"
>>>>>>> REPLACE"#;

    let file_edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 30,
        text_or_search_replace_blocks: search_replace.to_string(),
        thread_id: "test-search-replace".to_string(),
    };

    let response =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_edit)
            .await?;

    assert!(
        response.contains("Successfully") || response.contains("edited"),
        "Expected success message, got: {response}"
    );

    // Verify the edit was applied
    let final_content = std::fs::read_to_string(&file_path)?;

    assert!(final_content.contains("formal: bool = False"), "Type hint not added");
    assert!(final_content.contains("Good day"), "New code not present");
    assert!(final_content.contains("if formal:"), "Conditional not added");

    Ok(())
}

// ==================== Test 3: Whitelist Enforcement ====================

#[tokio::test(flavor = "multi_thread")]
async fn test_whitelist_enforcement_edit_without_read() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "test-whitelist").await?;

    // Create a file OUTSIDE the tool (simulating external file)
    let file_path = temp_dir.path().join("unread_file.txt");
    std::fs::write(&file_path, "Original content here.\n")?;

    // Try to edit WITHOUT reading first
    let search_replace = r"<<<<<<< SEARCH
Original content here.
=======
Modified content here.
>>>>>>> REPLACE";

    let file_edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 30,
        text_or_search_replace_blocks: search_replace.to_string(),
        thread_id: "test-whitelist".to_string(),
    };

    let result =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_edit)
            .await;

    // This should fail or return an error about needing to read first
    match result {
        Ok(response) => {
            // In wcgw mode with full permissions, it might work
            // But there should be some indication about whitelist

            // Verify the file was modified if it succeeded
            let content = std::fs::read_to_string(&file_path)?;
            if content.contains("Modified content") {}
        }
        Err(e) => {
            // Expected error about whitelist or reading file first
            let error_msg = e.to_string().to_lowercase();
            assert!(
                error_msg.contains("read")
                    || error_msg.contains("whitelist")
                    || error_msg.contains("access"),
                "Expected whitelist error, got: {e}"
            );
        }
    }

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
#[ignore = "race condition on macOS CI - whitelist async update timing"]
async fn test_whitelist_after_read() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "test-whitelist-read").await?;

    // Create a file OUTSIDE the tool
    let file_path = temp_dir.path().join("to_be_read.txt");
    std::fs::write(&file_path, "Original line one.\nOriginal line two.\n")?;

    // Read the file first (adds to whitelist)
    let read_files = ReadFiles {
        file_paths: vec![file_path.to_string_lossy().to_string()],
        start_line_nums: vec![None],
        end_line_nums: vec![None],
    };

    winx_code_agent::tools::read_files::handle_tool_call(&bash_state_arc, read_files).await?;

    // Give time for async whitelist update
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // Now edit should work
    let search_replace = r"<<<<<<< SEARCH
Original line one.
=======
Modified line one.
>>>>>>> REPLACE";

    let file_edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 30,
        text_or_search_replace_blocks: search_replace.to_string(),
        thread_id: "test-whitelist-read".to_string(),
    };

    let response =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_edit)
            .await?;

    assert!(
        response.contains("Successfully") || response.contains("edited"),
        "Expected success after reading file, got: {response}"
    );

    let content = std::fs::read_to_string(&file_path)?;
    assert!(content.contains("Modified line one"), "Edit was not applied");

    Ok(())
}

// ==================== Test 4: Multiple SEARCH/REPLACE Blocks ====================

#[tokio::test(flavor = "multi_thread")]
async fn test_multiple_search_replace_blocks() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "test-multi-blocks").await?;

    // Create a file with multiple functions
    let file_path = temp_dir.path().join("calculator.py");
    let initial_content = r#"#!/usr/bin/env python3
"""Multi-edit test file."""

class Calculator:
    """Simple calculator class."""

    def add(self, a, b):
        """Add two numbers."""
        return a + b

    def subtract(self, a, b):
        """Subtract b from a."""
        return a - b

    def multiply(self, a, b):
        """Multiply two numbers."""
        return a * b

if __name__ == "__main__":
    calc = Calculator()
    print(calc.add(1, 2))
"#;

    // Write initial file
    let file_write = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: initial_content.to_string(),
        thread_id: "test-multi-blocks".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write)
        .await?;

    // Read file to populate whitelist
    let read_files = ReadFiles {
        file_paths: vec![file_path.to_string_lossy().to_string()],
        start_line_nums: vec![None],
        end_line_nums: vec![None],
    };

    winx_code_agent::tools::read_files::handle_tool_call(&bash_state_arc, read_files).await?;

    // Apply multiple SEARCH/REPLACE blocks
    let multi_search_replace = r#"<<<<<<< SEARCH
    def add(self, a, b):
        """Add two numbers."""
        return a + b
=======
    def add(self, a: int, b: int) -> int:
        """Add two numbers together."""
        return a + b
>>>>>>> REPLACE
<<<<<<< SEARCH
    def subtract(self, a, b):
        """Subtract b from a."""
        return a - b
=======
    def subtract(self, a: int, b: int) -> int:
        """Subtract second number from first."""
        return a - b
>>>>>>> REPLACE
<<<<<<< SEARCH
    def multiply(self, a, b):
        """Multiply two numbers."""
        return a * b
=======
    def multiply(self, a: int, b: int) -> int:
        """Multiply two numbers together."""
        return a * b

    def divide(self, a: int, b: int) -> float:
        """Divide first number by second."""
        if b == 0:
            raise ValueError("Cannot divide by zero")
        return a / b
>>>>>>> REPLACE"#;

    let file_edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 40,
        text_or_search_replace_blocks: multi_search_replace.to_string(),
        thread_id: "test-multi-blocks".to_string(),
    };

    let response =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_edit)
            .await?;

    assert!(
        response.contains("Successfully") || response.contains("edited"),
        "Expected success message, got: {response}"
    );

    // Verify all edits were applied
    let final_content = std::fs::read_to_string(&file_path)?;

    // Check for all expected changes
    let checks = [
        (final_content.contains("a: int, b: int) -> int"), "Type hints added to add()"),
        (final_content.contains("Subtract second number"), "Docstring updated in subtract()"),
        (
            final_content.contains("Multiply two numbers together"),
            "Docstring updated in multiply()",
        ),
        (final_content.contains("def divide"), "New divide() method added"),
        (final_content.contains("Cannot divide by zero"), "Divide error handling present"),
    ];

    let mut all_passed = true;
    for (check, description) in &checks {
        if *check {
        } else {
            all_passed = false;
        }
    }

    assert!(all_passed, "Not all edits were applied.\nFinal content:\n{final_content}");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_search_replace_matches_with_indentation_tolerance() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "indent-tolerance").await?;

    let file_path = temp_dir.path().join("indent.py");
    std::fs::write(
        &file_path,
        "  class Example:\n      def method(self):\n          print('hello')\n",
    )?;
    read_file_before_edit(&bash_state_arc, &file_path).await?;

    let edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 10,
        text_or_search_replace_blocks: r"<<<<<<< SEARCH
class Example:
    def method(self):
        print('hello')
=======
class Example:
    def another_method(self):
        print('world')
>>>>>>> REPLACE"
            .to_string(),
        thread_id: "indenttolerance".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, edit).await?;

    let content = std::fs::read_to_string(&file_path)?;
    assert_eq!(
        content,
        "  class Example:\n      def another_method(self):\n          print('world')\n"
    );

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_search_replace_matches_across_extra_blank_lines() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "blank-lines").await?;

    let file_path = temp_dir.path().join("blank_lines.txt");
    std::fs::write(&file_path, "alpha\n\nbeta\ngamma\n")?;
    read_file_before_edit(&bash_state_arc, &file_path).await?;

    let edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 10,
        text_or_search_replace_blocks: r"<<<<<<< SEARCH
alpha
beta
=======
alpha
beta-updated
>>>>>>> REPLACE"
            .to_string(),
        thread_id: "blanklines".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, edit).await?;

    let content = std::fs::read_to_string(&file_path)?;
    assert_eq!(content, "alpha\nbeta-updated\ngamma\n");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_search_replace_normalizes_common_unicode_mistakes() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "unicode-mistakes").await?;

    let file_path = temp_dir.path().join("unicode.txt");
    std::fs::write(&file_path, "println!(\"hello - world...\");\n")?;
    read_file_before_edit(&bash_state_arc, &file_path).await?;

    let edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 10,
        text_or_search_replace_blocks: "<<<<<<< SEARCH\nprintln!(\u{201c}hello \u{2014} world\u{2026}\u{201d});\n=======\nprintln!(\"updated\");\n>>>>>>> REPLACE"
            .to_string(),
        thread_id: "unicodemistakes".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, edit).await?;

    let content = std::fs::read_to_string(&file_path)?;
    assert_eq!(content, "println!(\"updated\");\n");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_search_replace_removes_readfiles_line_numbers() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "line-nums").await?;

    let file_path = temp_dir.path().join("line_nums.rs");
    std::fs::write(&file_path, "fn main() {\n    println!(\"old\");\n}\n")?;
    read_file_before_edit(&bash_state_arc, &file_path).await?;

    let edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 10,
        text_or_search_replace_blocks: r#"<<<<<<< SEARCH
1 fn main() {
2     println!("old");
3 }
=======
1 fn main() {
2     println!("new");
3 }
>>>>>>> REPLACE"#
            .to_string(),
        thread_id: "linenums".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, edit).await?;

    let content = std::fs::read_to_string(&file_path)?;
    assert_eq!(content, "fn main() {\n    println!(\"new\");\n}\n");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_search_replace_uses_surrounding_blocks_to_disambiguate() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "context-match").await?;

    let file_path = temp_dir.path().join("context.txt");
    std::fs::write(&file_path, "A\nB\nC\nB\n")?;
    read_file_before_edit(&bash_state_arc, &file_path).await?;

    let edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 10,
        text_or_search_replace_blocks: r"<<<<<<< SEARCH
A
=======
A
>>>>>>> REPLACE
<<<<<<< SEARCH
B
=======
B_MODIFIED_FIRST
>>>>>>> REPLACE
<<<<<<< SEARCH
C
=======
C
>>>>>>> REPLACE"
            .to_string(),
        thread_id: "contextmatch".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, edit).await?;

    let content = std::fs::read_to_string(&file_path)?;
    assert_eq!(content, "A\nB_MODIFIED_FIRST\nC\nB\n");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_search_replace_applies_unordered_independent_blocks() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "unordered-blocks").await?;

    let file_path = temp_dir.path().join("unordered.txt");
    std::fs::write(&file_path, "A\nB\nC\nB\n")?;
    read_file_before_edit(&bash_state_arc, &file_path).await?;

    let edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 10,
        text_or_search_replace_blocks: r"<<<<<<< SEARCH
C
=======
CPrime
>>>>>>> REPLACE
<<<<<<< SEARCH
A
=======
A_MODIFIED
>>>>>>> REPLACE"
            .to_string(),
        thread_id: "unorderedblocks".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, edit).await?;

    let content = std::fs::read_to_string(&file_path)?;
    assert_eq!(content, "A_MODIFIED\nB\nCPrime\nB\n");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_search_replace_ambiguous_match_does_not_write() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "ambiguous-match").await?;

    let file_path = temp_dir.path().join("ambiguous.txt");
    let original = "A\nB\nB\n";
    std::fs::write(&file_path, original)?;
    read_file_before_edit(&bash_state_arc, &file_path).await?;

    let edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 10,
        text_or_search_replace_blocks: r"<<<<<<< SEARCH
B
=======
B_CHANGED
>>>>>>> REPLACE"
            .to_string(),
        thread_id: "ambiguousmatch".to_string(),
    };

    let result =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, edit).await;

    assert!(matches!(result, Err(WinxError::SearchBlockAmbiguous { .. })));
    assert_eq!(std::fs::read_to_string(&file_path)?, original);

    Ok(())
}

// ==================== Additional Edge Case Tests ====================

#[tokio::test(flavor = "multi_thread")]
async fn test_search_replace_not_found() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "test-not-found").await?;

    // Create a file
    let file_path = temp_dir.path().join("test.txt");
    let initial_content = "Line one\nLine two\nLine three\n";

    let file_write = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: initial_content.to_string(),
        thread_id: "test-not-found".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write)
        .await?;

    // Read to populate whitelist
    let read_files = ReadFiles {
        file_paths: vec![file_path.to_string_lossy().to_string()],
        start_line_nums: vec![None],
        end_line_nums: vec![None],
    };

    winx_code_agent::tools::read_files::handle_tool_call(&bash_state_arc, read_files).await?;

    // Try to edit with non-existent search block
    let search_replace = r"<<<<<<< SEARCH
This text does not exist in the file
=======
Replacement text
>>>>>>> REPLACE";

    let file_edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 30,
        text_or_search_replace_blocks: search_replace.to_string(),
        thread_id: "test-not-found".to_string(),
    };

    let result =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_edit)
            .await;

    // Should fail because search block was not found
    assert!(result.is_err(), "Expected error for non-existent search block");

    let error_msg = result.err().map_or_else(String::new, |error| error.to_string().to_lowercase());
    assert!(
        error_msg.contains("not found") || error_msg.contains("search"),
        "Expected 'not found' error, got: {error_msg}"
    );

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_empty_replacement() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "test-empty-replace").await?;

    // Create a file with some content to remove
    let file_path = temp_dir.path().join("remove_test.txt");
    let initial_content = "Keep this line\nRemove this line\nKeep this too\n";

    let file_write = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: initial_content.to_string(),
        thread_id: "test-empty-replace".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write)
        .await?;

    // Read to populate whitelist
    let read_files = ReadFiles {
        file_paths: vec![file_path.to_string_lossy().to_string()],
        start_line_nums: vec![None],
        end_line_nums: vec![None],
    };

    winx_code_agent::tools::read_files::handle_tool_call(&bash_state_arc, read_files).await?;

    // Edit with empty replacement (to remove a line)
    let search_replace = r"<<<<<<< SEARCH
Remove this line
=======
>>>>>>> REPLACE";

    let file_edit = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 30,
        text_or_search_replace_blocks: search_replace.to_string(),
        thread_id: "test-empty-replace".to_string(),
    };

    let response =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_edit)
            .await?;

    assert!(
        response.contains("Successfully") || response.contains("edited"),
        "Expected success message, got: {response}"
    );

    // Verify line was removed
    let final_content = std::fs::read_to_string(&file_path)?;
    assert!(!final_content.contains("Remove this line"), "Line was not removed");
    assert!(final_content.contains("Keep this line"), "Other content was incorrectly removed");
    assert!(final_content.contains("Keep this too"), "Other content was incorrectly removed");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_overwrite_existing_file_full_content() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "test-overwrite").await?;

    // Create a file
    let file_path = temp_dir.path().join("overwrite.txt");
    let initial_content = "Original content";

    let file_write = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: initial_content.to_string(),
        thread_id: "test-overwrite".to_string(),
    };

    winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write)
        .await?;

    // Read to populate whitelist
    let read_files = ReadFiles {
        file_paths: vec![file_path.to_string_lossy().to_string()],
        start_line_nums: vec![None],
        end_line_nums: vec![None],
    };

    winx_code_agent::tools::read_files::handle_tool_call(&bash_state_arc, read_files).await?;

    // Overwrite with new content (percentage > 50)
    let new_content = "Completely new content\nWith multiple lines\nAnd more text";

    let file_write2 = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: new_content.to_string(),
        thread_id: "test-overwrite".to_string(),
    };

    let response =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write2)
            .await?;

    assert!(
        response.contains("Successfully") || response.contains("wrote"),
        "Expected success message, got: {response}"
    );

    // Verify new content
    let final_content = std::fs::read_to_string(&file_path)?;
    assert!(!final_content.contains("Original"), "Old content still present");
    assert_eq!(final_content, new_content, "Content does not match new content");

    Ok(())
}

#[tokio::test(flavor = "multi_thread")]
async fn test_thread_id_mismatch() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let bash_state_arc = create_initialized_state(&temp_dir, "correct-thread-id").await?;

    let file_path = temp_dir.path().join("test.txt");

    // Try to write with wrong thread ID
    let file_write = FileWriteOrEdit {
        file_path: file_path.to_string_lossy().to_string(),
        percentage_to_change: 100,
        text_or_search_replace_blocks: "Test content".to_string(),
        thread_id: "wrong-thread-id".to_string(),
    };

    let result =
        winx_code_agent::tools::file_write_or_edit::handle_tool_call(&bash_state_arc, file_write)
            .await;

    // Should fail due to thread ID mismatch
    assert!(result.is_err(), "Expected error for thread ID mismatch");

    let error_msg = result.err().map_or_else(String::new, |error| error.to_string().to_lowercase());
    assert!(
        error_msg.contains("thread") || error_msg.contains("mismatch") || error_msg.contains("id"),
        "Expected thread ID mismatch error, got: {error_msg}"
    );

    Ok(())
}