use std::collections::BTreeMap;
use crate::tui::data::{ContainerStatus, Node};
use crate::tui::procs::ProcState;
use crate::tui::remote::{self, instance_key};
use super::{App, Tab};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Signal {
Term,
Kill,
}
impl Signal {
pub fn wire(self) -> &'static str {
match self {
Signal::Term => "TERM",
Signal::Kill => "KILL",
}
}
pub fn name(self) -> &'static str {
match self {
Signal::Term => "SIGTERM",
Signal::Kill => "SIGKILL",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingSignal {
pub instance: String,
pub pid: String,
pub signal: Signal,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingSessionRm {
pub instance: String,
pub id: String,
}
impl App {
pub(super) fn selected_session(&self) -> Option<(String, String)> {
let Node::Proc { instance, row } = self.selected_node()? else {
return None;
};
let inst = self.snapshot.as_ref()?.instances.get(instance)?;
let key = instance_key(inst);
let ProcState::Rows { rows, .. } = self.procs.get(&key)? else {
return None;
};
let id = crate::tui::procs::session_id(rows.get(row)?)?.to_string();
Some((key, id))
}
pub(super) fn attach_selected_session(&mut self) {
if let Some((key, id)) = self.selected_session() {
self.open_attach(&key, &id);
}
}
pub(super) fn end_selected_session(&mut self) {
let Some((instance, id)) = self.selected_session() else {
return;
};
self.status = Some(format!("ending session {id}…"));
self.pending_session_rm = Some(PendingSessionRm { instance, id });
}
pub fn take_pending_session_rm(&mut self) -> Option<PendingSessionRm> {
self.pending_session_rm.take()
}
pub fn on_session_row(&self) -> bool {
self.on_proc_row() && self.selected_session().is_some()
}
fn selected_proc(&self) -> Option<(String, String)> {
let snapshot = self.snapshot.as_ref()?;
let Node::Proc { instance, row } = self.selected_node()? else {
return None;
};
if row == crate::tui::procs::MESSAGE_ROW {
return None;
}
let inst = snapshot.instances.get(instance)?;
let ProcState::Rows { rows, signalable, .. } = self.procs.get(&instance_key(inst))? else {
return None;
};
if !signalable {
return None;
}
let proc = rows.get(row)?;
proc.pid.parse::<u32>().ok()?;
Some((instance_key(inst), proc.pid.clone()))
}
pub(super) fn signal_selected_proc(&mut self, signal: Signal) {
let Some((instance, pid)) = self.selected_proc() else {
return;
};
self.status = Some(format!("sending {} to pid {pid}…", signal.name()));
self.pending_signal = Some(PendingSignal {
instance,
pid,
signal,
});
}
pub fn take_pending_signal(&mut self) -> Option<PendingSignal> {
self.pending_signal.take()
}
pub fn on_proc_row(&self) -> bool {
self.tab == Tab::Instances && matches!(self.selected_node(), Some(Node::Proc { .. }))
}
pub fn proc_row_signalable(&self) -> bool {
self.selected_proc().is_some()
}
pub fn agent_count(&self, instance: &str) -> Option<usize> {
match self.procs.get(instance) {
Some(ProcState::Rows { rows, .. }) => Some(
rows.iter()
.filter(|r| {
![crate::tui::procs::RUN_PID, crate::tui::procs::SESSION_PID].contains(&r.pid.as_str())
&& crate::tui::procs::is_agent(&r.args)
})
.count(),
),
_ => None,
}
}
pub fn session_count(&self, instance: &str) -> Option<crate::tui::procs::SessionCount> {
match self.procs.get(instance) {
Some(ProcState::Rows { sessions, .. }) => *sessions,
_ => None,
}
}
fn selected_running_instance(&self) -> Option<String> {
let snapshot = self.snapshot.as_ref()?;
let idx = self.selected_instance_index()?;
let row = snapshot.instances.get(idx)?;
let reachable = !remote::unreachable(&self.machines, row.machine.as_deref());
(reachable && matches!(row.status, ContainerStatus::Running(_))).then(|| instance_key(row))
}
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> {
if self.tab != Tab::Instances {
return Vec::new();
}
let Some(snapshot) = &self.snapshot else {
return Vec::new();
};
let mut targets = Vec::new();
let mut not_running: Vec<(String, &str)> = Vec::new();
for name in &self.expanded_procs {
match remote::find_instance(snapshot, name) {
Some(row) if remote::unreachable(&self.machines, row.machine.as_deref()) => {
not_running.push((name.clone(), "(machine unreachable)"));
}
Some(row) if matches!(row.status, ContainerStatus::Running(_)) => {
targets.push(name.clone());
}
_ => not_running.push((name.clone(), "(not running)")),
}
}
for (name, why) in not_running {
self.procs.insert(name, ProcState::Message(why.to_string()));
}
if let Some(name) = self.selected_running_instance() {
if !targets.contains(&name) {
targets.push(name);
}
}
targets
}
pub fn apply_proc_fetch(&mut self, fetched: BTreeMap<String, ProcState>) {
self.procs.extend(fetched);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tui::app::test_support::*;
use crate::tui::app::*;
#[test]
fn proc_fetch_only_on_instances_tab() {
let mut app = new_app();
app.set_snapshot(snapshot_with_status(1, running()));
app.on_key(key(KeyCode::Down));
assert_eq!(app.proc_fetch_targets().len(), 1);
app.set_tab(Tab::Ports);
assert!(app.proc_fetch_targets().is_empty());
app.take_needs_proc_fetch();
app.set_tab(Tab::Instances);
assert!(app.take_needs_proc_fetch());
assert_eq!(app.proc_fetch_targets().len(), 1);
}
#[test]
fn procs_are_keyed_per_machine() {
use crate::serve::snapshots::LinkState;
let mut app = machine_app();
app.expanded_procs.extend(["inst0".to_string(), "box/inst0".to_string()]);
app.selected[Tab::Instances.index()] = 0;
let mut targets = app.proc_fetch_targets();
targets.sort();
assert_eq!(targets, ["box/inst0", "inst0"]);
app.machines[0].state = LinkState::Unreachable;
assert_eq!(app.proc_fetch_targets(), ["inst0"]);
assert_eq!(app.procs["box/inst0"], ProcState::Message("(machine unreachable)".into()));
app.machines[0].state = LinkState::Connected;
expand_with_rows(&mut app, "box/inst1", &["42"]);
let at = app.visible_nodes().iter().position(|n| *n == Node::Proc { instance: 3, row: 0 }).unwrap();
app.selected[Tab::Instances.index()] = at;
app.signal_selected_proc(Signal::Term);
assert_eq!(
app.take_pending_signal(),
Some(PendingSignal { instance: "box/inst1".into(), pid: "42".into(), signal: Signal::Term })
);
}
#[test]
fn snapshots_are_installed_without_carrying_cpu_mem() {
let mut app = new_app();
let mut full = snapshot_with_status(2, running());
for row in &mut full.instances {
row.cpu = Some("1%".into());
row.mem = Some("1MiB".into());
}
app.set_snapshot(full);
let mut next = snapshot_with_status(2, running());
next.depth = crate::snapshot::Depth::Listing;
next.instances[0].cpu = Some("2%".into());
next.instances[1].status = ContainerStatus::Exited("Exited (0)".into());
app.set_snapshot(next);
let rows = &app.snapshot.as_ref().unwrap().instances;
assert_eq!(rows[0].cpu.as_deref(), Some("2%"));
assert_eq!(rows[0].mem, None, "not filled from the last snapshot");
assert_eq!(rows[1].cpu, None, "stopped: no stale cpu");
}
#[test]
fn instance_shortcuts_disabled_on_proc_row() {
let mut app = app_on_proc_row(&["10"]);
for code in [
KeyCode::Char('s'),
KeyCode::Char('o'),
KeyCode::Char('r'),
KeyCode::Char('l'),
KeyCode::Char('e'),
KeyCode::Enter,
KeyCode::Char('T'),
] {
app.on_key(key(code));
}
assert!(app.stopping.is_empty());
assert!(app.take_pending_action().is_none());
assert!(app.take_pending_signal().is_none());
assert!(matches!(app.modal, Modal::None));
assert!(app.prompt.is_none());
assert!(app.terms.is_empty());
}
#[test]
fn t_and_shift_k_signal_the_selected_proc() {
let mut app = app_on_proc_row(&["10"]);
app.on_key(key(KeyCode::Char('t')));
assert_eq!(
app.take_pending_signal(),
Some(PendingSignal {
instance: "inst0".into(),
pid: "10".into(),
signal: Signal::Term,
}),
);
app.on_key(key(KeyCode::Char('K')));
assert_eq!(
app.take_pending_signal(),
Some(PendingSignal {
instance: "inst0".into(),
pid: "10".into(),
signal: Signal::Kill,
}),
);
}
#[test]
fn signal_noop_on_message_placeholder_row() {
use crate::tui::procs::ProcState;
let mut app = new_app();
app.set_snapshot(snapshot_with_status(1, running()));
app.expanded_procs.insert("inst0".into());
app.procs
.insert("inst0".into(), ProcState::Message("(not running)".into()));
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down));
assert!(matches!(app.selected_node(), Some(Node::Proc { .. })));
app.on_key(key(KeyCode::Char('t')));
assert!(app.take_pending_signal().is_none());
}
#[test]
fn help_bar_switches_to_signal_legend_on_proc_row() {
let app = app_on_proc_row(&["10"]);
assert!(app.on_proc_row());
assert!(app.proc_row_signalable());
let mut app2 = new_app();
app2.set_snapshot(snapshot_with_status(1, running()));
app2.on_key(key(KeyCode::Down));
assert!(!app2.on_proc_row());
}
#[test]
fn top_fallback_listing_is_not_signalable() {
use crate::tui::procs::{ProcRow, ProcState};
let mut app = new_app();
app.set_snapshot(snapshot_with_status(1, running()));
app.expanded_procs.insert("inst0".into());
app.procs.insert(
"inst0".into(),
ProcState::Rows {
rows: vec![ProcRow { pid: "660011".into(), depth: 0, args: "x".into() }],
signalable: false,
sessions: None,
},
);
app.on_key(key(KeyCode::Down));
app.on_key(key(KeyCode::Down));
assert!(app.on_proc_row());
assert!(!app.proc_row_signalable());
app.on_key(key(KeyCode::Char('t')));
app.on_key(key(KeyCode::Char('K')));
assert!(app.take_pending_signal().is_none());
}
#[test]
fn proc_fetch_targets_running_and_not_running() {
use crate::tui::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,
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 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(),
identity: Vec::new(),
dispatcher: false,
worktree_branch: None,
profiles: Vec::new(),
root: None,
mesh_root: None,
machine: None,
}],
services: Vec::new(),
sandbox_count: 1,
runtime_name: "docker".into(),
runtime_version: None,
collected_at: std::time::Instant::now(),
depth: crate::snapshot::Depth::Full,
error: None,
no_runtime: false,
};
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()]);
assert_eq!(
app.procs.get("down"),
Some(&crate::tui::procs::ProcState::Message("(not running)".into())),
);
}
#[test]
fn run_rows_are_not_signalable() {
let mut app = app_on_proc_row(&[crate::tui::procs::RUN_PID]);
assert!(app.on_proc_row());
assert!(!app.proc_row_signalable());
app.on_key(key(KeyCode::Char('t')));
assert!(app.take_pending_signal().is_none());
}
#[test]
fn session_rows_end_on_shift_k_and_never_signal() {
let mut app = new_app();
app.set_snapshot(snapshot_with_status(1, running()));
let mut app = select_session_row(app, "inst0", "1790000000-a1b2 attached bash -l");
assert!(app.on_session_row() && !app.proc_row_signalable());
app.on_key(key(KeyCode::Char('t')));
assert_eq!(app.status.as_deref(), Some("a attaches, K ends the session"));
assert!(app.take_pending_signal().is_none());
app.on_key(key(KeyCode::Char('K')));
assert_eq!(app.status.as_deref(), Some("ending session 1790000000-a1b2…"));
assert_eq!(
app.take_pending_session_rm(),
Some(PendingSessionRm { instance: "inst0".into(), id: "1790000000-a1b2".into() })
);
assert!(app.take_pending_signal().is_none());
let mut app = select_session_row(machine_app(), "box/inst1", "1790000000-a1b2 detached vim");
app.on_key(key(KeyCode::Char('K')));
assert_eq!(app.take_pending_session_rm().unwrap().instance, "box/inst1");
let mut app = app_on_proc_row(&[crate::tui::procs::RUN_PID]);
assert!(!app.on_session_row());
app.on_key(key(KeyCode::Char('K')));
assert!(app.take_pending_session_rm().is_none());
}
#[test]
fn agent_count_counts_agent_rows_in_cache() {
use crate::tui::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: "claude --resume".into() },
ProcRow {
pid: crate::tui::procs::RUN_PID.into(),
depth: 0,
args: "1790000000-a1b2 running claude -p x".into(),
},
ProcRow {
pid: crate::tui::procs::SESSION_PID.into(),
depth: 0,
args: "1790000001-a1b2 attached claude".into(),
},
];
app.procs.insert("x".into(), ProcState::Rows { rows, signalable: true, sessions: None });
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 session_count_reads_the_cached_listing() {
use crate::tui::procs::SessionCount;
use crate::tui::procs::ProcState;
let mut app = new_app();
assert_eq!(app.session_count("x"), None);
let count = SessionCount { running: 3, detached: 1 };
app.procs.insert("x".into(), ProcState::Rows { rows: Vec::new(), signalable: true, sessions: Some(count) });
assert_eq!(app.session_count("x"), Some(count));
app.procs.insert("old".into(), ProcState::Rows { rows: Vec::new(), signalable: true, sessions: None });
assert_eq!(app.session_count("old"), None);
app.procs.insert("y".into(), ProcState::Message("(not running)".into()));
assert_eq!(app.session_count("y"), None);
}
#[test]
fn proc_fetch_targets_includes_selected_running_instance() {
use crate::tui::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,
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,
};
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(),
identity: Vec::new(),
dispatcher: false,
worktree_branch: None,
profiles: Vec::new(),
root: None,
mesh_root: None,
machine: None,
}],
services: Vec::new(),
sandbox_count: 1,
runtime_name: "docker".into(),
runtime_version: None,
collected_at: std::time::Instant::now(),
depth: crate::snapshot::Depth::Full,
error: None,
no_runtime: false,
});
assert!(app.proc_fetch_targets().is_empty());
app.on_key(key(KeyCode::Down));
assert_eq!(app.proc_fetch_targets(), vec!["up".to_string()]);
assert!(app.expanded_procs.is_empty());
}
}