microsandbox 0.6.13

`microsandbox` is the core library for the microsandbox project.
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
//! Lightweight sandbox handle for metadata and signal-based lifecycle management.
//!
//! Per the SDK local-cloud parity plan (D6.4) `SandboxHandle` stays a single
//! type regardless of backend. It carries an `Arc<dyn Backend>` plus a
//! backend-private [`SandboxHandleInner`](crate::backend::SandboxHandleInner)
//! enum. Users reach variant-specific data via [`SandboxHandle::local`] /
//! [`SandboxHandle::cloud`].

use std::sync::Arc;

use crate::{
    MicrosandboxError, MicrosandboxResult,
    backend::{
        Backend, CloudCreateSandboxResponse, SandboxCloudState, SandboxHandleCloudState,
        SandboxHandleInner, SandboxHandleLocalState,
    },
    db::entity::sandbox as sandbox_entity,
    error::Operation,
};

use super::{Sandbox, SandboxConfig, SandboxModificationBuilder, SandboxStatus, SandboxStopResult};

//--------------------------------------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------------------------------------

/// Default timeout for the eager local agent connection made by
/// [`SandboxHandle::connect`].
pub const DEFAULT_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// Default timeout for [`SandboxHandle::stop`] before escalation.
pub const DEFAULT_STOP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// Default timeout for observing stopped state after force termination.
pub const DEFAULT_KILL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// A lightweight handle to a sandbox.
///
/// Provides metadata access and signal-based lifecycle management (stop, kill,
/// remove) without requiring a live agent bridge. Obtained via
/// [`Sandbox::get`] or [`Sandbox::list`].
///
/// For full runtime capabilities (exec, shell, fs), call
/// [`connect`](SandboxHandle::connect) when the sandbox is already running, or
/// [`start`](SandboxHandle::start) to boot a stopped sandbox.
pub struct SandboxHandle {
    backend: Arc<dyn Backend>,
    inner: SandboxHandleInner,
    name: String,
}

//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------

impl SandboxHandle {
    /// Build a handle from a local sandbox DB row + active PID.
    pub(crate) fn from_local_model(
        backend: Arc<dyn Backend>,
        model: sandbox_entity::Model,
        pid: Option<i32>,
    ) -> Self {
        let name = model.name.clone();
        Self {
            backend,
            inner: SandboxHandleInner::Local(SandboxHandleLocalState {
                db_id: model.id,
                status: model.status,
                config_json: model.config,
                active_config_json: model.active_config,
                created_at: model.created_at.map(|dt| dt.and_utc()),
                updated_at: model.updated_at.map(|dt| dt.and_utc()),
                pid,
            }),
            name,
        }
    }

    /// Build a handle from a [`CloudCreateSandboxResponse`] HTTP response.
    ///
    /// Preserves the cloud's optional curated spec as JSON for the
    /// `config_json()` inspection view. An absent spec is represented as JSON
    /// `null`; it is not replaced with a fabricated SDK configuration.
    pub(crate) fn from_cloud(
        backend: Arc<dyn Backend>,
        cloud: CloudCreateSandboxResponse,
    ) -> MicrosandboxResult<Self> {
        let status = crate::backend::sandbox::cloud_status_to_sandbox_status(cloud.status);
        let config_json = serde_json::to_string(&cloud.spec)?;
        let name = cloud.name.clone();
        Ok(Self {
            backend,
            inner: SandboxHandleInner::Cloud(SandboxHandleCloudState {
                id: cloud.id,
                org_id: cloud.org_id,
                status,
                config_json,
                created_at: Some(cloud.created_at),
                started_at: cloud.started_at,
                stopped_at: cloud.stopped_at,
                last_failure_message: cloud.last_failure_message,
            }),
            name,
        })
    }

    /// Unique name identifying this sandbox.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Which backend variant this handle is bound to.
    pub fn backend_kind(&self) -> crate::backend::BackendKind {
        self.backend.kind()
    }

    /// Local-only handle state. Returns `Some` for local-backed handles.
    pub fn local(&self) -> Option<&SandboxHandleLocalState> {
        match &self.inner {
            SandboxHandleInner::Local(s) => Some(s),
            SandboxHandleInner::Cloud(_) => None,
        }
    }

    /// Cloud-only handle state. Returns `Some` for cloud-backed handles.
    pub fn cloud(&self) -> Option<&SandboxHandleCloudState> {
        match &self.inner {
            SandboxHandleInner::Cloud(s) => Some(s),
            SandboxHandleInner::Local(_) => None,
        }
    }

    /// Snapshot of sandbox status captured when this handle was created.
    ///
    /// **Not live** — call [`Sandbox::status`](super::Sandbox::status) on the
    /// live `Sandbox` (or re-fetch via [`Sandbox::get`](super::Sandbox::get))
    /// for a fresh reading. The `_snapshot` suffix is deliberate to avoid
    /// confusion with `Sandbox::status()` which is async + fetch-live.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let handle = Sandbox::get("agent-1").await?;
    /// // Cheap, in-memory; reflects state at handle-creation time.
    /// let snap = handle.status_snapshot();
    ///
    /// // For a fresh reading, drive through the live Sandbox:
    /// let sb = handle.start().await?;
    /// let live = sb.status().await?;
    /// ```
    pub fn status_snapshot(&self) -> SandboxStatus {
        match &self.inner {
            SandboxHandleInner::Local(s) => s.status,
            SandboxHandleInner::Cloud(s) => s.status,
        }
    }

    /// Snapshot of the cloud `last_failure_message`, if any. Returns `None`
    /// for local handles (local errors flow through the typed error stack).
    pub fn last_failure_message_snapshot(&self) -> Option<String> {
        match &self.inner {
            SandboxHandleInner::Cloud(s) => s.last_failure_message.clone(),
            SandboxHandleInner::Local(_) => None,
        }
    }

    /// The serialized sandbox configuration as stored in the database (local)
    /// or returned by msb-cloud (cloud). Use [`config()`](Self::config) for a
    /// deserialized [`SandboxConfig`].
    pub fn config_json(&self) -> &str {
        match &self.inner {
            SandboxHandleInner::Local(s) => &s.config_json,
            SandboxHandleInner::Cloud(s) => &s.config_json,
        }
    }

    /// The serialized configuration used by the active VM, when known.
    ///
    /// Local handles return `Some` only while a sandbox has started under a
    /// runtime that records active config snapshots. Stopped sandboxes and
    /// older running sandboxes may return `None`.
    pub fn active_config_json(&self) -> Option<&str> {
        match &self.inner {
            SandboxHandleInner::Local(s) => s.active_config_json.as_deref(),
            SandboxHandleInner::Cloud(_) => None,
        }
    }

    /// Parse the stored configuration. Returns an error if the JSON
    /// is malformed (e.g., schema changed since the sandbox was created).
    ///
    /// For local handles this deserializes the persisted [`SandboxConfig`].
    /// For cloud handles this returns an `Unsupported` error: the cloud wire
    /// shape is [`CloudCreateSandboxRequest`](crate::backend::CloudCreateSandboxRequest),
    /// not `SandboxConfig`. Use [`config_json`](Self::config_json) to read the
    /// raw JSON, or [`cloud`](Self::cloud) to access the typed cloud state.
    pub fn config(&self) -> MicrosandboxResult<SandboxConfig> {
        match &self.inner {
            SandboxHandleInner::Local(s) => Ok(serde_json::from_str(&s.config_json)?),
            SandboxHandleInner::Cloud(_) => Err(MicrosandboxError::local_only(
                Operation::SandboxHandleConfig,
            )),
        }
    }

    /// Parse the active configuration snapshot, when one is available.
    pub fn active_config(&self) -> MicrosandboxResult<Option<SandboxConfig>> {
        self.active_config_json()
            .map(serde_json::from_str)
            .transpose()
            .map_err(Into::into)
    }

    /// Start planning a sandbox modification from this handle.
    ///
    /// The builder fetches a fresh handle during [`dry_run`](SandboxModificationBuilder::dry_run)
    /// so planning uses current status and persisted config rather than this
    /// handle's possibly stale snapshot.
    pub fn modify(&self) -> SandboxModificationBuilder {
        SandboxModificationBuilder::new(self.backend.clone(), self.name.clone())
    }

    /// Fail with a typed error when the sandbox is not running.
    fn require_running(&self, operation: &str) -> MicrosandboxResult<()> {
        let status = self.status_snapshot();
        if matches!(
            status,
            super::SandboxStatus::Running | super::SandboxStatus::Draining
        ) {
            return Ok(());
        }
        Err(MicrosandboxError::SandboxNotRunning(format!(
            "'{}' is not running (status: {status:?}); cannot {operation}",
            self.name
        )))
    }

    /// Return a fresh handle for the same sandbox name.
    pub async fn refresh(&self) -> MicrosandboxResult<SandboxHandle> {
        self.backend
            .sandboxes()
            .get(self.backend.clone(), &self.name)
            .await
    }

    /// When this sandbox was first created, if recorded.
    pub fn created_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        match &self.inner {
            SandboxHandleInner::Local(s) => s.created_at,
            SandboxHandleInner::Cloud(s) => s.created_at,
        }
    }

    /// Best-effort "last activity" timestamp.
    ///
    /// - Local: the database row's `updated_at` (modification time of the
    ///   persisted record).
    /// - Cloud: the most recent of `stopped_at` / `started_at` / `created_at`
    ///   from the msb-cloud response. msb-cloud has no dedicated
    ///   `updated_at` column, so this is synthesised on the client.
    pub fn updated_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        match &self.inner {
            SandboxHandleInner::Local(s) => s.updated_at,
            SandboxHandleInner::Cloud(s) => s.stopped_at.or(s.started_at).or(s.created_at),
        }
    }

    /// Read captured output from `exec.log` for this sandbox.
    ///
    /// Same backing data as [`Sandbox::logs`](super::Sandbox::logs).
    /// Works without starting the sandbox. **Local handles only**.
    pub async fn logs(
        &self,
        opts: &crate::logs::LogOptions,
    ) -> MicrosandboxResult<Vec<crate::logs::LogEntry>> {
        self.backend
            .sandboxes()
            .logs(self.backend.clone(), &self.name, opts)
            .await
    }

    /// Stream captured output for this sandbox.
    ///
    /// Same backing data as [`Sandbox::log_stream`](super::Sandbox::log_stream).
    /// Works without starting the sandbox.
    pub async fn log_stream(
        &self,
        opts: &crate::logs::LogStreamOptions,
    ) -> MicrosandboxResult<crate::backend::sandbox::LogStream> {
        self.backend
            .sandboxes()
            .log_stream(self.backend.clone(), &self.name, opts)
            .await
    }

    /// Get the latest metrics snapshot for this sandbox. **Local handles only**.
    pub async fn metrics(&self) -> MicrosandboxResult<super::SandboxMetrics> {
        let local = self
            .local()
            .ok_or_else(|| MicrosandboxError::local_only(Operation::SandboxHandleMetrics))?;

        if local.status != SandboxStatus::Running && local.status != SandboxStatus::Draining {
            return Err(MicrosandboxError::SandboxNotRunning(format!(
                "'{}' is not running (status: {:?})",
                self.name, local.status
            )));
        }

        let config = self.config()?;
        if config.effective_metrics_interval().is_none() {
            return Err(MicrosandboxError::MetricsDisabled(self.name.clone()));
        }

        let local_backend = self
            .backend
            .as_local()
            .ok_or_else(|| MicrosandboxError::local_only(Operation::SandboxHandleMetrics))?;
        let db = local_backend.db().await?.read();
        super::metrics::metrics_for_sandbox(db, local_backend, local.db_id, &config).await
    }

    /// Start this sandbox and return a live handle.
    ///
    /// Boots the VM using the persisted configuration and pinned rootfs state
    /// for local; routes through `POST /v1/sandboxes/by-name/:name/start` for
    /// cloud. The handle remains usable if start fails.
    pub async fn start(&self) -> MicrosandboxResult<Sandbox> {
        self.backend
            .sandboxes()
            .start(self.backend.clone(), &self.name)
            .await
    }

    /// Start this sandbox in detached/background mode.
    ///
    /// The handle remains usable if start fails.
    pub async fn start_detached(&self) -> MicrosandboxResult<Sandbox> {
        self.backend
            .sandboxes()
            .start_detached(self.backend.clone(), &self.name)
            .await
    }

    /// Connect to a running sandbox and return a live handle.
    ///
    /// Local sandboxes establish the agent relay connection eagerly. Cloud
    /// sandboxes return a backend-bound handle whose exec, SSH, and filesystem
    /// operations open authenticated agent WebSockets on demand.
    pub async fn connect(&self) -> MicrosandboxResult<Sandbox> {
        self.connect_with_timeout(DEFAULT_CONNECT_TIMEOUT).await
    }

    /// Connect to a running sandbox with an explicit local agent handshake
    /// timeout.
    ///
    /// Cloud reconnect is lazy and does not open an agent WebSocket here, so
    /// this timeout applies only to local handles.
    pub async fn connect_with_timeout(
        &self,
        timeout: std::time::Duration,
    ) -> MicrosandboxResult<Sandbox> {
        if !matches!(
            self.status_snapshot(),
            SandboxStatus::Running | SandboxStatus::Draining
        ) {
            return Err(MicrosandboxError::SandboxNotRunning(format!(
                "'{}' is not running (status: {:?})",
                self.name,
                self.status_snapshot()
            )));
        }

        match &self.inner {
            SandboxHandleInner::Local(local) => {
                let local_backend = self.backend.as_local().ok_or_else(|| {
                    MicrosandboxError::local_only(Operation::SandboxHandleConnect)
                })?;
                let client = crate::sandbox::fs::agent::connect_agent_with_timeout(
                    local_backend,
                    &self.name,
                    timeout,
                )
                .await?;
                let config: SandboxConfig = serde_json::from_str(&local.config_json)?;

                Ok(Sandbox::from_local(
                    self.backend.clone(),
                    crate::backend::SandboxLocalState {
                        db_id: local.db_id,
                        handle: None,
                        client: Arc::new(client),
                    },
                    config,
                ))
            }
            SandboxHandleInner::Cloud(cloud) => {
                // The cloud handle stores the optional curated spec exactly as
                // returned by the API. Decode it on reconnect, falling back to
                // SDK defaults when the server intentionally omitted it.
                let spec = serde_json::from_str(&cloud.config_json)?;
                let config =
                    crate::backend::sandbox::sandbox_config_from_cloud_spec(&self.name, spec);
                let created_at = cloud.created_at.ok_or_else(|| {
                    MicrosandboxError::Runtime(format!(
                        "cloud sandbox {:?} is missing its creation timestamp",
                        self.name
                    ))
                })?;

                Ok(Sandbox::from_cloud_state(
                    self.backend.clone(),
                    SandboxCloudState {
                        id: cloud.id.clone(),
                        org_id: cloud.org_id.clone(),
                        created_at,
                    },
                    self.name.clone(),
                    config,
                ))
            }
        }
    }

    /// Check whether agentd is reachable without refreshing the sandbox idle timer.
    ///
    /// Connects to the running sandbox and sends `core.ping`. Stopped sandboxes
    /// are not started implicitly; call [`start`](Self::start) first when that
    /// is the desired behavior.
    pub async fn ping(&self) -> MicrosandboxResult<super::SandboxPingResult> {
        self.require_running("ping")?;
        self.connect().await?.ping().await
    }

    /// Explicitly refresh the sandbox idle timer.
    ///
    /// Connects to the running sandbox and sends `core.touch`. Stopped sandboxes
    /// are not started implicitly; call [`start`](Self::start) first when that
    /// is the desired behavior.
    pub async fn touch(&self) -> MicrosandboxResult<super::SandboxTouchResult> {
        self.require_running("touch")?;
        self.connect().await?.touch().await
    }

    /// Snapshot this sandbox to a bare name under the default snapshots
    /// directory (`~/.microsandbox/snapshots/<name>/`).
    ///
    /// The sandbox must be stopped (or crashed); running sandboxes are
    /// rejected with `MicrosandboxError::SnapshotSandboxRunning`. **Local
    /// handles only** — cloud snapshot semantics are deferred.
    pub async fn snapshot(
        &self,
        name: &str,
    ) -> MicrosandboxResult<super::super::snapshot::Snapshot> {
        if self.local().is_none() {
            return Err(MicrosandboxError::local_only(
                Operation::SandboxHandleSnapshot,
            ));
        }
        use super::super::snapshot::Snapshot;
        Snapshot::builder(name)
            .from_sandbox(&self.name)
            .create()
            .await
    }

    /// Stop the sandbox gracefully using the default stop timeout.
    pub async fn stop(&self) -> MicrosandboxResult<()> {
        self.stop_with_timeout(DEFAULT_STOP_TIMEOUT).await
    }

    /// Stop the sandbox gracefully with an explicit timeout before escalation.
    pub async fn stop_with_timeout(&self, timeout: std::time::Duration) -> MicrosandboxResult<()> {
        let current = self.refresh().await?;
        if sandbox_status_is_terminal(current.status_snapshot()) {
            return Ok(());
        }

        if timeout.is_zero() {
            current.kill_with_timeout(DEFAULT_KILL_TIMEOUT).await?;
            return Ok(());
        }

        current.request_stop().await?;
        match tokio::time::timeout(timeout, current.wait_until_stopped()).await {
            Ok(Ok(_)) => {
                // Windows: the DB can record the guest poweroff while the VM
                // process never exits; a successful stop must mean "no
                // process".
                #[cfg(windows)]
                current.reap_leaked_local_runtime().await?;
                return Ok(());
            }
            Ok(Err(error)) => return Err(error),
            Err(_) => {}
        }

        tracing::warn!(
            sandbox = %current.name,
            timeout_secs = timeout.as_secs(),
            "graceful stop exceeded timeout, escalating to kill"
        );
        current.request_kill().await?;
        match tokio::time::timeout(DEFAULT_KILL_TIMEOUT, current.wait_until_stopped()).await {
            Ok(result) => {
                result?;
                Ok(())
            }
            Err(_) => Err(MicrosandboxError::Runtime(format!(
                "timed out observing stopped state for sandbox '{}'",
                current.name
            ))),
        }
    }

    /// Request graceful shutdown without waiting for observed stopped state.
    pub async fn request_stop(&self) -> MicrosandboxResult<()> {
        let current = self.refresh().await?;
        if sandbox_status_is_terminal(current.status_snapshot()) {
            return Ok(());
        }

        current
            .backend
            .sandboxes()
            .stop(current.backend.clone(), &current.name)
            .await
    }

    /// Kill the sandbox immediately and wait until it is observed stopped.
    pub async fn kill(&self) -> MicrosandboxResult<()> {
        self.kill_with_timeout(DEFAULT_KILL_TIMEOUT).await
    }

    /// Request force termination without waiting for observed stopped state.
    pub async fn request_kill(&self) -> MicrosandboxResult<()> {
        let current = self.refresh().await?;
        if sandbox_status_is_terminal(current.status_snapshot()) {
            return Ok(());
        }

        current
            .backend
            .sandboxes()
            .kill(current.backend.clone(), &current.name)
            .await
    }

    /// Force-kill the sandbox and wait up to `timeout` for stopped-state observation.
    pub async fn kill_with_timeout(&self, timeout: std::time::Duration) -> MicrosandboxResult<()> {
        let current = self.refresh().await?;
        if sandbox_status_is_terminal(current.status_snapshot()) {
            return Ok(());
        }

        current.request_kill().await?;
        match tokio::time::timeout(timeout, current.wait_until_stopped()).await {
            Ok(result) => {
                result?;
                Ok(())
            }
            Err(_) => Err(MicrosandboxError::Runtime(format!(
                "timed out observing stopped state for sandbox '{}'",
                current.name
            ))),
        }
    }

    /// Request drain without waiting for observed stopped state.
    pub async fn request_drain(&self) -> MicrosandboxResult<()> {
        let current = self.refresh().await?;
        if sandbox_status_is_terminal(current.status_snapshot()) {
            return Ok(());
        }

        current
            .backend
            .sandboxes()
            .drain(current.backend.clone(), &current.name)
            .await
    }

    /// Wait until this sandbox is observed in a terminal non-running state.
    pub async fn wait_until_stopped(&self) -> MicrosandboxResult<SandboxStopResult> {
        loop {
            let current = match self.refresh().await {
                Ok(current) => current,
                Err(error)
                    if self.is_local_ephemeral()
                        && super::sandbox_not_found_for_name(&error, &self.name) =>
                {
                    return Ok(super::ephemeral_cleanup_stop_result(&self.name));
                }
                Err(error) => return Err(error),
            };
            let status = current.status_snapshot();
            if sandbox_status_is_terminal(status) {
                return Ok(SandboxStopResult {
                    name: current.name,
                    status,
                    exit_code: None,
                    signal: None,
                    observed_at: chrono::Utc::now(),
                    source: Some("refreshed backend state".to_string()),
                });
            }

            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
    }

    /// Remove this sandbox.
    ///
    /// The sandbox must be stopped first. Use [`stop`](Self::stop) or
    /// [`kill`](Self::kill) to stop it before removing. Routes through the
    /// backend trait so cloud handles hit `DELETE /v1/sandboxes/by-name/:name`.
    pub async fn remove(&self) -> MicrosandboxResult<()> {
        match &self.inner {
            SandboxHandleInner::Local(_) => {
                let refreshed = self.refresh().await?;
                let local = refreshed
                    .local()
                    .ok_or_else(|| MicrosandboxError::local_only(Operation::SandboxHandleRemove))?;
                if matches!(
                    local.status,
                    SandboxStatus::Running | SandboxStatus::Draining | SandboxStatus::Paused
                ) {
                    return Err(MicrosandboxError::SandboxStillRunning(format!(
                        "cannot remove sandbox '{}': still running",
                        self.name
                    )));
                }

                let local_backend = self
                    .backend
                    .as_local()
                    .ok_or_else(|| MicrosandboxError::local_only(Operation::SandboxHandleRemove))?;

                // Windows: a terminal row can still be backed by a leaked VM
                // process. Deleting the row and run records now would orphan
                // it while it keeps serving this name's agent pipes, so kill
                // it (identity-checked) or fail before touching any state.
                #[cfg(windows)]
                super::reap_leaked_runtime_process(local_backend, local.db_id, &self.name).await?;
                super::remove_local_persisted_sandbox(local_backend, &self.name, local.db_id).await
            }
            SandboxHandleInner::Cloud(_) => {
                self.backend
                    .sandboxes()
                    .remove(self.backend.clone(), &self.name)
                    .await
            }
        }
    }

    /// Kill any leftover VM process still backing this local sandbox after
    /// its DB row went terminal. No-op for cloud handles.
    #[cfg(windows)]
    async fn reap_leaked_local_runtime(&self) -> MicrosandboxResult<()> {
        let Some(local) = self.local() else {
            return Ok(());
        };
        let Some(local_backend) = self.backend.as_local() else {
            return Ok(());
        };
        super::reap_leaked_runtime_process(local_backend, local.db_id, &self.name)
            .await
            .map(|_| ())
    }

    fn is_local_ephemeral(&self) -> bool {
        is_local_ephemeral_handle(&self.inner)
    }
}

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

fn is_local_ephemeral_handle(inner: &SandboxHandleInner) -> bool {
    let SandboxHandleInner::Local(state) = inner else {
        return false;
    };

    serde_json::from_str::<SandboxConfig>(&state.config_json)
        .map(|config| config.spec.lifecycle.ephemeral)
        .unwrap_or(false)
}

fn sandbox_status_is_terminal(status: SandboxStatus) -> bool {
    matches!(status, SandboxStatus::Stopped | SandboxStatus::Crashed)
}

//--------------------------------------------------------------------------------------------------
// Trait Implementations
//--------------------------------------------------------------------------------------------------

impl std::fmt::Debug for SandboxHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SandboxHandle")
            .field("name", &self.name)
            .field("backend_kind", &self.backend.kind())
            .field("status", &self.status_snapshot())
            .finish()
    }
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::{BackendKind, CloudBackend, CloudSandboxStatus};

    #[tokio::test]
    async fn cloud_connect_rebuilds_live_sandbox_without_http_request() {
        let handle = cloud_handle(CloudSandboxStatus::Running);

        let sandbox = handle.connect().await.unwrap();

        assert_eq!(sandbox.name(), "cloud-connect-test");
        assert_eq!(sandbox.backend_kind(), BackendKind::Cloud);
        assert_eq!(sandbox.cloud().unwrap().id, "sandbox-id");
        assert_eq!(sandbox.config().spec.name, "cloud-connect-test");
    }

    #[tokio::test]
    async fn cloud_connect_rejects_stopped_sandbox() {
        let handle = cloud_handle(CloudSandboxStatus::Stopped);

        let result = handle.connect().await;

        assert!(matches!(
            result,
            Err(MicrosandboxError::SandboxNotRunning(_))
        ));
    }

    fn cloud_handle(status: CloudSandboxStatus) -> SandboxHandle {
        let backend: Arc<dyn Backend> =
            Arc::new(CloudBackend::new("https://unused.invalid", "msb_test_connect").unwrap());
        SandboxHandle::from_cloud(
            backend,
            CloudCreateSandboxResponse {
                id: "sandbox-id".into(),
                org_id: "org-id".into(),
                name: "cloud-connect-test".into(),
                slug: "cloud-connect-test".into(),
                status,
                status_reason: None,
                spec: None,
                ephemeral: false,
                created_at: chrono::Utc::now(),
                started_at: None,
                stopped_at: None,
                last_failure_message: None,
            },
        )
        .unwrap()
    }
}