use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use crossterm::event::{
KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use ratatui::layout::Rect;
use crate::commands::run::DEFAULT_WORKTREE_BRANCH;
use crate::config::Config;
use crate::runtime::backend;
use super::data::{visible_nodes, ContainerStatus, InstanceRow, Node, Snapshot, ORPHANS_NAME};
use super::procs::ProcState;
use super::prompt::{Prompt, PromptAction, COMMANDS};
use super::term::{encode_key, TermSession, TermTabs, SHELL_FALLBACK_CMD};
use crate::runtime::NAME_PREFIX;
const HELP_BODY: &str = "\
Global
q, ctrl-c quit
tab / S-tab switch tab 1/2 jump to tab
: command prompt ? this help
Tables (Instances / Services)
↑/k ↓/j move selection
→/space expand (sandbox instances, instance processes)
← collapse / jump to parent
enter, e open config explorer
r run (sandbox) / o open in VS Code (Instances)
rename (instance)
s stop / start l logs (Instances tab)
(stops running / starts exited; s-start is a bare start —
:start runs services + postStartCommand too; a drifted
exited instance is rebuilt instead)
(process rows act on their parent instance)
Terminals
t open terminal (instance / service)
T force a new terminal for the same target
[ / ] previous / next terminal tab
x close the active terminal
ctrl-] / F12 focus terminal ⇄ back to dashboard
(while focused, all other keys go to the shell)
Config modal
t toggle original / resolved
tab switch pane (config ⇄ inspect)
< / > resize the divider (drag it too)
↑/k ↓/j scroll focused pane pgup/pgdn page
g / G top / bottom
esc, q close
Logs modal
↑/k ↓/j scroll pgup/pgdn page
g / G top / bottom
esc, q close
Command prompt (:)
run <sandbox> [--name n] [--branch b] exec <instance> <cmd…>
code <instance> rm <instance> rename <instance> <new-name>
stop <instance> start <instance>
tab complete / cycle
↑ ↓ history
ctrl-u clear line ctrl-w delete word
esc cancel";
pub struct TextModal {
pub title: String,
pub body: String,
pub scroll: u16,
}
impl TextModal {
pub fn new(title: String, body: String) -> Self {
Self { title, body, scroll: 0 }
}
fn on_scroll_key(&mut self, key: KeyEvent) -> bool {
scroll_key(&mut self.scroll, line_count(&self.body), key)
}
}
fn line_count(body: &str) -> u16 {
body.lines().count().min(u16::MAX as usize) as u16
}
fn scroll_key(scroll: &mut u16, lines: u16, key: KeyEvent) -> bool {
let max = lines.saturating_sub(1);
match key.code {
KeyCode::Up | KeyCode::Char('k') => *scroll = scroll.saturating_sub(1),
KeyCode::Down | KeyCode::Char('j') => *scroll = (*scroll).saturating_add(1).min(max),
KeyCode::PageUp => *scroll = scroll.saturating_sub(20),
KeyCode::PageDown => *scroll = (*scroll).saturating_add(20).min(max),
KeyCode::Char('g') => *scroll = 0,
KeyCode::Char('G') => *scroll = max,
_ => return false,
}
true
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Side {
Original,
Resolved,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Pane {
Config,
Inspect,
}
const SPLIT_MIN: u16 = 20;
const SPLIT_MAX: u16 = 80;
pub struct ConfigView {
pub title: String,
pub original: String,
pub resolved: String,
pub showing: Side,
pub scroll: u16,
pub hash: String,
pub inspect: String,
pub inspect_scroll: u16,
pub inspect_container: String,
pub focus: Pane,
pub split_pct: u16,
}
impl ConfigView {
pub fn body(&self) -> &str {
match self.showing {
Side::Original => &self.original,
Side::Resolved => &self.resolved,
}
}
fn line_count(&self) -> u16 {
line_count(self.body())
}
fn clamp_scroll(&mut self) {
let max = self.line_count().saturating_sub(1);
if self.scroll > max {
self.scroll = max;
}
}
fn scroll_focused(&mut self, key: KeyEvent) {
match self.focus {
Pane::Config => {
let lines = self.line_count();
scroll_key(&mut self.scroll, lines, key);
}
Pane::Inspect => {
let lines = line_count(&self.inspect);
scroll_key(&mut self.inspect_scroll, lines, key);
}
}
}
fn resize(&mut self, delta: i16) {
self.split_pct = clamp_split(self.split_pct as i16 + delta);
}
}
fn clamp_split(pct: i16) -> u16 {
pct.clamp(SPLIT_MIN as i16, SPLIT_MAX as i16) as u16
}
pub fn divider_pct(col: u16, width: u16) -> u16 {
if width == 0 {
return SPLIT_MIN;
}
let pct = (col as u32 * 100 / width as u32) as i16;
clamp_split(pct)
}
fn col_near(col: u16, divider: u16) -> bool {
col.abs_diff(divider) <= 1
}
fn point_in(rect: Rect, col: u16, row: u16) -> bool {
col >= rect.x
&& col < rect.x + rect.width
&& row >= rect.y
&& row < rect.y + rect.height
}
fn apply_delta(scroll: u16, delta: i16, max: u16) -> u16 {
let next = scroll as i32 + delta as i32;
next.clamp(0, max as i32) as u16
}
pub enum Modal {
None,
Config(ConfigView),
Help(TextModal),
Logs(TextModal),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Tab {
Instances,
Services,
}
impl Tab {
pub const ALL: [Tab; 2] = [Tab::Instances, Tab::Services];
pub fn title(self) -> &'static str {
match self {
Tab::Instances => "Instances",
Tab::Services => "Services",
}
}
fn index(self) -> usize {
match self {
Tab::Instances => 0,
Tab::Services => 1,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Focus {
Dashboard,
Terminal,
}
pub struct App {
pub dir: PathBuf,
pub tab: Tab,
selected: [usize; 2],
collapsed: BTreeSet<String>,
expanded_procs: BTreeSet<String>,
pub procs: BTreeMap<String, ProcState>,
pub needs_proc_fetch: bool,
pub snapshot: Option<Snapshot>,
pub modal: Modal,
pub prompt: Option<Prompt>,
pub pending_action: Option<PromptAction>,
pub pending_stop: Option<String>,
pub stopping: BTreeSet<String>,
pub pending_start: Option<String>,
pub starting: BTreeSet<String>,
pub status: Option<String>,
dragging_divider: bool,
pub focus: Focus,
pub terms: TermTabs,
pub should_quit: bool,
}
impl App {
pub fn new(dir: PathBuf) -> Self {
Self {
dir,
tab: Tab::Instances,
selected: [0, 0],
collapsed: BTreeSet::new(),
expanded_procs: BTreeSet::new(),
procs: BTreeMap::new(),
needs_proc_fetch: false,
snapshot: None,
modal: Modal::None,
prompt: None,
pending_action: None,
pending_stop: None,
stopping: BTreeSet::new(),
pending_start: None,
starting: BTreeSet::new(),
status: None,
dragging_divider: false,
focus: Focus::Dashboard,
terms: TermTabs::default(),
should_quit: false,
}
}
pub fn set_snapshot(&mut self, snapshot: Snapshot) {
self.snapshot = Some(snapshot);
self.clamp_selection();
}
fn clamp_selection(&mut self) {
for tab in Tab::ALL {
let rows = self.row_count_for(tab);
let slot = tab.index();
if rows == 0 {
self.selected[slot] = 0;
} else if self.selected[slot] >= rows {
self.selected[slot] = rows - 1;
}
}
}
pub fn selected(&self) -> usize {
self.selected[self.tab.index()]
}
fn row_count(&self) -> usize {
self.row_count_for(self.tab)
}
fn row_count_for(&self, tab: Tab) -> usize {
match tab {
Tab::Instances => self.visible_nodes().len(),
Tab::Services => self.snapshot.as_ref().map_or(0, |s| s.services.len()),
}
}
pub fn visible_nodes(&self) -> Vec<Node> {
match &self.snapshot {
Some(s) => visible_nodes(
&s.sandboxes,
&s.instances,
&self.collapsed,
&self.expanded_procs,
&self.procs,
),
None => Vec::new(),
}
}
pub fn is_collapsed_group(&self, key: &str) -> bool {
self.collapsed.contains(key)
}
fn selected_node(&self) -> Option<Node> {
self.visible_nodes()
.get(self.selected[Tab::Instances.index()])
.copied()
}
pub fn next_tab(&mut self) {
self.tab = match self.tab {
Tab::Instances => Tab::Services,
Tab::Services => Tab::Instances,
};
}
pub fn prev_tab(&mut self) {
self.next_tab();
}
fn select_up(&mut self) {
let slot = self.tab.index();
self.selected[slot] = self.selected[slot].saturating_sub(1);
self.needs_proc_fetch = true;
}
fn select_down(&mut self) {
let rows = self.row_count();
if rows == 0 {
return;
}
let slot = self.tab.index();
self.selected[slot] = (self.selected[slot] + 1).min(rows - 1);
self.needs_proc_fetch = true;
}
fn collapse_key(&self, node: Node) -> Option<String> {
let snapshot = self.snapshot.as_ref()?;
match node {
Node::Sandbox(i) => snapshot.sandboxes.get(i).map(|s| s.name.clone()),
Node::Orphans => Some(ORPHANS_NAME.to_string()),
Node::Instance(_) | Node::Empty(_) | Node::Proc { .. } => None,
}
}
fn tree_expand(&mut self) {
match self.selected_node() {
Some(Node::Instance(_)) => self.expand_procs(),
Some(node) => {
if let Some(key) = self.collapse_key(node) {
self.collapsed.remove(&key);
self.clamp_selection();
}
}
None => {}
}
}
fn tree_toggle(&mut self) {
match self.selected_node() {
Some(Node::Instance(_)) => {
if let Some(name) = self.selected_instance_name() {
if !self.expanded_procs.remove(&name) {
self.expanded_procs.insert(name);
self.needs_proc_fetch = true;
}
self.clamp_selection();
}
}
Some(node) => {
if let Some(key) = self.collapse_key(node) {
if !self.collapsed.remove(&key) {
self.collapsed.insert(key);
}
self.clamp_selection();
}
}
None => {}
}
}
fn expand_procs(&mut self) {
if let Some(name) = self.selected_instance_name() {
if self.expanded_procs.insert(name) {
self.needs_proc_fetch = true;
}
self.clamp_selection();
}
}
fn tree_collapse(&mut self) {
let Some(node) = self.selected_node() else {
return;
};
match node {
Node::Sandbox(_) | Node::Orphans => {
if let Some(key) = self.collapse_key(node) {
self.collapsed.insert(key);
self.clamp_selection();
}
}
Node::Proc { instance, .. } => {
if let Some(pos) = self.instance_node_position(instance) {
self.selected[Tab::Instances.index()] = pos;
}
}
Node::Instance(_) => {
if let Some(name) = self.selected_instance_name() {
if self.expanded_procs.remove(&name) {
self.clamp_selection();
return;
}
}
if let Some(parent) = self.parent_index(self.selected[Tab::Instances.index()]) {
self.selected[Tab::Instances.index()] = parent;
}
}
Node::Empty(_) => {
if let Some(parent) = self.parent_index(self.selected[Tab::Instances.index()]) {
self.selected[Tab::Instances.index()] = parent;
}
}
}
}
fn selected_instance_index(&self) -> Option<usize> {
match self.selected_node()? {
Node::Instance(i) => Some(i),
Node::Proc { instance, .. } => Some(instance),
_ => None,
}
}
fn selected_instance_name(&self) -> Option<String> {
let snapshot = self.snapshot.as_ref()?;
let idx = self.selected_instance_index()?;
snapshot.instances.get(idx).map(|r| r.name.clone())
}
fn instance_node_position(&self, instance: usize) -> Option<usize> {
self.visible_nodes()
.iter()
.position(|n| matches!(n, Node::Instance(i) if *i == instance))
}
fn parent_index(&self, pos: usize) -> Option<usize> {
let nodes = self.visible_nodes();
nodes[..pos.min(nodes.len())]
.iter()
.rposition(|n| matches!(n, Node::Sandbox(_) | Node::Orphans))
}
pub fn on_key(&mut self, key: KeyEvent) {
if self.prompt.is_some() {
self.on_key_prompt(key);
return;
}
if !matches!(self.modal, Modal::None) {
self.on_key_modal(key);
return;
}
if self.focus == Focus::Terminal {
self.on_key_terminal(key);
return;
}
self.status = None;
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
match key.code {
KeyCode::Char('q') => self.should_quit = true,
KeyCode::Char('c') if ctrl => self.should_quit = true,
KeyCode::Char(':') => self.open_prompt(),
KeyCode::Tab => self.next_tab(),
KeyCode::BackTab => self.prev_tab(),
KeyCode::Char('1') => self.tab = Tab::Instances,
KeyCode::Char('2') => self.tab = Tab::Services,
KeyCode::Char(']') if ctrl => self.enter_terminal(),
KeyCode::F(12) => self.enter_terminal(),
KeyCode::Char('t') => self.open_terminal(false),
KeyCode::Char('T') => self.open_terminal(true),
KeyCode::Char(']') => self.terms.next(),
KeyCode::Char('[') => self.terms.prev(),
KeyCode::Char('x') => self.terms.close_active(),
KeyCode::Up | KeyCode::Char('k') => self.select_up(),
KeyCode::Down | KeyCode::Char('j') => self.select_down(),
KeyCode::Right if self.tab == Tab::Instances => self.tree_expand(),
KeyCode::Char(' ') if self.tab == Tab::Instances => self.tree_toggle(),
KeyCode::Left if self.tab == Tab::Instances => self.tree_collapse(),
KeyCode::Enter | KeyCode::Char('e') => self.open_config(),
KeyCode::Char('r') if self.tab == Tab::Instances => self.open_rename_or_run_prompt(),
KeyCode::Char('o') if self.tab == Tab::Instances => self.attach_code(),
KeyCode::Char('s') if self.tab == Tab::Instances => self.stop_or_start_instance(),
KeyCode::Char('l') => self.open_logs(),
KeyCode::Char('?') => self.open_help(),
_ => {}
}
}
fn on_key_terminal(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
if matches!(key.code, KeyCode::Char(']') if ctrl) || key.code == KeyCode::F(12) {
self.focus = Focus::Dashboard;
return;
}
let Some(session) = self.terms.active_session_mut() else {
self.focus = Focus::Dashboard;
return;
};
if session.exited() {
return;
}
let application_cursor = session
.parser()
.lock()
.map(|p| p.screen().application_cursor())
.unwrap_or(false);
if let Some(bytes) = encode_key(key, application_cursor) {
session.write_key_bytes(&bytes);
}
}
fn enter_terminal(&mut self) {
if self.terms.is_empty() {
self.status = Some("no terminal open — press t".into());
} else {
self.focus = Focus::Terminal;
}
}
pub fn on_mouse(&mut self, ev: &MouseEvent, area: Rect) {
let Modal::Config(view) = &mut self.modal else {
self.dragging_divider = false;
self.terminal_mouse(ev, area);
return;
};
let divider = (area.width as u32 * view.split_pct as u32 / 100) as u16;
match ev.kind {
MouseEventKind::Down(MouseButton::Left) => {
if col_near(ev.column, divider) {
self.dragging_divider = true;
view.split_pct = divider_pct(ev.column, area.width);
}
}
MouseEventKind::Drag(MouseButton::Left) => {
if self.dragging_divider {
view.split_pct = divider_pct(ev.column, area.width);
}
}
MouseEventKind::Up(MouseButton::Left) => {
self.dragging_divider = false;
}
MouseEventKind::ScrollDown => {
Self::wheel_scroll(view, ev.column, divider, 3);
}
MouseEventKind::ScrollUp => {
Self::wheel_scroll(view, ev.column, divider, -3);
}
_ => {}
}
}
fn terminal_mouse(&mut self, ev: &MouseEvent, area: Rect) {
if self.terms.is_empty() {
return;
}
let prompt_open = self.prompt.is_some();
let panel = super::ui::terminal_panel_rect(area, prompt_open);
let inside = point_in(panel, ev.column, ev.row);
match ev.kind {
MouseEventKind::Down(MouseButton::Left) => {
if inside {
let focused = self.focus == Focus::Terminal;
if let Some(i) =
super::ui::terminal_tab_hit(self, panel, focused, ev.column, ev.row)
{
self.terms.set_active(i);
}
self.focus = Focus::Terminal;
} else if self.focus == Focus::Terminal {
self.focus = Focus::Dashboard;
}
}
MouseEventKind::ScrollUp if inside => self.scroll_active_terminal(3),
MouseEventKind::ScrollDown if inside => self.scroll_active_terminal(-3),
_ => {}
}
}
fn scroll_active_terminal(&mut self, delta: i16) {
let Some(session) = self.terms.active_session() else {
return;
};
let Ok(mut parser) = session.parser().lock() else {
return;
};
let current = parser.screen().scrollback() as i32;
let next = (current + delta as i32).max(0) as usize;
parser.screen_mut().set_scrollback(next);
}
fn wheel_scroll(view: &mut ConfigView, col: u16, divider: u16, delta: i16) {
if col < divider {
let max = view.line_count().saturating_sub(1);
view.scroll = apply_delta(view.scroll, delta, max);
} else {
let max = line_count(&view.inspect).saturating_sub(1);
view.inspect_scroll = apply_delta(view.inspect_scroll, delta, max);
}
}
fn open_prompt(&mut self) {
self.status = None;
self.prompt = Some(Prompt::new(super::prompt::load_history()));
}
fn open_run_prompt(&mut self) {
self.status = None;
let sandbox = self.snapshot.as_ref().and_then(|snapshot| {
match self.selected_node() {
Some(Node::Sandbox(i)) | Some(Node::Empty(i)) => {
snapshot.sandboxes.get(i).map(|s| s.name.clone())
}
Some(Node::Instance(i)) => snapshot.instances.get(i).map(|r| r.sandbox.clone()),
Some(Node::Proc { instance, .. }) => {
snapshot.instances.get(instance).map(|r| r.sandbox.clone())
}
Some(Node::Orphans) | None => None,
}
});
let history = super::prompt::load_history();
self.prompt = Some(match sandbox {
Some(name) => Prompt::with_input(history, format!("run {name} ")),
None => Prompt::new(history),
});
}
fn open_rename_or_run_prompt(&mut self) {
let Some(name) = self.selected_instance_name() else {
self.open_run_prompt();
return;
};
self.status = None;
let history = super::prompt::load_history();
self.prompt = Some(Prompt::with_input(history, format!("rename {name} ")));
}
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;
};
self.pending_action = Some(PromptAction::Code { instance: row.name.clone() });
}
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 = row.name.clone();
if self.stopping.contains(&name) || self.starting.contains(&name) {
return;
}
match row.status {
ContainerStatus::Running(_) => {
self.status = Some(format!("stopping {name}…"));
self.stopping.insert(name.clone());
self.pending_stop = Some(name);
}
ContainerStatus::Exited(_) if row.drift => {
self.pending_action = Some(PromptAction::Rebuild { instance: name });
}
ContainerStatus::Exited(_) => {
self.status = Some(format!("starting {name}…"));
self.starting.insert(name.clone());
self.pending_start = Some(name);
}
ContainerStatus::Missing => {}
}
}
pub fn stop_start_hint(&self) -> &'static str {
let exited = self
.selected_instance_index()
.and_then(|i| self.snapshot.as_ref()?.instances.get(i))
.is_some_and(|row| matches!(row.status, ContainerStatus::Exited(_)));
if exited { "start" } else { "stop" }
}
pub fn take_pending_stop(&mut self) -> Option<String> {
self.pending_stop.take()
}
pub fn take_pending_start(&mut self) -> Option<String> {
self.pending_start.take()
}
pub fn agent_count(&self, instance: &str) -> Option<usize> {
match self.procs.get(instance) {
Some(ProcState::Rows(rows)) => {
Some(rows.iter().filter(|r| super::procs::is_agent(&r.args)).count())
}
_ => None,
}
}
fn selected_running_instance(&self) -> Option<(String, String)> {
let snapshot = self.snapshot.as_ref()?;
let idx = self.selected_instance_index()?;
let row = snapshot.instances.get(idx)?;
matches!(row.status, ContainerStatus::Running(_))
.then(|| (row.name.clone(), row.container.clone()))
}
pub fn take_needs_proc_fetch(&mut self) -> bool {
std::mem::take(&mut self.needs_proc_fetch)
}
pub fn proc_fetch_targets(&mut self) -> Vec<(String, String)> {
let Some(snapshot) = &self.snapshot else {
return Vec::new();
};
let mut targets = Vec::new();
let mut not_running: Vec<String> = Vec::new();
for name in &self.expanded_procs {
match snapshot.instances.iter().find(|r| &r.name == name) {
Some(row) if matches!(row.status, ContainerStatus::Running(_)) => {
targets.push((row.name.clone(), row.container.clone()));
}
_ => not_running.push(name.clone()),
}
}
for name in not_running {
self.procs
.insert(name, ProcState::Message("(not running)".to_string()));
}
if let Some((name, container)) = self.selected_running_instance() {
if !targets.iter().any(|(n, _)| n == &name) {
targets.push((name, container));
}
}
targets
}
pub fn apply_proc_fetch(&mut self, fetched: BTreeMap<String, ProcState>) {
self.procs.extend(fetched);
}
fn on_key_prompt(&mut self, key: KeyEvent) {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
match key.code {
KeyCode::Esc => {
self.prompt = None;
}
KeyCode::Char('c') if ctrl => {
self.prompt = None;
}
KeyCode::Enter => {
let Some(prompt) = &mut self.prompt else {
return;
};
if let Some(action) = prompt.parse() {
let line = prompt.input().to_string();
super::prompt::append_history(&line);
let action = match action {
PromptAction::Rebuild { instance } if self.tab == Tab::Services => {
PromptAction::ServiceRebuild { name: instance }
}
other => other,
};
self.pending_action = Some(action);
self.prompt = None;
}
}
KeyCode::Tab => {
let instances = self.instance_names();
let services = self.service_names();
let tab = self.tab;
let config = Config::load(&self.dir).ok();
let sandboxes: Vec<String> = config
.as_ref()
.map(|c| c.sandboxes.keys().cloned().collect())
.unwrap_or_default();
if let Some(prompt) = &mut self.prompt {
prompt.complete(|idx, tokens| {
Self::candidates_for(
tab,
idx,
tokens,
&sandboxes,
&instances,
&services,
config.as_ref(),
)
});
}
}
KeyCode::Up => {
if let Some(prompt) = &mut self.prompt {
prompt.history_prev();
}
}
KeyCode::Down => {
if let Some(prompt) = &mut self.prompt {
prompt.history_next();
}
}
KeyCode::Left => self.with_prompt(Prompt::left),
KeyCode::Right => self.with_prompt(Prompt::right),
KeyCode::Home => self.with_prompt(Prompt::home),
KeyCode::End => self.with_prompt(Prompt::end),
KeyCode::Backspace => self.with_prompt(Prompt::backspace),
KeyCode::Delete => self.with_prompt(Prompt::delete),
KeyCode::Char('u') if ctrl => self.with_prompt(Prompt::clear),
KeyCode::Char('w') if ctrl => self.with_prompt(Prompt::delete_word),
KeyCode::Char(c) if !ctrl => {
if let Some(prompt) = &mut self.prompt {
prompt.insert_char(c);
}
}
_ => {}
}
}
fn with_prompt(&mut self, f: impl FnOnce(&mut Prompt)) {
if let Some(prompt) = &mut self.prompt {
f(prompt);
}
}
fn candidates_for(
tab: Tab,
idx: usize,
tokens: &[String],
sandboxes: &[String],
instances: &[String],
services: &[String],
config: Option<&Config>,
) -> Vec<String> {
if idx == 0 {
return COMMANDS.iter().map(|s| s.to_string()).collect();
}
match tokens.first().map(String::as_str) {
Some("run") => Self::run_candidates(idx, tokens, sandboxes, config),
Some("rebuild" | "recreate") if idx == 1 && tab == Tab::Services => services.to_vec(),
Some("exec" | "code" | "rm" | "rename" | "stop" | "start" | "rebuild" | "recreate")
if idx == 1 =>
{
instances.to_vec()
}
_ => Vec::new(),
}
}
fn run_candidates(
idx: usize,
tokens: &[String],
sandboxes: &[String],
config: Option<&Config>,
) -> Vec<String> {
match tokens.get(idx - 1).map(String::as_str) {
Some("--branch") => {
let branch = Self::run_sandbox_token(tokens, idx)
.and_then(|s| config?.resolve_sandbox(s).ok()?.properties.worktree_branch)
.unwrap_or_else(|| DEFAULT_WORKTREE_BRANCH.to_string());
return vec![branch];
}
Some("--name") => return Vec::new(), _ => {}
}
let stem = tokens.get(idx).map(String::as_str).unwrap_or("");
if !stem.starts_with('-') && Self::run_sandbox_token(tokens, idx).is_none() {
return sandboxes.to_vec();
}
["--name", "--branch"]
.into_iter()
.filter(|flag| !tokens.iter().enumerate().any(|(i, t)| i != idx && t == flag))
.map(str::to_string)
.collect()
}
fn run_sandbox_token(tokens: &[String], skip: usize) -> Option<&str> {
let mut i = 1;
while i < tokens.len() {
match tokens[i].as_str() {
"--name" | "--branch" => i += 2,
_ if i == skip => i += 1,
other => return Some(other),
}
}
None
}
fn instance_names(&self) -> Vec<String> {
self.snapshot
.as_ref()
.map(|s| s.instances.iter().map(|r| r.name.clone()).collect())
.unwrap_or_default()
}
fn service_names(&self) -> Vec<String> {
self.snapshot
.as_ref()
.map(|s| s.services.iter().map(|r| r.name.clone()).collect())
.unwrap_or_default()
}
pub fn take_pending_action(&mut self) -> Option<PromptAction> {
self.pending_action.take()
}
fn on_key_modal(&mut self, key: KeyEvent) {
match &mut self.modal {
Modal::None => {}
Modal::Config(view) => match key.code {
KeyCode::Esc | KeyCode::Char('q') => self.modal = Modal::None,
KeyCode::Char('t') => {
view.showing = match view.showing {
Side::Original => Side::Resolved,
Side::Resolved => Side::Original,
};
view.clamp_scroll();
}
KeyCode::Tab => {
view.focus = match view.focus {
Pane::Config => Pane::Inspect,
Pane::Inspect => Pane::Config,
};
}
KeyCode::Char('<') => view.resize(-5),
KeyCode::Char('>') => view.resize(5),
_ => view.scroll_focused(key),
},
Modal::Help(view) => {
if matches!(key.code, KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('?')) {
self.modal = Modal::None;
} else {
view.on_scroll_key(key);
}
}
Modal::Logs(view) => {
if matches!(key.code, KeyCode::Esc | KeyCode::Char('q')) {
self.modal = Modal::None;
} else {
view.on_scroll_key(key);
}
}
}
}
fn open_help(&mut self) {
self.modal = Modal::Help(TextModal::new(" help — keys ".to_string(), HELP_BODY.to_string()));
}
fn term_target(&self) -> Result<(String, String, bool), String> {
let snapshot = self
.snapshot
.as_ref()
.ok_or_else(|| "terminal: no data yet".to_string())?;
match self.tab {
Tab::Instances => {
let idx = self
.selected_instance_index()
.ok_or_else(|| "terminal: select an instance".to_string())?;
let row = snapshot
.instances
.get(idx)
.ok_or_else(|| "terminal: select an instance".to_string())?;
if !matches!(row.status, ContainerStatus::Running(_)) {
return Err(format!("terminal: `{}` is not running", row.name));
}
Ok((row.name.clone(), row.container.clone(), true))
}
Tab::Services => {
let row = snapshot
.services
.get(self.selected())
.ok_or_else(|| "terminal: select a service".to_string())?;
let container = row
.containers
.iter()
.find(|(_, status)| matches!(status, ContainerStatus::Running(_)))
.map(|(name, _)| name.clone())
.ok_or_else(|| {
format!("terminal: no running container for `{}`", row.name)
})?;
let title = container
.strip_prefix(NAME_PREFIX)
.unwrap_or(&container)
.to_string();
Ok((title, container, false))
}
}
}
fn open_terminal(&mut self, force_new: bool) {
let (title, container, is_instance) = match self.term_target() {
Ok(t) => t,
Err(msg) => {
self.status = Some(msg);
return;
}
};
if !force_new {
if let Some(idx) = self.terms.find(&container) {
self.terms.set_active(idx);
self.focus = Focus::Terminal;
self.status = None;
return;
}
}
let shell: Vec<String> = SHELL_FALLBACK_CMD.iter().map(|s| s.to_string()).collect();
let mut argv = if is_instance {
let state = match crate::state::State::load() {
Ok(s) => s,
Err(e) => {
self.status = Some(format!("terminal: {e:#}"));
return;
}
};
let Some(instance) = state.instances.get(&title) else {
self.status = Some(format!("terminal: `{title}` not in state"));
return;
};
crate::commands::exec::exec_argv(instance, true, true, &shell)
} else {
let mut a = vec!["exec".to_string(), "-i".to_string(), "-t".to_string()];
a.push(container.clone());
a.extend(shell);
a
};
argv.insert(0, backend().bin().to_string());
let (rows, cols) = self
.terms
.active_session()
.map(|s| s.size())
.unwrap_or((24, 80));
match TermSession::spawn(title, container, argv, rows, cols) {
Ok(session) => {
self.terms.open(session);
self.focus = Focus::Terminal;
self.status = None;
}
Err(e) => self.status = Some(format!("terminal: {e:#}")),
}
}
fn open_logs(&mut self) {
if self.tab != Tab::Instances {
return;
}
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 container = row.container.clone();
let body = match backend().logs_tail(&container, 50) {
Ok(out) if out.trim().is_empty() => "(no log output)".to_string(),
Ok(out) => out,
Err(e) => format!("{e:#}"),
};
let title = format!(" logs — {container} (last 50) ");
self.modal = Modal::Logs(TextModal::new(title, body));
}
fn open_config(&mut self) {
let Some(snapshot) = &self.snapshot else {
return;
};
let (mut view, target) = match self.tab {
Tab::Instances => {
let (name, target) = match self.selected_node() {
Some(Node::Sandbox(i)) | Some(Node::Empty(i)) => {
let name = snapshot.sandboxes.get(i).map(|s| s.name.clone());
let target = name
.as_deref()
.and_then(|n| inspect_target(&snapshot.instances, Target::Sandbox(n)));
(name, target)
}
Some(Node::Instance(i)) => {
let name = snapshot.instances.get(i).map(|r| r.sandbox.clone());
let target = inspect_target(&snapshot.instances, Target::Instance(i));
(name, target)
}
Some(Node::Proc { instance, .. }) => {
let name = snapshot.instances.get(instance).map(|r| r.sandbox.clone());
let target =
inspect_target(&snapshot.instances, Target::Instance(instance));
(name, target)
}
Some(Node::Orphans) | None => (None, None),
};
let Some(name) = name else {
return;
};
(Self::build_sandbox_view(&self.dir, &name), target)
}
Tab::Services => {
let Some(row) = snapshot.services.get(self.selected()) else {
return;
};
let target = service_inspect_target(&row.containers);
(Self::build_service_view(&self.dir, &row.name), target)
}
};
let placeholder = match self.tab {
Tab::Instances => "(no running instance)",
Tab::Services => "(no containers)",
};
set_inspect(&mut view, target, placeholder);
self.modal = Modal::Config(view);
}
fn build_sandbox_view(dir: &PathBuf, name: &str) -> ConfigView {
let mut view = ConfigView {
title: name.to_string(),
original: String::new(),
resolved: String::new(),
showing: Side::Original,
scroll: 0,
hash: String::new(),
inspect: String::new(),
inspect_scroll: 0,
inspect_container: String::new(),
focus: Pane::Config,
split_pct: 50,
};
match Config::load(dir) {
Ok(cfg) => {
view.original = match cfg.sandbox_table(name) {
Ok(t) => to_toml(t),
Err(e) => format!("{e:#}"),
};
match cfg.resolved_table(name) {
Ok((t, hash)) => {
view.resolved = to_toml(&t);
view.hash = hash;
}
Err(e) => view.resolved = format!("{e:#}"),
}
}
Err(e) => {
let msg = format!("{e:#}");
view.original = msg.clone();
view.resolved = msg;
}
}
view
}
fn build_service_view(dir: &PathBuf, name: &str) -> ConfigView {
let body = match Config::load(dir) {
Ok(cfg) => match cfg.services.get(name) {
Some(t) => to_toml(t),
None => format!("unknown service `{name}`"),
},
Err(e) => format!("{e:#}"),
};
ConfigView {
title: name.to_string(),
original: body.clone(),
resolved: body,
showing: Side::Original,
scroll: 0,
hash: String::new(),
inspect: String::new(),
inspect_scroll: 0,
inspect_container: String::new(),
focus: Pane::Config,
split_pct: 50,
}
}
}
enum Target<'a> {
Instance(usize),
Sandbox(&'a str),
}
fn inspect_target(instances: &[InstanceRow], target: Target) -> Option<String> {
match target {
Target::Instance(i) => instances.get(i).map(|r| r.container.clone()),
Target::Sandbox(name) => instances
.iter()
.find(|r| r.sandbox == name && matches!(r.status, ContainerStatus::Running(_)))
.map(|r| r.container.clone()),
}
}
fn service_inspect_target(containers: &[(String, ContainerStatus)]) -> Option<String> {
containers
.iter()
.find(|(_, s)| matches!(s, ContainerStatus::Running(_)))
.or_else(|| containers.first())
.map(|(name, _)| name.clone())
}
fn set_inspect(view: &mut ConfigView, target: Option<String>, placeholder: &str) {
let Some(container) = target else {
view.inspect = placeholder.to_string();
return;
};
view.inspect_container = container.clone();
view.inspect = match backend().inspect_json(&container) {
Ok(out) => crate::commands::inspect::pretty_inspect(&out),
Err(e) => format!("{e:#}"),
};
}
fn to_toml(table: &toml::Table) -> String {
match toml::to_string_pretty(table) {
Ok(s) => s,
Err(e) => format!("cannot serialize config: {e}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn new_app() -> App {
App::new(PathBuf::from("."))
}
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
#[test]
fn tab_switching() {
let mut app = new_app();
assert_eq!(app.tab, Tab::Instances);
app.on_key(key(KeyCode::Tab));
assert_eq!(app.tab, Tab::Services);
app.on_key(key(KeyCode::BackTab));
assert_eq!(app.tab, Tab::Instances);
app.on_key(key(KeyCode::Char('2')));
assert_eq!(app.tab, Tab::Services);
app.on_key(key(KeyCode::Char('1')));
assert_eq!(app.tab, Tab::Instances);
}
#[test]
fn quit_keys() {
let mut app = new_app();
app.on_key(key(KeyCode::Char('q')));
assert!(app.should_quit);
let mut app = new_app();
app.on_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
assert!(app.should_quit);
let mut app = new_app();
app.on_key(key(KeyCode::Char('c')));
assert!(!app.should_quit);
}
#[test]
fn selection_clamps() {
let mut app = new_app();
app.on_key(key(KeyCode::Up));
assert_eq!(app.selected(), 0);
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('j')));
assert_eq!(app.selected(), 0);
}
fn snapshot_with(n: usize) -> Snapshot {
use super::super::data::{ContainerStatus, InstanceRow, SandboxRow};
let instances = (0..n)
.map(|i| InstanceRow {
name: format!("inst{i}"),
sandbox: "s".into(),
container: format!("devsandbox-inst{i}"),
status: ContainerStatus::Missing,
uptime_secs: 0,
cpu: None,
mem: None,
folder: "/f".into(),
worktree: false,
services: Vec::new(),
workspace: "/w".into(),
remote_user: None,
remote_env_len: 0,
base_folder: "/f".into(),
drift: false,
})
.collect();
let sandboxes = vec![SandboxRow {
name: "s".into(),
source: "image x".into(),
folder: None,
services: Vec::new(),
extends: Vec::new(),
config_hash: "hash".into(),
build_hash: String::new(),
issues: Vec::new(),
}];
Snapshot {
instances,
sandboxes,
services: Vec::new(),
sandbox_count: 1,
runtime_name: "docker",
runtime_version: None,
collected_at: std::time::Instant::now(),
error: None,
}
}
#[test]
fn selection_clamps_when_snapshot_shrinks() {
let mut app = new_app();
app.set_snapshot(snapshot_with(3));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down));
assert_eq!(app.selected(), 3);
app.set_snapshot(snapshot_with(1));
assert_eq!(app.selected(), 1);
app.set_snapshot(snapshot_with(0));
assert_eq!(app.selected(), 1);
}
#[test]
fn left_on_instance_jumps_to_parent_sandbox() {
let mut app = new_app();
app.set_snapshot(snapshot_with(2)); app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down)); assert_eq!(app.selected(), 2);
assert_eq!(app.selected_node(), Some(Node::Instance(1)));
app.on_key(key(KeyCode::Left)); assert_eq!(app.selected(), 0);
assert_eq!(app.selected_node(), Some(Node::Sandbox(0)));
}
#[test]
fn collapse_hides_children_and_reclamps_selection() {
let mut app = new_app();
app.set_snapshot(snapshot_with(2)); app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down)); assert_eq!(app.selected(), 2);
app.on_key(key(KeyCode::Left));
assert_eq!(app.selected(), 0);
app.on_key(key(KeyCode::Left));
assert_eq!(app.visible_nodes(), vec![Node::Sandbox(0)]);
assert_eq!(app.selected(), 0);
app.on_key(key(KeyCode::Char(' ')));
assert_eq!(
app.visible_nodes(),
vec![Node::Sandbox(0), Node::Instance(0), Node::Instance(1)],
);
}
#[test]
fn collapse_survives_snapshot_refresh_and_clamps() {
let mut app = new_app();
app.set_snapshot(snapshot_with(3)); app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down)); assert_eq!(app.selected(), 3);
app.on_key(key(KeyCode::Left)); app.on_key(key(KeyCode::Left)); assert_eq!(app.visible_nodes().len(), 1);
app.set_snapshot(snapshot_with(3));
assert_eq!(app.visible_nodes().len(), 1);
assert_eq!(app.selected(), 0);
}
fn open_modal(app: &mut App) {
app.modal = Modal::Config(ConfigView {
title: "s".into(),
original: "[sandbox.s]\nimage = \"a\"\n".into(),
resolved: (0..10).map(|i| format!("line{i}\n")).collect(),
showing: Side::Original,
scroll: 0,
hash: "deadbeef".into(),
inspect: (0..20).map(|i| format!("insp{i}\n")).collect(),
inspect_scroll: 0,
inspect_container: "devsandbox-s".into(),
focus: Pane::Config,
split_pct: 50,
});
}
fn view(app: &App) -> &ConfigView {
match &app.modal {
Modal::Config(v) => v,
_ => panic!("config modal not open"),
}
}
#[test]
fn modal_toggles_side_and_closes() {
let mut app = new_app();
open_modal(&mut app);
assert_eq!(view(&app).showing, Side::Original);
app.on_key(key(KeyCode::Char('t')));
assert_eq!(view(&app).showing, Side::Resolved);
app.on_key(key(KeyCode::Char('t')));
assert_eq!(view(&app).showing, Side::Original);
app.on_key(key(KeyCode::Tab));
assert_eq!(view(&app).showing, Side::Original);
app.on_key(key(KeyCode::Esc));
assert!(matches!(app.modal, Modal::None));
open_modal(&mut app);
app.on_key(key(KeyCode::Char('q')));
assert!(matches!(app.modal, Modal::None));
}
#[test]
fn modal_scroll_clamps() {
let mut app = new_app();
open_modal(&mut app);
app.on_key(key(KeyCode::Char('t')));
app.on_key(key(KeyCode::Up));
assert_eq!(view(&app).scroll, 0);
app.on_key(key(KeyCode::Down));
assert_eq!(view(&app).scroll, 1);
app.on_key(key(KeyCode::Char('G')));
assert_eq!(view(&app).scroll, 9);
app.on_key(key(KeyCode::PageDown));
assert_eq!(view(&app).scroll, 9);
app.on_key(key(KeyCode::Char('g')));
assert_eq!(view(&app).scroll, 0);
}
#[test]
fn modal_swallows_dashboard_keys() {
let mut app = new_app();
open_modal(&mut app);
app.on_key(key(KeyCode::Char('2')));
assert_eq!(app.tab, Tab::Instances);
assert!(matches!(app.modal, Modal::Config(_)));
}
#[test]
fn help_overlay_opens_and_closes() {
let mut app = new_app();
app.on_key(key(KeyCode::Char('?')));
assert!(matches!(app.modal, Modal::Help(_)));
app.on_key(key(KeyCode::Char('2')));
assert_eq!(app.tab, Tab::Instances);
assert!(matches!(app.modal, Modal::Help(_)));
app.on_key(key(KeyCode::Char('?')));
assert!(matches!(app.modal, Modal::None));
app.on_key(key(KeyCode::Char('?')));
app.on_key(key(KeyCode::Esc));
assert!(matches!(app.modal, Modal::None));
app.on_key(key(KeyCode::Char('?')));
app.on_key(key(KeyCode::Char('q')));
assert!(matches!(app.modal, Modal::None));
}
#[test]
fn text_modal_scroll_shares_config_logic() {
let mut m = TextModal::new("t".into(), (0..10).map(|i| format!("l{i}\n")).collect());
assert_eq!(m.scroll, 0);
assert!(m.on_scroll_key(key(KeyCode::Up))); assert_eq!(m.scroll, 0);
assert!(m.on_scroll_key(key(KeyCode::Down)));
assert_eq!(m.scroll, 1);
assert!(m.on_scroll_key(key(KeyCode::Char('G'))));
assert_eq!(m.scroll, 9);
assert!(m.on_scroll_key(key(KeyCode::PageDown))); assert_eq!(m.scroll, 9);
assert!(m.on_scroll_key(key(KeyCode::Char('g'))));
assert_eq!(m.scroll, 0);
assert!(!m.on_scroll_key(key(KeyCode::Char('x'))));
}
#[test]
fn logs_modal_opens_on_selected_instance() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('l')));
match &app.modal {
Modal::Logs(v) => {
assert!(v.title.contains("devsandbox-inst0"));
assert!(!v.body.is_empty());
}
_ => panic!("logs modal not open"),
}
app.on_key(key(KeyCode::Char('q')));
assert!(matches!(app.modal, Modal::None));
}
#[test]
fn logs_key_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('l')));
assert!(matches!(app.modal, Modal::None));
}
fn orphan_snapshot() -> Snapshot {
use super::super::data::{ContainerStatus, InstanceRow};
let instances = vec![InstanceRow {
name: "orphan0".into(),
sandbox: "gone".into(),
container: "devsandbox-orphan0".into(),
status: ContainerStatus::Missing,
uptime_secs: 0,
cpu: None,
mem: None,
folder: "/f".into(),
worktree: false,
services: Vec::new(),
workspace: "/w".into(),
remote_user: None,
remote_env_len: 0,
base_folder: "/f".into(),
drift: false,
}];
Snapshot {
instances,
sandboxes: Vec::new(),
services: Vec::new(),
sandbox_count: 0,
runtime_name: "docker",
runtime_version: None,
collected_at: std::time::Instant::now(),
error: None,
}
}
fn prompt(app: &App) -> &Prompt {
app.prompt.as_ref().expect("prompt open")
}
#[test]
fn r_on_sandbox_prefills_run() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1)); app.on_key(key(KeyCode::Char('r')));
let p = prompt(&app);
assert_eq!(p.input(), "run s ");
assert_eq!(p.cursor(), "run s ".chars().count());
}
#[test]
fn r_on_empty_marker_prefills_run() {
let mut app = new_app();
app.set_snapshot(snapshot_with(0)); app.on_key(key(KeyCode::Down)); assert_eq!(app.selected_node(), Some(Node::Empty(0)));
app.on_key(key(KeyCode::Char('r')));
assert_eq!(prompt(&app).input(), "run s ");
}
#[test]
fn r_on_instance_prefills_rename() {
let mut app = new_app();
app.set_snapshot(snapshot_with(2)); app.on_key(key(KeyCode::Down)); assert_eq!(app.selected_node(), Some(Node::Instance(0)));
app.on_key(key(KeyCode::Char('r')));
assert_eq!(prompt(&app).input(), "rename inst0 ");
}
#[test]
fn r_on_orphans_gives_empty_prompt() {
let mut app = new_app();
app.set_snapshot(orphan_snapshot()); assert_eq!(app.selected_node(), Some(Node::Orphans));
app.on_key(key(KeyCode::Char('r')));
assert_eq!(prompt(&app).input(), "");
}
#[test]
fn r_with_no_snapshot_gives_empty_prompt() {
let mut app = new_app();
app.on_key(key(KeyCode::Char('r')));
assert_eq!(prompt(&app).input(), "");
}
#[test]
fn prefilled_prompt_history_up_stashes_prefill() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1));
app.prompt = Some(Prompt::with_input(vec!["run other".into()], "run s ".into()));
app.on_key(key(KeyCode::Up));
assert_eq!(prompt(&app).input(), "run other");
app.on_key(key(KeyCode::Down));
assert_eq!(prompt(&app).input(), "run s ");
}
#[test]
fn o_on_instance_sets_pending_code() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1)); app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Char('o')));
assert_eq!(
app.take_pending_action(),
Some(PromptAction::Code { instance: "inst0".into() }),
);
}
#[test]
fn o_on_orphan_instance_sets_pending_code() {
let mut app = new_app();
app.set_snapshot(orphan_snapshot()); app.on_key(key(KeyCode::Down)); 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() }),
);
}
#[test]
fn o_on_sandbox_is_noop() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1)); app.on_key(key(KeyCode::Char('o')));
assert_eq!(app.take_pending_action(), None);
}
#[test]
fn prompt_rebuild_on_services_tab_queues_service_rebuild() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1));
app.tab = Tab::Services;
app.on_key(key(KeyCode::Char(':')));
for c in "rebuild db".chars() {
app.on_key(key(KeyCode::Char(c)));
}
app.on_key(key(KeyCode::Enter));
assert_eq!(
app.take_pending_action(),
Some(PromptAction::ServiceRebuild { name: "db".into() }),
);
}
#[test]
fn prompt_rebuild_on_instances_tab_stays_instance_rebuild() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1));
app.tab = Tab::Instances;
app.on_key(key(KeyCode::Char(':')));
for c in "rebuild inst0".chars() {
app.on_key(key(KeyCode::Char(c)));
}
app.on_key(key(KeyCode::Enter));
assert_eq!(
app.take_pending_action(),
Some(PromptAction::Rebuild { instance: "inst0".into() }),
);
}
#[test]
fn r_and_o_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('r')));
assert!(app.prompt.is_none());
app.on_key(key(KeyCode::Char('o')));
assert_eq!(app.take_pending_action(), None);
}
fn snapshot_with_status(n: usize, status: ContainerStatus) -> Snapshot {
let mut snap = snapshot_with(n);
for row in &mut snap.instances {
row.status = status.clone();
}
snap
}
fn running() -> ContainerStatus {
ContainerStatus::Running("Up".into())
}
#[test]
fn s_on_running_instance_sets_pending_stop() {
let mut app = new_app();
app.set_snapshot(snapshot_with_status(1, running())); app.on_key(key(KeyCode::Down)); 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_stop(), Some("inst0".into()));
assert_eq!(app.take_pending_start(), None);
}
#[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)); 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_start(), Some("inst0".into()));
assert_eq!(app.take_pending_stop(), 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)); app.on_key(key(KeyCode::Char('s')));
assert_eq!(
app.take_pending_action(),
Some(PromptAction::Rebuild { instance: "inst0".into() })
);
assert_eq!(app.take_pending_start(), None);
assert!(app.starting.is_empty());
assert_eq!(app.take_pending_stop(), None);
}
#[test]
fn s_on_exited_undrifted_instance_still_bare_starts() {
let mut app = new_app();
let status = ContainerStatus::Exited("Exited (0)".into());
let snap = snapshot_with_status(1, status); app.set_snapshot(snap);
app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Char('s')));
assert!(app.starting.contains("inst0"));
assert_eq!(app.take_pending_start(), Some("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)); app.on_key(key(KeyCode::Char('s')));
assert!(app.stopping.contains("inst0"));
assert_eq!(app.take_pending_stop(), Some("inst0".into()));
assert_eq!(app.take_pending_action(), None);
assert_eq!(app.take_pending_start(), None);
}
#[test]
fn s_on_missing_container_is_noop() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1)); app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Char('s')));
assert_eq!(app.take_pending_stop(), None);
assert_eq!(app.take_pending_start(), 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(); snap.instances[0].status = running();
app.set_snapshot(snap);
app.on_key(key(KeyCode::Down)); assert_eq!(app.selected_node(), Some(Node::Instance(0)));
app.on_key(key(KeyCode::Char('s')));
assert_eq!(app.take_pending_stop(), Some("orphan0".into()));
}
#[test]
fn s_on_sandbox_is_noop() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1)); app.on_key(key(KeyCode::Char('s')));
assert_eq!(app.take_pending_stop(), 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)); app.on_key(key(KeyCode::Char('s')));
assert_eq!(app.take_pending_stop(), Some("inst0".into()));
app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Char('s')));
assert_eq!(app.take_pending_stop(), 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)); app.on_key(key(KeyCode::Char('s')));
assert_eq!(app.take_pending_start(), Some("inst0".into()));
app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Char('s')));
assert_eq!(app.take_pending_start(), None);
}
#[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_stop(), None);
}
fn expand_with_rows(app: &mut App, instance: &str, pids: &[&str]) {
use super::super::procs::{ProcRow, ProcState};
let rows = pids
.iter()
.map(|p| ProcRow { pid: p.to_string(), depth: 0, args: "x".into() })
.collect();
app.expanded_procs.insert(instance.to_string());
app.procs.insert(instance.to_string(), ProcState::Rows(rows));
}
#[test]
fn right_on_instance_expands_procs_and_signals_fetch() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1)); app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Right));
assert!(app.expanded_procs.contains("inst0"));
assert!(app.take_needs_proc_fetch());
assert!(!app.take_needs_proc_fetch());
}
#[test]
fn space_toggles_procs_on_instance() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1));
app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Char(' ')));
assert!(app.expanded_procs.contains("inst0"));
app.on_key(key(KeyCode::Char(' ')));
assert!(!app.expanded_procs.contains("inst0"));
}
#[test]
fn left_ladder_proc_to_instance_to_sandbox() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1)); expand_with_rows(&mut app, "inst0", &["10", "20"]);
app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Down)); assert_eq!(app.selected_node(), Some(Node::Proc { instance: 0, row: 1 }));
app.on_key(key(KeyCode::Left));
assert_eq!(app.selected_node(), Some(Node::Instance(0)));
assert!(app.expanded_procs.contains("inst0"));
app.on_key(key(KeyCode::Left));
assert_eq!(app.selected_node(), Some(Node::Instance(0)));
assert!(!app.expanded_procs.contains("inst0"));
app.on_key(key(KeyCode::Left));
assert_eq!(app.selected_node(), Some(Node::Sandbox(0)));
}
#[test]
fn s_on_proc_row_stops_parent_instance() {
let mut app = new_app();
app.set_snapshot(snapshot_with_status(1, running()));
expand_with_rows(&mut app, "inst0", &["10"]);
app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Down)); assert_eq!(app.selected_node(), Some(Node::Proc { instance: 0, row: 0 }));
app.on_key(key(KeyCode::Char('s')));
assert!(app.stopping.contains("inst0"));
assert_eq!(app.take_pending_stop(), Some("inst0".into()));
}
#[test]
fn o_on_proc_row_codes_parent_instance() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1));
expand_with_rows(&mut app, "inst0", &["10"]);
app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Down)); app.on_key(key(KeyCode::Char('o')));
assert_eq!(
app.take_pending_action(),
Some(PromptAction::Code { instance: "inst0".into() }),
);
}
#[test]
fn proc_fetch_targets_running_and_not_running() {
use super::super::data::{ContainerStatus, InstanceRow, SandboxRow};
let mut app = new_app();
let mk = |name: &str, status: ContainerStatus| InstanceRow {
name: name.into(),
sandbox: "s".into(),
container: format!("devsandbox-{name}"),
status,
uptime_secs: 0,
cpu: None,
mem: None,
folder: "/f".into(),
worktree: false,
services: Vec::new(),
workspace: "/w".into(),
remote_user: None,
remote_env_len: 0,
base_folder: "/f".into(),
drift: false,
};
let snap = Snapshot {
instances: vec![
mk("up", ContainerStatus::Running("Up".into())),
mk("down", ContainerStatus::Exited("Exited".into())),
],
sandboxes: vec![SandboxRow {
name: "s".into(),
source: "image x".into(),
folder: None,
services: Vec::new(),
extends: Vec::new(),
config_hash: "h".into(),
build_hash: String::new(),
issues: Vec::new(),
}],
services: Vec::new(),
sandbox_count: 1,
runtime_name: "docker",
runtime_version: None,
collected_at: std::time::Instant::now(),
error: None,
};
app.set_snapshot(snap);
app.expanded_procs.insert("up".into());
app.expanded_procs.insert("down".into());
let targets = app.proc_fetch_targets();
assert_eq!(targets, vec![("up".to_string(), "devsandbox-up".to_string())]);
assert_eq!(
app.procs.get("down"),
Some(&super::super::procs::ProcState::Message("(not running)".into())),
);
}
#[test]
fn agent_count_counts_agent_rows_in_cache() {
use super::super::procs::{ProcRow, ProcState};
let mut app = new_app();
assert_eq!(app.agent_count("x"), None);
let rows = vec![
ProcRow { pid: "1".into(), depth: 0, args: "/sbin/init".into() },
ProcRow { pid: "2".into(), depth: 1, args: "node /usr/local/bin/claude".into() },
ProcRow { pid: "3".into(), depth: 1, args: "zidane --resume".into() },
];
app.procs.insert("x".into(), ProcState::Rows(rows));
assert_eq!(app.agent_count("x"), Some(2));
app.procs.insert("y".into(), ProcState::Message("(not running)".into()));
assert_eq!(app.agent_count("y"), None);
}
#[test]
fn proc_fetch_targets_includes_selected_running_instance() {
use super::super::data::{ContainerStatus, InstanceRow, SandboxRow};
let mut app = new_app();
let row = InstanceRow {
name: "up".into(),
sandbox: "s".into(),
container: "devsandbox-up".into(),
status: ContainerStatus::Running("Up".into()),
uptime_secs: 0,
cpu: None,
mem: None,
folder: "/f".into(),
worktree: false,
services: Vec::new(),
workspace: "/w".into(),
remote_user: None,
remote_env_len: 0,
base_folder: "/f".into(),
drift: false,
};
app.set_snapshot(Snapshot {
instances: vec![row],
sandboxes: vec![SandboxRow {
name: "s".into(),
source: "image x".into(),
folder: None,
services: Vec::new(),
extends: Vec::new(),
config_hash: "h".into(),
build_hash: String::new(),
issues: Vec::new(),
}],
services: Vec::new(),
sandbox_count: 1,
runtime_name: "docker",
runtime_version: None,
collected_at: std::time::Instant::now(),
error: None,
});
assert!(app.proc_fetch_targets().is_empty());
app.on_key(key(KeyCode::Down));
assert_eq!(
app.proc_fetch_targets(),
vec![("up".to_string(), "devsandbox-up".to_string())],
);
assert!(app.expanded_procs.is_empty());
}
#[test]
fn scroll_reclamps_on_side_toggle() {
let mut app = new_app();
open_modal(&mut app);
app.on_key(key(KeyCode::Char('t')));
app.on_key(key(KeyCode::Char('G')));
assert_eq!(view(&app).scroll, 9);
app.on_key(key(KeyCode::Char('t')));
assert_eq!(view(&app).showing, Side::Original);
assert_eq!(view(&app).scroll, 1);
}
fn mouse(kind: MouseEventKind, column: u16) -> MouseEvent {
MouseEvent { kind, column, row: 0, modifiers: KeyModifiers::NONE }
}
fn mouse_at(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent {
MouseEvent { kind, column, row, modifiers: KeyModifiers::NONE }
}
fn term_sess(title: &str, container: &str) -> TermSession {
TermSession::test_session(title, container, 24, 80)
}
const FRAME: Rect = Rect { x: 0, y: 0, width: 100, height: 40 };
const MODAL_AREA: Rect = Rect { x: 0, y: 0, width: 100, height: 40 };
#[test]
fn mouse_click_in_panel_focuses_terminal() {
let mut app = new_app();
app.terms.open(term_sess("web-1", "devsandbox-web-1"));
assert_eq!(app.focus, Focus::Dashboard);
let panel = super::super::ui::terminal_panel_rect(FRAME, false);
let click = mouse_at(
MouseEventKind::Down(MouseButton::Left),
panel.x + 2,
panel.y + 2,
);
app.on_mouse(&click, FRAME);
assert_eq!(app.focus, Focus::Terminal);
}
#[test]
fn mouse_click_outside_panel_unfocuses() {
let mut app = new_app();
app.terms.open(term_sess("web-1", "devsandbox-web-1"));
app.focus = Focus::Terminal;
let click = mouse_at(MouseEventKind::Down(MouseButton::Left), 0, 0);
app.on_mouse(&click, FRAME);
assert_eq!(app.focus, Focus::Dashboard);
}
#[test]
fn mouse_click_on_tab_label_activates_it() {
let mut app = new_app();
app.terms.open(term_sess("web-1", "devsandbox-web-1"));
app.terms.open(term_sess("api-2", "devsandbox-api-2"));
assert_eq!(app.terms.active(), 1);
let panel = super::super::ui::terminal_panel_rect(FRAME, false);
let click = mouse_at(
MouseEventKind::Down(MouseButton::Left),
panel.x + 1,
panel.y,
);
app.on_mouse(&click, FRAME);
assert_eq!(app.terms.active(), 0);
assert_eq!(app.focus, Focus::Terminal);
let click2 = mouse_at(
MouseEventKind::Down(MouseButton::Left),
panel.x + 1 + 2 + 7 + 2,
panel.y,
);
app.on_mouse(&click2, FRAME);
assert_eq!(app.terms.active(), 1);
}
#[test]
fn mouse_click_in_gap_between_tabs_keeps_active() {
let mut app = new_app();
app.terms.open(term_sess("web-1", "devsandbox-web-1"));
app.terms.open(term_sess("api-2", "devsandbox-api-2"));
app.terms.set_active(0);
let panel = super::super::ui::terminal_panel_rect(FRAME, false);
let click = mouse_at(
MouseEventKind::Down(MouseButton::Left),
panel.x + 1 + 7,
panel.y,
);
app.on_mouse(&click, FRAME);
assert_eq!(app.terms.active(), 0);
assert_eq!(app.focus, Focus::Terminal);
}
#[test]
fn mouse_in_panel_ignored_when_no_terminal() {
let mut app = new_app();
let click = mouse_at(MouseEventKind::Down(MouseButton::Left), 50, 30);
app.on_mouse(&click, FRAME);
assert_eq!(app.focus, Focus::Dashboard);
}
#[test]
fn mouse_wheel_scrolls_active_terminal_scrollback() {
let mut app = new_app();
app.terms.open(term_sess("web-1", "devsandbox-web-1"));
{
let session = app.terms.active_session().unwrap();
let mut parser = session.parser().lock().unwrap();
for i in 0..60 {
parser.process(format!("line {i}\r\n").as_bytes());
}
}
let panel = super::super::ui::terminal_panel_rect(FRAME, false);
let body = (panel.x + 2, panel.y + 2);
fn offset(app: &App) -> usize {
app.terms
.active_session()
.unwrap()
.parser()
.lock()
.unwrap()
.screen()
.scrollback()
}
assert_eq!(offset(&app), 0);
app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, body.0, body.1), FRAME);
assert_eq!(offset(&app), 3);
app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, body.0, body.1), FRAME);
assert_eq!(offset(&app), 6);
app.on_mouse(&mouse_at(MouseEventKind::ScrollDown, body.0, body.1), FRAME);
assert_eq!(offset(&app), 3);
for _ in 0..5 {
app.on_mouse(&mouse_at(MouseEventKind::ScrollDown, body.0, body.1), FRAME);
}
assert_eq!(offset(&app), 0);
app.on_mouse(&mouse_at(MouseEventKind::ScrollUp, 0, 0), FRAME);
assert_eq!(offset(&app), 0);
}
#[test]
fn tab_switches_focus_between_panes() {
let mut app = new_app();
open_modal(&mut app);
assert_eq!(view(&app).focus, Pane::Config);
app.on_key(key(KeyCode::Tab));
assert_eq!(view(&app).focus, Pane::Inspect);
app.on_key(key(KeyCode::Tab));
assert_eq!(view(&app).focus, Pane::Config);
app.on_key(key(KeyCode::Char('t')));
assert_eq!(view(&app).focus, Pane::Config);
}
#[test]
fn scroll_routes_to_focused_pane() {
let mut app = new_app();
open_modal(&mut app);
app.on_key(key(KeyCode::Char('t')));
app.on_key(key(KeyCode::Down));
assert_eq!(view(&app).scroll, 1);
assert_eq!(view(&app).inspect_scroll, 0);
app.on_key(key(KeyCode::Tab));
app.on_key(key(KeyCode::Down));
assert_eq!(view(&app).scroll, 1);
assert_eq!(view(&app).inspect_scroll, 1);
app.on_key(key(KeyCode::Char('G')));
assert_eq!(view(&app).inspect_scroll, 19);
}
#[test]
fn split_pct_clamps_via_resize_keys() {
let mut app = new_app();
open_modal(&mut app);
assert_eq!(view(&app).split_pct, 50);
app.on_key(key(KeyCode::Char('<')));
assert_eq!(view(&app).split_pct, 45);
app.on_key(key(KeyCode::Char('>')));
app.on_key(key(KeyCode::Char('>')));
assert_eq!(view(&app).split_pct, 55);
for _ in 0..20 {
app.on_key(key(KeyCode::Char('<')));
}
assert_eq!(view(&app).split_pct, SPLIT_MIN);
for _ in 0..40 {
app.on_key(key(KeyCode::Char('>')));
}
assert_eq!(view(&app).split_pct, SPLIT_MAX);
}
#[test]
fn divider_pct_maps_column_to_clamped_percentage() {
assert_eq!(divider_pct(50, 100), 50);
assert_eq!(divider_pct(0, 100), SPLIT_MIN);
assert_eq!(divider_pct(100, 100), SPLIT_MAX);
assert_eq!(divider_pct(5, 100), SPLIT_MIN);
assert_eq!(divider_pct(95, 100), SPLIT_MAX);
assert_eq!(divider_pct(10, 0), SPLIT_MIN);
}
#[test]
fn mouse_drag_resizes_divider() {
let mut app = new_app();
open_modal(&mut app);
app.on_mouse(&mouse(MouseEventKind::Down(MouseButton::Left), 50), MODAL_AREA);
app.on_mouse(&mouse(MouseEventKind::Drag(MouseButton::Left), 30), MODAL_AREA);
assert_eq!(view(&app).split_pct, 30);
app.on_mouse(&mouse(MouseEventKind::Up(MouseButton::Left), 30), MODAL_AREA);
app.on_mouse(&mouse(MouseEventKind::Drag(MouseButton::Left), 70), MODAL_AREA);
assert_eq!(view(&app).split_pct, 30);
}
#[test]
fn mouse_press_far_from_divider_ignored() {
let mut app = new_app();
open_modal(&mut app);
app.on_mouse(&mouse(MouseEventKind::Down(MouseButton::Left), 10), MODAL_AREA);
app.on_mouse(&mouse(MouseEventKind::Drag(MouseButton::Left), 70), MODAL_AREA);
assert_eq!(view(&app).split_pct, 50);
}
#[test]
fn wheel_scrolls_pane_under_cursor() {
let mut app = new_app();
open_modal(&mut app);
app.on_key(key(KeyCode::Char('t'))); app.on_mouse(&mouse(MouseEventKind::ScrollDown, 10), MODAL_AREA);
assert_eq!(view(&app).scroll, 3);
assert_eq!(view(&app).inspect_scroll, 0);
app.on_mouse(&mouse(MouseEventKind::ScrollDown, 90), MODAL_AREA);
assert_eq!(view(&app).inspect_scroll, 3);
app.on_mouse(&mouse(MouseEventKind::ScrollUp, 10), MODAL_AREA);
app.on_mouse(&mouse(MouseEventKind::ScrollUp, 10), MODAL_AREA);
assert_eq!(view(&app).scroll, 0);
}
#[test]
fn inspect_target_picks_per_node_kind() {
use super::super::data::{ContainerStatus, InstanceRow};
let mk = |name: &str, sandbox: &str, status: ContainerStatus| InstanceRow {
name: name.into(),
sandbox: sandbox.into(),
container: format!("devsandbox-{name}"),
status,
uptime_secs: 0,
cpu: None,
mem: None,
folder: "/f".into(),
worktree: false,
services: Vec::new(),
workspace: "/w".into(),
remote_user: None,
remote_env_len: 0,
base_folder: "/f".into(),
drift: false,
};
let rows = vec![
mk("a", "s", ContainerStatus::Exited("x".into())),
mk("b", "s", ContainerStatus::Running("Up".into())),
mk("c", "t", ContainerStatus::Missing),
];
assert_eq!(
inspect_target(&rows, Target::Instance(0)),
Some("devsandbox-a".into()),
);
assert_eq!(
inspect_target(&rows, Target::Sandbox("s")),
Some("devsandbox-b".into()),
);
assert_eq!(inspect_target(&rows, Target::Sandbox("t")), None);
assert_eq!(inspect_target(&rows, Target::Instance(9)), None);
}
#[test]
fn service_inspect_target_prefers_running() {
use super::super::data::ContainerStatus;
let running = vec![
("svc-1".to_string(), ContainerStatus::Exited("x".into())),
("svc-2".to_string(), ContainerStatus::Running("Up".into())),
];
assert_eq!(service_inspect_target(&running), Some("svc-2".into()));
let none_running = vec![
("svc-1".to_string(), ContainerStatus::Exited("x".into())),
("svc-2".to_string(), ContainerStatus::Missing),
];
assert_eq!(service_inspect_target(&none_running), Some("svc-1".into()));
assert_eq!(service_inspect_target(&[]), None);
}
fn toks(line: &str) -> Vec<String> {
line.split_whitespace().map(str::to_string).collect()
}
fn cfg() -> Config {
Config::parse(
"[sandbox.web]\nfolder = \"code\"\nworktree-branch = \"wt/${instance}\"\n\n[sandbox.api]\nfolder = \"code\"\n",
)
.unwrap()
}
#[test]
fn run_candidates_sandbox_position() {
let sandboxes = vec!["api".to_string(), "web".to_string()];
assert_eq!(
App::candidates_for(Tab::Instances, 1, &toks("run"), &sandboxes, &[], &[], None),
sandboxes
);
assert_eq!(
App::candidates_for(Tab::Instances, 3, &toks("run --name x"), &sandboxes, &[], &[], None),
sandboxes
);
}
#[test]
fn run_candidates_flags_after_sandbox() {
let sandboxes = vec!["web".to_string()];
assert_eq!(
App::candidates_for(Tab::Instances, 2, &toks("run web"), &sandboxes, &[], &[], None),
vec!["--name".to_string(), "--branch".to_string()]
);
assert_eq!(
App::candidates_for(Tab::Instances, 2, &toks("run web --"), &sandboxes, &[], &[], None),
vec!["--name".to_string(), "--branch".to_string()]
);
assert_eq!(
App::candidates_for(Tab::Instances, 4, &toks("run web --name x"), &sandboxes, &[], &[], None),
vec!["--branch".to_string()]
);
}
#[test]
fn run_candidates_branch_value_offers_default() {
let config = cfg();
let sandboxes: Vec<String> = config.sandboxes.keys().cloned().collect();
assert_eq!(
App::candidates_for(Tab::Instances, 3, &toks("run web --branch"), &sandboxes, &[], &[], Some(&config)),
vec!["wt/${instance}".to_string()]
);
assert_eq!(
App::candidates_for(Tab::Instances, 3, &toks("run api --branch"), &sandboxes, &[], &[], Some(&config)),
vec![DEFAULT_WORKTREE_BRANCH.to_string()]
);
assert!(App::candidates_for(Tab::Instances, 3, &toks("run web --name"), &sandboxes, &[], &[], Some(&config))
.is_empty());
}
#[test]
fn rebuild_completes_instance_names() {
let instances = vec!["a".to_string(), "b".to_string()];
assert_eq!(
App::candidates_for(Tab::Instances, 1, &toks("rebuild"), &[], &instances, &[], None),
instances
);
assert_eq!(
App::candidates_for(Tab::Instances, 1, &toks("recreate"), &[], &instances, &[], None),
instances
);
}
#[test]
fn rebuild_completes_service_names_on_services_tab() {
let instances = vec!["a".to_string(), "b".to_string()];
let services = vec!["cache".to_string(), "db".to_string()];
assert_eq!(
App::candidates_for(
Tab::Services,
1,
&toks("rebuild"),
&[],
&instances,
&services,
None,
),
services
);
assert_eq!(
App::candidates_for(
Tab::Services,
1,
&toks("recreate"),
&[],
&instances,
&services,
None,
),
services
);
}
use super::super::data::ServiceRow;
fn service_snapshot(containers: Vec<(String, ContainerStatus)>) -> Snapshot {
Snapshot {
instances: Vec::new(),
sandboxes: Vec::new(),
services: vec![ServiceRow {
name: "svc".into(),
scope: "isolated",
source: "image x".into(),
ports: Vec::new(),
containers,
used_by: Vec::new(),
env_len: 0,
command: None,
config_hash: "hash".into(),
drift: false,
}],
sandbox_count: 0,
runtime_name: "docker",
runtime_version: None,
collected_at: std::time::Instant::now(),
error: None,
}
}
fn open_test_term(app: &mut App, title: &str, container: &str) {
app.terms
.open(TermSession::test_session(title, container, 24, 80));
app.focus = Focus::Terminal;
}
#[test]
fn terminal_focus_swallows_dashboard_keys() {
let mut app = new_app();
open_test_term(&mut app, "web-1", "devsandbox-web-1");
let before = app.tab;
app.on_key(key(KeyCode::Tab));
assert_eq!(app.tab, before);
app.on_key(key(KeyCode::Char('q')));
assert!(!app.should_quit);
assert_eq!(app.focus, Focus::Terminal);
}
#[test]
fn ctrl_bracket_and_f12_leave_terminal() {
let mut app = new_app();
open_test_term(&mut app, "web-1", "devsandbox-web-1");
app.on_key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL));
assert_eq!(app.focus, Focus::Dashboard);
open_test_term(&mut app, "web-1", "devsandbox-web-1");
app.on_key(key(KeyCode::F(12)));
assert_eq!(app.focus, Focus::Dashboard);
}
#[test]
fn enter_terminal_needs_a_terminal() {
let mut app = new_app();
app.on_key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL));
assert_eq!(app.focus, Focus::Dashboard);
assert_eq!(app.status.as_deref(), Some("no terminal open — press t"));
app.on_key(key(KeyCode::F(12)));
assert_eq!(app.focus, Focus::Dashboard);
assert_eq!(app.status.as_deref(), Some("no terminal open — press t"));
app.terms
.open(TermSession::test_session("web-1", "devsandbox-web-1", 24, 80));
app.on_key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL));
assert_eq!(app.focus, Focus::Terminal);
}
#[test]
fn dashboard_brackets_cycle_and_x_closes() {
let mut app = new_app();
app.terms
.open(TermSession::test_session("a", "devsandbox-a", 24, 80));
app.terms
.open(TermSession::test_session("b", "devsandbox-b", 24, 80)); app.on_key(key(KeyCode::Char(']')));
assert_eq!(app.terms.active(), 0);
app.on_key(key(KeyCode::Char('[')));
assert_eq!(app.terms.active(), 1);
app.on_key(key(KeyCode::Char('x')));
assert_eq!(app.terms.sessions().len(), 1);
assert_eq!(app.terms.active_session().unwrap().title, "a");
}
#[test]
fn exited_terminal_swallows_keys_but_leaves() {
let mut app = new_app();
app.terms
.open(TermSession::test_session("web-1", "devsandbox-web-1", 24, 80));
app.terms.active_session().unwrap().set_exited();
app.focus = Focus::Terminal;
app.on_key(key(KeyCode::Char('a')));
app.on_key(key(KeyCode::Enter));
assert_eq!(app.focus, Focus::Terminal);
app.on_key(key(KeyCode::F(12)));
assert_eq!(app.focus, Focus::Dashboard);
}
#[test]
fn stop_start_hint_tracks_selection_status() {
let mut app = new_app();
assert_eq!(app.stop_start_hint(), "stop");
app.set_snapshot(snapshot_with_status(
1,
ContainerStatus::Exited("Exited (0)".into()),
));
app.on_key(key(KeyCode::Down)); assert_eq!(app.stop_start_hint(), "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(), "stop");
}
#[test]
fn term_target_instance_requires_running() {
let mut app = new_app();
app.set_snapshot(snapshot_with_status(1, ContainerStatus::Missing));
app.on_key(key(KeyCode::Down)); assert_eq!(
app.term_target(),
Err("terminal: `inst0` is not running".into())
);
app.set_snapshot(snapshot_with_status(1, running()));
app.on_key(key(KeyCode::Down));
assert_eq!(
app.term_target(),
Ok(("inst0".into(), "devsandbox-inst0".into(), true))
);
}
#[test]
fn term_target_service_picks_first_running() {
let mut app = new_app();
app.tab = Tab::Services;
app.set_snapshot(service_snapshot(vec![(
"devsandbox-svc-web-1".into(),
ContainerStatus::Exited("Exited (0)".into()),
)]));
assert_eq!(
app.term_target(),
Err("terminal: no running container for `svc`".into())
);
app.set_snapshot(service_snapshot(vec![
(
"devsandbox-svc-web-1".into(),
ContainerStatus::Exited("Exited (0)".into()),
),
("devsandbox-svc-api-2".into(), running()),
]));
assert_eq!(
app.term_target(),
Ok(("svc-api-2".into(), "devsandbox-svc-api-2".into(), false))
);
}
#[test]
fn find_dedup_vs_force_new() {
let mut app = new_app();
let dead = TermSession::test_session("web-1", "devsandbox-web-1", 24, 80);
dead.set_exited();
app.terms.open(dead);
assert_eq!(app.terms.find("devsandbox-web-1"), None);
app.terms
.open(TermSession::test_session("web-1", "devsandbox-web-1", 24, 80));
assert_eq!(app.terms.find("devsandbox-web-1"), Some(1));
}
}