use std::collections::BTreeMap;
use chrono::{DateTime, Local, Utc};
use iced::widget::{Column, column, container, row, text};
use iced::{Alignment, Element, Length, Task};
use iced_fonts::lucide;
use crate::automations::{Automation, StoredTrigger};
use super::ToastMessage;
use super::common::PolledList;
use super::menus::{ContextMenu, MenuItem};
use super::{theme, widgets};
const ALREADY_GONE: &str = "Automation was already gone";
#[derive(Debug, Clone)]
pub(crate) enum AutomationsMessage {
Tick,
Refreshed(Result<Vec<Automation>, String>),
Delete { id: String, session_id: String },
Toast(ToastMessage),
}
pub(crate) struct AutomationsState {
list: PolledList<Automation>,
}
impl AutomationsState {
pub(crate) const fn new() -> Self {
Self {
list: PolledList::new(),
}
}
pub(crate) fn refresh(&mut self) -> Task<AutomationsMessage> {
if !self.list.begin() {
return Task::none();
}
Task::perform(load(), AutomationsMessage::Refreshed)
}
pub(crate) fn update(&mut self, message: AutomationsMessage) -> Task<AutomationsMessage> {
match message {
AutomationsMessage::Tick => self.refresh(),
AutomationsMessage::Refreshed(result) => {
self.list.settle(result);
Task::none()
}
AutomationsMessage::Delete { id, session_id } => Task::perform(
async move {
crate::automations::remove_automation(&session_id, &id)
.await
.map_err(|e| e.to_string())
},
delete_outcome,
),
AutomationsMessage::Toast(_) => Task::none(),
}
}
pub(crate) fn view(&self) -> Element<'_, AutomationsMessage> {
let mut content = column![];
content = widgets::push_error_banner_inset(content, self.list.error());
if !self.list.loaded() {
content = content.push(widgets::scroll_h_inset(widgets::loading_text()));
} else if self.list.entries().is_empty() {
if self.list.error().is_none() {
content = content.push(widgets::empty_state_placeholder(
lucide::workflow::<iced::Theme, iced::Renderer>(),
"No active automations",
theme::TEXT_MUTED,
));
}
} else {
let now = Local::now();
let mut sections = Column::new().spacing(theme::SPACE_16);
for (owner, automations) in group_by_owner(self.list.entries()) {
let mut cards = Column::new().spacing(theme::SPACE_8);
for automation in automations {
cards = cards.push(render_automation(automation, now));
}
let section = Column::new()
.spacing(theme::SPACE_6)
.push(widgets::section_heading(owner))
.push(cards);
sections = sections.push(section);
}
content = content.push(widgets::vscroll(sections));
}
widgets::page(content)
}
}
async fn load() -> Result<Vec<Automation>, String> {
crate::automations::list_all_active_automations()
.await
.map_err(|e| e.to_string())
}
fn group_by_owner(automations: &[Automation]) -> Vec<(&str, Vec<&Automation>)> {
let mut groups: BTreeMap<&str, Vec<&Automation>> = BTreeMap::new();
for automation in automations {
groups
.entry(automation.user_name.as_str())
.or_default()
.push(automation);
}
groups.into_iter().collect()
}
fn render_args(trigger: &StoredTrigger) -> Option<String> {
let StoredTrigger::Tool(trigger) = trigger else {
return None;
};
(!trigger.args.is_empty()).then(|| {
trigger
.args
.iter()
.map(|(key, value)| match value {
serde_json::Value::String(raw) => format!("{key}: {raw}"),
value => format!("{key}: {value}"),
})
.collect::<Vec<_>>()
.join(", ")
})
}
fn render_automation(
automation: &Automation,
now: DateTime<Local>,
) -> Element<'_, AutomationsMessage> {
let mut headline = row![];
let mut demoted_text = None;
match &automation.trigger {
None => {
headline = headline.push(
text(&automation.text)
.size(theme::TEXT_14)
.color(theme::TEXT_PRIMARY)
.width(Length::Fill),
);
}
Some(trigger) => {
let mut check = row![
text(trigger.name())
.size(theme::TEXT_14)
.color(theme::TEXT_PRIMARY)
]
.spacing(theme::SPACE_6)
.align_y(Alignment::Center);
if let Some(args) = render_args(trigger) {
check = check.push(
text(args)
.size(theme::TEXT_11)
.font(super::JETBRAINS_MONO)
.color(theme::TEXT_SECONDARY)
.wrapping(iced::widget::text::Wrapping::WordOrGlyph),
);
}
headline = headline.push(check.width(Length::Fill));
if !automation.text.trim().is_empty() {
demoted_text = Some(
text(&automation.text)
.size(theme::TEXT_13)
.color(theme::TEXT_SECONDARY)
.width(Length::Fill),
);
}
}
}
let mut entry = Column::new().spacing(theme::SPACE_2).push(
headline
.push(
text(format_next_fire(&automation.next_fire_at, now))
.size(theme::TEXT_12)
.font(super::JETBRAINS_MONO)
.color(theme::TEXT_PRIMARY),
)
.spacing(theme::SPACE_12)
.align_y(Alignment::Start),
);
if let Some(demoted_text) = demoted_text {
entry = entry.push(demoted_text);
}
if let Some(target) = automation.role_target() {
entry = entry.push(
text(target)
.size(theme::TEXT_11)
.font(super::JETBRAINS_MONO)
.color(theme::TEXT_MUTED),
);
}
ContextMenu::new(
container(entry)
.padding(theme::PAD_6)
.width(Length::Fill)
.style(theme::surface_card_style),
vec![MenuItem::with_icon(
lucide::advanced_text::trash,
"Delete".into(),
AutomationsMessage::Delete {
id: automation.id.clone(),
session_id: automation.session_id.clone(),
},
)],
)
.key(&automation.id)
.into()
}
fn delete_outcome(result: Result<Option<Automation>, String>) -> AutomationsMessage {
match result {
Ok(Some(_)) => AutomationsMessage::Toast(ToastMessage::Deleted),
Ok(None) => AutomationsMessage::Toast(ToastMessage::Warning(ALREADY_GONE.to_string())),
Err(e) => AutomationsMessage::Toast(ToastMessage::Error(e)),
}
}
fn format_next_fire(next_fire_at: &str, now: DateTime<Local>) -> String {
let Ok(fire) = crate::db::parse_utc_timestamp(next_fire_at) else {
return next_fire_at.to_string();
};
let now_utc = now.with_timezone(&Utc);
if fire <= now_utc {
return "now".to_string();
}
let local = fire.with_timezone(&Local);
if local.date_naive() != now.date_naive() {
return format!("at {}", local.format("%H:%M %d.%m"));
}
let seconds = (fire - now_utc).num_seconds();
format!(
"{}h {}m {}s",
seconds / 3600,
(seconds % 3600) / 60,
seconds % 60
)
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{Duration, TimeZone as _};
fn local_now() -> DateTime<Local> {
Local
.with_ymd_and_hms(2026, 9, 17, 12, 0, 0)
.single()
.expect("a valid local time")
}
fn stored(at: DateTime<Local>) -> String {
at.with_timezone(&Utc).to_rfc3339()
}
#[test]
fn format_next_fire_covers_due_countdown_other_day_and_junk() {
let now = local_now();
let at = |offset: Duration| stored(now + offset);
let hms = Duration::seconds(2 * 3600 + 5 * 60 + 3);
let cases: &[(&str, Duration, &str)] = &[
("overdue", Duration::minutes(-1), "now"),
("exactly due", Duration::zero(), "now"),
("seconds later", Duration::seconds(30), "0h 0m 30s"),
("hours minutes seconds", hms, "2h 5m 3s"),
("another day", Duration::days(1), "at 12:00 18.09"),
];
for &(name, offset, expected) in cases {
assert_eq!(format_next_fire(&at(offset), now), expected, "case {name}");
}
assert_eq!(format_next_fire("not a timestamp", now), "not a timestamp");
}
fn automation(owner: &str, text: &str) -> Automation {
Automation {
id: String::new(),
session_id: String::new(),
user_name: owner.to_string(),
kind: "one-shot".to_string(),
text: text.to_string(),
trigger: None,
role: None,
identifier: None,
workspace: None,
interval_seconds: None,
next_fire_at: String::new(),
unfinished_attempts: 0,
}
}
fn trigger(args: serde_json::Value) -> StoredTrigger {
let serde_json::Value::Object(args) = args else {
unreachable!("test arguments are an object")
};
StoredTrigger::Tool(crate::automations::Trigger {
tool: "wait".to_string(),
args,
})
}
#[test]
fn render_args_cases() {
let cases: &[(&str, StoredTrigger, Option<&str>)] = &[
("unreadable trigger", StoredTrigger::Unreadable, None),
("no arguments", trigger(serde_json::json!({})), None),
(
"every value kind",
trigger(serde_json::json!({
"action": "night",
"dry_run": true,
"probe_seconds": 120,
"window": {"from": "09:00"},
})),
Some(
"action: night, dry_run: true, probe_seconds: 120, window: {\"from\":\"09:00\"}",
),
),
];
for (name, stored, expected) in cases {
assert_eq!(
render_args(stored),
expected.map(str::to_string),
"case {name}: rendered arguments"
);
}
}
#[test]
fn group_by_owner_orders_by_owner_and_keeps_members() {
let automations = [
automation("bob", "two"),
automation("alice", "one"),
automation("alice", "three"),
];
let groups = group_by_owner(&automations);
let owners: Vec<&str> = groups.iter().map(|(owner, _)| *owner).collect();
assert_eq!(owners, ["alice", "bob"]);
let texts: Vec<Vec<&str>> = groups
.iter()
.map(|(_, group)| group.iter().map(|a| a.text.as_str()).collect())
.collect();
assert_eq!(texts, [vec!["one", "three"], vec!["two"]]);
}
}