mxc-sdk 1.1.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Pipe relay primitives used by the IsolationSession backend to bridge
//! wxc-exec's stdio with the agent process's pipe handles across the
//! desktop-session boundary.
//!
//! Two relay variants:
//! - [`create_relay_thread`] — cancellable and progress-reporting; used for
//!   stdout / stderr and pipe/file-backed stdin. Ends at EOF or when its
//!   [`PipeReadCanceller`] fires.
//! - [`create_relay_thread_with_stop`] — stop-event-aware; used for
//!   console-backed stdin when the agent can exit while the local stdin handle
//!   remains open.

use std::io::Read;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::mxc_common::error::WxcError;
use crate::mxc_common::process_util::{InterruptiblePipeReader, OwnedHandle, PipeReadCanceller};
use crate::mxc_common::sandbox_process::StreamCloser;

use windows::Win32::Foundation::{
    DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows::Win32::Storage::FileSystem::{FlushFileBuffers, ReadFile, WriteFile};
use windows::Win32::System::Threading::{
    CreateThread, GetCurrentProcess, WaitForMultipleObjects, THREAD_CREATION_FLAGS,
};

const BUFFER_SIZE: u32 = 4096;
const DRAIN_POLL_INTERVAL: Duration = Duration::from_millis(200);

pub(super) fn duplicate_handle(handle: HANDLE) -> Result<OwnedHandle, WxcError> {
    let mut duplicated = HANDLE::default();
    unsafe {
        DuplicateHandle(
            GetCurrentProcess(),
            handle,
            GetCurrentProcess(),
            &mut duplicated,
            0,
            false,
            DUPLICATE_SAME_ACCESS,
        )
    }
    .map_err(|e| WxcError::Process(format!("DuplicateHandle for pipe relay failed: {}", e)))?;
    Ok(OwnedHandle::new(duplicated))
}

/// Parameters for a pipe relay thread. The thread reads `reader` and writes
/// every chunk to `h_write`, flushing after each write.
///
/// `progress_bytes` is bumped after each successful destination write. The
/// teardown path polls it to distinguish a healthy slow drain from a relay that
/// is stuck because a child process still holds the pipe open.
///
/// # Ownership
/// Ownership of this struct transfers to the relay thread, which frees it on
/// exit. The caller must **not** keep or free it. Both handles are owned.
struct PipeRelayParams {
    reader: InterruptiblePipeReader,
    h_write: OwnedHandle,
    progress_bytes: Arc<AtomicU64>,
}

pub(super) struct PipeRelay {
    thread: OwnedHandle,
    canceller: PipeReadCanceller,
    progress_bytes: Arc<AtomicU64>,
}

impl PipeRelay {
    pub(super) fn into_thread_and_canceller(self) -> (OwnedHandle, PipeReadCanceller) {
        (self.thread, self.canceller)
    }

    pub(super) fn thread(&self) -> &OwnedHandle {
        &self.thread
    }

    pub(super) fn cancel_read(&self) {
        self.canceller.close();
    }

    fn progress_bytes(&self) -> u64 {
        self.progress_bytes.load(Ordering::Relaxed)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum OutputRelayDrain {
    Drained,
    GaveUp,
}

/// Thread procedure for relaying data between two handles.
///
/// # Safety
/// `param` must be the `Box::into_raw` pointer produced by
/// [`create_relay_thread`], passed exactly once.
unsafe extern "system" fn pipe_relay_thread_proc(param: *mut core::ffi::c_void) -> u32 {
    // Reclaim ownership at entry so every exit path below frees exactly once,
    // and so the params outlive the thread's use of them regardless of what
    // the spawning frame does. This is what makes an unjoined thread sound.
    let mut params = unsafe { Box::from_raw(param as *mut PipeRelayParams) };
    let mut buffer = [0u8; BUFFER_SIZE as usize];

    loop {
        let bytes_read = match params.reader.read(&mut buffer) {
            Ok(0) | Err(_) => break,
            Ok(n) => n,
        };

        let mut bytes_written = 0u32;
        if WriteFile(
            params.h_write.get(),
            Some(&buffer[..bytes_read]),
            Some(&mut bytes_written),
            None,
        )
        .is_err()
            || bytes_written as usize != bytes_read
        {
            break;
        }
        params
            .progress_bytes
            .fetch_add(bytes_written as u64, Ordering::Relaxed);

        let _ = FlushFileBuffers(params.h_write.get());
    }

    0
}

/// Create a relay thread via `CreateThread`, returning a `PipeRelay` that
/// wraps the thread handle, a read canceller, and a shared progress counter.
///
/// The thread reads a **duplicate** of `h_read` and writes a **duplicate** of
/// `h_write`, so releasing either source handle cannot invalidate it, and
/// joining is not required for memory safety — an abandoned relay thread reads
/// memory and handles it owns.
pub(super) unsafe fn create_relay_thread(
    h_read: HANDLE,
    h_write: HANDLE,
) -> Result<PipeRelay, WxcError> {
    let reader = InterruptiblePipeReader::new(duplicate_handle(h_read)?);
    let canceller = reader.canceller();
    let progress_bytes = Arc::new(AtomicU64::new(0));
    let raw = Box::into_raw(Box::new(PipeRelayParams {
        reader,
        h_write: duplicate_handle(h_write)?,
        progress_bytes: Arc::clone(&progress_bytes),
    }));
    match unsafe {
        CreateThread(
            None,
            0,
            Some(pipe_relay_thread_proc),
            Some(raw as *const core::ffi::c_void),
            THREAD_CREATION_FLAGS(0),
            None,
        )
    } {
        Ok(handle) => Ok(PipeRelay {
            thread: OwnedHandle::new(handle),
            canceller,
            progress_bytes,
        }),
        Err(e) => {
            // The thread never started, so nothing will run the proc that
            // frees the box. Reclaim it here or it leaks.
            drop(unsafe { Box::from_raw(raw) });
            Err(WxcError::Process(format!(
                "CreateThread for pipe relay failed: {}",
                e
            )))
        }
    }
}

/// Wait for output relays to finish while they are still making progress.
///
/// Each successful output write restarts the idle timeout, but not the overall
/// timeout. On timeout, reads cancel. Blocked writes or flushes cannot be
/// cancelled, so callers must also limit how long they wait for the relay
/// threads to exit.
pub(super) fn drain_output_relays_within(
    relays: &[&PipeRelay],
    idle_window: Duration,
    absolute_cap: Duration,
) -> Result<OutputRelayDrain, WxcError> {
    if relays.is_empty() {
        return Ok(OutputRelayDrain::Drained);
    }

    let handles: Vec<HANDLE> = relays.iter().map(|relay| relay.thread().get()).collect();
    let started = Instant::now();
    let mut idle_started = started;
    let mut last_progress = total_progress(relays);

    loop {
        let now = Instant::now();
        let progress = total_progress(relays);
        if progress != last_progress {
            last_progress = progress;
            idle_started = now;
        }

        let idle_elapsed = now.saturating_duration_since(idle_started);
        let total_elapsed = now.saturating_duration_since(started);
        let remaining_idle = idle_window.saturating_sub(idle_elapsed);
        let remaining_cap = absolute_cap.saturating_sub(total_elapsed);
        let wait_for = DRAIN_POLL_INTERVAL.min(remaining_idle).min(remaining_cap);
        // SAFETY: relays own all handles throughout the wait.
        match unsafe { WaitForMultipleObjects(&handles, true, wait_for.as_millis() as u32) } {
            WAIT_OBJECT_0 => return Ok(OutputRelayDrain::Drained),
            WAIT_TIMEOUT => {
                if idle_elapsed >= idle_window || total_elapsed >= absolute_cap {
                    for relay in relays {
                        relay.cancel_read();
                    }
                    return Ok(OutputRelayDrain::GaveUp);
                }
            }
            _ => {
                return Err(WxcError::Process(format!(
                    "WaitForMultipleObjects for output relays failed: {}",
                    std::io::Error::last_os_error()
                )));
            }
        }
    }
}

fn total_progress(relays: &[&PipeRelay]) -> u64 {
    relays
        .iter()
        .map(|relay| relay.progress_bytes())
        .sum::<u64>()
}

// ── Stop-event-aware pipe relay ────────────────────────────────────────────
//
// Used for the IsolationSession stdin relay when wxc-exec's stdin is a console
// handle and the agent process can exit naturally while that handle remains
// open. Without an external signal the relay sits in `ReadFile` forever.
//
// `CancelSynchronousIo` is the obvious alternative but has documented edge
// cases on console handles, and wxc-exec's stdin is a console handle in the
// dominant `spawnSandbox` (node-pty) and direct-cmd cases. The output relays
// read anonymous pipes, where that objection does not apply, and use
// [`PipeReadCanceller`] instead.
//
// `h_read` MUST be a waitable handle whose signal state correctly reflects
// "input available" (a console input handle is the canonical case; events
// also work). Anonymous pipe handles are NOT supported: they appear "always
// signalled when open", so the wait returns immediately, the relay enters
// `ReadFile`, and from there the stop event cannot interrupt it. For
// pipe-backed stdin, use the simpler EOF-driven
// `create_relay_thread` and rely on natural EOF or its canceller for cleanup.

/// Parameters for a stop-event-aware relay thread. The thread loops
/// `WaitForMultipleObjects({h_stop_event, h_read})`; copies a chunk when
/// `h_read` is ready; exits when `h_stop_event` is signalled, on read EOF,
/// on read error, on write error, or on `WaitForMultipleObjects` failure.
///
/// `h_stop_event` should be a manual-reset event so the relay observes it
/// even if signalled before the next loop iteration.
///
/// `h_read` must be a waitable handle (console input, event). Anonymous
/// pipes are not supported — see module-level comment above.
///
/// # Ownership
/// Ownership of this struct transfers to the relay thread, which frees it on
/// exit. The caller must **not** keep or free it. `h_write` and `h_stop_event`
/// are owned duplicates; `h_read` is borrowed — see the safety contract on
/// [`create_relay_thread_with_stop`].
pub(super) struct PipeRelayWithStopParams {
    pub h_read: HANDLE,
    pub h_write: OwnedHandle,
    pub h_stop_event: OwnedHandle,
}

/// Thread procedure for a stop-event-aware relay.
///
/// # Safety
/// `param` must be the `Box::into_raw` pointer produced by
/// [`create_relay_thread_with_stop`], passed exactly once.
unsafe extern "system" fn pipe_relay_with_stop_thread_proc(param: *mut core::ffi::c_void) -> u32 {
    // Reclaim ownership at entry — see `pipe_relay_thread_proc`.
    let params = unsafe { Box::from_raw(param as *mut PipeRelayWithStopParams) };
    let mut buffer = [0u8; BUFFER_SIZE as usize];
    let wait_handles = [params.h_stop_event.get(), params.h_read];

    loop {
        let wait_result = WaitForMultipleObjects(&wait_handles, false, u32::MAX);
        // `WAIT_OBJECT_0 + 1` means `h_read` signalled (data available or EOF).
        // Anything else (stop event = `WAIT_OBJECT_0`, `WAIT_FAILED`, etc.) → exit.
        if wait_result.0 != WAIT_OBJECT_0.0 + 1 {
            break;
        }

        let mut bytes_read = 0u32;
        if ReadFile(
            params.h_read,
            Some(&mut buffer),
            Some(&mut bytes_read),
            None,
        )
        .is_err()
            || bytes_read == 0
        {
            break;
        }

        let mut bytes_written = 0u32;
        if WriteFile(
            params.h_write.get(),
            Some(&buffer[..bytes_read as usize]),
            Some(&mut bytes_written),
            None,
        )
        .is_err()
            || bytes_written != bytes_read
        {
            break;
        }

        let _ = FlushFileBuffers(params.h_write.get());
    }

    0
}

/// Create a stop-event-aware relay thread via `CreateThread`. Returns the
/// thread HANDLE wrapped in `OwnedHandle`.
///
/// Takes `params` by value and moves it to the heap for the thread to own and
/// free — see [`create_relay_thread`].
///
/// # Safety
/// `h_read` is borrowed and must remain valid until the thread exits.
pub(super) unsafe fn create_relay_thread_with_stop(
    params: PipeRelayWithStopParams,
) -> Result<OwnedHandle, WxcError> {
    let raw = Box::into_raw(Box::new(params));
    match unsafe {
        CreateThread(
            None,
            0,
            Some(pipe_relay_with_stop_thread_proc),
            Some(raw as *const core::ffi::c_void),
            THREAD_CREATION_FLAGS(0),
            None,
        )
    } {
        Ok(handle) => Ok(OwnedHandle::new(handle)),
        Err(e) => {
            drop(unsafe { Box::from_raw(raw) });
            Err(WxcError::Process(format!(
                "CreateThread for stop-aware pipe relay failed: {}",
                e
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::process_util::{create_std_pipes, read_from_pipe, SendOwnedHandle};
    use crate::mxc_common::string_util;
    use windows::Win32::Foundation::{ERROR_BROKEN_PIPE, ERROR_NO_DATA, WAIT_TIMEOUT};
    use windows::Win32::System::Pipes::CreatePipe;
    use windows::Win32::System::Threading::{
        CreateEventW, CreateProcessW, SetEvent, WaitForSingleObject, CREATE_NO_WINDOW,
        PROCESS_INFORMATION, STARTF_USESTDHANDLES, STARTUPINFOW,
    };
    use windows_core::{PCWSTR, PWSTR};

    /// Creates a non-inheritable pipe pair for use in tests. Unlike
    /// `create_std_pipes`, neither end is marked inheritable, which prevents
    /// handles from leaking into child processes spawned by other tests
    /// running concurrently (cargo test runs in parallel). Leaked write-ends
    /// would keep pipes open and cause `read_from_pipe` to block.
    fn create_test_pipes() -> (OwnedHandle, OwnedHandle) {
        let mut h_read = HANDLE::default();
        let mut h_write = HANDLE::default();
        unsafe {
            CreatePipe(&mut h_read, &mut h_write, None, 0).unwrap();
        }
        (OwnedHandle::new(h_read), OwnedHandle::new(h_write))
    }

    /// Helper: create a manual-reset, initially-unsignalled event for tests.
    fn create_test_stop_event() -> OwnedHandle {
        unsafe {
            let h = CreateEventW(None, true, false, PCWSTR::null()).unwrap();
            OwnedHandle::new(h)
        }
    }

    /// Helper: spawn a child process with specified std handles.
    /// Returns (process_handle, thread_handle).
    fn spawn_child(
        cmd: &str,
        stdin: Option<HANDLE>,
        stdout: Option<HANDLE>,
        stderr: Option<HANDLE>,
    ) -> (OwnedHandle, OwnedHandle) {
        let si = STARTUPINFOW {
            cb: std::mem::size_of::<STARTUPINFOW>() as u32,
            dwFlags: STARTF_USESTDHANDLES,
            hStdInput: stdin.unwrap_or_default(),
            hStdOutput: stdout.unwrap_or_default(),
            hStdError: stderr.unwrap_or_default(),
            ..Default::default()
        };
        let mut pi = PROCESS_INFORMATION::default();
        let mut cmd_wide = string_util::to_wide(cmd);

        unsafe {
            CreateProcessW(
                PCWSTR::null(),
                Some(PWSTR(cmd_wide.as_mut_ptr())),
                None,
                None,
                true,
                CREATE_NO_WINDOW,
                None,
                PCWSTR::null(),
                &si,
                &mut pi,
            )
            .unwrap();
        }
        (OwnedHandle::new(pi.hProcess), OwnedHandle::new(pi.hThread))
    }

    #[test]
    fn test_pipe_relay_copies_data() {
        // Create two pipe pairs: source and destination.
        // Relay thread reads from source_read and writes to dest_write.
        // We write to source_write and read from dest_read to verify the relay.
        let (source_read, source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();

        let relay = unsafe { create_relay_thread(source_read.get(), dest_write.get()).unwrap() };

        // Read from dest concurrently — the relay calls FlushFileBuffers after
        // each write, which blocks until the reader drains the pipe buffer.
        // Without a concurrent reader the relay and main thread deadlock.
        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let reader = std::thread::spawn(move || read_from_pipe(dest_send.get()));

        // Write test data to the source pipe
        let test_data = b"Hello from relay test!";
        let mut bytes_written = 0u32;
        unsafe {
            WriteFile(
                source_write.get(),
                Some(test_data),
                Some(&mut bytes_written),
                None,
            )
            .unwrap();
        }

        // Close the source write end to signal EOF to the relay thread.
        // drop() calls CloseHandle via OwnedHandle::Drop.
        drop(source_write);

        // Wait for relay thread to finish
        unsafe {
            WaitForSingleObject(relay.thread().get(), 5000);
        }

        // Close the dest write end so the reader sees EOF
        drop(dest_write);

        let output = reader.join().unwrap();
        assert_eq!(output, "Hello from relay test!");
    }

    /// The write end stays open, so the relay's `ReadFile` never reaches EOF.
    /// Cancelling it must still end the thread.
    ///
    /// This is the case a descendant that inherited the agent's write ends
    /// produces: the workload exits, the descendant holds the pipe, and a join
    /// waiting for EOF waits for the descendant's whole lifetime.
    #[test]
    fn a_cancelled_relay_exits_while_the_write_end_is_still_open() {
        let (source_read, _source_write) = create_test_pipes();
        let (_dest_read, dest_write) = create_test_pipes();

        let relay = unsafe { create_relay_thread(source_read.get(), dest_write.get()).unwrap() };

        // Parked in `ReadFile`: nothing was written and `_source_write` keeps
        // the pipe from reporting EOF.
        assert_eq!(
            unsafe { WaitForSingleObject(relay.thread().get(), 250) },
            WAIT_TIMEOUT,
            "the relay should still be blocked before the cancel"
        );

        relay.cancel_read();

        assert_eq!(
            unsafe { WaitForSingleObject(relay.thread().get(), 5000) },
            WAIT_OBJECT_0,
            "the cancelled relay should exit without EOF"
        );
    }

    /// Pipe-backed stdin uses `create_relay_thread` so shutdown can cancel the
    /// blocked source read. Once cancelled, the relay must also release its
    /// duplicate of the agent stdin write handle so the reader observes EOF.
    #[test]
    fn a_cancelled_stdin_pipe_relay_releases_its_destination_handle() {
        let (source_read, _source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();

        let (relay_thread, canceller) =
            unsafe { create_relay_thread(source_read.get(), dest_write.get()).unwrap() }
                .into_thread_and_canceller();

        // Mirror `process.Close()`: the caller drops its original agent-stdin
        // write handle while the relay's duplicate is still live.
        drop(dest_write);

        assert_eq!(
            unsafe { WaitForSingleObject(relay_thread.get(), 250) },
            WAIT_TIMEOUT,
            "the relay should still be blocked before the cancel"
        );

        canceller.close();

        assert_eq!(
            unsafe { WaitForSingleObject(relay_thread.get(), 5000) },
            WAIT_OBJECT_0,
            "the cancelled stdin relay should exit promptly"
        );

        let dest_send = SendOwnedHandle::take(&mut dest_read);
        assert_eq!(read_from_pipe(dest_send.get()), "");
    }

    /// Closing the source handle the relay was built from does not disturb it:
    /// it reads a duplicate. This is what lets `IsoSessionProcess::Close` run
    /// unconditionally.
    #[test]
    fn the_relay_reads_a_duplicate_of_the_source_handle() {
        let (source_read, source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();

        let relay = unsafe { create_relay_thread(source_read.get(), dest_write.get()).unwrap() };

        drop(source_read);

        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let reader = std::thread::spawn(move || read_from_pipe(dest_send.get()));

        let payload = b"still relayed";
        let mut written = 0u32;
        unsafe {
            WriteFile(source_write.get(), Some(payload), Some(&mut written), None).unwrap();
        }
        drop(source_write);

        assert_eq!(
            unsafe { WaitForSingleObject(relay.thread().get(), 5000) },
            WAIT_OBJECT_0,
            "the relay should reach EOF on its own duplicate"
        );
        drop(dest_write);

        assert_eq!(reader.join().unwrap(), "still relayed");
    }

    #[test]
    fn test_pipe_relay_handles_large_data() {
        let (source_read, mut source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();

        let relay = unsafe { create_relay_thread(source_read.get(), dest_write.get()).unwrap() };

        // Write data larger than the pipe buffer (4096 bytes default).
        // Use ASCII to avoid from_utf8_lossy expansion of invalid bytes.
        let test_data: Vec<u8> = (0..10000).map(|i| b'A' + (i % 26) as u8).collect();
        let write_data = test_data.clone();
        let expected_len = test_data.len();

        // Read from dest in a concurrent thread to prevent deadlock —
        // the relay's WriteFile would block if the dest pipe buffer fills.
        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let reader = std::thread::spawn(move || read_from_pipe(dest_send.get()));

        // Write in a separate thread (pipe buffer can fill between write and relay).
        let send_write = SendOwnedHandle::take(&mut source_write);
        let writer = std::thread::spawn(move || {
            let mut bytes_written = 0u32;
            unsafe {
                let _ = WriteFile(
                    send_write.get(),
                    Some(&write_data),
                    Some(&mut bytes_written),
                    None,
                );
            }
            // SendOwnedHandle::Drop closes the handle, signaling EOF.
            drop(send_write);
        });

        writer.join().unwrap();
        // Wait for relay thread to finish (source EOF propagated)
        unsafe {
            WaitForSingleObject(relay.thread().get(), 5000);
        }
        // Close the dest write end so the reader sees EOF
        drop(dest_write);

        let output = reader.join().unwrap();
        assert_eq!(output.len(), expected_len);
    }

    /// Tests the production pattern: relay a child process's stdout to the
    /// parent. Mirrors the wxc-exec scenario where Process B writes output
    /// and the relay copies it for Process A to read.
    #[test]
    fn test_pipe_relay_child_stdout() {
        // child_stdout: inheritable write end (child writes here)
        let (child_stdout_read, child_stdout_write) = create_std_pipes(true).unwrap();
        // dest: non-inheritable (only the test reads here)
        let (mut dest_read, dest_write) = create_test_pipes();

        let relay =
            unsafe { create_relay_thread(child_stdout_read.get(), dest_write.get()).unwrap() };

        // Concurrent reader to avoid FlushFileBuffers deadlock
        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let reader = std::thread::spawn(move || read_from_pipe(dest_send.get()));

        let (child, _child_thread) = spawn_child(
            "cmd.exe /c echo hello from child process",
            None,
            Some(child_stdout_write.get()),
            None,
        );

        // Close parent's copy — child and relay still have theirs
        drop(child_stdout_write);

        // Child exits → last write-end closes → relay sees EOF → relay exits
        unsafe {
            WaitForSingleObject(child.get(), 10000);
            WaitForSingleObject(relay.thread().get(), 5000);
        }

        // Close relay's dest write so reader sees EOF
        drop(dest_write);

        let output = reader.join().unwrap();
        assert!(
            output.trim().contains("hello from child process"),
            "Expected child output relayed to dest, got: {:?}",
            output
        );
    }

    /// Tests the production pattern: relay data from the parent into a
    /// child process's stdin. Mirrors the wxc-exec scenario where Process A
    /// sends input that the relay copies to Process B's stdin.
    #[test]
    fn test_pipe_relay_child_stdin() {
        // source: non-inheritable (test writes here)
        let (source_read, source_write) = create_test_pipes();
        // child_stdin: inheritable read end (child reads from here)
        let (child_stdin_read, child_stdin_write) = create_std_pipes(false).unwrap();
        // child_stdout: inheritable write end (to capture child output)
        let (mut child_stdout_read, child_stdout_write) = create_std_pipes(true).unwrap();

        // Relay: test input → child stdin
        let relay =
            unsafe { create_relay_thread(source_read.get(), child_stdin_write.get()).unwrap() };

        // findstr /R "." echoes all non-empty lines from stdin to stdout
        let (child, _child_thread) = spawn_child(
            "cmd.exe /c findstr /R \".\"",
            Some(child_stdin_read.get()),
            Some(child_stdout_write.get()),
            None,
        );

        // Close parent copies of child-side handles
        drop(child_stdin_read);
        drop(child_stdout_write);

        // Read child stdout concurrently
        let stdout_send = SendOwnedHandle::take(&mut child_stdout_read);
        let reader = std::thread::spawn(move || read_from_pipe(stdout_send.get()));

        // Write data through: test → source → relay → child stdin
        let mut bw = 0u32;
        unsafe {
            WriteFile(
                source_write.get(),
                Some(b"relayed to child\r\n"),
                Some(&mut bw),
                None,
            )
            .unwrap();
        }
        // Close source → relay sees EOF → relay exits
        drop(source_write);

        unsafe {
            WaitForSingleObject(relay.thread().get(), 5000);
        }

        // Close child_stdin_write → child sees EOF → child exits
        drop(child_stdin_write);

        unsafe {
            WaitForSingleObject(child.get(), 10000);
        }

        let output = reader.join().unwrap();
        assert!(
            output.contains("relayed to child"),
            "Expected relayed input in child output, got: {:?}",
            output
        );
    }

    #[test]
    fn output_drain_waits_for_all_relays_to_exit() {
        let (first_read, first_write) = create_test_pipes();
        let (second_read, mut second_write) = create_test_pipes();
        let (_destination_read, destination_write) = create_test_pipes();
        let first =
            unsafe { create_relay_thread(first_read.get(), destination_write.get()).unwrap() };
        let second =
            unsafe { create_relay_thread(second_read.get(), destination_write.get()).unwrap() };
        drop(first_write);
        assert_eq!(
            unsafe { WaitForSingleObject(first.thread().get(), 1000) },
            WAIT_OBJECT_0
        );

        let source = SendOwnedHandle::take(&mut second_write);
        let writer = std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(40));
            drop(source);
        });
        let result = drain_output_relays_within(
            &[&first, &second],
            Duration::from_secs(1),
            Duration::from_secs(2),
        )
        .unwrap();
        let second_finished = unsafe { WaitForSingleObject(second.thread().get(), 0) };
        writer.join().unwrap();

        assert_eq!(result, OutputRelayDrain::Drained);
        assert_eq!(second_finished, WAIT_OBJECT_0, "must wait for both relays");
        assert_eq!(
            drain_output_relays_within(&[&first, &second], Duration::ZERO, Duration::ZERO).unwrap(),
            OutputRelayDrain::Drained,
            "finished relays must be recognized even with no remaining drain time"
        );
    }

    #[test]
    fn output_drain_without_relays_finishes_immediately() {
        assert_eq!(
            drain_output_relays_within(&[], Duration::ZERO, Duration::ZERO).unwrap(),
            OutputRelayDrain::Drained
        );
    }

    #[test]
    fn output_drain_reports_a_failed_thread_wait() {
        let (source_read, _source_write) = create_test_pipes();
        let (_destination_read, destination_write) = create_test_pipes();
        let mut relay =
            unsafe { create_relay_thread(source_read.get(), destination_write.get()).unwrap() };
        let thread = std::mem::replace(&mut relay.thread, OwnedHandle::new(HANDLE::default()));
        let result =
            drain_output_relays_within(&[&relay], Duration::from_secs(1), Duration::from_secs(2));
        relay.cancel_read();
        assert_eq!(
            unsafe { WaitForSingleObject(thread.get(), 1000) },
            WAIT_OBJECT_0
        );
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("WaitForMultipleObjects"),
            "wait failures must not be reported as successful draining"
        );
    }

    #[test]
    fn output_drain_extends_while_progress_continues() {
        let (source_read, mut source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();
        let relay = unsafe { create_relay_thread(source_read.get(), dest_write.get()).unwrap() };

        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let reader = std::thread::spawn(move || read_from_pipe(dest_send.get()));

        let source_send = SendOwnedHandle::take(&mut source_write);
        let writer = std::thread::spawn(move || {
            for _ in 0..8 {
                let mut written = 0u32;
                unsafe {
                    WriteFile(
                        source_send.get(),
                        Some(b"chunk\n"),
                        Some(&mut written),
                        None,
                    )
                    .unwrap();
                }
                std::thread::sleep(Duration::from_millis(20));
            }
            drop(source_send);
        });

        let started = Instant::now();
        let result = drain_output_relays_within(
            &[&relay],
            Duration::from_millis(100),
            Duration::from_secs(2),
        )
        .unwrap();
        let elapsed = started.elapsed();

        writer.join().unwrap();
        drop(dest_write);
        let output = reader.join().unwrap();

        assert_eq!(result, OutputRelayDrain::Drained);
        assert!(
            elapsed >= Duration::from_millis(120),
            "the drain returned before the slow producer finished: {elapsed:?}"
        );
        assert_eq!(output, "chunk\n".repeat(8));
    }

    #[test]
    fn output_drain_cancels_and_releases_handles_once_idle() {
        let (source_read, source_write) = create_test_pipes();
        let (dest_read, dest_write) = create_test_pipes();
        let relay = unsafe { create_relay_thread(source_read.get(), dest_write.get()).unwrap() };
        drop(source_read);
        drop(dest_write);

        let started = Instant::now();
        let result = drain_output_relays_within(
            &[&relay],
            Duration::from_millis(30),
            Duration::from_millis(500),
        )
        .unwrap();
        let elapsed = started.elapsed();

        assert_eq!(result, OutputRelayDrain::GaveUp);
        assert!(
            elapsed < Duration::from_secs(2),
            "the drain must be bounded, took {elapsed:?}"
        );

        assert_eq!(
            unsafe { WaitForSingleObject(relay.thread().get(), 5000) },
            WAIT_OBJECT_0,
            "the relay must exit while the source writer is still open"
        );
        let mut written = 0;
        let error = unsafe {
            WriteFile(
                source_write.get(),
                Some(b"still open"),
                Some(&mut written),
                None,
            )
        }
        .unwrap_err();
        assert!(
            error.code() == ERROR_BROKEN_PIPE.to_hresult()
                || error.code() == ERROR_NO_DATA.to_hresult(),
            "expected the relay's source duplicate to be closed: {error}"
        );
        assert_eq!(
            read_from_pipe(dest_read.get()),
            "",
            "destination must reach EOF"
        );
    }

    #[test]
    fn output_drain_honors_absolute_cap_while_progress_continues() {
        let (source_read, mut source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();
        let relay = unsafe { create_relay_thread(source_read.get(), dest_write.get()).unwrap() };
        drop(source_read);
        drop(dest_write);

        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let reader = std::thread::spawn(move || read_from_pipe(dest_send.get()));
        let source_send = SendOwnedHandle::take(&mut source_write);
        let writer = std::thread::spawn(move || {
            for _ in 0..200 {
                let mut written = 0;
                if let Err(error) = unsafe {
                    WriteFile(
                        source_send.get(),
                        Some(b"chunk\n"),
                        Some(&mut written),
                        None,
                    )
                } {
                    assert!(
                        error.code() == ERROR_BROKEN_PIPE.to_hresult()
                            || error.code() == ERROR_NO_DATA.to_hresult(),
                        "expected cancellation to close the reader: {error}"
                    );
                    return;
                }
                std::thread::sleep(Duration::from_millis(10));
            }
        });

        let cap = Duration::from_millis(600);
        let started = Instant::now();
        let result =
            drain_output_relays_within(&[&relay], Duration::from_millis(300), cap).unwrap();
        let elapsed = started.elapsed();
        assert_eq!(
            unsafe { WaitForSingleObject(relay.thread().get(), 5000) },
            WAIT_OBJECT_0
        );
        writer.join().unwrap();
        let output = reader.join().unwrap();

        assert_eq!(result, OutputRelayDrain::GaveUp);
        assert!(
            elapsed >= cap,
            "the idle timer fired during progress: {elapsed:?}"
        );
        assert!(
            elapsed < Duration::from_millis(1600),
            "cap was exceeded: {elapsed:?}"
        );
        assert!(output.len() >= 12 && output.len() < 200 * 6);
        assert_eq!(output, "chunk\n".repeat(output.len() / 6));
        assert_eq!(relay.progress_bytes(), output.len() as u64);
    }

    // ── Tests for `create_relay_thread_with_stop` ──────────────────────────
    //
    // These exercise the stop-event-aware relay variant. Cancellation (test #1)
    // is the load-bearing case: it's the reason this primitive exists and
    // distinguishes it from the EOF-driven `create_relay_thread`.

    #[test]
    fn test_pipe_relay_with_stop_exits_on_stop_event() {
        // Core cancellation case: relay is blocked in WaitForMultipleObjects
        // (no data on h_read, h_read not closed). Signal the stop event;
        // verify the relay exits within a short timeout.
        let (source_read, _source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();
        let stop_event = create_test_stop_event();

        let params = PipeRelayWithStopParams {
            h_read: source_read.get(),
            h_write: duplicate_handle(dest_write.get()).unwrap(),
            h_stop_event: duplicate_handle(stop_event.get()).unwrap(),
        };
        let relay_thread = unsafe { create_relay_thread_with_stop(params).unwrap() };

        // Source has no data and is not closed → relay sits in
        // WaitForMultipleObjects. Without the stop event it would hang.
        unsafe {
            SetEvent(stop_event.get()).unwrap();
        }

        let wait_result = unsafe { WaitForSingleObject(relay_thread.get(), 5000) };
        assert_eq!(
            wait_result, WAIT_OBJECT_0,
            "Relay did not exit within 5s of stop event"
        );

        // Drain the dest pipe so its handles can drop cleanly.
        drop(dest_write);
        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let _ = std::thread::spawn(move || read_from_pipe(dest_send.get())).join();
    }

    #[test]
    fn test_pipe_relay_with_stop_exits_on_read_eof() {
        // Stop event never signalled; source closed → read EOF → relay exits.
        let (source_read, source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();
        let stop_event = create_test_stop_event();

        let params = PipeRelayWithStopParams {
            h_read: source_read.get(),
            h_write: duplicate_handle(dest_write.get()).unwrap(),
            h_stop_event: duplicate_handle(stop_event.get()).unwrap(),
        };
        let relay_thread = unsafe { create_relay_thread_with_stop(params).unwrap() };

        // Concurrent reader (no-op here, but defensive in case data flows on
        // any FlushFileBuffers iteration; avoids any pipe-buffer deadlock).
        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let reader = std::thread::spawn(move || read_from_pipe(dest_send.get()));

        // Close source write end → relay's read returns EOF → break.
        drop(source_write);

        let wait_result = unsafe { WaitForSingleObject(relay_thread.get(), 5000) };
        assert_eq!(wait_result, WAIT_OBJECT_0, "Relay did not exit on read EOF");

        drop(dest_write);
        let _ = reader.join();
    }

    #[test]
    fn test_pipe_relay_with_stop_copies_data_before_exit() {
        // Stop event never signalled; data is written; verify it is copied.
        let (source_read, source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();
        let stop_event = create_test_stop_event();

        let params = PipeRelayWithStopParams {
            h_read: source_read.get(),
            h_write: duplicate_handle(dest_write.get()).unwrap(),
            h_stop_event: duplicate_handle(stop_event.get()).unwrap(),
        };
        let relay_thread = unsafe { create_relay_thread_with_stop(params).unwrap() };

        // Concurrent reader to avoid FlushFileBuffers deadlock.
        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let reader = std::thread::spawn(move || read_from_pipe(dest_send.get()));

        let test_data = b"hello via stop-aware relay";
        let mut bytes_written = 0u32;
        unsafe {
            WriteFile(
                source_write.get(),
                Some(test_data),
                Some(&mut bytes_written),
                None,
            )
            .unwrap();
        }
        drop(source_write); // EOF → relay exits.

        let wait_result = unsafe { WaitForSingleObject(relay_thread.get(), 5000) };
        assert_eq!(wait_result, WAIT_OBJECT_0);

        drop(dest_write);
        let output = reader.join().unwrap();
        assert_eq!(output, "hello via stop-aware relay");
    }

    /// The relay writes to its own duplicate, so releasing the caller's
    /// destination handle mid-relay does not break the copy.
    ///
    /// `RelayScope` closes the session process's pipe handles unconditionally,
    /// including the stdin end this relay writes to, while this relay may still
    /// be running. Borrowing that handle would leave the relay writing to a
    /// closed — and possibly reissued — value.
    #[test]
    fn the_stop_relay_writes_to_a_duplicate_of_the_destination_handle() {
        let (source_read, source_write) = create_test_pipes();
        let (mut dest_read, dest_write) = create_test_pipes();
        let stop_event = create_test_stop_event();

        let params = PipeRelayWithStopParams {
            h_read: source_read.get(),
            h_write: duplicate_handle(dest_write.get()).unwrap(),
            h_stop_event: duplicate_handle(stop_event.get()).unwrap(),
        };
        let relay_thread = unsafe { create_relay_thread_with_stop(params).unwrap() };

        // What `process.Close()` does to the agent's stdin end while the relay
        // is live. The relay's duplicate is now the only write handle, so its
        // own exit is what closes the pipe.
        drop(dest_write);

        let dest_send = SendOwnedHandle::take(&mut dest_read);
        let reader = std::thread::spawn(move || read_from_pipe(dest_send.get()));

        let test_data = b"written after the caller's handle closed";
        let mut bytes_written = 0u32;
        unsafe {
            WriteFile(
                source_write.get(),
                Some(test_data),
                Some(&mut bytes_written),
                None,
            )
            .unwrap();
        }
        drop(source_write); // EOF → relay exits, freeing its duplicate.

        assert_eq!(
            unsafe { WaitForSingleObject(relay_thread.get(), 5000) },
            WAIT_OBJECT_0,
            "the relay should exit on source EOF"
        );

        assert_eq!(
            reader.join().unwrap(),
            "written after the caller's handle closed"
        );
    }

    // Note: a "signal-stop-mid-data" test using anonymous pipes is not viable —
    // anonymous pipe handles appear always-signalled to WaitForMultipleObjects,
    // so once the relay returns from the wait into ReadFile, the stop event
    // cannot interrupt the blocked read. The intended production usage is with
    // a console input handle (or other waitable handle) where signal state
    // accurately reflects data-available. The "stop-event-only" path
    // (test_pipe_relay_with_stop_exits_on_stop_event) and the "EOF-after-data"
    // path (test_pipe_relay_with_stop_copies_data_before_exit) together cover
    // the invariants that matter for the production case.

    #[test]
    fn test_pipe_relay_with_stop_exits_on_invalid_handle() {
        // Defensive path: pass a default (invalid) HANDLE for h_read.
        // WaitForMultipleObjects returns WAIT_FAILED → relay loop breaks →
        // thread exits cleanly. No panic, no hang.
        let (_, dest_write) = create_test_pipes();
        let stop_event = create_test_stop_event();

        let params = PipeRelayWithStopParams {
            h_read: HANDLE::default(), // invalid — not a kernel handle
            h_write: duplicate_handle(dest_write.get()).unwrap(),
            h_stop_event: duplicate_handle(stop_event.get()).unwrap(),
        };
        let relay_thread = unsafe { create_relay_thread_with_stop(params).unwrap() };

        let wait_result = unsafe { WaitForSingleObject(relay_thread.get(), 5000) };
        assert_eq!(
            wait_result, WAIT_OBJECT_0,
            "Relay did not exit on invalid h_read"
        );
    }
}