mxc-sdk 1.2.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use crate::mxc_common::logger::Logger;
use crate::mxc_common::process_util::{OwnedHandle, PipeReadCanceller};
use crate::mxc_common::sandbox_process::StreamCloser;
use crate::mxc_common::state_aware_backend::{ExecHandle, ExecOutcome};

use crate::isolation_session_bindings::bindings::{
    IsoSessionFeature, IsoSessionOps, IsoSessionProcess, IsoSessionProcessResult,
    IsoSessionUserResult,
};
use windows::Win32::Foundation::HANDLE;
use windows::Win32::System::Console::{
    GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
};
use windows::Win32::System::Threading::{CreateEventW, SetEvent};
use windows::UI::WindowId;
use windows_core::{HSTRING, PCWSTR};

use super::console_mode::{get_local_console_size, ConsoleModeRestorer, CtrlHandlerGuard};
use super::error::{
    activation_error, check_result, format_iso_error, lifecycle_err, op, transport_err,
    IsolationSessionError, StalePromotion,
};
use super::manager::{
    create_stdin_relay, feature_supported_from, stdin_closer_with_diagnostics, wait_for_relay,
    IsolationSessionManager, MtaReference, ProvisionedUser, AGENT_IDENTITY_MARKER,
};
use super::owned_thread::{self, Impersonation};
use super::pipe_relay::{
    create_relay_thread, drain_output_relays_within, OutputRelayDrain, PipeRelay,
};
use super::process::{ClosingProcess, StartedProcess};
use super::process_options::{
    build_iso_process_options, with_service_timeout_grace, ProcessOptions,
};
/// Activates the in-proc IsolationSession runtime factory and returns the
/// instance.
fn check_service_available_and_activate() -> Result<IsoSessionOps, IsolationSessionError> {
    #[cfg(feature = "isosession-test-support")]
    super::manager::check_expected_manager("legacy")?;
    match IsoSessionOps::new() {
        Ok(ops) => Ok(ops),
        // The HRESULT→error mapping lives in `activation_error` so it stays
        // testable without depending on whether this host can activate the
        // API at all.
        Err(e) => Err(activation_error(e.code().0 as u32, &e.message())),
    }
}

const ZERO_WINDOW_ID: WindowId = WindowId { Value: 0 };

/// Manages the isolation session lifecycle. Methods map 1:1 to the granular
/// API steps.
pub(super) struct IsolationSessionManagerLegacy {
    /// The OS-assigned agent user name returned by `add_user`. Used as the
    /// `agentUserName` argument to every subsequent lifecycle op.
    agent_user_name: HSTRING,
    /// The activated service instance. Held for the manager's lifetime so
    /// the WinRT factory is reused across calls.
    ops: IsoSessionOps,
    /// The impersonation of the thread that created this manager: every call
    /// the manager makes, and every call for a process it starts, is made
    /// under it.
    impersonation: Impersonation,
    /// Declared after `ops` so it drops last: the apartment outlives every
    /// object activated in it.
    _mta: MtaReference,
}

impl IsolationSessionManagerLegacy {
    /// Pegs a manager to an existing OS-assigned agent user name (the value
    /// returned by `add_user`). Activates the service factory once and
    /// reuses it for the manager's lifetime.
    pub(super) fn new(agent_user_name: &str) -> Result<Self, IsolationSessionError> {
        let impersonation = Impersonation::of_this_thread()?;
        owned_thread::call(&impersonation, || {
            let mta = MtaReference::acquire()?;
            let ops = check_service_available_and_activate()?;
            Ok(Self {
                agent_user_name: HSTRING::from(agent_user_name),
                ops,
                impersonation: impersonation.clone(),
                _mta: mta,
            })
        })
    }

    /// Provisions an agent user and returns its provision-time facts (the
    /// OS-assigned account name — which addresses every subsequent lifecycle
    /// op — plus the agent SID and the shared ephemeral workspace path),
    /// together with a manager already pegged to that account.
    ///
    /// The manager is returned rather than left to the caller to build with
    /// [`Self::new`] because building it separately would activate the service
    /// a second time. That second activation can fail *after* the agent user
    /// has been minted, and at that point the account cannot be removed —
    /// removal needs the very service instance that just failed to activate —
    /// so the sandbox would leak with no way to clean it up. Handing back the
    /// instance `add_user` already holds removes that window entirely.
    ///
    /// Once the API reports success the account exists, so every failure after
    /// that point deprovisions best-effort rather than abandoning it. The sole
    /// exception is a failure to read the account name itself, which leaves
    /// nothing to address a removal to.
    ///
    /// Note: the in-proc API exposes no session-lifetime knob, so `lifecycle`
    /// cannot be honored here. Unsupported values are refused by the calling
    /// surface rather than ignored — one-shot rejects `destroyOnExit: false`
    /// and `preservePolicy: true` in `validate_runner`, and the state-aware
    /// parser rejects the whole `lifecycle` section.
    pub(super) fn add_user(
        app_id: Option<&str>,
    ) -> Result<(ProvisionedUser, Self), IsolationSessionError> {
        let impersonation = Impersonation::of_this_thread()?;
        owned_thread::call(&impersonation, || {
            let mta = MtaReference::acquire()?;
            let ops = check_service_available_and_activate()?;
            // Prefer the newest overload the host advertises.
            let (op_add_user, started) = if feature_supported_from(
                ops.GetFeatureLevel(IsoSessionFeature::DeducedEnterpriseAgentUser),
            ) {
                (
                    op::ADD_USER_DEDUCED,
                    ops.AddUserAsync3(&HSTRING::from(app_id.unwrap_or_default()), ZERO_WINDOW_ID),
                )
            } else if feature_supported_from(
                ops.GetFeatureLevel(IsoSessionFeature::AppScopedRegistration),
            ) {
                (
                    op::ADD_USER,
                    ops.AddUserAsync2(
                        &HSTRING::from(app_id.unwrap_or_default()),
                        &HSTRING::new(),
                        &HSTRING::new(),
                    ),
                )
            } else {
                (
                    op::ADD_USER_LEGACY,
                    ops.AddUserAsync(&HSTRING::new(), &HSTRING::new()),
                )
            };
            let user_result: IsoSessionUserResult = owned_thread::wait_for(op_add_user, started)?;

            let err = user_result
                .Error()
                .map_err(|e| transport_err(op_add_user, "get Error failed", &e))?;
            let is_error = err
                .IsError()
                .map_err(|e| transport_err(op_add_user, "get IsError failed", &e))?;
            if is_error {
                // Provision mints the agent user, so `ERROR_NOT_FOUND` here can
                // never mean "the sandbox is gone" — there is no sandbox id yet.
                return Err(format_iso_error(
                    op_add_user,
                    &err,
                    StalePromotion::NotEligible,
                ));
            }

            let agent_user_name = user_result
                .AgentUserName()
                .map_err(|e| transport_err(op_add_user, "get AgentUserName failed", &e))?;

            // Past this point the OS account exists and `agent_user_name` is the
            // key that removes it, so build the manager now rather than after the
            // remaining getters. That makes every subsequent failure recoverable:
            // the removal key and a live service instance are both already in hand.
            //
            // A failure of `AgentUserName()` above is the one case with no
            // in-process remedy — without the name there is nothing to address a
            // removal to — so it is left to propagate.
            let manager = Self {
                agent_user_name: agent_user_name.clone(),
                ops,
                impersonation: impersonation.clone(),
                _mta: mta,
            };

            let provisioned =
                match Self::read_remaining_facts(&user_result, &agent_user_name, op_add_user) {
                    Ok(provisioned) => provisioned,
                    Err(e) => {
                        // Best-effort: returning here without this would abandon an
                        // account we are still able to remove.
                        let _ = manager.deprovision_agent_user();
                        return Err(e);
                    }
                };

            Ok((provisioned, manager))
        })
    }

    /// Reads the provision-time facts that remain after the agent user name.
    ///
    /// Split out of [`Self::add_user`] so that a failure in any of them lands
    /// on one error path, where the freshly created account can be removed
    /// instead of orphaned. `op_add_user` is the operation label of the
    /// provisioning overload actually invoked, so these getters' failures are
    /// attributed to the same API call in telemetry.
    fn read_remaining_facts(
        user_result: &IsoSessionUserResult,
        agent_user_name: &HSTRING,
        op_add_user: &'static str,
    ) -> Result<ProvisionedUser, IsolationSessionError> {
        let agent_user_sid = user_result
            .AgentUserSid()
            .map_err(|e| transport_err(op_add_user, "get AgentUserSid failed", &e))?;
        let ephemeral_workspace_path = user_result
            .EphemeralWorkspacePath()
            .map_err(|e| transport_err(op_add_user, "get EphemeralWorkspacePath failed", &e))?;

        Ok(ProvisionedUser {
            agent_user_name: agent_user_name.to_string(),
            agent_user_sid: agent_user_sid.to_string(),
            ephemeral_workspace_path: ephemeral_workspace_path.to_string(),
        })
    }

    /// Step 3a: Start a process inside the started isolation session, and
    /// return it **without waiting**.
    ///
    /// Split out of [`Self::create_process`] so the caller chooses how the
    /// streams are consumed: the relayed path bridges them with its own relay
    /// threads and blocks (see `create_process`), while an in-process SDK
    /// caller takes the raw handles and drives them itself.
    fn start_process(
        &self,
        options: &ProcessOptions,
        logger: Option<&Logger>,
    ) -> Result<StartedProcess, IsolationSessionError> {
        let proc_options = build_iso_process_options(options)?;

        let result: IsoSessionProcessResult = owned_thread::wait_for(
            op::RUN_PROCESS,
            self.ops.RunProcessWithOptionsAsync(
                &self.agent_user_name,
                &HSTRING::from(&options.process_path),
                &HSTRING::from(&options.arguments),
                &proc_options,
            ),
        )?;

        let err = result
            .Error()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get Error failed", &e))?;
        let is_error = err
            .IsError()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get IsError failed", &e))?;
        if is_error {
            return Err(format_iso_error(
                op::RUN_PROCESS,
                &err,
                StalePromotion::Eligible,
            ));
        }

        let process: IsoSessionProcess = result
            .Process()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get Process failed", &e))?;

        StartedProcess::new(process, AGENT_IDENTITY_MARKER, logger)
    }
}

impl IsolationSessionManager for IsolationSessionManagerLegacy {
    /// Start an interactive process whose ConPTY handles remain caller-driven.
    fn pty_process(
        &self,
        options: &ProcessOptions,
        logger: Option<&Logger>,
    ) -> Result<Arc<ClosingProcess>, IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            let mta = MtaReference::acquire()?;
            Ok(Arc::new(ClosingProcess::new(
                self.start_process(options, logger)?,
                self.impersonation.clone(),
                mta,
            )))
        })
    }

    /// Step 2: Start the isolation session for the pegged agent user.
    fn start_session(&self) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            // Prefer the newest overload the host advertises.
            let (op_start_session, started) = if feature_supported_from(
                self.ops
                    .GetFeatureLevel(IsoSessionFeature::DeducedEnterpriseAgentUser),
            ) {
                (
                    op::START_SESSION_DEDUCED,
                    self.ops
                        .StartSessionAsync2(&self.agent_user_name, ZERO_WINDOW_ID),
                )
            } else {
                (
                    op::START_SESSION,
                    self.ops
                        .StartSessionAsync(&self.agent_user_name, &HSTRING::new()),
                )
            };
            let result = owned_thread::wait_for(op_start_session, started)?;
            check_result(&result, op_start_session, StalePromotion::Eligible)
        })
    }

    /// Step 3: Create a process inside the started isolation session and run it
    /// to completion. Output is streamed live to the calling process's stdio via
    /// internal relay threads; only the exit code or timeout is returned.
    ///
    /// `options.timeout_ms` is enforced locally; the service-side timer is armed
    /// with [`with_service_timeout_grace`] so a timeout is never reported as an
    /// ordinary exit.
    ///
    /// This is the **relay** path, reached by `wxc-exec` and by an in-process
    /// caller that asked to attach. A caller that wants the streams handed back
    /// uses [`Self::piped_exec_handle`] instead.
    ///
    /// [`with_service_timeout_grace`]: super::process_options::with_service_timeout_grace
    fn create_process(
        &self,
        options: &ProcessOptions,
        logger: Option<&mut Logger>,
    ) -> Result<ExecOutcome, IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            // Everything fallible that does not need the workload runs first, so no
            // failure can strand a running one.
            let wxc_stdout = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }
                .map_err(|e| lifecycle_err(format!("GetStdHandle(stdout) failed: {}", e)))?;
            let wxc_stderr = unsafe { GetStdHandle(STD_ERROR_HANDLE) }
                .map_err(|e| lifecycle_err(format!("GetStdHandle(stderr) failed: {}", e)))?;
            let wxc_stdin = unsafe { GetStdHandle(STD_INPUT_HANDLE) }
                .map_err(|e| lifecycle_err(format!("GetStdHandle(stdin) failed: {}", e)))?;

            // Manual-reset stop event for console-backed stdin relays.
            let stdin_stop_event = unsafe {
                CreateEventW(None, true, false, PCWSTR::null())
                    .map_err(|e| lifecycle_err(format!("CreateEventW(stdin stop): {}", e)))?
            };
            // Declared before `scope`, which holds a raw copy: it must drop last.
            let stdin_stop_owned = OwnedHandle::new(stdin_stop_event);

            // Relay threads bridge the calling process's stdio to
            // `IsoSessionProcess`'s pipes: console-handle inheritance cannot cross
            // the desktop-session boundary.
            //
            // Handle ownership across four sources:
            //   - Pipe handles owned by `IsoSessionProcess` (`OutputHandle()` /
            //     `ErrorHandle()` / `InputHandle()`, returned as u64): released
            //     by `process.Close()`. We do NOT close them. The output relays
            //     read their own duplicates, so `Close()` does not disturb them.
            //   - The calling process's std handles (`GetStdHandle`): OS-owned.
            //     We do NOT close them.
            //   - Stop event for stdin relay (`CreateEventW`): RAII-closed via
            //     `OwnedHandle`.
            //   - Relay thread handles: RAII-closed via `OwnedHandle` after we
            //     `WaitForSingleObject` on each.
            //
            // Lifetime: each relay's param struct is moved to the heap and owned
            // by its thread, which frees it on exit, so joining is not required
            // for memory safety.
            let service_options = with_service_timeout_grace(options.clone());
            let started = self.start_process(&service_options, logger.as_deref())?;
            let process = &started.process;
            let stdout_handle_val = started.stdout;
            let stderr_handle_val = started.stderr;
            let stdin_handle_val = started.stdin;

            let mut scope = RelayScope::new(&started, stdin_stop_owned.get());

            // In interactive mode, switch the calling process's console to raw VT
            // so only the agent's ConPTY echoes and renders; otherwise both do.
            // RAII-restored on scope exit. No-op when stdio is not a console.
            let _console_guard = if options.interactive {
                Some(ConsoleModeRestorer::install_raw_vt())
            } else {
                None
            };

            // Install a console Ctrl handler that signals `stdin_stop_owned`
            // on Ctrl-C or terminal-close events, so the relay loops drain
            // cleanly instead of being terminated by the OS default
            // `ExitProcess`. Interactive mode only — non-interactive mode
            // wants the default behavior so the parent can terminate
            // wxc-exec via Ctrl-C. Installed after the workload starts: the
            // event is manual-reset and never cleared, so an earlier Ctrl-C
            // would stop the stdin relay for the session's lifetime.
            let _ctrl_guard = if options.interactive {
                Some(CtrlHandlerGuard::install(stdin_stop_owned.get()))
            } else {
                None
            };

            // Push the local console's viewport size into the agent's inner ConPTY.
            // Without it the inner HPCON keeps its default dimensions and VT-aware
            // agents (e.g. PSReadLine) anchor their prompt to that smaller last row,
            // overlaying text once they reach it. Mid-session resize is not handled
            // here.
            if options.interactive {
                if let Some((cols, rows)) = get_local_console_size() {
                    let _ = process.ResizeConsole(cols, rows);
                }
            }

            scope.stdout = if stdout_handle_val != 0 {
                Some(
                    unsafe {
                        create_relay_thread(
                            HANDLE(stdout_handle_val as *mut core::ffi::c_void),
                            wxc_stdout,
                        )
                    }
                    .map_err(|e| lifecycle_err(format!("create stdout relay: {}", e)))?,
                )
            } else {
                None
            };
            scope.stderr = if stderr_handle_val != 0 {
                Some(
                    unsafe {
                        create_relay_thread(
                            HANDLE(stderr_handle_val as *mut core::ffi::c_void),
                            wxc_stderr,
                        )
                    }
                    .map_err(|e| lifecycle_err(format!("create stderr relay: {}", e)))?,
                )
            } else {
                None
            };
            if stdin_handle_val != 0 {
                // Callback used to close stdin on end of input.
                let stdin_closer = {
                    let process = process.clone();
                    let impersonation = self.impersonation.clone();
                    let close_lock = Arc::clone(&started.close_lock);
                    stdin_closer_with_diagnostics(
                        move || {
                            owned_thread::call(&impersonation, || {
                                let _close =
                                    close_lock.lock().unwrap_or_else(PoisonError::into_inner);
                                process.CloseStandardInput().map_err(|error| {
                                    transport_err(
                                        op::RUN_PROCESS,
                                        "CloseStandardInput failed",
                                        &error,
                                    )
                                })
                            })
                        },
                        logger
                            .as_deref()
                            .map(Logger::clone_diagnostic_sink)
                            .unwrap_or_else(Logger::inherit_thread_diagnostic_sink),
                    )
                };

                // The console relay needs its own process reference for resize calls.
                let process_for_resize = process.clone();
                let impersonation = self.impersonation.clone();
                // SAFETY: process and standard handles outlive relay setup;
                // the host's console input remains valid during execution.
                let (thread, canceller) = unsafe {
                    create_stdin_relay(
                        wxc_stdin,
                        HANDLE(stdin_handle_val as *mut core::ffi::c_void),
                        stdin_stop_owned.get(),
                        options.interactive,
                        Some(stdin_closer),
                        move |cols, rows| {
                            let _ = owned_thread::call(&impersonation, || {
                                let _ = process_for_resize.ResizeConsole(cols, rows);
                                Ok(())
                            });
                        },
                    )
                }?;
                scope.stdin = Some(thread);
                scope.stdin_canceller = canceller;
            }

            let outcome = started.wait(options.timeout_ms, || scope.stop_stdin())?;
            scope.finish()?;

            Ok(outcome)
        })
    }

    /// Start a process and hand back its live pipes as an [`ExecHandle`].
    ///
    /// Shared by the state-aware `Piped` exec and the one-shot streaming
    /// backend.
    ///
    /// `timeout_ms` is the caller's deadline, enforced by the waiter. Arm the
    /// service-side timer with [`with_service_timeout_grace`] before calling:
    /// without that margin the two deadlines coincide, and a timeout can arrive
    /// as an ordinary exit.
    ///
    /// [`with_service_timeout_grace`]: super::process_options::with_service_timeout_grace
    fn piped_exec_handle(
        &self,
        options: &ProcessOptions,
        timeout_ms: u32,
        logger: Option<&Logger>,
    ) -> Result<ExecHandle, IsolationSessionError> {
        let started = owned_thread::call(&self.impersonation, || {
            // Acquired before the workload starts, so a failure here cannot
            // leave one running with no handle to reach it.
            let mta = MtaReference::acquire()?;
            Ok(Arc::new(ClosingProcess::new(
                self.start_process(options, logger)?,
                self.impersonation.clone(),
                mta,
            )))
        })?;

        // Read the handles before the closures take ownership. A zero means the
        // stream is genuinely absent, which is exactly the sentinel the
        // consumer already treats as "no stream".
        let stdout = HANDLE(started.stdout as *mut std::ffi::c_void);
        let stderr = HANDLE(started.stderr as *mut std::ffi::c_void);
        let stdin = HANDLE(started.stdin as *mut std::ffi::c_void);

        // `IsoSessionProcess` answers `IAgileObject`, so the closures may hold it
        // on whatever thread runs them; the calls they make go through
        // `owned_thread`.
        let waiter_process = Arc::clone(&started);
        let stdin_process = Arc::clone(&started);
        Ok(ExecHandle {
            stdout,
            stderr,
            stdin,
            stdin_closer: Some(Box::new(move || {
                let _ = stdin_process.close_standard_input();
            })),
            // Reports `TimedOut` when the deadline elapsed with the process
            // still running — see `StartedProcess::wait`, which samples that
            // before the shutdown ladder destroys the evidence.
            waiter: Box::new(move || {
                waiter_process
                    .wait_for_exit(timeout_ms)
                    .map_err(super::error::map_lifecycle_error)
            }),
            // Reports whether the platform *accepted* the kill: `terminate`'s
            // bounded post-kill wait is not consulted, so a `Terminate` that
            // was accepted and then did not take effect still reports success.
            terminator: Box::new(move || {
                started
                    .terminate_process()
                    .map_err(super::error::map_lifecycle_error)
            }),
        })
    }

    /// Step 4: Stop the isolation session.
    fn stop_session(&self) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            let result = owned_thread::wait_for(
                op::STOP_SESSION,
                self.ops.StopSessionAsync(&self.agent_user_name),
            )?;
            check_result(&result, op::STOP_SESSION, StalePromotion::Eligible)
        })
    }

    /// Step 5: Deprovision the agent user.
    fn deprovision_agent_user(&self) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            let result = owned_thread::wait_for(
                op::REMOVE_USER,
                self.ops.RemoveUserAsync(&self.agent_user_name),
            )?;
            check_result(&result, op::REMOVE_USER, StalePromotion::Eligible)
        })
    }
}
/// Owns the relay threads and the workload for the span of `create_process`.
///
/// [`finish`](Self::finish) tears down a workload that has already exited.
/// Dropping without it cancels output reads and terminates the workload.
/// Every join is bounded; cancellation does not interrupt destination writes.
struct RelayScope<'a> {
    process: &'a IsoSessionProcess,
    close_lock: &'a Mutex<()>,
    stop_event: HANDLE,
    stdout: Option<PipeRelay>,
    stderr: Option<PipeRelay>,
    stdin: Option<OwnedHandle>,
    /// Ends a pipe/file-backed stdin relay. Console stdin relays use the stop
    /// event instead because `CancelSynchronousIo` has console-handle edge
    /// cases.
    stdin_canceller: Option<PipeReadCanceller>,
    finished: bool,
}

impl<'a> RelayScope<'a> {
    const JOIN_MS: u32 = 1000;
    /// Stop waiting only after all output relays are idle for this long.
    const IDLE_MS: u64 = 5000;
    /// Overall cap so a pathological one-byte-forever trickle still returns.
    const ABSOLUTE_CAP_MS: u64 = 60_000;

    fn new(started: &'a StartedProcess, stop_event: HANDLE) -> Self {
        Self {
            process: &started.process,
            close_lock: &started.close_lock,
            stop_event,
            stdout: None,
            stderr: None,
            stdin: None,
            stdin_canceller: None,
            finished: false,
        }
    }

    fn signal_stop(&self) {
        // SAFETY: the event outlives this scope.
        unsafe {
            let _ = SetEvent(self.stop_event);
        }
    }

    fn cancel_stdin_read(&self) {
        if let Some(canceller) = &self.stdin_canceller {
            canceller.close();
        }
    }

    /// Whether the relay exited. An absent relay was never spawned.
    fn join(relay: Option<&OwnedHandle>, timeout_ms: u32) -> bool {
        wait_for_relay(relay, timeout_ms).unwrap_or(false)
    }

    fn join_output(relay: &Option<PipeRelay>, timeout_ms: u32) -> bool {
        Self::join(relay.as_ref().map(PipeRelay::thread), timeout_ms)
    }

    fn output_relays(&self) -> Vec<&PipeRelay> {
        [&self.stdout, &self.stderr]
            .into_iter()
            .filter_map(Option::as_ref)
            .collect()
    }

    /// Release the process's handles. Surviving relays own their duplicates
    /// independently.
    fn close_handles(&self) {
        let _close = self
            .close_lock
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        let _ = self.process.Close();
    }

    fn stop_stdin(&mut self) -> Result<bool, IsolationSessionError> {
        self.signal_stop();
        self.cancel_stdin_read();
        let exited = wait_for_relay(self.stdin.as_ref(), Self::JOIN_MS)?;
        if exited {
            self.stdin = None;
            self.stdin_canceller = None;
        }
        Ok(exited)
    }

    /// Teardown for a workload that has already exited.
    fn finish(&mut self) -> Result<(), IsolationSessionError> {
        self.signal_stop();
        self.cancel_stdin_read();
        let output_relays = self.output_relays();
        let output_drain = drain_output_relays_within(
            &output_relays,
            Duration::from_millis(Self::IDLE_MS),
            Duration::from_millis(Self::ABSOLUTE_CAP_MS),
        )
        .map_err(|error| lifecycle_err(format!("drain output relays: {error}")))?;
        if output_drain == OutputRelayDrain::GaveUp {
            Self::join_output(&self.stdout, Self::JOIN_MS);
            Self::join_output(&self.stderr, Self::JOIN_MS);
        }
        Self::join(self.stdin.as_ref(), Self::JOIN_MS);
        self.close_handles();
        self.finished = true;
        Ok(())
    }
}

impl Drop for RelayScope<'_> {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        self.signal_stop();
        self.cancel_stdin_read();
        for relay in self.output_relays() {
            relay.cancel_read();
        }
        let _ = self.process.Terminate();
        Self::join_output(&self.stdout, Self::JOIN_MS);
        Self::join_output(&self.stderr, Self::JOIN_MS);
        Self::join(self.stdin.as_ref(), Self::JOIN_MS);
        self.close_handles();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn feature_unavailable_returns_clean_error() {
        // Initialize COM (required for WinRT activation).
        let _ = unsafe {
            windows::Win32::System::Com::CoInitializeEx(
                None,
                windows::Win32::System::Com::COINIT_MULTITHREADED,
            )
        };

        match check_service_available_and_activate() {
            Ok(_ops) => {
                // Service IS available on this machine (e.g., a test VM
                // with the feature enabled). The test is not applicable
                // — skip.
            }
            Err(IsolationSessionError::ServiceUnavailable(failure)) => {
                // Service is NOT available. Verify the error is clean and
                // descriptive (not a panic or cryptic COM error), and that
                // it names the activation operation it failed on.
                assert!(
                    failure.message.contains("not available")
                        || failure.message.contains("activation failed"),
                    "Expected descriptive error message, got: {}",
                    failure.message
                );
                assert_eq!(failure.operation, op::ACTIVATE);
                assert!(
                    failure.code.is_some(),
                    "activation failure carries no HRESULT"
                );
            }
            Err(other) => {
                panic!("expected ServiceUnavailable variant, got: {:?}", other);
            }
        }
    }
}