devsandbox 0.3.2

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
//! Interactive dashboard (`devsandbox` with no subcommand on a TTY).
//!
//! This module owns all terminal I/O: raw mode, the alternate screen, the
//! panic hook that restores them, and the crossterm event loop. The state
//! machine ([`app::App`]) and rendering ([`ui::draw`]) stay I/O-free.

mod app;
mod data;
mod procs;
mod prompt;
mod spec;
mod term;
mod ui;

use std::collections::BTreeMap;
use std::io::{self, Stdout, Write};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use crossterm::event::{self, DisableMouseCapture, EnableMouseCapture, Event};
use ratatui::layout::Rect;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use crossterm::execute;
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;

use crate::commands;

use app::{App, PendingSignal};
use data::Snapshot;
use procs::{parse_top, build_forest, ProcState};
use prompt::PromptAction;

/// How long each `event::poll` blocks before we redraw when no terminal is open.
const POLL_INTERVAL: Duration = Duration::from_millis(250);
/// Shorter poll used while any integrated terminal is open. Key events already
/// wake `event::poll`, but child *output* arrives on the reader threads and only
/// becomes visible on the next draw — a 250ms cadence makes shell echo feel
/// laggy, so we redraw ~33×/s to keep echo snappy while terminals exist.
const TERM_POLL_INTERVAL: Duration = Duration::from_millis(30);
/// Data-refresh cadence: how often a background collection is kicked off.
const TICK_INTERVAL: Duration = Duration::from_secs(2);
/// Process-refresh cadence for expanded instances (separate from the snapshot).
const PROC_TICK: Duration = Duration::from_secs(5);

type Term = Terminal<CrosstermBackend<Stdout>>;

/// Launch the dashboard, guaranteeing the terminal is restored on every exit
/// path (normal, error, or panic).
pub fn dashboard(dir: &Path) -> Result<()> {
    install_panic_hook();
    let mut terminal = setup().context("failed to set up terminal")?;

    let result = run(&mut terminal, App::new(dir.to_path_buf()));

    // Restore on both the Ok and Err paths before returning.
    restore();
    result
}

/// Enable raw mode, enter the alternate screen, build the ratatui terminal.
fn setup() -> Result<Term> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let terminal = Terminal::new(CrosstermBackend::new(stdout))?;
    Ok(terminal)
}

/// Best-effort teardown: leave the alternate screen and disable raw mode.
/// Errors are ignored — there is nothing useful to do while cleaning up.
fn restore() {
    let _ = execute!(io::stdout(), DisableMouseCapture, LeaveAlternateScreen);
    let _ = disable_raw_mode();
}

/// Restore the terminal before the default panic hook prints, so a panic never
/// leaves the shell in raw mode / the alternate screen.
fn install_panic_hook() {
    let default = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        restore();
        default(info);
    }));
}

fn run(terminal: &mut Term, mut app: App) -> Result<()> {
    let dir = app.dir.clone();
    // At most one collection thread in flight; `Some` while one is running.
    let mut pending: Option<Receiver<Snapshot>> = Some(spawn_collect(&dir));
    // Background `s` stops/starts, each reporting completion over its own
    // channel; paired with the instance name so the guard clears even if the
    // thread dies.
    let mut stops: Vec<(String, Receiver<OpDone>)> = Vec::new();
    let mut starts: Vec<(String, Receiver<OpDone>)> = Vec::new();
    // Background process signals (SIGTERM/SIGKILL from a process row); no guard
    // needed since each keypress targets a concrete pid.
    let mut signals: Vec<Receiver<OpDone>> = Vec::new();
    let mut last_tick = Instant::now();
    // At most one process fetch in flight; `Some` while one is running.
    let mut proc_pending: Option<Receiver<BTreeMap<String, ProcState>>> = None;
    let mut last_proc_tick = Instant::now();
    // ssh-agent relays, one per running instance while the dashboard is open
    // (docs/sandbox-helper.md). Owned by a worker thread so `State::load` and
    // the per-instance `exec` spawns never block the UI; the snapshot arm just
    // sends it the running set. Its `Drop` (any exit path, including `?` early
    // returns) closes the channel and joins the thread, killing every bridge
    // before the terminal is restored.
    #[cfg(unix)]
    let bridges = crate::devsbd::bridge::Bridges::spawn_worker();

    while !app.should_quit {
        // Full-frame area, shared by the pre-draw PTY resize and mouse routing.
        let size = terminal.size()?;
        let area = Rect::new(0, 0, size.width, size.height);

        // Pre-draw: size every PTY to the panel the draw path is about to lay
        // out, so the shell's winsize matches what gets rendered. Resize is a
        // cheap no-op when unchanged; every tab (not just the active one) is
        // sized so a background tab is already correct when switched to.
        if !app.terms.is_empty() {
            if let Some((rows, cols)) = ui::term_pane_size(area, app.prompt.is_some()) {
                app.terms.resize_all(rows, cols);
            }
        }

        terminal.draw(|frame| ui::draw(frame, &app))?;

        // Shorter cadence while terminals are open so shell echo stays snappy.
        let poll = if app.terms.is_empty() {
            POLL_INTERVAL
        } else {
            TERM_POLL_INTERVAL
        };
        if event::poll(poll)? {
            match event::read()? {
                Event::Key(key) if key.kind == event::KeyEventKind::Press => app.on_key(key),
                // Feed the full frame area so the modal divider math and the
                // terminal-panel hit-testing stay I/O-free.
                Event::Mouse(ev) => app.on_mouse(&ev, area),
                _ => {}
            }
        }

        // A prompt command is ready: suspend the TUI (or, for `code`, just
        // launch it), then force a redraw + immediate refresh on return.
        if let Some(action) = app.take_pending_action() {
            match action {
                PromptAction::Code { instance } => {
                    app.status = Some(launch_code(&dir, &instance));
                }
                // Rename is pure state I/O (`rename_exact`: no stdout, no
                // prompts — plain `rename` would scribble on the alternate
                // screen): run it in place (no suspend) and force an immediate
                // resnapshot so the renamed row shows now.
                PromptAction::Rename { instance, new_name } => {
                    app.status = Some(match commands::rename::rename_exact(&instance, &new_name) {
                        Ok(new_name) => format!("renamed {instance} -> {new_name}"),
                        Err(e) => format!("rename failed: {e:#}"),
                    });
                    last_tick = Instant::now();
                    pending = Some(spawn_collect(&dir));
                }
                other => {
                    run_suspended(terminal, &dir, other)?;
                    // Redraw from scratch: the child scribbled over the screen.
                    terminal.clear()?;
                    // Refresh data now rather than waiting for the next tick.
                    last_tick = Instant::now();
                    pending = Some(spawn_collect(&dir));
                }
            }
        }

        // A background stop/start was requested by `s`: spawn it without
        // suspending.
        if let Some(instance) = app.take_pending_stop() {
            stops.push((instance.clone(), spawn_stop(&instance)));
        }
        if let Some(instance) = app.take_pending_start() {
            starts.push((instance.clone(), spawn_start(&instance)));
        }
        // A process-row SIGTERM/SIGKILL was requested: send it off-thread.
        if let Some(sig) = app.take_pending_signal() {
            signals.push(spawn_signal(sig));
        }

        // Drain any finished background stops/starts: update the status line,
        // clear the in-flight guard, and force an immediate snapshot refresh so
        // the row's new status shows without waiting for the next tick.
        stops.retain_mut(|(instance, rx)| match rx.try_recv() {
            Ok(done) => {
                app.stopping.remove(instance);
                app.status = Some(done.status);
                last_tick = Instant::now();
                if pending.is_none() {
                    pending = Some(spawn_collect(&dir));
                }
                false
            }
            Err(TryRecvError::Empty) => true,
            // Thread died without sending; clear the guard so `s` works again.
            Err(TryRecvError::Disconnected) => {
                app.stopping.remove(instance);
                false
            }
        });
        starts.retain_mut(|(instance, rx)| match rx.try_recv() {
            Ok(done) => {
                app.starting.remove(instance);
                app.status = Some(done.status);
                last_tick = Instant::now();
                if pending.is_none() {
                    pending = Some(spawn_collect(&dir));
                }
                false
            }
            Err(TryRecvError::Empty) => true,
            // Thread died without sending; clear the guard so `s` works again.
            Err(TryRecvError::Disconnected) => {
                app.starting.remove(instance);
                false
            }
        });
        // Drain finished signals: show the outcome and force a proc refresh so a
        // killed process drops off the forest without waiting for the next tick.
        signals.retain_mut(|rx| match rx.try_recv() {
            Ok(done) => {
                app.status = Some(done.status);
                app.needs_proc_fetch = true;
                false
            }
            Err(TryRecvError::Empty) => true,
            Err(TryRecvError::Disconnected) => false,
        });

        // Drain a finished collection into the app, freeing the in-flight slot.
        if let Some(rx) = &pending {
            match rx.try_recv() {
                Ok(snapshot) => {
                    #[cfg(unix)]
                    {
                        // Owned list handed to the worker; never blocks the UI.
                        let running: Vec<String> = snapshot
                            .instances
                            .iter()
                            .filter(|r| matches!(r.status, data::ContainerStatus::Running(_)))
                            .map(|r| r.container.clone())
                            .collect();
                        bridges.send(running);
                    }
                    app.set_snapshot(snapshot);
                    pending = None;
                }
                Err(TryRecvError::Empty) => {}
                // Thread died without sending; drop the slot so the next tick retries.
                Err(TryRecvError::Disconnected) => pending = None,
            }
        }

        if last_tick.elapsed() >= TICK_INTERVAL {
            last_tick = Instant::now();
            // Skip if a collection is still running so docker calls can't pile up.
            if pending.is_none() {
                pending = Some(spawn_collect(&dir));
            }
        }

        // Drain a finished process fetch into the app, freeing the in-flight slot.
        if let Some(rx) = &proc_pending {
            match rx.try_recv() {
                Ok(procs) => {
                    app.apply_proc_fetch(procs);
                    proc_pending = None;
                }
                Err(TryRecvError::Empty) => {}
                Err(TryRecvError::Disconnected) => proc_pending = None,
            }
        }

        // Process refresh: fetch now on expand / cursor move, else every
        // PROC_TICK, whenever no fetch is already running. Targets are the
        // expanded instances plus the selected running one (for the Detail agent
        // count); an empty set means there is nothing to fetch.
        let want_now = app.take_needs_proc_fetch();
        let tick_due = last_proc_tick.elapsed() >= PROC_TICK;
        if (want_now || tick_due) && proc_pending.is_none() {
            last_proc_tick = Instant::now();
            // Non-running expanded instances get their `(not running)` row here;
            // running ones (and the selection) come back as fetch targets.
            let targets = app.proc_fetch_targets();
            if !targets.is_empty() {
                proc_pending = Some(spawn_proc_fetch(targets));
            }
        }
    }
    Ok(())
}

/// Leave the TUI, run a prompt command with inherited stdio, wait for one
/// keypress, then re-enter the TUI. Command errors are printed (not propagated)
/// so a failed `run`/`exec`/`rm` returns the user to the dashboard.
fn run_suspended(terminal: &mut Term, dir: &Path, action: PromptAction) -> Result<()> {
    restore();

    let result = match &action {
        PromptAction::Run { sandbox, name, branch, base } => {
            commands::run::run(dir, Some(sandbox.clone()), name.clone(), branch.clone(), base.clone())
        }
        PromptAction::Exec { instance, argv } => {
            commands::exec::exec_status(instance, true, true, argv).map(|_| ())
        }
        PromptAction::Rm { instance } => commands::rm::rm(instance),
        PromptAction::Stop { instance } => commands::stop::stop(Some(instance.clone()), false),
        PromptAction::Start { instance } => {
            commands::start::start(dir, Some(instance.clone()), false)
        }
        PromptAction::Rebuild { instance, force } => {
            commands::rebuild::rebuild(dir, Some(instance.clone()), false, *force)
        }
        PromptAction::ServiceRebuild { name } => commands::services::rebuild(dir, name),
        // `code` and `rename` never suspend; handled by the caller.
        PromptAction::Code { .. } | PromptAction::Rename { .. } => Ok(()),
    };
    if let Err(e) = result {
        match log_error(&action, &e) {
            Some(path) => eprintln!("error: {e:#}\nlogged to {}", path.display()),
            None => eprintln!("error: {e:#}"),
        }
    }

    print!("\r\n\x1b[2mpress any key to return\x1b[0m");
    let _ = io::stdout().flush();
    // Raw mode first: cooked mode is line-buffered, so "any key" would
    // otherwise need an Enter before the event arrives.
    enable_raw_mode()?;
    wait_for_key();

    // Re-enter: the outer setup already ran once; re-arm the alt screen + mouse.
    execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?;
    terminal.hide_cursor()?;
    Ok(())
}

/// Write a failed suspended command's error to a timestamped log file under the
/// data dir (`<data>/devsandbox/logs/<verb>-<unix>.log`, alongside `state.toml`)
/// and return its path so the caller can point the user at it. Best-effort:
/// `None` on any I/O failure, so the caller falls back to a plain stderr print.
fn log_error(action: &PromptAction, err: &anyhow::Error) -> Option<PathBuf> {
    let verb = match action {
        PromptAction::Run { .. } => "run",
        PromptAction::Exec { .. } => "exec",
        PromptAction::Rm { .. } => "rm",
        PromptAction::Stop { .. } => "stop",
        PromptAction::Start { .. } => "start",
        PromptAction::Rebuild { .. } => "rebuild",
        PromptAction::ServiceRebuild { .. } => "service rebuild",
        PromptAction::Code { .. } => "code",
        PromptAction::Rename { .. } => "rename",
    };
    let dir = crate::state::State::path().ok()?.parent()?.join("logs");
    std::fs::create_dir_all(&dir).ok()?;
    let path = dir.join(format!("{verb}-{}.log", crate::state::Instance::now()));
    std::fs::write(&path, format!("{verb} failed: {err:#}\n")).ok()?;
    Some(path)
}

/// Block until the next key press (consuming it), ignoring release/repeat.
fn wait_for_key() {
    loop {
        match event::read() {
            Ok(Event::Key(key)) if key.kind == event::KeyEventKind::Press => break,
            Ok(_) => continue,
            Err(_) => break,
        }
    }
}

/// Launch VS Code attached to `instance` (a snapshot row name, which equals
/// the state instance key). Returns a one-line status for the help-bar.
fn launch_code(dir: &Path, instance: &str) -> String {
    let state = match crate::state::State::load() {
        Ok(s) => s,
        Err(e) => return format!("code: {e:#}"),
    };
    let Some(info) = state.instances.get(instance) else {
        return format!("code: unknown instance `{instance}`");
    };
    commands::vscode::launch(dir, instance, info).unwrap_or_else(|e| format!("{e:#}"))
}

/// Result of a background `s` stop/start, drained by the event loop.
struct OpDone {
    /// One-line outcome for the help-bar status.
    status: String,
}

/// Spawn a detached thread that stops `instance` (docker stop can block ~10s on
/// the SIGTERM timeout) and reports a one-line status back. Docker calls go
/// through the screen-safe quiet path so stderr can't corrupt the TUI. `instance`
/// is a snapshot row name, which equals the state instance key.
fn spawn_stop(instance: &str) -> Receiver<OpDone> {
    let (tx, rx) = mpsc::channel();
    let instance = instance.to_string();
    std::thread::spawn(move || {
        let status = match crate::state::State::load() {
            Ok(state) => match state.instances.get(&instance) {
                Some(info) => {
                    let services =
                        commands::stop::service_containers(&info.project, &info.instance_id);
                    commands::stop::stop_containers(&info.container, &services, true);
                    format!("stopped {instance}")
                }
                None => format!("stop: unknown instance `{instance}`"),
            },
            Err(e) => format!("stop: {e:#}"),
        };
        let _ = tx.send(OpDone { status });
    });
    rx
}

/// Spawn a detached thread that starts `instance`'s containers (isolated
/// services first, then the instance) and reports a one-line status back. The
/// bare-start path is used — no service recreation or lifecycle commands — so
/// nothing can write to the alternate screen; docker calls go through the
/// screen-safe quiet path. `instance` is a snapshot row name, which equals the
/// state instance key.
fn spawn_start(instance: &str) -> Receiver<OpDone> {
    let (tx, rx) = mpsc::channel();
    let instance = instance.to_string();
    std::thread::spawn(move || {
        let status = match crate::state::State::load() {
            Ok(state) => match state.instances.get(&instance) {
                Some(info) => {
                    // Bare start bypasses `start_instance`, so re-point the agent
                    // symlink here too, so a restart after host agent rotation
                    // re-captures the live socket (docs/ssh-agent.md).
                    commands::run::ssh_agent_refresh(info);
                    let services =
                        commands::stop::service_containers(&info.project, &info.instance_id);
                    commands::start::start_containers(&info.container, &services, true);
                    // Reinstall the helper (no-op when current): covers CLI
                    // upgrades and images that mount a tmpfs at `/run`.
                    crate::devsbd::ensure_recorded(&instance, info, true);
                    format!("started {instance}")
                }
                None => format!("start: unknown instance `{instance}`"),
            },
            Err(e) => format!("start: {e:#}"),
        };
        let _ = tx.send(OpDone { status });
    });
    rx
}

/// Spawn a detached thread that sends `sig.signal` to a pid inside a container
/// (`kill -<n>` via the runtime's screen-safe exec) and reports a one-line
/// status back.
fn spawn_signal(sig: PendingSignal) -> Receiver<OpDone> {
    let (tx, rx) = mpsc::channel();
    std::thread::spawn(move || {
        let status = match crate::runtime::backend().signal_proc(
            &sig.container,
            &sig.pid,
            sig.signal.num(),
        ) {
            Ok(()) => format!("sent {} to pid {}", sig.signal.name(), sig.pid),
            Err(e) => format!("{}: {e:#}", sig.signal.name()),
        };
        let _ = tx.send(OpDone { status });
    });
    rx
}

/// Spawn one detached thread that runs the runtime's `proc_list` for each target
/// `(instance name, container)` and sends back a name→[`ProcState`] map. Docker
/// calls go through the screen-safe quiet path; a per-container error becomes a
/// `(processes unavailable: …)` message row rather than failing the batch.
fn spawn_proc_fetch(targets: Vec<(String, String)>) -> Receiver<BTreeMap<String, ProcState>> {
    let (tx, rx) = mpsc::channel();
    std::thread::spawn(move || {
        let mut out: BTreeMap<String, ProcState> = BTreeMap::new();
        for (instance, container) in targets {
            let state = match crate::runtime::backend().proc_list(&container) {
                Ok(list) => ProcState::Rows {
                    rows: build_forest(parse_top(&list.text)),
                    signalable: list.container_pids,
                },
                Err(e) => ProcState::Message(format!("(processes unavailable: {e:#})")),
            };
            out.insert(instance, state);
        }
        // Receiver may be gone if the UI quit mid-fetch; ignore send errors.
        let _ = tx.send(out);
    });
    rx
}

/// Spawn a detached thread that collects one [`Snapshot`] and sends it back.
/// The receiver is polled from the event loop, keeping [`App`] I/O-free.
fn spawn_collect(dir: &Path) -> Receiver<Snapshot> {
    let (tx, rx) = mpsc::channel();
    let dir: PathBuf = dir.to_path_buf();
    std::thread::spawn(move || {
        // Receiver may be gone if the UI quit mid-collection; ignore send errors.
        let _ = tx.send(data::collect(&dir));
    });
    rx
}