devsandbox 0.9.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! One-key instance actions (stop/start, remove, open in VS Code, stop
//! forward) and the pending-request queue `tui::mod` drains onto background
//! threads.

use crate::snapshot::{InstanceRow, PhaseRow};
use crate::tui::data::ContainerStatus;
use crate::tui::prompt::PromptAction;
use crate::tui::remote::instance_key;

use super::{App, PortRequest};

/// Why `row` is off-limits to the one-key actions: a live `run`/`rebuild`
/// is materializing it, and anything else would race it (the CLI guards
/// refuse too, but the dashboard shouldn't offer it). `None` = go.
fn busy(row: &InstanceRow) -> Option<String> {
    match &row.phase {
        Some(PhaseRow::InFlight { step }) => {
            Some(format!("`{}` is still {}", row.name, crate::commands::doing(step)))
        }
        _ => None,
    }
}

/// VS Code on a machine's instance: not yet (docs/plans/active/machines-next.md, *2. VS Code on a remote machine (rollout step 7, spike)*).
pub fn not_yet_code(machine: &str, name: &str) -> String {
    format!("code {machine}/{name}: VS Code on a machine isn't supported yet")
}

/// How a verb request the event loop sent for a [`PromptAction`] ended.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum VerbEnd {
    /// Its status line, and whether it failed.
    Done { status: String, failed: bool },
    /// rm's `confirm`: its branch question, nothing removed yet.
    Confirm(String),
}

/// A done-flag write for the event loop to send (`instances.done`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingDone {
    /// State key (a snapshot row name).
    pub instance: String,
    /// Set (`true`) or clear the flag.
    pub done: bool,
    /// Whether the outcome replaces the status line. A thread's child write
    /// leaves the thread's own status (which already names the child) unless
    /// it fails.
    pub report: bool,
}

impl App {
    /// `d` (Instances tab): remove the instance under the cursor right away,
    /// no prompt, as the same `rm` request `:rm` sends (non-forced, so `rm`'s
    /// own dirty-worktree refusal and branch-delete question, a Confirm modal
    /// via [`Self::verb_answered`], still guard it).
    /// A no-op off an instance (process rows are filtered by the caller). An
    /// in-flight one can't be removed: `d` asks to cancel its build instead
    /// (a cancelled `run` rolls back, so that's its removal); a failed one is
    /// removable.
    pub(super) fn remove_instance(&mut self) {
        let Some(i) = self.selected_instance_index() else {
            return;
        };
        let Some(row) = self.snapshot.as_ref().and_then(|s| s.instances.get(i)) else {
            return;
        };
        let key = instance_key(row);
        if busy(row).is_some() {
            self.confirm_cancel_build(key);
            return;
        }
        self.pending_action = Some(PromptAction::Rm { instance: key, force: false, delete_branch: None });
    }

    /// Queue a done-flag write for `instance` on behalf of an Inbox thread
    /// (its outcome only shows on failure).
    pub(super) fn request_child_done(&mut self, instance: String, done: bool) {
        self.pending_done.push(PendingDone { instance, done, report: false });
    }

    /// Take the pending done-flag writes for the event loop to send.
    pub fn take_pending_done(&mut self) -> Vec<PendingDone> {
        std::mem::take(&mut self.pending_done)
    }

    /// `d` (Ports tab): stop the selected forward, queuing its id for the event
    /// loop to remove through the daemon worker. No-op with no row selected.
    pub(super) fn stop_selected_forward(&mut self) {
        let Some(row) = self.ports.get(self.selected()) else {
            return;
        };
        self.status = Some(format!("stopping {}", row.local));
        self.pending_unport = Some(row.id);
    }

    /// `a` (Machines tab): flip the selected machine's `agent`, queuing the
    /// new value for the event loop to set through the daemon worker. The row
    /// changes with the next snapshot push. No-op with no row selected. Any
    /// kind: registered, inbound or routed (the grant is by member key,
    /// fleet plan decision 67).
    pub(super) fn toggle_selected_agent(&mut self) {
        let Some(m) = self.machines.get(self.selected()) else {
            return;
        };
        let agent = !m.agent;
        self.status = Some(format!("{}: agent {}…", m.name, if agent { "on" } else { "off" }));
        self.pending_machine_set = Some((m.name.clone(), agent));
    }

    /// Take the pending `agent` change (machine name, new value) for the
    /// event loop to send, if any.
    pub fn take_pending_machine_set(&mut self) -> Option<(String, bool)> {
        self.pending_machine_set.take()
    }

    /// Take the pending forward request for the event loop to start, if any.
    pub fn take_pending_port(&mut self) -> Option<PortRequest> {
        self.pending_port.take()
    }

    /// Take the pending forward-stop id for the event loop to remove, if any.
    pub fn take_pending_unport(&mut self) -> Option<u64> {
        self.pending_unport.take()
    }

    /// `o` (Instances tab): VS Code attach for the instance under the cursor,
    /// routed through the same [`PromptAction::Code`] path the `code` command
    /// uses. Works for orphan-group instance children and process rows (routing
    /// to the parent instance); a no-op on sandbox / empty / orphan-group nodes.
    pub(super) fn attach_code(&mut self) {
        let Some(i) = self.selected_instance_index() else {
            return;
        };
        let Some(snapshot) = &self.snapshot else {
            return;
        };
        let Some(row) = snapshot.instances.get(i) else {
            return;
        };
        if let Some(m) = &row.machine {
            self.status = Some(not_yet_code(m, &row.name));
            return;
        }
        self.pending_action = Some(PromptAction::Code { instance: row.name.clone(), goto: None });
    }

    /// `s` (Instances tab): stop the running instance under the cursor, or
    /// start it when its container is exited, as a `stop` / detached `start`
    /// verb request the event loop sends (keeping [`App`] I/O-free). Works for
    /// orphan-group instance children and process rows (routing to the parent
    /// instance); a no-op on sandbox / empty / orphan-group nodes and while a
    /// stop/start for the same instance is in flight.
    ///
    /// Two cases can't be served by a `start` and are *rebuilt* instead, by queuing a [`PromptAction::Rebuild`] like the `:` prompt's
    /// (the loop runs it as a detached `devsandbox rebuild`): an exited
    /// instance whose container drifted from the current config, and a
    /// missing container — `rebuild` is the worktree-preserving way to
    /// recreate it (`run` refuses the taken name, `rm` destroys the
    /// worktree). It needs no `starting` guard: once the rebuild records its
    /// phase the row is in flight, which `busy` refuses, and `rebuild`
    /// itself refuses an in-flight instance.
    ///
    /// The phase comes first: an in-flight instance gets nothing (a status
    /// line says what it's doing), and a failed one is rebuilt, the retry
    /// (`rebuild` re-materializes it whatever its container's state).
    pub(super) fn stop_or_start_instance(&mut self) {
        let Some(i) = self.selected_instance_index() else {
            return;
        };
        let Some(snapshot) = &self.snapshot else {
            return;
        };
        let Some(row) = snapshot.instances.get(i) else {
            return;
        };
        let name = instance_key(row);
        if self.stopping.contains(&name) || self.starting.contains(&name) {
            return;
        }
        if let Some(why) = busy(row) {
            self.status = Some(why);
            return;
        }
        if let Some(PhaseRow::Failed { .. }) = row.phase {
            self.pending_action = Some(PromptAction::Rebuild { instance: name, force: false });
            return;
        }
        match row.status {
            ContainerStatus::Running(_) => {
                self.status = Some(format!("stopping {name}…"));
                self.stopping.insert(name.clone());
                self.pending_action = Some(PromptAction::Stop { instance: name });
            }
            ContainerStatus::Exited(_) if row.drift => {
                // Config drifted: recreate the container (worktree preserved)
                // with a detached rebuild instead of a start.
                self.pending_action =
                    Some(PromptAction::Rebuild { instance: name, force: false });
            }
            ContainerStatus::Exited(_) => {
                self.status = Some(format!("starting {name}…"));
                self.starting.insert(name.clone());
                self.pending_action = Some(PromptAction::Start { instance: name });
            }
            ContainerStatus::Unknown => {
                self.status = Some(format!("{name}: status still loading"));
            }
            ContainerStatus::Missing => {
                // No container to start: recreate it via the CLI rebuild (its
                // "config label gone → rebuild anyway" rule covers exactly
                // this).
                self.pending_action =
                    Some(PromptAction::Rebuild { instance: name, force: false });
            }
        }
    }

    /// Help-bar verb for the `r` key: `rename` when the cursor is on an
    /// instance (or one of its process rows), `run` otherwise — mirrors what
    /// [`Self::open_rename_or_run_prompt`] would do.
    pub fn run_rename_hint(&self) -> &'static str {
        if self.selected_instance_index().is_some() {
            "rename"
        } else {
            "run"
        }
    }

    /// Help-bar verb for the `s` key, matching what
    /// [`Self::stop_or_start_instance`] would actually do to the instance under
    /// the cursor: `wait` while it's in flight, `rebuild` once failed, `start`
    /// when it is exited or missing (drifted/missing ones rebuild, which is
    /// still a start from the user's seat), `stop` otherwise.
    pub fn stop_start_hint(&self) -> &'static str {
        let row = self.selected_instance_index().and_then(|i| self.snapshot.as_ref()?.instances.get(i));
        match row {
            Some(InstanceRow { phase: Some(PhaseRow::InFlight { .. }), .. }) => "wait",
            Some(InstanceRow { phase: Some(PhaseRow::Failed { .. }), .. }) => "rebuild",
            Some(row) if matches!(row.status, ContainerStatus::Exited(_) | ContainerStatus::Missing) => "start",
            _ => "stop",
        }
    }

    /// Help-bar verb for the `d` key, matching [`Self::remove_instance`]:
    /// `cancel` on an in-flight instance, else `rm`.
    pub fn remove_hint(&self) -> &'static str {
        let row = self.selected_instance_index().and_then(|i| self.snapshot.as_ref()?.instances.get(i));
        match row {
            Some(row) if busy(row).is_some() => "cancel",
            _ => "rm",
        }
    }

    /// The event loop's report that the verb request for `action` ended:
    /// show its status, clear `s`'s in-flight guard (a detached start
    /// answers once spawned: a thread action waiting on it runs when a
    /// snapshot shows the instance up, [`Self::set_snapshot`]), and turn rm's
    /// branch question into a Confirm modal whose answer resends it.
    pub fn verb_answered(&mut self, action: &PromptAction, end: VerbEnd) {
        match (action, end) {
            (PromptAction::Rm { instance, force, .. }, VerbEnd::Confirm(question)) => {
                self.status = None;
                self.confirm_rm_branch(instance.clone(), *force, question);
            }
            // Only rm asks.
            (_, VerbEnd::Confirm(question)) => self.status = Some(question),
            (action, VerbEnd::Done { status, failed }) => {
                self.status = Some(status);
                match action {
                    PromptAction::Stop { instance } => {
                        self.stopping.remove(instance);
                    }
                    PromptAction::Start { instance } => self.start_answered(instance, failed),
                    _ => {}
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::tui::app::test_support::*;
    use crate::tui::app::*;

    #[test]
    fn d_on_ports_sets_pending_unport() {
        let mut app = new_app();
        app.tab = Tab::Ports;
        app.set_ports(port_rows(3));
        app.on_key(key(KeyCode::Down)); // onto id 1
        app.on_key(key(KeyCode::Char('d')));
        assert_eq!(app.take_pending_unport(), Some(1));
        assert_eq!(app.status.as_deref(), Some("stopping 127.0.0.1:3001"));
    }

    #[test]
    fn a_on_machines_queues_the_flipped_agent() {
        use crate::serve::snapshots::LinkState;
        use crate::tui::remote::tests::sm;
        let mut app = new_app();
        let mut on = sm("b", LinkState::Unreachable);
        on.agent = true;
        app.set_machines(vec![sm("a", LinkState::Connected), on]);
        // Another tab: nothing.
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_machine_set(), None);

        app.on_key(key(KeyCode::Char('5')));
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_machine_set(), Some(("a".into(), true)));
        assert_eq!(app.status.as_deref(), Some("a: agent on…"));
        // Not applied ahead of the push.
        assert!(!app.machines[0].agent);
        app.on_key(key(KeyCode::Down));
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_machine_set(), Some(("b".into(), false)));
        assert_eq!(app.status.as_deref(), Some("b: agent off…"));

        // Inbound and routed machines alike: a grant by member key (fleet
        // plan decision 67), queued.
        let lap = crate::serve::snapshots::SnapshotMachine {
            kind: crate::serve::machines::MachineKind::Inbound,
            target: None,
            ..sm("lap", LinkState::Connected)
        };
        let x = crate::serve::snapshots::SnapshotMachine {
            kind: crate::serve::machines::MachineKind::Routed,
            via: Some("k".into()),
            target: None,
            agent: true,
            ..sm("x", LinkState::Connected)
        };
        app.set_machines(vec![lap, x]);
        app.on_key(key(KeyCode::Up));
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_machine_set(), Some(("lap".into(), true)));
        app.on_key(key(KeyCode::Down));
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_machine_set(), Some(("x".into(), false)));
        assert_eq!(app.status.as_deref(), Some("x: agent off…"));
    }

    #[test]
    fn a_with_no_machine_row_queues_nothing() {
        let mut app = new_app();
        app.tab = Tab::Machines;
        app.on_key(key(KeyCode::Char('a')));
        assert_eq!(app.take_pending_machine_set(), None);
        assert_eq!(app.status, None);
    }

    #[test]
    fn d_on_an_instance_queues_rm_without_a_prompt() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with(1));
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('d')));
        assert_eq!(
            app.take_pending_action(),
            Some(PromptAction::Rm { instance: "inst0".into(), force: false, delete_branch: None })
        );
        assert!(app.prompt.is_none());
        assert_eq!(app.take_pending_done(), []);
    }

    #[test]
    fn d_and_u_off_an_instance_queue_nothing() {
        // A process row.
        let mut app = app_on_proc_row(&["10"]);
        app.on_key(key(KeyCode::Char('d')));
        app.on_key(key(KeyCode::Char('u')));
        assert_eq!(app.take_pending_action(), None);
        // The sandbox node.
        let mut app = new_app();
        app.set_snapshot(snapshot_with(1));
        app.on_key(key(KeyCode::Char('d')));
        assert_eq!(app.take_pending_action(), None);
        // Another tab.
        app.on_key(key(KeyCode::Down));
        app.tab = Tab::Services;
        app.on_key(key(KeyCode::Char('d')));
        assert_eq!(app.take_pending_action(), None);
    }

    #[test]
    fn u_on_an_instance_does_nothing() {
        let mut app = new_app();
        let mut snap = snapshot_with(1);
        snap.instances[0].done = true;
        app.set_snapshot(snap);
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('u')));
        assert_eq!(app.take_pending_done(), []);
        assert_eq!(app.take_pending_action(), None);
    }

    #[test]
    fn d_elsewhere_does_nothing_new() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with(1)); // Instances tab
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('d')));
        assert_eq!(app.take_pending_unport(), None);
    }

    #[test]
    fn o_on_instance_sets_pending_code() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with(1)); // [Sandbox(0), inst0]
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('o')));
        assert_eq!(
            app.take_pending_action(),
            Some(PromptAction::Code { instance: "inst0".into(), goto: None }),
        );
    }

    #[test]
    fn o_on_orphan_instance_sets_pending_code() {
        let mut app = new_app();
        app.set_snapshot(orphan_snapshot()); // [Orphans, orphan0]
        app.on_key(key(KeyCode::Down)); // onto orphan0
        assert_eq!(app.selected_node(), Some(Node::Instance(0)));
        app.on_key(key(KeyCode::Char('o')));
        assert_eq!(
            app.take_pending_action(),
            Some(PromptAction::Code { instance: "orphan0".into(), goto: None }),
        );
    }

    #[test]
    fn o_on_sandbox_is_noop() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with(1)); // cursor on Sandbox(0)
        app.on_key(key(KeyCode::Char('o')));
        assert_eq!(app.take_pending_action(), None);
    }

    #[test]
    fn s_on_running_instance_sets_pending_stop() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with_status(1, running())); // [Sandbox(0), inst0]
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        assert!(app.stopping.contains("inst0"));
        assert_eq!(app.status.as_deref(), Some("stopping inst0…"));
        assert_eq!(app.take_pending_action(), Some(PromptAction::Stop { instance: "inst0".into() }));
        assert_eq!(app.take_pending_action(), None);
    }

    /// A machine's row: the actions name it qualified (the event loop
    /// routes it, `tui::verb_route`), its in-flight guard is its own, and
    /// VS Code isn't offered yet.
    #[test]
    fn actions_on_a_machines_row_queue_its_key() {
        let mut app = machine_app();
        app.selected[Tab::Instances.index()] = 5; // box/inst1
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.status.as_deref(), Some("stopping box/inst1…"));
        assert!(app.stopping.contains("box/inst1") && !app.stopping.contains("inst1"));
        assert_eq!(app.take_pending_action(), Some(PromptAction::Stop { instance: "box/inst1".into() }));
        // The local `inst1` isn't guarded by box's.
        app.selected[Tab::Instances.index()] = 2;
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.take_pending_action(), Some(PromptAction::Stop { instance: "inst1".into() }));

        app.selected[Tab::Instances.index()] = 4; // box/inst0
        app.on_key(key(KeyCode::Char('d')));
        assert_eq!(
            app.take_pending_action(),
            Some(PromptAction::Rm { instance: "box/inst0".into(), force: false, delete_branch: None })
        );
        app.on_key(key(KeyCode::Char('o')));
        assert_eq!(app.take_pending_action(), None);
        assert_eq!(app.status.as_deref(), Some("code box/inst0: VS Code on a machine isn't supported yet"));
        // `p` prefills the key, which the prompt resolves back to the machine.
        app.on_key(key(KeyCode::Char('p')));
        assert_eq!(prompt(&app).input(), "port box/inst0 ");
        app.prompt = None;

        // Reads name the remote target by key; the daemon worker splits it.
        app.on_key(key(KeyCode::Char('l')));
        assert_eq!(app.take_pending_fetch(), [Fetch::Logs { container: "box/devsandbox-inst0".into() }]);
        app.modal = Modal::None;
        app.on_key(key(KeyCode::Char('e')));
        assert_eq!(
            app.take_pending_fetch(),
            [
                Fetch::Config { kind: ConfigKind::Sandbox, name: "box/s".into() },
                Fetch::Inspect { container: "box/devsandbox-inst0".into() },
            ]
        );
    }

    #[test]
    fn s_on_exited_instance_sets_pending_start() {
        let mut app = new_app();
        let status = ContainerStatus::Exited("Exited (0)".into());
        app.set_snapshot(snapshot_with_status(1, status));
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        assert!(app.starting.contains("inst0"));
        assert_eq!(app.status.as_deref(), Some("starting inst0…"));
        assert_eq!(app.take_pending_action(), Some(PromptAction::Start { instance: "inst0".into() }));
        assert_eq!(app.take_pending_action(), None);
    }

    /// Before the runtime is listed, `s` can't know whether to stop or start.
    #[test]
    fn s_on_unknown_instance_does_nothing() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with_status(1, ContainerStatus::Unknown));
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.status.as_deref(), Some("inst0: status still loading"));
        assert_eq!(app.take_pending_action(), None);
    }

    #[test]
    fn s_on_exited_drifted_instance_queues_rebuild() {
        let mut app = new_app();
        let status = ContainerStatus::Exited("Exited (0)".into());
        let mut snap = snapshot_with_status(1, status);
        snap.instances[0].drift = true;
        app.set_snapshot(snap);
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(
            app.take_pending_action(),
            Some(PromptAction::Rebuild { instance: "inst0".into(), force: false })
        );
        // Drift rebuilds: no start guard.
        assert_eq!(app.take_pending_action(), None);
        assert!(app.starting.is_empty());
        assert_eq!(app.take_pending_action(), None);
    }

    #[test]
    fn s_on_exited_undrifted_instance_still_starts() {
        let mut app = new_app();
        let status = ContainerStatus::Exited("Exited (0)".into());
        let snap = snapshot_with_status(1, status); // drift: false
        app.set_snapshot(snap);
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        assert!(app.starting.contains("inst0"));
        assert_eq!(app.take_pending_action(), Some(PromptAction::Start { instance: "inst0".into() }));
        assert_eq!(app.take_pending_action(), None);
    }

    #[test]
    fn s_on_running_drifted_instance_still_stops() {
        let mut app = new_app();
        let mut snap = snapshot_with_status(1, running());
        snap.instances[0].drift = true;
        app.set_snapshot(snap);
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        assert!(app.stopping.contains("inst0"));
        assert_eq!(app.take_pending_action(), Some(PromptAction::Stop { instance: "inst0".into() }));
        assert_eq!(app.take_pending_action(), None);
    }

    #[test]
    fn s_on_missing_container_queues_rebuild() {
        // A missing container can't be started; `s` recreates it via a
        // detached rebuild (worktree preserved), like the drifted-exited case.
        let mut app = new_app();
        app.set_snapshot(snapshot_with(1)); // status Missing
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(
            app.take_pending_action(),
            Some(PromptAction::Rebuild { instance: "inst0".into(), force: false })
        );
        assert_eq!(app.take_pending_action(), None);
        assert!(app.stopping.is_empty());
        assert!(app.starting.is_empty());
    }

    #[test]
    fn s_on_orphan_instance_sets_pending_stop() {
        let mut app = new_app();
        let mut snap = orphan_snapshot(); // [Orphans, orphan0]
        snap.instances[0].status = running();
        app.set_snapshot(snap);
        app.on_key(key(KeyCode::Down)); // onto orphan0
        assert_eq!(app.selected_node(), Some(Node::Instance(0)));
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.take_pending_action(), Some(PromptAction::Stop { instance: "orphan0".into() }));
    }

    #[test]
    fn s_on_sandbox_is_noop() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with(1)); // cursor on Sandbox(0)
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.take_pending_action(), None);
        assert!(app.stopping.is_empty());
    }

    #[test]
    fn s_dedupes_while_stop_in_flight() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with_status(1, running()));
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.take_pending_action(), Some(PromptAction::Stop { instance: "inst0".into() }));
        // Still in flight (loop hasn't cleared `stopping`): a second `s` is a no-op.
        app.on_key(key(KeyCode::Down)); // keep cursor on inst0
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.take_pending_action(), None);
    }

    #[test]
    fn s_dedupes_while_start_in_flight() {
        let mut app = new_app();
        let status = ContainerStatus::Exited("Exited (0)".into());
        app.set_snapshot(snapshot_with_status(1, status));
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.take_pending_action(), Some(PromptAction::Start { instance: "inst0".into() }));
        // Still in flight (loop hasn't cleared `starting`): a second `s` is a no-op.
        app.on_key(key(KeyCode::Down)); // keep cursor on inst0
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.take_pending_action(), None);
    }

    /// The answer to `s`'s request clears its guard (failed or not), so `s`
    /// works again; the status line is the answer's.
    #[test]
    fn s_guards_clear_when_the_answer_arrives() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with_status(1, running()));
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('s')));
        let stop = app.take_pending_action().unwrap();
        app.verb_answered(&stop, VerbEnd::Done { status: "stopped inst0".into(), failed: false });
        assert!(app.stopping.is_empty());
        assert_eq!(app.status.as_deref(), Some("stopped inst0"));

        app.set_snapshot(snapshot_with_status(1, ContainerStatus::Exited("Exited (0)".into())));
        app.on_key(key(KeyCode::Char('s')));
        let start = app.take_pending_action().unwrap();
        assert_eq!(start, PromptAction::Start { instance: "inst0".into() });
        app.verb_answered(&start, VerbEnd::Done { status: "start inst0 failed: boom".into(), failed: true });
        assert!(app.starting.is_empty());
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.take_pending_action(), Some(start));
    }

    /// rm's branch question opens the Confirm modal as rm words it: `y`/
    /// `enter` resend with `deleteBranch: true`, `n` with `false` (same
    /// `force`), `esc`/`q` send nothing.
    #[test]
    fn rms_question_is_a_three_way_confirm() {
        let q = "delete branch `b`? it has commits not on its remote";
        let ask = |app: &mut App, force| {
            let rm = PromptAction::Rm { instance: "inst0".into(), force, delete_branch: None };
            app.verb_answered(&rm, VerbEnd::Confirm(q.into()));
            match &app.modal {
                Modal::Confirm(c) => {
                    assert_eq!(c.question, q);
                    assert_eq!(c.keys_hint(), "y/enter yes · n no · esc cancel");
                }
                _ => panic!("no confirm"),
            }
        };
        let resent = |force, delete| Some(PromptAction::Rm { instance: "inst0".into(), force, delete_branch: Some(delete) });
        let mut app = new_app();
        for (code, force, want) in [
            (KeyCode::Char('y'), false, resent(false, true)),
            (KeyCode::Enter, true, resent(true, true)),
            (KeyCode::Char('n'), true, resent(true, false)),
            (KeyCode::Esc, false, None),
            (KeyCode::Char('q'), false, None),
        ] {
            ask(&mut app, force);
            // Other keys neither answer nor reach the dashboard.
            app.on_key(key(KeyCode::Char('s')));
            assert!(matches!(app.modal, Modal::Confirm(_)));
            app.on_key(key(code));
            assert!(matches!(app.modal, Modal::None), "{code:?}");
            assert_eq!(app.take_pending_action(), want, "{code:?}");
            assert_eq!(app.take_pending_cancel(), None);
        }
        assert_eq!(app.status.as_deref(), Some("rm inst0: cancelled"));
    }

    #[test]
    fn s_ignored_on_services_tab() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with(1));
        app.tab = Tab::Services;
        app.on_key(key(KeyCode::Char('s')));
        assert_eq!(app.take_pending_action(), None);
    }

    #[test]
    fn stop_start_hint_tracks_selection_status() {
        let mut app = new_app();
        // No snapshot / nothing selected → the default verb.
        assert_eq!(app.stop_start_hint(), "stop");
        // Exited instance under the cursor → `start`.
        app.set_snapshot(snapshot_with_status(
            1,
            ContainerStatus::Exited("Exited (0)".into()),
        ));
        app.on_key(key(KeyCode::Down)); // onto inst0
        assert_eq!(app.stop_start_hint(), "start");
        // Running → `stop`; Missing (s rebuilds — a start from the user's
        // seat) → `start`.
        app.set_snapshot(snapshot_with_status(1, running()));
        assert_eq!(app.stop_start_hint(), "stop");
        app.set_snapshot(snapshot_with_status(1, ContainerStatus::Missing));
        assert_eq!(app.stop_start_hint(), "start");
    }

    /// An in-flight row offers nothing that would race the build: `s` only
    /// says what it's doing, whatever its container does, and `d` asks to
    /// cancel it rather than remove it.
    #[test]
    fn s_and_d_on_an_in_flight_instance_queue_nothing() {
        for status in [ContainerStatus::Missing, running(), ContainerStatus::Exited("Exited (1)".into())] {
            let mut app = new_app();
            app.set_snapshot(snapshot_with_phase(1, status, in_flight("postCreateCommand")));
            app.on_key(key(KeyCode::Down)); // onto inst0
            assert_eq!(app.stop_start_hint(), "wait");
            app.on_key(key(KeyCode::Char('s')));
            assert_eq!(app.status.as_deref(), Some("`inst0` is still running postCreateCommand"));
            app.on_key(key(KeyCode::Char('d')));
            assert!(matches!(app.modal, Modal::Confirm(_)));
            app.on_key(key(KeyCode::Esc));
            assert_eq!(app.take_pending_action(), None);
            assert_eq!(app.take_pending_cancel(), None);
        }
    }

    /// `d` on an in-flight row: confirm, then the loop SIGINTs its build;
    /// any answer but yes queues nothing.
    #[test]
    fn d_on_an_in_flight_instance_confirms_a_cancel() {
        let mut app = new_app();
        app.set_snapshot(snapshot_with_phase(1, ContainerStatus::Missing, in_flight("building")));
        app.on_key(key(KeyCode::Down)); // onto inst0
        app.on_key(key(KeyCode::Char('d')));
        match &app.modal {
            Modal::Confirm(c) => assert_eq!(c.question, "cancel inst0's build?"),
            _ => panic!("no confirm"),
        }
        // Other keys neither answer nor reach the dashboard.
        app.on_key(key(KeyCode::Char('s')));
        assert!(matches!(app.modal, Modal::Confirm(_)));
        app.on_key(key(KeyCode::Char('n')));
        assert!(matches!(app.modal, Modal::None));
        assert_eq!(app.take_pending_cancel(), None);
        app.on_key(key(KeyCode::Char('d')));
        app.on_key(key(KeyCode::Char('y')));
        assert!(matches!(app.modal, Modal::None));
        assert_eq!(app.take_pending_cancel(), Some("inst0".into()));
        assert_eq!(app.status.as_deref(), Some("cancelling inst0…"));
        assert_eq!(app.take_pending_action(), None);
        // `enter` is yes too.
        app.on_key(key(KeyCode::Char('d')));
        app.on_key(key(KeyCode::Enter));
        assert_eq!(app.take_pending_cancel(), Some("inst0".into()));
    }

    /// A failed row retries with `s` (a rebuild, even over a running or
    /// exited container) and removes with `d`.
    #[test]
    fn s_rebuilds_and_d_removes_a_failed_instance() {
        for status in [ContainerStatus::Missing, running(), ContainerStatus::Exited("Exited (1)".into())] {
            let mut app = new_app();
            app.set_snapshot(snapshot_with_phase(1, status, failed("postCreateCommand")));
            app.on_key(key(KeyCode::Down)); // onto inst0
            assert_eq!(app.stop_start_hint(), "rebuild");
            app.on_key(key(KeyCode::Char('s')));
            assert_eq!(
                app.take_pending_action(),
                Some(PromptAction::Rebuild { instance: "inst0".into(), force: false })
            );
            assert_eq!(app.take_pending_action(), None);
            app.on_key(key(KeyCode::Char('d')));
            assert_eq!(app.take_pending_action(), Some(PromptAction::Rm { instance: "inst0".into(), force: false, delete_branch: None }));
        }
    }

    #[test]
    fn run_rename_hint_tracks_selection() {
        let mut app = new_app();
        // No snapshot / sandbox row selected → `run`.
        assert_eq!(app.run_rename_hint(), "run");
        app.set_snapshot(snapshot_with(2)); // [Sandbox(0), inst0, inst1]
        assert_eq!(app.run_rename_hint(), "run");
        // Instance row under the cursor → `rename`.
        app.on_key(key(KeyCode::Down)); // onto inst0
        assert_eq!(app.run_rename_hint(), "rename");
    }
}