use super::command::{self, Command, CommandBar, Completions, TabName};
use super::market::{FeedId, FeedState, HubWrite};
use super::model::{visible_rows, MeshSnapshot, RowRef, Sort};
use crate::agent::summary::Summary;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::time::{Duration, Instant};
pub const TOAST_FOR: Duration = Duration::from_secs(6);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Tab {
Mesh,
Account,
Share,
Models,
Jobs,
Envs,
Spaces,
}
impl Tab {
pub const ALL: [Tab; 7] = [
Tab::Mesh,
Tab::Account,
Tab::Share,
Tab::Models,
Tab::Jobs,
Tab::Envs,
Tab::Spaces,
];
pub fn title(self) -> &'static str {
match self {
Tab::Mesh => "Mesh",
Tab::Account => "Account",
Tab::Share => "Share",
Tab::Models => "Models",
Tab::Jobs => "Jobs",
Tab::Envs => "Envs",
Tab::Spaces => "Spaces",
}
}
pub fn feed(self) -> Option<FeedId> {
match self {
Tab::Models => Some(FeedId::Models),
Tab::Jobs => Some(FeedId::Jobs),
Tab::Envs => Some(FeedId::Envs),
Tab::Spaces => Some(FeedId::Spaces),
_ => None,
}
}
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),
Feed(FeedId, Result<crate::market::fmt::Doc, String>),
HubDone(Result<String, String>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Effect {
RefreshMesh,
RefreshAgent,
RefreshMarket,
Hub(HubWrite),
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 feeds: HashMap<FeedId, (FeedState, Option<Instant>)>,
pub market_sel: HashMap<Tab, usize>,
pub market_filter: String,
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,
feeds: HashMap::new(),
market_sel: HashMap::new(),
market_filter: String::new(),
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,
}
}
pub fn feed(&self, id: FeedId) -> &FeedState {
static LOADING: FeedState = FeedState::Loading;
self.feeds.get(&id).map(|(s, _)| s).unwrap_or(&LOADING)
}
pub fn market_rows(&self, tab: Tab) -> Vec<Vec<String>> {
let Some(FeedState::Ready(doc)) = tab.feed().map(|f| self.feed(f)) else {
return Vec::new();
};
let rows = doc.table.as_ref().map(|t| t.rows.as_slice()).unwrap_or(&[]);
let words: Vec<String> = match tab {
Tab::Models => self
.market_filter
.split_whitespace()
.map(str::to_lowercase)
.collect(),
_ => Vec::new(),
};
rows.iter()
.filter(|r| {
let hay = r.join(" ").to_lowercase();
words.iter().all(|w| hay.contains(w))
})
.cloned()
.collect()
}
pub fn market_selected(&self, tab: Tab) -> usize {
self.market_sel.get(&tab).copied().unwrap_or(0)
}
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::Feed(id, result) => {
let state = match result {
Ok(doc) => FeedState::Ready(doc),
Err(e) => FeedState::Failed(e),
};
app.feeds.insert(id, (state, Some(Instant::now())));
for tab in Tab::ALL {
let len = app.market_rows(tab).len();
if let Some(sel) = app.market_sel.get_mut(&tab) {
*sel = (*sel).min(len.saturating_sub(1));
}
}
vec![]
}
Event::HubDone(result) => {
app.toast(match result {
Ok(line) => line,
Err(e) => e,
});
vec![Effect::RefreshMarket]
}
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 {
let models = app.tab == Tab::Models;
match k {
Key::Esc => {
match models {
true => app.market_filter.clear(),
false => app.filter.clear(),
}
app.filtering = false;
}
Key::Enter => app.filtering = false,
Key::Backspace => {
match models {
true => app.market_filter.pop(),
false => app.filter.pop(),
};
}
Key::Char(c) => match models {
true => app.market_filter.push(c),
false => app.filter.push(c),
},
ref m if is_move(m) => move_in_tab(app, m),
_ => {}
}
clamp_selection(app);
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::Char('4') => app.tab = Tab::Models,
Key::Char('5') => app.tab = Tab::Jobs,
Key::Char('6') => app.tab = Tab::Envs,
Key::Char('7') => app.tab = Tab::Spaces,
Key::Tab => app.tab = Tab::ALL[(app.tab.index() + 1) % Tab::ALL.len()],
Key::BackTab => app.tab = Tab::ALL[(app.tab.index() + Tab::ALL.len() - 1) % Tab::ALL.len()],
Key::Char('r') => return refresh_all(),
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),
Tab::Models | Tab::Jobs | Tab::Envs | Tab::Spaces => on_market_key(app, other),
}
}
}
app.detail = false;
vec![]
}
fn refresh_all() -> Vec<Effect> {
vec![
Effect::RefreshMesh,
Effect::RefreshAgent,
Effect::RefreshMarket,
]
}
fn move_in_tab(app: &mut App, k: &Key) {
match app.tab {
Tab::Mesh => {
let len = app.rows().len();
move_sel(&mut app.mesh_sel, len, k)
}
t if t.feed().is_some() => {
let len = app.market_rows(t).len();
move_sel(app.market_sel.entry(t).or_insert(0), len, k)
}
_ => {}
}
}
fn clamp_selection(app: &mut App) {
let len = app.rows().len();
app.mesh_sel = app.mesh_sel.min(len.saturating_sub(1));
let t = app.tab;
if t.feed().is_some() {
let len = app.market_rows(t).len();
let sel = app.market_sel.entry(t).or_insert(0);
*sel = (*sel).min(len.saturating_sub(1));
}
}
fn on_market_key(app: &mut App, k: Key) -> Vec<Effect> {
if is_move(&k) {
move_in_tab(app, &k);
return vec![];
}
if k == Key::Char('/') && app.tab == Tab::Models {
app.filtering = true;
}
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 => refresh_all(),
Command::Models(q) => {
app.tab = Tab::Models;
app.market_filter = q;
app.market_sel.insert(Tab::Models, 0);
vec![]
}
Command::EnvStop(id) => {
app.toast(format!("stopping environment {id}…"));
vec![Effect::Hub(HubWrite::StopEnv(id))]
}
Command::SpaceAct(verb, id) => {
app.toast(format!("{verb} {id}…"));
vec![Effect::Hub(HubWrite::Space(verb, id))]
}
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,
TabName::Models => Tab::Models,
TabName::Jobs => Tab::Jobs,
TabName::Envs => Tab::Envs,
TabName::Spaces => Tab::Spaces,
};
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::Models);
key(&mut a, Key::BackTab);
assert_eq!(a.tab, Tab::Share);
}
#[test]
fn the_marketplace_tabs_have_their_numbers_and_the_cycle_wraps() {
let mut a = App::new();
for (c, t) in [
('4', Tab::Models),
('5', Tab::Jobs),
('6', Tab::Envs),
('7', Tab::Spaces),
] {
key(&mut a, Key::Char(c));
assert_eq!(a.tab, t);
}
key(&mut a, Key::Tab);
assert_eq!(a.tab, Tab::Mesh);
key(&mut a, Key::BackTab);
assert_eq!(a.tab, Tab::Spaces);
}
pub(crate) fn models_doc() -> crate::market::fmt::Doc {
let mut t = crate::market::fmt::Table::new(&["ID", "MODEL", "TASK"]);
for (id, name, task) in [
("m1", "o/vit-base", "image-classification"),
("m2", "o/whisper-small", "speech"),
("m3", "o/qwen", "text-generation"),
] {
t.rows.push(vec![id.into(), name.into(), task.into()]);
}
crate::market::fmt::Doc::table(t)
}
fn with_models() -> App {
let mut a = App::new();
update(&mut a, Event::Feed(FeedId::Models, Ok(models_doc())));
a.tab = Tab::Models;
a
}
#[test]
fn a_feed_lands_as_a_table_or_as_its_error() {
let mut a = App::new();
assert_eq!(a.feed(FeedId::Jobs), &FeedState::Loading);
update(
&mut a,
Event::Feed(FeedId::Jobs, Err("needs a newer hub".into())),
);
assert_eq!(
a.feed(FeedId::Jobs),
&FeedState::Failed("needs a newer hub".into())
);
update(&mut a, Event::Feed(FeedId::Models, Ok(models_doc())));
assert_eq!(a.market_rows(Tab::Models).len(), 3);
assert!(a.market_rows(Tab::Jobs).is_empty());
}
#[test]
fn the_selection_moves_inside_a_marketplace_tab_and_stays_in_range() {
let mut a = with_models();
key(&mut a, Key::Down);
key(&mut a, Key::Char('j'));
key(&mut a, Key::Down);
assert_eq!(a.market_selected(Tab::Models), 2);
key(&mut a, Key::Home);
assert_eq!(a.market_selected(Tab::Models), 0);
key(&mut a, Key::End);
let mut t = crate::market::fmt::Table::new(&["ID", "MODEL", "TASK"]);
t.rows.push(vec!["m1".into(), "o/vit".into(), "x".into()]);
update(
&mut a,
Event::Feed(FeedId::Models, Ok(crate::market::fmt::Doc::table(t))),
);
assert_eq!(a.market_selected(Tab::Models), 0);
}
#[test]
fn slash_searches_the_models_and_escape_clears_it() {
let mut a = with_models();
key(&mut a, Key::Char('/'));
assert!(a.filtering);
for c in "Whis".chars() {
key(&mut a, Key::Char(c));
}
assert_eq!(a.market_filter, "Whis");
assert_eq!(
a.market_rows(Tab::Models),
vec![vec!["m2", "o/whisper-small", "speech"]]
);
assert!(a.filter.is_empty(), "the mesh filter is a different one");
key(&mut a, Key::Enter);
assert!(!a.filtering);
assert_eq!(a.market_rows(Tab::Models).len(), 1);
key(&mut a, Key::Char('/'));
key(&mut a, Key::Esc);
assert!(a.market_filter.is_empty());
assert_eq!(a.market_rows(Tab::Models).len(), 3);
}
#[test]
fn slash_does_nothing_on_the_other_marketplace_tabs() {
let mut a = with_models();
a.tab = Tab::Jobs;
key(&mut a, Key::Char('/'));
assert!(!a.filtering);
}
#[test]
fn marketplace_commands_open_tabs_and_write_to_the_hub() {
let mut a = with_models();
a.tab = Tab::Mesh;
run_command(&mut a, Command::Models("whisper".into()));
assert_eq!((a.tab, a.market_filter.as_str()), (Tab::Models, "whisper"));
assert_eq!(
run_command(&mut a, Command::EnvStop("e1".into())),
vec![Effect::Hub(HubWrite::StopEnv("e1".into()))]
);
assert_eq!(
run_command(&mut a, Command::SpaceAct("pause", "s1".into())),
vec![Effect::Hub(HubWrite::Space("pause", "s1".into()))]
);
run_command(&mut a, Command::Tab(TabName::Spaces));
assert_eq!(a.tab, Tab::Spaces);
}
#[test]
fn a_finished_hub_write_is_said_and_refreshes_the_feeds() {
let mut a = App::new();
let fx = update(
&mut a,
Event::HubDone(Ok("space s1: pause done, now paused".into())),
);
assert_eq!(fx, vec![Effect::RefreshMarket]);
assert!(a.toast.as_ref().unwrap().0.contains("now paused"));
update(
&mut a,
Event::HubDone(Err("needs a newer hub: /api/spaces/s/pause".into())),
);
assert!(a.toast.as_ref().unwrap().0.contains("needs a newer hub"));
}
#[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,
Effect::RefreshMarket
]
);
}
#[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"));
}
}