use std::cell::Cell;
use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
use ratatui::layout::Rect;
use ratatui::text::Line;
use crate::broker::asks::Answer;
use crate::build_log::Tail;
use crate::commands::vscode::Goto;
use crate::config::SandboxText;
use crate::snapshot::PhaseRow;
use crate::tui::data::{ContainerStatus, InstanceRow, Node};
use crate::tui::settings::{SETTINGS, Settings};
use crate::tui::prompt::PromptAction;
use crate::serve::verbs_client::identity::{Choice, Group};
use crate::tui::remote::{Route, instance_key, qualify, sandbox_key, service_key};
use super::identity::IdentityOn;
use super::{App, Tab};
const HELP_BODY: &str = "\
Global
q, ctrl-c quit
tab / S-tab switch tab 1-5 jump to tab (5: Machines, when listed)
: command prompt ? settings & help
drag select (copies on release with \"copy on select\" on, above)
{copy}
shift-drag the outer terminal's own selection (whole rows, across panes)
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, with services and
postStartCommand like :start; a drifted exited or a
failed instance is rebuilt instead)
b build log of the instance (follows a build in flight;
G sticks to the bottom again)
p forward a port (instance / service selection prefills the prompt)
P switch the instance's profile: to the other one when its
sandbox allows two, a picker when more (like :profile)
d remove the instance now, no prompt (Instances; like :rm,
so a dirty worktree still refuses); on an instance still
building: cancel it, after a y/n (a cancelled run is undone)
U update configs that assume root in the container (the
header's \"uses /root\" line): update / continue as is / later
run, rebuild and start (s, :run, :rebuild, :start) run in the background
and outlive the dashboard: the row shows their phase, b their output;
on a sandbox that uses /root they ask first: update / continue as is /
skip this time
Ports tab
↑/k ↓/j move selection
d stop the selected forward
Machines tab (listed while a machine is registered)
↑/k ↓/j move selection
a turn the selected machine's agent on/off
Inbox tab (dispatcher threads + devsbd notify records)
The list is on the left, the selected thread on the right; selecting a
thread marks it read. esc steps back: input → thread → list.
Inbox list
↑/k ↓/j move selection
← / → previous / next view: Needs you / Active / Done / All
(Needs you: threads asking for you + unread notify records;
leaving the tab marks the notify records it showed read)
enter focus the thread
r / i focus the reply input (when the thread takes replies)
d dismiss a notify record; on a dispatcher thread, mark it done
u reopen a done thread
D clear all notify records (dispatcher threads stay)
o t l p VS Code / terminal / logs / forward prompt on the thread's
child (or its sender when it has none)
Inbox thread (shadows the dashboard keys while focused)
The header (title, state, child, action row) stays put; the feed
under it is newest first and scrolls on its own.
↑/k ↓/j scroll pgup/pgdn page g / G newest / oldest
enter open the thread's link (↗)
1-9 run an action: host verbs (⌂) run now; the rest is an
event the dispatcher pulls with `devsbd events` (✓ = done)
r / i focus the reply input
tab focus the open forms (pinned under the header), else the
reply input
d / u mark done / reopen (each also an event for the dispatcher;
also marks / clears the thread's child done)
o t l p as in the list (the [o] [t] [l] [p] buttons)
m markdown: rendered / raw source (every thread, this session)
esc back to the list q quit : prompt ? help
Inbox form (the open forms pinned under the thread's header)
tab / S-tab next / previous question (across every open form)
↑ ↓ ← → move over the options
space pick (several-pick: toggle; a text question: edit)
e edit a text question in the composer box; enter or esc
keeps the edit, alt-enter inserts a newline
enter confirm: the summary (or what's missing); enter again
submits, esc cancels
r / i the reply input esc back to the thread
(every pick and kept edit is saved as the form's draft)
Inbox reply input
enter send (the input stays, empty, for the next message)
esc back to the thread
Process rows (expanded instance)
← jump to the parent instance
t SIGTERM K SIGKILL
(the instance shortcuts above are disabled on a process row;
signals need `ps` in the image — a `top` fallback listing hides them)
a / enter on a `session` row: attach it (takes it over if attached)
K on a `session` row: end the session
Terminals
t open terminal (instance / service)
T force a new terminal for the same target
a attach to a running session (Instances; a picker when several)
[ / ] 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
wheel scroll the pane under the pointer
g / G top / bottom
esc, q close
Logs, build log and this help
↑/k ↓/j scroll pgup/pgdn page wheel scroll
g / G top / bottom
esc, q close
Command prompt (:)
run <sandbox> [--name n] [--branch b] [--base ref]
exec <instance> <cmd…>
code <instance> [--goto path[:line[:col]]] [--allow-credential-leak]
rm <instance> rename <instance> <new-name>
profile <instance> <profile>
stop <instance> start <instance>
port <instance> [--service s] [--address a] <[host:]port>
(an instance is required; a global service is reached by
naming any instance that references it)
access the oldest pending permission request (the header counts
them): o once · i this instance · a always (not on a
presence one) · d deny · esc later (it stays pending; a
new one opens by itself)
tab complete / cycle
↑ ↓ history
ctrl-u clear line ctrl-w delete word
esc cancel";
fn help_body(copy_key_intercepted: bool) -> String {
let copy = if copy_key_intercepted {
" ctrl-c / cmd-c copy the selection to the clipboard (OSC 52)\n \
(ctrl-c not in a focused terminal: the shell gets it there)"
} else {
" ctrl-shift-c / cmd-c copy the selection to the clipboard (OSC 52)\n \
(ctrl-c too over a dashboard selection: legacy terminals)"
};
HELP_BODY.replacen("{copy}", copy, 1)
}
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)
}
pub(super) fn scroll_by(&mut self, delta: i16) -> u16 {
self.scroll = apply_delta(self.scroll, delta, line_count(&self.body).saturating_sub(1));
self.scroll
}
}
pub struct HelpModal {
pub text: TextModal,
pub cursor: usize,
}
pub const BUILD_LOG_LINES: usize = 500;
pub const BUILD_LOG_REREAD: std::time::Duration = std::time::Duration::from_millis(100);
pub const LOG_LINES: usize = 50;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Fetch {
Logs { container: String },
Config { kind: ConfigKind, name: String },
Inspect { container: String },
Sessions { instance: String },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConfigKind {
Sandbox,
Service,
}
const LOADING: &str = "(loading…)";
pub struct BuildLogModal {
pub instance: String,
pub instance_id: String,
pub text: TextModal,
pub styled: Vec<Line<'static>>,
pub stick: bool,
cut: Option<bool>,
live: bool,
pub height: Cell<u16>,
}
pub(super) fn bottom_top(lines: u16, height: u16) -> u16 {
lines.saturating_sub(height)
}
impl BuildLogModal {
pub fn top(&self) -> u16 {
if self.stick { bottom_top(line_count(&self.text.body), self.height.get()) } else { self.text.scroll }
}
fn scroll_with(&mut self, f: impl FnOnce(&mut TextModal)) -> u16 {
self.text.scroll = self.top();
f(&mut self.text);
self.stick = self.text.scroll >= bottom_top(line_count(&self.text.body), self.height.get());
self.top()
}
fn on_scroll_key(&mut self, key: KeyEvent) {
self.scroll_with(|t| {
t.on_scroll_key(key);
});
}
pub(super) fn scroll_by(&mut self, delta: i16) -> u16 {
self.scroll_with(|t| {
t.scroll_by(delta);
})
}
}
fn build_log_title(instance: &str, phase: Option<&PhaseRow>) -> String {
match phase {
Some(PhaseRow::InFlight { step }) => format!(" build log — {instance} ({}) ", crate::commands::doing(step)),
Some(PhaseRow::Failed { step, .. }) => format!(" build log — {instance} (failed at {step}) "),
None => format!(" build log — {instance} "),
}
}
pub struct ConfirmModal {
pub question: String,
pub body: Vec<String>,
action: Confirmed,
}
impl ConfirmModal {
pub(super) fn new(question: String, body: Vec<String>, action: Confirmed) -> ConfirmModal {
ConfirmModal { question, body, action }
}
pub fn keys_hint(&self) -> &'static str {
match self.action {
Confirmed::CancelBuild(_) | Confirmed::CodeLeak { .. } => "y/enter yes · n/esc no",
Confirmed::RmBranch { .. } => "y/enter yes · n no · esc cancel",
Confirmed::Identity { .. } => "u update · c continue as is · s/esc skip",
Confirmed::IdentityOffer(_) => "u update · c continue as is · l/esc later",
Confirmed::Profile { .. } => "↑↓ move · enter switch · esc cancel",
Confirmed::Attach { .. } => "↑↓ move · enter attach · esc cancel",
Confirmed::Access { presence: false, .. } => "o once · i this instance · a always · d deny · esc later",
Confirmed::Access { presence: true, .. } => "o once · i this instance · d deny · esc later",
}
}
pub fn choices(&self) -> &'static str {
match self.action {
Confirmed::CancelBuild(_) | Confirmed::RmBranch { .. } | Confirmed::CodeLeak { .. } => "[y] yes [n] no",
Confirmed::Identity { .. } => "[u] update [c] continue as is (don't ask again) [s] skip this time",
Confirmed::IdentityOffer(_) => "[u] update [c] continue as is [l] later",
Confirmed::Profile { .. } => "[enter] switch [esc] cancel",
Confirmed::Attach { .. } => "[enter] attach (an attached one is taken over) [esc] cancel",
Confirmed::Access { presence: false, .. } => "[o] once [i] this instance [a] always [d] deny [esc] later",
Confirmed::Access { presence: true, .. } => "[o] once [i] this instance (this target) [d] deny [esc] later",
}
}
pub fn is_identity(&self) -> bool {
matches!(self.action, Confirmed::Identity { .. } | Confirmed::IdentityOffer(_))
}
pub fn access_id(&self) -> Option<&str> {
match &self.action {
Confirmed::Access { id, .. } => Some(id),
_ => None,
}
}
}
#[derive(Clone)]
pub(super) enum Confirmed {
CancelBuild(String),
RmBranch { instance: String, force: bool },
Identity { route: Route, ids: Vec<String>, action: PromptAction },
IdentityOffer(Vec<Group>),
Profile { instance: String, profiles: Vec<String>, current: Option<String>, cursor: usize },
Attach { instance: String, sessions: Vec<(String, String)>, cursor: usize },
Access { id: String, presence: bool },
CodeLeak { instance: String, goto: Option<Goto>, note: Option<String> },
}
pub(super) fn session_lines(sessions: &[(String, String)], cursor: usize) -> Vec<String> {
sessions
.iter()
.enumerate()
.map(|(i, (_, line))| format!("{} {line}", if i == cursor { '›' } else { ' ' }))
.collect()
}
pub(super) fn profile_lines(profiles: &[String], current: Option<&str>, cursor: usize) -> Vec<String> {
profiles
.iter()
.enumerate()
.map(|(i, p)| {
let mark = if i == cursor { '›' } else { ' ' };
let note = if Some(p.as_str()) == current { " (current)" } else { "" };
format!("{mark} {p}{note}")
})
.collect()
}
fn slid_by(old: &[&str], new: &[&str]) -> Option<usize> {
let whole = old.len().checked_sub(1)?;
if let Some(k) = (0..whole).find(|&k| new.starts_with(&old[k..whole])) {
return Some(k);
}
let shared = |k: usize| old[k..whole].iter().zip(new).take_while(|(a, b)| a == b).count();
let (k, n) = (0..whole).map(|k| (k, shared(k))).fold((0, 0), |best, (k, n)| if n > best.1 { (k, n) } else { best });
(n > 0).then_some(k)
}
fn line_count(body: &str) -> u16 {
body.lines().count().min(u16::MAX as usize) as u16
}
pub(super) 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 kind: ConfigKind,
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);
}
}
}
pub(super) fn scroll_pane(&mut self, pane: Pane, delta: i16) -> u16 {
match pane {
Pane::Config => {
self.scroll = apply_delta(self.scroll, delta, self.line_count().saturating_sub(1));
self.scroll
}
Pane::Inspect => {
let max = line_count(&self.inspect).saturating_sub(1);
self.inspect_scroll = apply_delta(self.inspect_scroll, delta, max);
self.inspect_scroll
}
}
}
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)
}
pub(super) fn col_near(col: u16, divider: u16) -> bool {
col.abs_diff(divider) <= 1
}
pub(super) 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(HelpModal),
Logs(TextModal),
BuildLog(BuildLogModal),
Confirm(ConfirmModal),
}
impl App {
pub(super) fn wheel_scroll(view: &mut ConfigView, col: u16, divider: u16, delta: i16) {
view.scroll_pane(if col < divider { Pane::Config } else { Pane::Inspect }, delta);
}
pub(super) 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) => {
let n = SETTINGS.len();
match key.code {
KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('?') => self.modal = Modal::None,
KeyCode::Tab if n > 0 => view.cursor = (view.cursor + 1) % n,
KeyCode::BackTab if n > 0 => view.cursor = (view.cursor + n - 1) % n,
KeyCode::Char(' ') | KeyCode::Enter => {
let i = view.cursor;
self.toggle_setting(i);
}
_ => {
view.text.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);
}
}
Modal::BuildLog(view) => {
if matches!(key.code, KeyCode::Esc | KeyCode::Char('q')) {
self.modal = Modal::None;
} else {
view.on_scroll_key(key);
}
}
Modal::Confirm(view) if view.is_identity() => {
let offer = matches!(view.action, Confirmed::IdentityOffer(_));
let choice = match key.code {
KeyCode::Char('u') => Choice::Update,
KeyCode::Char('c') => Choice::Keep,
KeyCode::Char('s') if !offer => Choice::Skip,
KeyCode::Char('l') if offer => Choice::Skip,
KeyCode::Esc | KeyCode::Char('q') => Choice::Skip,
_ => return,
};
let action = view.action.clone();
self.modal = Modal::None;
match action {
Confirmed::Identity { route, ids, action } => {
self.identity_chosen(choice, IdentityOn::Notes { route, ids }, Some(action));
}
Confirmed::IdentityOffer(groups) => self.identity_chosen(choice, IdentityOn::Groups(groups), None),
_ => {}
}
}
Modal::Confirm(view) if view.access_id().is_some() => {
let answer = match key.code {
KeyCode::Char('o') => Some(Answer::Once),
KeyCode::Char('i') => Some(Answer::Instance),
KeyCode::Char('a') if !matches!(view.action, Confirmed::Access { presence: true, .. }) => {
Some(Answer::Always)
}
KeyCode::Char('d') => Some(Answer::Deny),
KeyCode::Esc | KeyCode::Char('q') => None,
_ => return,
};
let id = view.access_id().unwrap_or_default().to_string();
if answer.is_some() && self.access_guarded() {
return;
}
self.access_chosen(id, answer);
}
Modal::Confirm(view) if matches!(view.action, Confirmed::Profile { .. }) => {
let Confirmed::Profile { instance, profiles, current, cursor } = &mut view.action else { return };
let n = profiles.len();
match key.code {
KeyCode::Up | KeyCode::Char('k') if n > 0 => *cursor = (*cursor + n - 1) % n,
KeyCode::Down | KeyCode::Char('j') if n > 0 => *cursor = (*cursor + 1) % n,
KeyCode::Enter => {
let pick = profiles.get(*cursor).cloned();
let instance = instance.clone();
self.modal = Modal::None;
if let Some(profile) = pick {
self.pending_action = Some(PromptAction::Profile { instance, profile });
}
return;
}
KeyCode::Esc | KeyCode::Char('q') => {
self.modal = Modal::None;
return;
}
_ => return,
}
view.body = profile_lines(profiles, current.as_deref(), *cursor);
}
Modal::Confirm(view) if matches!(view.action, Confirmed::Attach { .. }) => {
let Confirmed::Attach { instance, sessions, cursor } = &mut view.action else { return };
let n = sessions.len();
match key.code {
KeyCode::Up | KeyCode::Char('k') if n > 0 => *cursor = (*cursor + n - 1) % n,
KeyCode::Down | KeyCode::Char('j') if n > 0 => *cursor = (*cursor + 1) % n,
KeyCode::Enter => {
let pick = sessions.get(*cursor).map(|(id, _)| id.clone());
let instance = instance.clone();
self.modal = Modal::None;
if let Some(id) = pick {
self.open_attach(&instance, &id);
}
return;
}
KeyCode::Esc | KeyCode::Char('q') => {
self.modal = Modal::None;
return;
}
_ => return,
}
view.body = session_lines(sessions, *cursor);
}
Modal::Confirm(view) => {
let yes = match key.code {
KeyCode::Char('y') | KeyCode::Enter => Some(true),
KeyCode::Char('n') => Some(false),
KeyCode::Esc | KeyCode::Char('q') => None,
_ => return,
};
let action = view.action.clone();
self.modal = Modal::None;
match (action, yes) {
(Confirmed::CancelBuild(instance), Some(true)) => {
self.status = Some(format!("cancelling {instance}…"));
self.pending_cancel = Some(instance);
}
(Confirmed::CancelBuild(_), _) => {}
(Confirmed::RmBranch { instance, force }, Some(delete)) => {
self.pending_action = Some(PromptAction::Rm { instance, force, delete_branch: Some(delete) });
}
(Confirmed::RmBranch { instance, .. }, None) => {
self.status = Some(format!("rm {instance}: cancelled"));
}
(Confirmed::CodeLeak { instance, goto, note }, Some(true)) => {
self.code_note = note;
self.pending_action = Some(PromptAction::Code { instance, goto, allow_credential_leak: true });
}
(Confirmed::CodeLeak { .. }, _) => {}
(
Confirmed::Identity { .. }
| Confirmed::IdentityOffer(_)
| Confirmed::Profile { .. }
| Confirmed::Attach { .. }
| Confirmed::Access { .. },
_,
) => {}
}
}
}
}
pub(super) fn confirm_rm_branch(&mut self, instance: String, force: bool, question: String) {
self.modal = Modal::Confirm(ConfirmModal::new(question, Vec::new(), Confirmed::RmBranch { instance, force }));
}
pub(super) fn confirm_cancel_build(&mut self, instance: String) {
self.modal = Modal::Confirm(ConfirmModal::new(
format!("cancel {instance}'s build?"),
Vec::new(),
Confirmed::CancelBuild(instance),
));
}
pub fn take_pending_cancel(&mut self) -> Option<String> {
self.pending_cancel.take()
}
pub(super) fn open_build_log(&mut self) {
if self.tab != Tab::Instances {
return;
}
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 name = instance_key(row);
let id = qualify(row.machine.as_deref(), &row.instance_id);
let title = build_log_title(&name, row.phase.as_ref());
let (body, read) = if row.instance_id.is_empty() {
(format!("(no build log: `{name}` is not a recorded instance)"), None)
} else {
("(loading…)".to_string(), Some(id.clone()))
};
self.pending_build_log = read;
self.modal = Modal::BuildLog(BuildLogModal {
instance: name,
instance_id: if row.instance_id.is_empty() { String::new() } else { id },
text: TextModal::new(title, body),
styled: Vec::new(),
stick: true,
cut: None,
live: matches!(row.phase, Some(PhaseRow::InFlight { .. })),
height: Cell::new(0),
});
}
pub fn tick_build_log(&mut self, now: std::time::Instant) {
let Modal::BuildLog(view) = &self.modal else {
self.build_log_due = None;
return;
};
if !view.live || self.build_log_in_flight || self.pending_build_log.is_some() {
return;
}
match self.build_log_due {
Some(due) if now < due => {}
Some(_) => {
self.build_log_due = Some(now + BUILD_LOG_REREAD);
self.pending_build_log = Some(view.instance_id.clone());
}
None => self.build_log_due = Some(now + BUILD_LOG_REREAD),
}
}
pub fn following_build_log(&self) -> bool {
matches!(&self.modal, Modal::BuildLog(view) if view.live)
}
pub fn take_build_log_read(&mut self) -> Option<String> {
if self.build_log_in_flight {
return None;
}
let read = self.pending_build_log.take();
self.build_log_in_flight = read.is_some();
read
}
pub fn set_build_log(&mut self, instance_id: &str, read: Result<Option<Tail>, String>) {
self.build_log_in_flight = false;
self.build_log_due = None;
let Modal::BuildLog(view) = &mut self.modal else {
return;
};
if view.instance_id != instance_id {
return;
}
let (body, styled, cut) = match read {
Ok(Some(tail)) if tail.text.is_empty() && !tail.cut => ("(empty build log)".to_string(), Vec::new(), None),
Ok(Some(tail)) => {
let note = tail.cut.then(|| format!("… (earlier lines: devsandbox logs --build {})", view.instance));
let (plain, mut styled): (Vec<String>, Vec<Line<'static>>) =
tail.text.lines().map(crate::tui::ansi::parse_line).unzip();
let mut body = plain.join("\n");
if let Some(note) = note {
body = format!("{note}\n{body}");
styled.insert(0, Line::from(note));
}
(body, styled, Some(tail.cut))
}
Ok(None) => (
format!("(no build log for `{}` yet: run, rebuild and start write one)", view.instance),
Vec::new(),
None,
),
Err(e) => (e, Vec::new(), None),
};
if let (false, Some(old_cut), Some(true)) = (view.stick, view.cut, cut) {
let skip = usize::from(old_cut);
let old: Vec<&str> = view.text.body.lines().skip(skip).collect();
let new: Vec<&str> = body.lines().skip(1).collect();
let shown = usize::from(view.text.scroll);
if let (Some(k), true) = (slid_by(&old, &new), shown >= skip) {
let line = shown - skip;
let scroll = if line >= k { 1 + line - k } else { 0 };
view.text.scroll = scroll.min(u16::MAX as usize) as u16;
}
}
view.text.body = body;
view.styled = styled;
view.cut = cut;
let max = line_count(&view.text.body).saturating_sub(1);
view.text.scroll = view.text.scroll.min(max);
}
pub(super) fn refresh_build_log(&mut self) {
let Modal::BuildLog(view) = &mut self.modal else {
return;
};
let row = self
.snapshot
.as_ref()
.and_then(|s| {
s.instances.iter().find(|r| {
!view.instance_id.is_empty() && qualify(r.machine.as_deref(), &r.instance_id) == view.instance_id
})
});
let Some(row) = row else {
view.live = false;
return;
};
view.instance = instance_key(row);
view.text.title = build_log_title(&view.instance, row.phase.as_ref());
let was = std::mem::replace(&mut view.live, matches!(row.phase, Some(PhaseRow::InFlight { .. })));
if was || view.live {
self.pending_build_log = Some(view.instance_id.clone());
}
}
pub(super) fn open_help(&mut self) {
let text = TextModal::new(" settings & help ".to_string(), help_body(self.copy_key_intercepted));
self.modal = Modal::Help(HelpModal { text, cursor: 0 });
}
pub(super) fn toggle_setting(&mut self, i: usize) {
if i >= SETTINGS.len() {
return;
}
self.settings.toggle(i);
self.settings_dirty = true;
if let Modal::Help(view) = &mut self.modal {
view.cursor = i;
}
}
pub fn take_settings_save(&mut self) -> Option<Settings> {
std::mem::take(&mut self.settings_dirty).then_some(self.settings)
}
pub(super) fn help_mouse(&mut self, ev: &MouseEvent, area: Rect) {
if ev.kind != MouseEventKind::Down(MouseButton::Left) || !matches!(self.modal, Modal::Help(_)) {
return;
}
if let Some(i) = crate::tui::ui::help_setting_hit(area, ev.column, ev.row) {
self.toggle_setting(i);
}
}
pub(super) 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 = qualify(row.machine.as_deref(), &row.container);
self.open_logs_for(&container);
}
pub(super) fn open_logs_for(&mut self, container: &str) {
let title = format!(" logs — {container} (last {LOG_LINES}) ");
self.modal = Modal::Logs(TextModal::new(title, LOADING.to_string()));
self.logs_container = Some(container.to_string());
self.pending_fetch.push(Fetch::Logs { container: container.to_string() });
}
pub fn take_pending_fetch(&mut self) -> Vec<Fetch> {
std::mem::take(&mut self.pending_fetch)
}
pub fn set_logs(&mut self, container: &str, body: String) {
let Modal::Logs(view) = &mut self.modal else {
return;
};
if self.logs_container.as_deref() != Some(container) {
return;
}
view.body = body;
view.scroll = view.scroll.min(line_count(&view.body).saturating_sub(1));
}
pub fn set_config(&mut self, kind: ConfigKind, name: &str, text: Result<SandboxText, String>) {
let Modal::Config(view) = &mut self.modal else {
return;
};
if view.kind != kind || view.title != name {
return;
}
match text {
Ok(text) => (view.original, view.resolved, view.hash) = (text.original, text.resolved, text.hash),
Err(msg) => {
view.original = msg.clone();
view.resolved = msg;
}
}
view.clamp_scroll();
}
pub fn set_inspect(&mut self, container: &str, body: String) {
let Modal::Config(view) = &mut self.modal else {
return;
};
if view.inspect_container.is_empty() || view.inspect_container != container {
return;
}
view.inspect = body;
view.inspect_scroll = view.inspect_scroll.min(line_count(&view.inspect).saturating_sub(1));
}
pub(super) fn open_config(&mut self) {
let Some(snapshot) = &self.snapshot else {
return;
};
let (kind, name, 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(sandbox_key);
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| qualify(r.machine.as_deref(), &r.sandbox));
let target = inspect_target(&snapshot.instances, Target::Instance(i));
(name, target)
}
Some(Node::Proc { instance, .. }) => {
let name = snapshot.instances.get(instance).map(|r| qualify(r.machine.as_deref(), &r.sandbox));
let target =
inspect_target(&snapshot.instances, Target::Instance(instance));
(name, target)
}
Some(Node::Orphans) | None => (None, None),
};
let Some(name) = name else {
return;
};
(ConfigKind::Sandbox, name, target)
}
Tab::Services => {
let Some(row) = snapshot.services.get(self.selected()) else {
return;
};
let target = service_inspect_target(&row.containers).map(|c| qualify(row.machine.as_deref(), &c));
(ConfigKind::Service, service_key(row), target)
}
Tab::Ports | Tab::Inbox | Tab::Machines => return,
};
let placeholder = match self.tab {
Tab::Instances => "(no running instance)",
Tab::Services => "(no containers)",
Tab::Ports | Tab::Inbox | Tab::Machines => "",
};
self.pending_fetch.push(Fetch::Config { kind, name: name.clone() });
let (inspect, inspect_container) = match target {
Some(container) => {
self.pending_fetch.push(Fetch::Inspect { container: container.clone() });
(LOADING.to_string(), container)
}
None => (placeholder.to_string(), String::new()),
};
self.modal = Modal::Config(ConfigView {
title: name,
kind,
original: LOADING.to_string(),
resolved: LOADING.to_string(),
showing: Side::Original,
scroll: 0,
hash: String::new(),
inspect,
inspect_scroll: 0,
inspect_container,
focus: Pane::Config,
split_pct: 50,
});
}
}
enum Target<'a> {
Instance(usize),
Sandbox(&'a str),
}
fn inspect_target(instances: &[InstanceRow], target: Target) -> Option<String> {
let container = |r: &InstanceRow| qualify(r.machine.as_deref(), &r.container);
match target {
Target::Instance(i) => instances.get(i).map(container),
Target::Sandbox(key) => instances
.iter()
.find(|r| qualify(r.machine.as_deref(), &r.sandbox) == key && matches!(r.status, ContainerStatus::Running(_)))
.map(container),
}
}
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())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tui::app::test_support::*;
use crate::tui::app::*;
#[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));
}
fn help(app: &App) -> &HelpModal {
match &app.modal {
Modal::Help(v) => v,
_ => panic!("help not open"),
}
}
#[test]
fn settings_toggle_in_the_help_modal_and_are_marked_for_saving() {
let mut app = new_app();
app.on_key(key(KeyCode::Char('?')));
assert_eq!(app.take_settings_save(), None, "opening changes nothing");
assert_eq!(help(&app).cursor, 0);
app.on_key(key(KeyCode::Char(' ')));
assert!(!app.settings.copy_on_select, "on by default");
assert_eq!(app.take_settings_save(), Some(app.settings));
assert_eq!(app.take_settings_save(), None, "once per change");
app.on_key(key(KeyCode::Tab));
assert_eq!(help(&app).cursor, 1);
app.on_key(key(KeyCode::Enter));
assert!(!app.settings.terminal_clipboard);
app.on_key(key(KeyCode::Tab));
assert_eq!(help(&app).cursor, 0);
app.on_key(key(KeyCode::BackTab));
assert_eq!(help(&app).cursor, 1);
app.on_key(key(KeyCode::Down));
assert_eq!((help(&app).cursor, help(&app).text.scroll), (1, 1));
assert_eq!(
app.take_settings_save(),
Some(Settings { copy_on_select: false, terminal_clipboard: false })
);
}
#[test]
fn the_help_names_ctrl_c_where_the_terminal_keeps_ctrl_shift_c() {
let body = |intercepted| {
let mut app = new_app();
app.copy_key_intercepted = intercepted;
app.on_key(key(KeyCode::Char('?')));
help(&app).text.body.clone()
};
let plain = body(false);
let line = |b: &str, start: &str| b.lines().find(|l| l.starts_with(start)).map(str::to_string);
let copy = line(&plain, " ctrl-shift-c / cmd-c").expect("copy line");
assert!(!plain.contains("{copy}"));
let moved = body(true);
assert!(line(&moved, " ctrl-shift-c").is_none(), "{moved}");
let ctrl_c = line(&moved, " ctrl-c / cmd-c ").expect("ctrl-c line");
let col = |l: &str| l.find("copy the selection").unwrap();
assert_eq!(col(&ctrl_c), col(©));
assert_eq!(plain.lines().count(), moved.lines().count());
}
#[test]
fn a_click_on_a_settings_row_toggles_it() {
let mut app = new_app();
app.on_key(key(KeyCode::Char('?')));
let press = |col, row| mouse_at(MouseEventKind::Down(MouseButton::Left), col, row);
app.on_mouse(&press(5, 2), FRAME);
assert!(!app.settings.terminal_clipboard);
assert_eq!(help(&app).cursor, 1, "the cursor follows");
assert!(app.take_settings_save().is_some());
for (col, row) in [(5, 0), (0, 1), (5, 3), (5, 10)] {
app.on_mouse(&press(col, row), FRAME);
assert_eq!(app.take_settings_save(), None, "({col}, {row})");
}
app.on_key(key(KeyCode::Esc));
app.on_mouse(&press(5, 1), FRAME);
assert_eq!(app.settings, Settings { copy_on_select: true, terminal_clipboard: false });
}
#[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'))));
}
fn logs(app: &App) -> &TextModal {
match &app.modal {
Modal::Logs(v) => v,
_ => panic!("logs modal not open"),
}
}
#[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')));
assert!(logs(&app).title.contains("devsandbox-inst0"));
assert_eq!(logs(&app).body, "(loading…)");
assert_eq!(app.take_pending_fetch(), [Fetch::Logs { container: "devsandbox-inst0".into() }]);
assert_eq!(app.take_pending_fetch(), [], "once");
app.on_key(key(KeyCode::Char('q')));
assert!(matches!(app.modal, Modal::None));
}
#[test]
fn the_logs_answer_fills_its_own_modal_only() {
let mut app = new_app();
app.open_logs_for("devsandbox-a");
app.set_logs("devsandbox-b", "b's".into());
assert_eq!(logs(&app).body, "(loading…)");
app.set_logs("devsandbox-a", "l1\nl2".into());
assert_eq!(logs(&app).body, "l1\nl2");
app.on_key(key(KeyCode::Esc));
app.open_logs_for("devsandbox-b");
app.set_logs("devsandbox-a", "late".into());
assert_eq!(logs(&app).body, "(loading…)");
app.on_key(key(KeyCode::Esc));
app.set_logs("devsandbox-b", "late".into());
assert!(matches!(app.modal, Modal::None));
app.open_help();
app.set_logs("devsandbox-b", "a late answer".into());
assert!(!help(&app).text.body.contains("a late answer"));
}
#[test]
fn the_config_view_loads_then_fills_from_its_answers() {
let mut app = new_app();
let mut snap = snapshot_with(1);
snap.instances[0].status = ContainerStatus::Running("Up".into());
app.set_snapshot(snap);
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('e')));
assert_eq!((view(&app).original.as_str(), view(&app).resolved.as_str()), ("(loading…)", "(loading…)"));
assert_eq!((view(&app).inspect.as_str(), view(&app).inspect_container.as_str()), ("(loading…)", "devsandbox-inst0"));
let sandbox = view(&app).title.clone();
assert_eq!(
app.take_pending_fetch(),
[
Fetch::Config { kind: ConfigKind::Sandbox, name: sandbox.clone() },
Fetch::Inspect { container: "devsandbox-inst0".into() },
]
);
let text = |o: &str| SandboxText { original: o.into(), resolved: format!("{o}+"), hash: "abc".into() };
app.set_config(ConfigKind::Service, &sandbox, Ok(text("svc")));
app.set_config(ConfigKind::Sandbox, "other", Ok(text("other")));
app.set_inspect("devsandbox-x", "x's".into());
assert_eq!((view(&app).original.as_str(), view(&app).inspect.as_str()), ("(loading…)", "(loading…)"));
app.set_config(ConfigKind::Sandbox, &sandbox, Ok(text("mine")));
app.set_inspect("devsandbox-inst0", "[\n {}\n]".into());
let v = view(&app);
assert_eq!((v.original.as_str(), v.resolved.as_str(), v.hash.as_str()), ("mine", "mine+", "abc"));
assert_eq!(v.inspect, "[\n {}\n]");
app.set_config(ConfigKind::Sandbox, &sandbox, Err("config: needs devsandbox serve".into()));
assert_eq!((view(&app).original.as_str(), view(&app).resolved.as_str()), ("config: needs devsandbox serve", "config: needs devsandbox serve"));
app.on_key(key(KeyCode::Esc));
app.set_config(ConfigKind::Sandbox, &sandbox, Ok(text("late")));
app.set_inspect("devsandbox-inst0", "late".into());
assert!(matches!(app.modal, Modal::None));
}
#[test]
fn the_config_view_keeps_its_placeholder_without_a_target() {
let mut app = new_app();
app.set_snapshot(snapshot_with(1)); app.on_key(key(KeyCode::Char('e')));
assert_eq!(view(&app).inspect, "(no running instance)");
assert_eq!(view(&app).kind, ConfigKind::Sandbox);
let fetches = app.take_pending_fetch();
assert!(matches!(fetches.as_slice(), [Fetch::Config { kind: ConfigKind::Sandbox, .. }]), "{fetches:?}");
app.set_inspect("", "x".into());
assert_eq!(view(&app).inspect, "(no running instance)");
let mut app = new_app();
app.set_snapshot(service_snapshot(Vec::new()));
app.tab = Tab::Services;
app.on_key(key(KeyCode::Char('e')));
assert_eq!(view(&app).inspect, "(no containers)");
assert_eq!(app.take_pending_fetch(), [Fetch::Config { kind: ConfigKind::Service, name: "svc".into() }]);
let mut app = new_app();
app.set_snapshot(service_snapshot(vec![("devsandbox-svc-1".into(), ContainerStatus::Running("Up".into()))]));
app.tab = Tab::Services;
app.on_key(key(KeyCode::Char('e')));
assert_eq!(view(&app).kind, ConfigKind::Service);
assert_eq!(
app.take_pending_fetch(),
[
Fetch::Config { kind: ConfigKind::Service, name: "svc".into() },
Fetch::Inspect { container: "devsandbox-svc-1".into() },
]
);
app.set_config(ConfigKind::Service, "svc", Ok(SandboxText { original: "o".into(), resolved: "o".into(), hash: String::new() }));
assert_eq!(view(&app).resolved, "o");
}
#[test]
fn one_build_log_read_is_outstanding_at_a_time() {
let mut app = new_app();
app.set_snapshot(recorded(Some(in_flight("building"))));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
assert_eq!(app.take_build_log_read(), Some("id0".into()));
app.set_snapshot(recorded(Some(in_flight("building"))));
app.set_snapshot(recorded(Some(in_flight("building"))));
assert_eq!(app.take_build_log_read(), None);
app.set_build_log("id0", tail(0..1));
assert_eq!(app.take_build_log_read(), Some("id0".into()), "the waiting one, after the answer");
assert_eq!(app.take_build_log_read(), None);
app.on_key(key(KeyCode::Esc));
app.set_build_log("id0", tail(0..1));
app.on_key(key(KeyCode::Char('b')));
assert_eq!(app.take_build_log_read(), Some("id0".into()));
}
fn build_log(app: &App) -> &BuildLogModal {
match &app.modal {
Modal::BuildLog(v) => v,
_ => panic!("build log not open"),
}
}
fn tail(lines: std::ops::Range<usize>) -> Result<Option<Tail>, String> {
let text = lines.map(|i| format!("l{i}")).collect::<Vec<_>>().join("\n");
Ok(Some(Tail { text, cut: false }))
}
fn recorded(phase: Option<PhaseRow>) -> crate::tui::data::Snapshot {
let mut snap = snapshot_with(1);
snap.instances[0].instance_id = "id0".into();
snap.instances[0].phase = phase;
snap
}
#[test]
fn b_opens_the_build_log_for_the_loop_to_read() {
let mut app = new_app();
app.set_snapshot(recorded(Some(in_flight("building"))));
app.on_key(key(KeyCode::Char('b'))); assert!(matches!(app.modal, Modal::None));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
assert_eq!(build_log(&app).text.title, " build log — inst0 (building) ");
assert_eq!(app.take_build_log_read(), Some("id0".into()));
assert_eq!(app.take_build_log_read(), None, "once");
app.set_build_log("id0", tail(0..3));
assert_eq!(build_log(&app).text.body, "l0\nl1\nl2");
app.set_build_log("other", tail(0..1));
assert_eq!(build_log(&app).text.body, "l0\nl1\nl2");
app.on_key(key(KeyCode::Char('q')));
assert!(matches!(app.modal, Modal::None));
app.set_build_log("id0", tail(0..1));
assert!(matches!(app.modal, Modal::None));
}
#[test]
fn the_build_log_says_when_there_is_none() {
let mut app = new_app();
app.set_snapshot(recorded(None));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
assert_eq!(build_log(&app).text.title, " build log — inst0 ");
app.set_build_log("id0", Ok(None));
assert!(build_log(&app).text.body.starts_with("(no build log for `inst0` yet"), "{}", build_log(&app).text.body);
app.set_build_log("id0", Ok(Some(Tail { text: "x".into(), cut: true })));
assert_eq!(build_log(&app).text.body, "… (earlier lines: devsandbox logs --build inst0)\nx");
app.set_build_log("id0", Err("cannot read".into()));
assert_eq!(build_log(&app).text.body, "cannot read");
let mut app = new_app();
app.set_snapshot(snapshot_with(1)); app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
assert_eq!(app.take_build_log_read(), None);
assert!(build_log(&app).text.body.contains("not a recorded instance"));
}
#[test]
fn the_build_log_rereads_while_in_flight_and_once_after() {
let mut app = new_app();
app.set_snapshot(recorded(Some(in_flight("building"))));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
app.take_build_log_read();
app.set_build_log("id0", tail(0..1));
app.set_snapshot(recorded(Some(in_flight("postCreateCommand"))));
assert_eq!(app.take_build_log_read(), Some("id0".into()));
assert_eq!(build_log(&app).text.title, " build log — inst0 (running postCreateCommand) ");
app.set_build_log("id0", tail(0..2));
app.set_snapshot(recorded(Some(failed("postCreateCommand"))));
assert_eq!(app.take_build_log_read(), Some("id0".into()));
app.set_build_log("id0", tail(0..3));
assert_eq!(build_log(&app).text.title, " build log — inst0 (failed at postCreateCommand) ");
app.set_snapshot(recorded(Some(failed("postCreateCommand"))));
assert_eq!(app.take_build_log_read(), None);
let mut app = new_app();
app.set_snapshot(recorded(None));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
assert_eq!(app.take_build_log_read(), Some("id0".into()));
app.set_snapshot(recorded(None));
assert_eq!(app.take_build_log_read(), None);
}
#[test]
fn the_build_log_rereads_on_a_timer_while_in_flight() {
let t0 = std::time::Instant::now();
let mut app = new_app();
app.set_snapshot(recorded(Some(in_flight("building"))));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
assert!(app.following_build_log());
assert_eq!(app.take_build_log_read(), Some("id0".into()));
app.tick_build_log(t0);
assert_eq!(app.take_build_log_read(), None, "the open read is unanswered");
app.set_build_log("id0", tail(0..1));
app.tick_build_log(t0);
assert_eq!(app.take_build_log_read(), None, "the first tick starts the interval");
app.tick_build_log(t0 + BUILD_LOG_REREAD / 2);
assert_eq!(app.take_build_log_read(), None);
app.tick_build_log(t0 + BUILD_LOG_REREAD);
assert_eq!(app.take_build_log_read(), Some("id0".into()));
app.tick_build_log(t0 + BUILD_LOG_REREAD * 3);
assert_eq!(app.take_build_log_read(), None);
app.set_build_log("id0", tail(0..2));
app.tick_build_log(t0 + BUILD_LOG_REREAD * 3);
assert_eq!(app.take_build_log_read(), None, "due an interval after the answer");
app.tick_build_log(t0 + BUILD_LOG_REREAD * 4);
assert_eq!(app.take_build_log_read(), Some("id0".into()));
app.set_build_log("id0", tail(0..3));
app.set_snapshot(recorded(Some(failed("building"))));
assert_eq!(app.take_build_log_read(), Some("id0".into()));
app.set_build_log("id0", tail(0..4));
assert!(!app.following_build_log());
app.tick_build_log(t0 + BUILD_LOG_REREAD * 10);
assert_eq!(app.take_build_log_read(), None);
app.set_snapshot(recorded(Some(in_flight("building"))));
app.take_build_log_read();
app.set_build_log("id0", tail(0..4));
app.on_key(key(KeyCode::Esc));
app.tick_build_log(t0 + BUILD_LOG_REREAD * 20);
assert_eq!(app.take_build_log_read(), None);
}
#[test]
fn the_build_log_sticks_to_the_bottom_until_scrolled_up() {
let mut app = new_app();
app.set_snapshot(recorded(Some(in_flight("building"))));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
build_log(&app).height.set(10); app.set_build_log("id0", tail(0..30));
assert!(build_log(&app).stick);
assert_eq!(build_log(&app).top(), 20, "the last line at the bottom");
app.set_build_log("id0", tail(0..40));
assert_eq!(build_log(&app).top(), 30, "follows new lines");
app.on_key(key(KeyCode::Up));
assert!(!build_log(&app).stick);
assert_eq!(build_log(&app).top(), 29);
app.set_build_log("id0", tail(0..50));
assert_eq!(build_log(&app).top(), 29);
app.on_key(key(KeyCode::PageDown));
assert!(build_log(&app).stick);
assert_eq!(build_log(&app).top(), 40);
app.on_key(key(KeyCode::Char('g')));
assert_eq!(build_log(&app).top(), 0);
app.on_key(key(KeyCode::Char('G')));
assert!(build_log(&app).stick);
app.set_build_log("id0", tail(0..60));
assert_eq!(build_log(&app).top(), 50);
app.on_key(key(KeyCode::Char('g')));
app.on_key(key(KeyCode::PageDown));
assert_eq!(build_log(&app).top(), 20);
app.set_build_log("id0", tail(0..5));
assert_eq!(build_log(&app).top(), 4);
}
fn cut_tail(lines: std::ops::Range<usize>) -> Result<Option<Tail>, String> {
let text = lines.map(|i| format!("l{i}")).collect::<Vec<_>>().join("\n");
Ok(Some(Tail { text, cut: true }))
}
fn shown(app: &App) -> &str {
let view = build_log(app);
view.text.body.lines().nth(usize::from(view.top())).unwrap_or("")
}
#[test]
fn a_sliding_build_log_window_keeps_the_shown_lines() {
let mut app = new_app();
app.set_snapshot(recorded(Some(in_flight("building"))));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
build_log(&app).height.set(10);
app.set_build_log("id0", tail(0..400));
app.on_key(key(KeyCode::Char('g')));
for _ in 0..5 {
app.on_key(key(KeyCode::PageDown));
}
assert_eq!(shown(&app), "l100");
app.set_build_log("id0", cut_tail(50..550));
assert_eq!(shown(&app), "l100");
assert_eq!(build_log(&app).top(), 51);
app.set_build_log("id0", cut_tail(53..553));
assert_eq!(shown(&app), "l100");
app.set_build_log("id0", cut_tail(53..553));
assert_eq!(shown(&app), "l100");
app.set_build_log("id0", cut_tail(120..620));
assert_eq!(build_log(&app).top(), 0);
app.set_build_log("id0", cut_tail(130..630));
assert_eq!(build_log(&app).top(), 0, "the note stays");
app.on_key(key(KeyCode::PageDown));
let top = build_log(&app).top();
let fresh = (0..500).map(|i| format!("m{i}")).collect::<Vec<_>>().join("\n");
app.set_build_log("id0", Ok(Some(Tail { text: fresh, cut: true })));
assert_eq!(build_log(&app).top(), top);
app.on_key(key(KeyCode::Char('G')));
app.set_build_log("id0", cut_tail(140..640));
assert!(build_log(&app).stick);
assert_eq!(shown(&app), "l630");
}
#[test]
fn the_build_log_keeps_plain_text_and_styled_lines_side_by_side() {
use ratatui::style::{Color, Style};
let mut app = new_app();
app.set_snapshot(recorded(None));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
let text = "plain\n\x1b[0;32mgreen\x1b[0m tail\x1b[1A".to_string();
app.set_build_log("id0", Ok(Some(Tail { text, cut: true })));
let view = build_log(&app);
assert_eq!(view.text.body, "… (earlier lines: devsandbox logs --build inst0)\nplain\ngreen tail");
assert_eq!(view.styled.len(), 3, "one per body line");
assert_eq!(view.styled[0], Line::from("… (earlier lines: devsandbox logs --build inst0)"));
let green: Vec<_> = view.styled[2].spans.iter().map(|s| (s.content.to_string(), s.style)).collect();
assert_eq!(green, [("green".to_string(), Style::default().fg(Color::Green)), (" tail".to_string(), Style::default())]);
app.set_build_log("id0", Err("cannot read".into()));
assert!(build_log(&app).styled.is_empty());
app.set_build_log("id0", Ok(None));
assert!(build_log(&app).styled.is_empty());
}
#[test]
fn a_sliding_replayed_window_keeps_the_shown_lines_while_its_screen_redraws() {
let window = |from: usize, step: usize| -> Result<Option<Tail>, String> {
let mut lines: Vec<String> = (from..from + 495).map(|i| format!("l{i}")).collect();
lines.extend((0..5).map(|r| format!("[+] Building {step} row {r}")));
Ok(Some(Tail { text: lines.join("\n"), cut: true }))
};
let mut app = new_app();
app.set_snapshot(recorded(Some(in_flight("building"))));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
build_log(&app).height.set(10);
app.set_build_log("id0", window(0, 0));
app.on_key(key(KeyCode::Char('g')));
for _ in 0..10 {
app.on_key(key(KeyCode::PageDown));
}
assert_eq!(shown(&app), "l199");
app.set_build_log("id0", window(30, 1));
assert_eq!(shown(&app), "l199", "slid by 30 though the screen rows changed");
app.set_build_log("id0", window(31, 2));
assert_eq!(shown(&app), "l199");
}
#[test]
fn slid_by_matches_the_overlap() {
let old = ["a", "b", "c", "d"];
assert_eq!(slid_by(&old, &["a", "b", "c", "d", "e"]), Some(0));
assert_eq!(slid_by(&old, &["c", "d", "e", "f"]), Some(2));
assert_eq!(slid_by(&old, &["b", "c", "dd", "e"]), Some(1));
assert_eq!(slid_by(&["x", "x", "x", "y"], &["x", "x", "y", "z"]), Some(1));
assert_eq!(slid_by(&old, &["e", "f"]), None);
assert_eq!(slid_by(&["a"], &["a"]), None, "nothing to overlap");
assert_eq!(slid_by(&old, &["b", "c", "x", "y"]), Some(1));
assert_eq!(slid_by(&["a", "b", "c", "d", "e"], &["c", "x", "y"]), Some(2));
}
#[test]
fn the_wheel_scrolls_the_text_modals() {
let panel = crate::tui::ui::terminal_panel_rect(FRAME, false);
let wheel = |app: &mut App, kind| app.on_mouse(&mouse_at(kind, panel.x + 2, panel.y + 2), FRAME);
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 body = (0..30).map(|i| format!("l{i}")).collect::<Vec<_>>().join("\n");
app.modal = Modal::Logs(TextModal::new(" logs ".into(), body));
wheel(&mut app, MouseEventKind::ScrollDown);
wheel(&mut app, MouseEventKind::ScrollDown);
let Modal::Logs(view) = &app.modal else { panic!("logs closed") };
assert_eq!(view.scroll, 6);
wheel(&mut app, MouseEventKind::ScrollUp);
let Modal::Logs(view) = &app.modal else { panic!("logs closed") };
assert_eq!(view.scroll, 3);
let scrollback = app.terms.active_session().unwrap().parser().lock().unwrap().screen().scrollback();
assert_eq!(scrollback, 0, "the terminal under the modal didn't see it");
let mut app = new_app();
app.on_key(key(KeyCode::Char('?')));
wheel(&mut app, MouseEventKind::ScrollDown);
let Modal::Help(view) = &app.modal else { panic!("help closed") };
assert_eq!(view.text.scroll, 3);
wheel(&mut app, MouseEventKind::ScrollUp);
wheel(&mut app, MouseEventKind::ScrollUp);
let Modal::Help(view) = &app.modal else { panic!("help closed") };
assert_eq!(view.text.scroll, 0, "clamped");
let mut app = new_app();
app.set_snapshot(recorded(Some(in_flight("building"))));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Char('b')));
build_log(&app).height.set(10);
app.set_build_log("id0", tail(0..30));
wheel(&mut app, MouseEventKind::ScrollUp);
assert!(!build_log(&app).stick);
assert_eq!(build_log(&app).top(), 17);
wheel(&mut app, MouseEventKind::ScrollDown);
assert!(build_log(&app).stick);
assert_eq!(build_log(&app).top(), 20);
}
#[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));
}
#[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);
}
#[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 crate::tui::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,
instance_id: String::new(),
dispatcher: None,
done: false,
profile: None,
profile_disallowed: false,
browser_sandbox: None, github_repos: Vec::new(), build_notes: Vec::new(),
phase: None,
root: None,
mesh_root: None,
machine: None,
};
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 crate::tui::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);
}
}