use super::command::{self, Command, CommandBar, Completions, TabName};
use super::model::{visible_rows, MeshSnapshot, RowRef, Sort};
use crate::agent::summary::Summary;
use std::collections::{BTreeMap, HashSet};
use std::time::{Duration, Instant};
pub const TOAST_FOR: Duration = Duration::from_secs(6);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tab {
Mesh,
Account,
Share,
}
impl Tab {
pub const ALL: [Tab; 3] = [Tab::Mesh, Tab::Account, Tab::Share];
pub fn title(self) -> &'static str {
match self {
Tab::Mesh => "Mesh",
Tab::Account => "Account",
Tab::Share => "Share",
}
}
pub fn index(self) -> usize {
Tab::ALL.iter().position(|t| *t == self).unwrap_or(0)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Key {
Char(char),
Enter,
Esc,
Tab,
BackTab,
Up,
Down,
PageUp,
PageDown,
Home,
End,
Left,
Right,
Backspace,
CtrlC,
}
#[derive(Debug, Clone, PartialEq)]
pub enum AgentState {
Running(Box<Summary>),
NotRunning(Option<String>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Write {
Sharing(bool),
Workers(u32),
Price(f64),
}
#[derive(Debug, Clone)]
pub enum Event {
Key(Key),
Tick,
Mesh(MeshSnapshot),
Agent(AgentState),
Done(Write, Result<Box<Summary>, String>),
AgentStarted(Result<(), String>),
Note(String),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Effect {
RefreshMesh,
RefreshAgent,
Copy(String),
Apply(Write),
StartAgent,
OpenUrl(String),
Suspend(Vec<String>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct PriceEdit {
pub buf: String,
pub min: u32,
pub max: u32,
pub step: u32,
}
impl PriceEdit {
pub fn value(&self) -> Option<f64> {
let v: f64 = self.buf.parse().ok()?;
(v >= self.min as f64 && v <= self.max as f64).then_some(v)
}
}
pub struct App {
pub tab: Tab,
pub mesh: Option<MeshSnapshot>,
pub mesh_at: Option<Instant>,
pub agent: Option<AgentState>,
pub agent_at: Option<Instant>,
pub agent_failures: u32,
pub mesh_sel: usize,
pub expanded: HashSet<String>,
pub filter: String,
pub filtering: bool,
pub sort: Sort,
pub account_sel: usize,
pub share_sel: usize,
pub price_edit: Option<PriceEdit>,
pub pending: Option<Write>,
pub toast: Option<(String, Instant)>,
pub bar: Option<CommandBar>,
pub history: Vec<String>,
pub help: bool,
pub detail: bool,
pub changes: BTreeMap<&'static str, (String, String)>,
pub ticks: u64,
pub starting: bool,
pub quit: bool,
}
impl Default for App {
fn default() -> Self {
Self::new()
}
}
impl App {
pub fn new() -> Self {
App {
tab: Tab::Mesh,
mesh: None,
mesh_at: None,
agent: None,
agent_at: None,
agent_failures: 0,
mesh_sel: 0,
expanded: HashSet::new(),
filter: String::new(),
filtering: false,
sort: Sort::Price,
account_sel: 0,
share_sel: 0,
price_edit: None,
pending: None,
toast: None,
bar: None,
history: Vec::new(),
help: false,
detail: false,
changes: BTreeMap::new(),
ticks: 0,
starting: false,
quit: false,
}
}
pub fn rows(&self) -> Vec<RowRef> {
match &self.mesh {
Some(m) => visible_rows(m, &self.expanded, &self.filter, self.sort),
None => Vec::new(),
}
}
pub fn selected_row(&self) -> Option<RowRef> {
self.rows().get(self.mesh_sel).copied()
}
pub fn summary(&self) -> Option<&Summary> {
match &self.agent {
Some(AgentState::Running(s)) => Some(s),
_ => None,
}
}
fn selected_address(&self) -> Option<String> {
let m = self.mesh.as_ref()?;
let i = match self.selected_row()? {
RowRef::Node(i) | RowRef::Worker(i, _) => i,
};
Some(m.nodes[i].address())
}
pub fn completions(&self) -> Completions {
Completions {
addresses: self
.mesh
.as_ref()
.map(|m| m.nodes.iter().map(|n| n.address()).collect())
.unwrap_or_default(),
}
}
fn toast(&mut self, msg: impl Into<String>) {
let msg = msg.into();
if !msg.is_empty() {
self.toast = Some((msg, Instant::now()));
}
}
}
pub fn sdk_line(address: &str) -> String {
format!("fn.to(zk.Compute(uri=\"{address}\"))(...)")
}
fn move_sel(sel: &mut usize, len: usize, key: &Key) {
if len == 0 {
*sel = 0;
return;
}
let last = len - 1;
*sel = match key {
Key::Up | Key::Char('k') => sel.saturating_sub(1),
Key::Down | Key::Char('j') => (*sel + 1).min(last),
Key::PageUp => sel.saturating_sub(10),
Key::PageDown => (*sel + 10).min(last),
Key::Home | Key::Char('g') => 0,
Key::End | Key::Char('G') => last,
_ => *sel,
};
}
fn is_move(key: &Key) -> bool {
matches!(
key,
Key::Up
| Key::Down
| Key::PageUp
| Key::PageDown
| Key::Home
| Key::End
| Key::Char('j' | 'k' | 'g' | 'G')
)
}
pub fn update(app: &mut App, ev: Event) -> Vec<Effect> {
match ev {
Event::Tick => {
app.ticks += 1;
if app
.toast
.as_ref()
.is_some_and(|(_, at)| at.elapsed() >= TOAST_FOR)
{
app.toast = None;
}
vec![]
}
Event::Note(msg) => {
app.toast(msg);
vec![]
}
Event::Mesh(snap) => {
app.mesh = Some(snap);
app.mesh_at = Some(Instant::now());
let len = app.rows().len();
if app.mesh_sel >= len {
app.mesh_sel = len.saturating_sub(1);
}
vec![]
}
Event::Agent(state) => {
match (&app.agent, state) {
(Some(AgentState::Running(_)), AgentState::NotRunning(Some(_))) => {
app.agent_failures += 1;
}
(_, s) => {
if matches!(s, AgentState::Running(_)) {
app.agent_failures = 0;
app.agent_at = Some(Instant::now());
}
app.agent = Some(s);
}
}
vec![]
}
Event::Done(w, result) => on_done(app, w, result),
Event::AgentStarted(Ok(())) => {
app.starting = false;
app.toast("zc agent started");
vec![Effect::RefreshAgent]
}
Event::AgentStarted(Err(e)) => {
app.starting = false;
app.toast(e);
vec![]
}
Event::Key(k) => on_key(app, k),
}
}
fn on_key(app: &mut App, k: Key) -> Vec<Effect> {
if k == Key::CtrlC {
app.quit = true;
return vec![];
}
if app.help {
if matches!(k, Key::Esc | Key::Char('?')) {
app.help = false;
}
return vec![];
}
if app.bar.is_some() {
return on_bar_key(app, k);
}
if app.price_edit.is_some() {
return on_price_key(app, k);
}
if app.filtering {
match k {
Key::Esc => {
app.filter.clear();
app.filtering = false;
}
Key::Enter => app.filtering = false,
Key::Backspace => {
app.filter.pop();
}
Key::Char(c) => app.filter.push(c),
ref m if is_move(m) => {
let len = app.rows().len();
move_sel(&mut app.mesh_sel, len, m)
}
_ => {}
}
app.mesh_sel = app.mesh_sel.min(app.rows().len().saturating_sub(1));
return vec![];
}
if app.detail && k == Key::Esc {
app.detail = false;
return vec![];
}
match k {
Key::Char('q') => {
app.quit = true;
return vec![];
}
Key::Char('?') => {
app.help = true;
return vec![];
}
Key::Char(':') => {
app.bar = Some(CommandBar::new());
return vec![];
}
Key::Char('1') => app.tab = Tab::Mesh,
Key::Char('2') => app.tab = Tab::Account,
Key::Char('3') => app.tab = Tab::Share,
Key::Tab => app.tab = Tab::ALL[(app.tab.index() + 1) % 3],
Key::BackTab => app.tab = Tab::ALL[(app.tab.index() + 2) % 3],
Key::Char('r') => return vec![Effect::RefreshMesh, Effect::RefreshAgent],
other => {
return match app.tab {
Tab::Mesh => on_mesh_key(app, other),
Tab::Account => on_account_key(app, other),
Tab::Share => on_share_key(app, other),
}
}
}
app.detail = false;
vec![]
}
fn on_mesh_key(app: &mut App, k: Key) -> Vec<Effect> {
let rows = app.rows();
if is_move(&k) {
move_sel(&mut app.mesh_sel, rows.len(), &k);
return vec![];
}
match k {
Key::Enter => match rows.get(app.mesh_sel) {
Some(RowRef::Node(i)) => {
if let Some(m) = &app.mesh {
let fp = m.nodes[*i].fp.clone();
if !app.expanded.remove(&fp) {
app.expanded.insert(fp);
}
}
vec![]
}
Some(RowRef::Worker(..)) => {
app.detail = true;
vec![]
}
None => vec![],
},
Key::Char('/') => {
app.filtering = true;
vec![]
}
Key::Char('s') => {
app.sort = app.sort.next();
vec![]
}
Key::Char('c') => app
.selected_address()
.map(Effect::Copy)
.into_iter()
.collect(),
Key::Char('y') => app
.selected_address()
.map(|a| Effect::Copy(sdk_line(&a)))
.into_iter()
.collect(),
_ => vec![],
}
}
fn start_agent(app: &mut App) -> Vec<Effect> {
if app.starting {
return vec![];
}
app.starting = true;
app.toast("starting zc agent…");
vec![Effect::StartAgent]
}
pub const ACCOUNT_FIXED_ROWS: usize = 4;
pub const SHARE_ROWS: [&str; 5] = ["Sharing", "Workers", "Price", "Broker", "Requests"];
fn num(v: f64) -> String {
super::model::price_text(v).replace("free", "0")
}
fn describe(w: &Write, s: Option<&Summary>) -> (&'static str, String, String) {
match w {
Write::Sharing(on) => (
"sharing",
s.map(|s| if s.this_mac.sharing { "on" } else { "off" }.to_string())
.unwrap_or_default(),
if *on { "on" } else { "off" }.to_string(),
),
Write::Workers(n) => (
"workers",
s.map(|s| s.this_mac.workers.desired.to_string())
.unwrap_or_default(),
n.to_string(),
),
Write::Price(p) => (
"price",
s.and_then(|s| s.prices.this_mac.per_hour.or(s.prices.default_per_hour))
.map(num)
.unwrap_or_default(),
num(*p),
),
}
}
fn apply(app: &mut App, w: Write) -> Vec<Effect> {
if app.summary().is_none() {
app.toast("zc agent is not running — press a to start it");
return vec![];
}
if app.pending.is_some() {
return vec![];
}
app.pending = Some(w.clone());
vec![Effect::Apply(w)]
}
fn on_done(app: &mut App, w: Write, result: Result<Box<Summary>, String>) -> Vec<Effect> {
app.pending = None;
match result {
Ok(s) => {
let (field, from, to) = describe(&w, app.summary());
app.changes
.entry(field)
.and_modify(|c| c.1 = to.clone())
.or_insert((from, to));
app.agent = Some(AgentState::Running(s));
app.agent_at = Some(Instant::now());
app.agent_failures = 0;
}
Err(e) => app.toast(e),
}
vec![]
}
pub fn exit_summary(app: &App) -> Option<String> {
let parts: Vec<String> = app
.changes
.iter()
.filter(|(_, (from, to))| from != to)
.map(|(field, (from, to))| match *field {
"sharing" => format!("sharing {to}"),
"price" => format!("price {from} → {to}/h"),
other => format!("{other} {from} → {to}"),
})
.collect();
(!parts.is_empty()).then(|| format!("✓ {}", parts.join(" · ")))
}
fn device_count(app: &App) -> usize {
app.summary()
.and_then(|s| s.devices.as_ref())
.map(Vec::len)
.unwrap_or(0)
}
pub(super) fn on_account_key(app: &mut App, k: Key) -> Vec<Effect> {
if k == Key::Char('a') && app.summary().is_none() {
return start_agent(app);
}
if is_move(&k) {
let len = ACCOUNT_FIXED_ROWS + device_count(app);
move_sel(&mut app.account_sel, len, &k);
return vec![];
}
if k == Key::Enter && app.account_sel >= ACCOUNT_FIXED_ROWS {
let link = app
.summary()
.and_then(|s| s.devices.as_ref())
.and_then(|d| d.get(app.account_sel - ACCOUNT_FIXED_ROWS))
.and_then(|d| d.link.clone());
return link.map(Effect::OpenUrl).into_iter().collect();
}
vec![]
}
pub(super) fn on_share_key(app: &mut App, k: Key) -> Vec<Effect> {
if k == Key::Char('a') && app.summary().is_none() {
return start_agent(app);
}
if is_move(&k) {
move_sel(&mut app.share_sel, SHARE_ROWS.len(), &k);
return vec![];
}
let Some(s) = app.summary().cloned() else {
return vec![];
};
let w = s.this_mac.workers;
match k {
Key::Char(' ') => apply(app, Write::Sharing(!s.this_mac.sharing)),
Key::Char('+' | '=') if w.desired < w.max => apply(app, Write::Workers(w.desired + 1)),
Key::Char('-') if w.desired > 0 => apply(app, Write::Workers(w.desired - 1)),
Key::Char('p') => open_price_editor(app, &s),
Key::Enter if app.share_sel == 2 => open_price_editor(app, &s),
_ => vec![],
}
}
fn open_price_editor(app: &mut App, s: &Summary) -> Vec<Effect> {
let b = s.prices.bounds;
let current = s
.prices
.this_mac
.per_hour
.or(s.prices.default_per_hour)
.unwrap_or(b.min as f64);
app.price_edit = Some(PriceEdit {
buf: num(current),
min: b.min,
max: b.max,
step: b.step.max(1),
});
vec![]
}
fn on_price_key(app: &mut App, k: Key) -> Vec<Effect> {
let Some(ed) = app.price_edit.as_mut() else {
return vec![];
};
match k {
Key::Esc => app.price_edit = None,
Key::Left | Key::Right => {
let cur: f64 = ed.buf.parse().unwrap_or(ed.min as f64);
let step = ed.step as f64;
let next = if k == Key::Right {
cur + step
} else {
cur - step
};
ed.buf = num(next.clamp(ed.min as f64, ed.max as f64));
}
Key::Backspace => {
ed.buf.pop();
}
Key::Char(c) if c.is_ascii_digit() || (c == '.' && !ed.buf.contains('.')) => ed.buf.push(c),
Key::Enter => match ed.value() {
Some(v) => {
app.price_edit = None;
return apply(app, Write::Price(v));
}
None => {
let (min, max) = (ed.min, ed.max);
app.toast(format!("price must be between {min} and {max} yen/h"));
}
},
_ => {}
}
vec![]
}
fn on_bar_key(app: &mut App, k: Key) -> Vec<Effect> {
let comps = app.completions();
let history = app.history.clone();
let Some(bar) = app.bar.as_mut() else {
return vec![];
};
match k {
Key::Esc => app.bar = None,
Key::Tab => bar.tab(&comps),
Key::Up => bar.history_up(&history),
Key::Down => bar.history_down(&history),
Key::Backspace => {
bar.input.pop();
bar.matches.clear();
}
Key::Char(c) => {
bar.input.push(c);
bar.matches.clear();
}
Key::Enter => {
let line = bar.input.trim().to_string();
return match command::parse(&line) {
Ok(cmd) => {
app.bar = None;
if app.history.last() != Some(&line) {
app.history.push(line);
}
run_command(app, cmd)
}
Err(e) if e.is_empty() => {
app.bar = None;
vec![]
}
Err(e) => {
app.toast(e);
vec![]
}
};
}
_ => {}
}
vec![]
}
fn run_command(app: &mut App, cmd: Command) -> Vec<Effect> {
match cmd {
Command::Price(p) => {
if let Some(b) = app.summary().map(|s| s.prices.bounds) {
if p < b.min as f64 || p > b.max as f64 {
app.toast(format!(
"price must be between {} and {} yen/h",
b.min, b.max
));
return vec![];
}
}
apply(app, Write::Price(p))
}
Command::Workers(n) => {
if let Some(max) = app.summary().map(|s| s.this_mac.workers.max) {
if n > max {
app.toast(format!("workers must be between 0 and {max}"));
return vec![];
}
}
apply(app, Write::Workers(n))
}
Command::Share(on) => apply(app, Write::Sharing(on)),
Command::Refresh => vec![Effect::RefreshMesh, Effect::RefreshAgent],
Command::Copy(s) => vec![Effect::Copy(s)],
Command::Quit => {
app.quit = true;
vec![]
}
Command::Tab(t) => {
app.tab = match t {
TabName::Mesh => Tab::Mesh,
TabName::Account => Tab::Account,
TabName::Share => Tab::Share,
};
vec![]
}
Command::External(args) => vec![Effect::Suspend(args)],
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::session::model::{MeshNode, MeshWorker};
pub(crate) fn summary() -> Summary {
serde_json::from_str(include_str!("../../docs/agent-api/summary.v1.json")).unwrap()
}
fn worker(name: &str) -> MeshWorker {
MeshWorker::from_json(&serde_json::json!({"name": name, "status": "healthy",
"cpus_total": 4.0, "price_per_hour": 2.0}))
}
pub(crate) fn mesh() -> MeshSnapshot {
MeshSnapshot {
nodes: vec![
MeshNode {
fp: "aaaa".into(),
name: Some("i9".into()),
is_self: false,
workers: vec![worker("w0"), worker("w1")],
},
MeshNode {
fp: "bbbb".into(),
name: Some("broker-0".into()),
is_self: false,
workers: vec![MeshWorker::from_json(&serde_json::json!({
"name": "x0", "status": "healthy", "cpus_total": 4.0, "price_per_hour": 5.0
}))],
},
MeshNode {
fp: "cccc".into(),
name: Some("idle".into()),
is_self: false,
workers: vec![],
},
],
..Default::default()
}
}
fn key(app: &mut App, k: Key) -> Vec<Effect> {
update(app, Event::Key(k))
}
#[test]
fn tabs_switch_by_number_and_tab_key() {
let mut a = App::new();
key(&mut a, Key::Char('3'));
assert_eq!(a.tab, Tab::Share);
key(&mut a, Key::Tab);
assert_eq!(a.tab, Tab::Mesh);
key(&mut a, Key::BackTab);
assert_eq!(a.tab, Tab::Share);
}
#[test]
fn q_and_ctrl_c_quit_but_esc_does_not() {
let mut a = App::new();
key(&mut a, Key::Esc);
assert!(!a.quit);
key(&mut a, Key::Char('q'));
assert!(a.quit);
let mut a = App::new();
key(&mut a, Key::CtrlC);
assert!(a.quit);
}
#[test]
fn esc_closes_the_innermost_thing_first() {
let mut a = App::new();
update(&mut a, Event::Mesh(mesh()));
key(&mut a, Key::Char('/'));
key(&mut a, Key::Char('?'));
assert!(!a.help, "while filtering, ? is a character");
assert_eq!(a.filter, "?");
key(&mut a, Key::Esc);
assert!(!a.filtering);
key(&mut a, Key::Char('?'));
assert!(a.help);
key(&mut a, Key::Esc);
assert!(!a.help && !a.quit);
}
#[test]
fn help_opens_and_esc_closes_it() {
let mut a = App::new();
key(&mut a, Key::Char('?'));
assert!(a.help);
key(&mut a, Key::Char('q'));
assert!(!a.quit, "q inside help does not quit");
key(&mut a, Key::Esc);
assert!(!a.help);
}
#[test]
fn enter_expands_a_node_and_selection_moves_over_workers() {
let mut a = App::new();
update(&mut a, Event::Mesh(mesh()));
assert_eq!(a.rows().len(), 2);
key(&mut a, Key::Enter);
assert_eq!(a.rows().len(), 4);
key(&mut a, Key::Down);
assert_eq!(a.selected_row(), Some(RowRef::Worker(0, 0)));
key(&mut a, Key::End);
assert_eq!(a.selected_row(), Some(RowRef::Node(1)));
key(&mut a, Key::Down);
assert_eq!(a.selected_row(), Some(RowRef::Node(1)), "stops at the end");
}
#[test]
fn c_copies_the_node_address_even_on_a_worker_row() {
let mut a = App::new();
update(&mut a, Event::Mesh(mesh()));
key(&mut a, Key::Enter);
key(&mut a, Key::Down);
assert_eq!(
key(&mut a, Key::Char('c')),
vec![Effect::Copy("zc://node-aaaa".into())]
);
assert_eq!(
key(&mut a, Key::Char('y')),
vec![Effect::Copy(sdk_line("zc://node-aaaa"))]
);
}
#[test]
fn empty_mesh_keys_are_noops() {
let mut a = App::new();
update(&mut a, Event::Mesh(MeshSnapshot::default()));
for k in [
Key::Enter,
Key::Down,
Key::Up,
Key::End,
Key::Char('c'),
Key::Char('y'),
] {
assert!(key(&mut a, k).is_empty());
}
assert_eq!(a.selected_row(), None);
}
#[test]
fn filtering_takes_typed_characters_and_esc_clears() {
let mut a = App::new();
update(&mut a, Event::Mesh(mesh()));
key(&mut a, Key::Char('/'));
key(&mut a, Key::Char('b'));
key(&mut a, Key::Char('r'));
assert_eq!(a.filter, "br");
assert_eq!(a.rows(), vec![RowRef::Node(1), RowRef::Worker(1, 0)]);
key(&mut a, Key::Esc);
assert_eq!(a.filter, "");
assert!(!a.filtering);
}
#[test]
fn s_cycles_sort_and_r_refreshes_both_sources() {
let mut a = App::new();
key(&mut a, Key::Char('s'));
assert_eq!(a.sort, Sort::Cpus);
assert_eq!(
key(&mut a, Key::Char('r')),
vec![Effect::RefreshMesh, Effect::RefreshAgent]
);
}
#[test]
fn a_new_mesh_snapshot_keeps_the_selection_in_range() {
let mut a = App::new();
update(&mut a, Event::Mesh(mesh()));
key(&mut a, Key::End);
update(&mut a, Event::Mesh(MeshSnapshot::default()));
assert_eq!(a.mesh_sel, 0);
}
#[test]
fn agent_failure_after_success_keeps_snapshot() {
let mut a = App::new();
update(
&mut a,
Event::Agent(AgentState::Running(Box::new(summary()))),
);
update(
&mut a,
Event::Agent(AgentState::NotRunning(Some("timed out".into()))),
);
assert!(matches!(a.agent, Some(AgentState::Running(_))));
assert_eq!(a.agent_failures, 1);
update(
&mut a,
Event::Agent(AgentState::Running(Box::new(summary()))),
);
assert_eq!(a.agent_failures, 0);
update(&mut a, Event::Agent(AgentState::NotRunning(None)));
assert!(
matches!(a.agent, Some(AgentState::NotRunning(None))),
"agent.json gone: really stopped"
);
}
#[test]
fn a_toast_expires_after_six_seconds_of_ticks() {
let mut a = App::new();
update(&mut a, Event::Note("copied".into()));
assert!(a.toast.is_some());
a.toast.as_mut().unwrap().1 -= std::time::Duration::from_secs(7);
update(&mut a, Event::Tick);
assert!(a.toast.is_none());
}
fn running() -> App {
let mut a = App::new();
update(
&mut a,
Event::Agent(AgentState::Running(Box::new(summary()))),
);
a
}
#[test]
fn space_toggles_sharing_once_until_the_agent_answers() {
let mut a = running();
a.tab = Tab::Share;
let on = a.summary().unwrap().this_mac.sharing;
assert_eq!(
key(&mut a, Key::Char(' ')),
vec![Effect::Apply(Write::Sharing(!on))]
);
assert_eq!(a.pending, Some(Write::Sharing(!on)));
assert!(
key(&mut a, Key::Char(' ')).is_empty(),
"one write at a time"
);
}
#[test]
fn plus_minus_change_workers_within_bounds() {
let mut a = running();
a.tab = Tab::Share;
let w = a.summary().unwrap().this_mac.workers;
assert_eq!(
key(&mut a, Key::Char('+')),
vec![Effect::Apply(Write::Workers(w.desired + 1))]
);
a.pending = None;
let mut s = summary();
s.this_mac.workers.desired = s.this_mac.workers.max;
update(&mut a, Event::Agent(AgentState::Running(Box::new(s))));
assert!(key(&mut a, Key::Char('+')).is_empty(), "at max");
let mut s = summary();
s.this_mac.workers.desired = 0;
update(&mut a, Event::Agent(AgentState::Running(Box::new(s))));
assert!(key(&mut a, Key::Char('-')).is_empty(), "at zero");
}
#[test]
fn the_price_editor_steps_within_bounds_and_applies() {
let mut a = running();
a.tab = Tab::Share;
key(&mut a, Key::Char('p'));
let ed = a.price_edit.clone().expect("editor open");
assert_eq!(ed.buf, "18");
key(&mut a, Key::Right);
assert_eq!(a.price_edit.as_ref().unwrap().buf, "19");
for _ in 0..500 {
key(&mut a, Key::Right);
}
assert_eq!(a.price_edit.as_ref().unwrap().buf, ed.max.to_string());
key(&mut a, Key::Backspace);
key(&mut a, Key::Backspace);
key(&mut a, Key::Backspace);
key(&mut a, Key::Char('2'));
key(&mut a, Key::Char('2'));
assert_eq!(
key(&mut a, Key::Enter),
vec![Effect::Apply(Write::Price(22.0))]
);
assert!(a.price_edit.is_none());
}
#[test]
fn an_out_of_bounds_price_is_not_applied() {
let mut a = running();
a.tab = Tab::Share;
key(&mut a, Key::Char('p'));
a.price_edit.as_mut().unwrap().buf = "9999".into();
assert!(key(&mut a, Key::Enter).is_empty());
assert!(a.price_edit.is_some(), "stays open to fix");
assert!(a.toast.as_ref().unwrap().0.contains("between"));
key(&mut a, Key::Esc);
assert!(a.price_edit.is_none());
}
#[test]
fn failed_write_reverts_and_toasts() {
let mut a = running();
a.tab = Tab::Share;
let before = a.summary().unwrap().clone();
key(&mut a, Key::Char(' '));
update(
&mut a,
Event::Done(
Write::Sharing(!before.this_mac.sharing),
Err("hub unreachable".into()),
),
);
assert_eq!(a.pending, None);
assert_eq!(a.summary().unwrap(), &before);
assert_eq!(a.toast.as_ref().unwrap().0, "hub unreachable");
assert!(exit_summary(&a).is_none());
}
#[test]
fn a_confirmed_write_replaces_the_summary_and_is_summarised_on_exit() {
let mut a = running();
let mut s = summary();
s.prices.this_mac.per_hour = Some(22.0);
update(
&mut a,
Event::Done(Write::Price(22.0), Ok(Box::new(s.clone()))),
);
let mut s2 = s.clone();
s2.prices.this_mac.per_hour = Some(25.0);
update(&mut a, Event::Done(Write::Price(25.0), Ok(Box::new(s2))));
assert_eq!(a.summary().unwrap().prices.this_mac.per_hour, Some(25.0));
assert_eq!(exit_summary(&a).as_deref(), Some("✓ price 18 → 25/h"));
}
#[test]
fn without_an_agent_a_offers_to_start_it() {
let mut a = App::new();
update(&mut a, Event::Agent(AgentState::NotRunning(None)));
a.tab = Tab::Share;
assert_eq!(key(&mut a, Key::Char('a')), vec![Effect::StartAgent]);
assert!(key(&mut a, Key::Char(' ')).is_empty(), "nothing to toggle");
let mut a = running();
a.tab = Tab::Share;
assert!(key(&mut a, Key::Char('a')).is_empty(), "already running");
}
#[test]
fn a_starts_the_agent_once_until_it_answers() {
let mut a = App::new();
update(&mut a, Event::Agent(AgentState::NotRunning(None)));
a.tab = Tab::Share;
assert_eq!(key(&mut a, Key::Char('a')), vec![Effect::StartAgent]);
assert!(key(&mut a, Key::Char('a')).is_empty());
update(&mut a, Event::AgentStarted(Err("did not answer".into())));
assert_eq!(
key(&mut a, Key::Char('a')),
vec![Effect::StartAgent],
"can retry after a failure"
);
}
#[test]
fn enter_on_a_device_opens_its_link() {
let mut a = running();
a.tab = Tab::Account;
let link = a.summary().unwrap().devices.clone().unwrap()[0]
.link
.clone()
.unwrap();
for _ in 0..ACCOUNT_FIXED_ROWS {
key(&mut a, Key::Down);
}
assert_eq!(key(&mut a, Key::Enter), vec![Effect::OpenUrl(link)]);
}
#[test]
fn the_bar_runs_native_and_external_commands() {
let mut a = running();
key(&mut a, Key::Char(':'));
for c in "workers 1".chars() {
key(&mut a, Key::Char(c));
}
assert_eq!(
key(&mut a, Key::Enter),
vec![Effect::Apply(Write::Workers(1))]
);
assert!(a.bar.is_none());
assert_eq!(a.history, vec!["workers 1".to_string()]);
a.pending = None;
key(&mut a, Key::Char(':'));
for c in "connect".chars() {
key(&mut a, Key::Char(c));
}
assert_eq!(
key(&mut a, Key::Enter),
vec![Effect::Suspend(vec!["connect".into()])]
);
}
#[test]
fn the_bar_reports_errors_and_stays_open() {
let mut a = running();
key(&mut a, Key::Char(':'));
for c in "rm x".chars() {
key(&mut a, Key::Char(c));
}
assert!(key(&mut a, Key::Enter).is_empty());
assert!(a.bar.is_some());
assert!(a.toast.as_ref().unwrap().0.contains("unknown command"));
}
#[test]
fn a_bar_price_outside_bounds_is_refused() {
let mut a = running();
key(&mut a, Key::Char(':'));
for c in "price 100000".chars() {
key(&mut a, Key::Char(c));
}
assert!(key(&mut a, Key::Enter).is_empty());
assert!(a.toast.as_ref().unwrap().0.contains("between"));
}
}