| 1 | //! Live scheduled-work projection for the activity band |
| 2 | //! (AUTOMATION-VISIBILITY-SPEC §2.1). |
| 3 | //! |
| 4 | //! One owner per fact: this projection is the single reader of "how much |
| 5 | //! scheduled work is live" — Active automations (`N`), runs currently |
| 6 | //! Queued|Running (`M`), and failed runs not yet acknowledged. The top |
| 7 | //! strip reads it; `background_indicator.rs` keeps owning |
| 8 | //! shells/tasks/agents and never learns about automations. |
| 9 | //! |
| 10 | //! The disk scan lives in `tui/ui/task_projection.rs` |
| 11 | //! (`refresh_automation_panel`): taken on a blocking thread, folded on the |
| 12 | //! same ~2.5 s cadence as the task panel. Everything here is a pure, |
| 13 | //! testable fold over that scan. |
| 14 | //! |
| 15 | //! The fold also detects the one transition Slice 1 can observe without an |
| 16 | //! engine change: a run this session watched go live and then settle. |
| 17 | //! Each such run is reported once (`ScanDelta::settled`) so the projection's |
| 18 | //! owner can post the typed `completed in background` / `failed` receipt |
| 19 | //! (spec §2.2) — the transcript learns about background work from the same |
| 20 | //! scan that lights the band, never from a second reader. |
| 21 | |
| 22 | use std::collections::{BTreeMap, BTreeSet}; |
| 23 | |
| 24 | use chrono::{DateTime, Utc}; |
| 25 | |
| 26 | use codewhale_engine::automation_manager::{ |
| 27 | AutomationRecord, AutomationRunRecord, AutomationRunStatus, AutomationStatus, |
| 28 | }; |
| 29 | use codewhale_localization::{Locale, MessageId, tr}; |
| 30 | use codewhale_palette::ChromeInk; |
| 31 | |
| 32 | /// Band glyph for the automation slot. Composed in code (locales/AGENTS.md); |
| 33 | /// the ASCII-safe projection comes from `glyphs::ascii_fallback`. |
| 34 | const SLOT_GLYPH: &str = "⏱"; |
| 35 | |
| 36 | /// One scan of the durable automation store — every definition plus the |
| 37 | /// newest runs of each — taken off the runtime thread and handed to |
| 38 | /// [`AutomationPanelState::fold_scan`] on the task-panel tick. |
| 39 | #[derive(Debug, Default)] |
| 40 | pub struct AutomationScan { |
| 41 | pub records: Vec<AutomationRecord>, |
| 42 | pub runs: Vec<AutomationRunRecord>, |
| 43 | pub execution_scope: Option<String>, |
| 44 | } |
| 45 | |
| 46 | /// Snapshot of live scheduled work, refreshed on the task-panel cadence. |
| 47 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 48 | pub struct AutomationPanelState { |
| 49 | /// Automations whose status is `Active`. |
| 50 | pub active_automations: usize, |
| 51 | /// Runs currently `Queued` or `Running` within the scan window. |
| 52 | pub live_runs: usize, |
| 53 | /// Ids of the runs behind `live_runs`, so the next fold can tell which |
| 54 | /// of them settled (a settle is reported once, then forgotten). |
| 55 | live_run_ids: BTreeSet<String>, |
| 56 | /// Which automation owns each live run (`run_id -> automation_id`), so |
| 57 | /// the next scan can re-fetch runs this session watched go live even |
| 58 | /// after newer runs push them past the newest-run window. |
| 59 | live_run_owners: BTreeMap<String, String>, |
| 60 | /// Failed runs (`{automation_id}/{run_id}`) observed this session and not |
| 61 | /// yet acknowledged by an automation-surface interaction. A failure, once |
| 62 | /// seen, stays unacknowledged even after it ages out of the scan window — |
| 63 | /// that is the point of the acknowledgement contract. |
| 64 | unacknowledged_failures: BTreeSet<String>, |
| 65 | /// Failures the operator already acknowledged. The ~2.5s fold re-sees |
| 66 | /// every persisted Failed run, so without this watermark it would |
| 67 | /// re-light an acknowledged failure forever. An acknowledgement lasts |
| 68 | /// until the run leaves the records (automation deleted). |
| 69 | acknowledged_failures: BTreeSet<String>, |
| 70 | } |
| 71 | |
| 72 | /// How a run the session watched go live ended up. |
| 73 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 74 | pub enum SettledOutcome { |
| 75 | Completed, |
| 76 | Failed, |
| 77 | /// The run was canceled — by the operator, a cancel timeout or shutdown |
| 78 | /// (#6162). It gets a receipt so a stopped run is never silent, but it |
| 79 | /// never lights the failure demand: nothing crashed. |
| 80 | Canceled, |
| 81 | } |
| 82 | |
| 83 | /// A run this session saw live that has now settled — surfaced exactly once |
| 84 | /// so the owner can post its receipt (spec §2.2). Carries the raw definition |
| 85 | /// name and error; the receipt producer display-sanitizes them. |
| 86 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 87 | pub struct SettledRun { |
| 88 | pub automation_id: String, |
| 89 | pub automation_name: String, |
| 90 | pub run_id: String, |
| 91 | pub outcome: SettledOutcome, |
| 92 | /// Wall-clock `started_at → ended_at` when both are recorded. |
| 93 | pub duration_ms: Option<u64>, |
| 94 | pub error: Option<String>, |
| 95 | } |
| 96 | |
| 97 | /// What one fold changed: whether the band needs a repaint, and which runs |
| 98 | /// settled since the previous fold. |
| 99 | #[derive(Debug, Default, PartialEq, Eq)] |
| 100 | pub struct ScanDelta { |
| 101 | /// Anything the band paints changed (#3757: an unchanged scan must not |
| 102 | /// force a redraw). |
| 103 | pub changed: bool, |
| 104 | pub settled: Vec<SettledRun>, |
| 105 | } |
| 106 | |
| 107 | impl AutomationPanelState { |
| 108 | /// Fold one scan into the projection. |
| 109 | /// |
| 110 | /// A run failure counts only when it finished at or after session start: |
| 111 | /// the scheduler is host-durable, and without that gate every TUI launch |
| 112 | /// would re-light the band for history the operator already saw. Settled |
| 113 | /// runs are likewise gated on having been seen live by a previous fold, |
| 114 | /// so the first scan of a session never replays old receipts. |
| 115 | #[cfg(test)] |
| 116 | pub(crate) fn fold_scan( |
| 117 | &mut self, |
| 118 | records: &[AutomationRecord], |
| 119 | runs: &[AutomationRunRecord], |
| 120 | session_started_at: DateTime<Utc>, |
| 121 | ) -> ScanDelta { |
| 122 | self.fold_scan_in_scope(records, runs, session_started_at, None) |
| 123 | } |
| 124 | |
| 125 | pub(crate) fn fold_scan_in_scope( |
| 126 | &mut self, |
| 127 | records: &[AutomationRecord], |
| 128 | runs: &[AutomationRunRecord], |
| 129 | session_started_at: DateTime<Utc>, |
| 130 | execution_scope: Option<&str>, |
| 131 | ) -> ScanDelta { |
| 132 | let previous = std::mem::take(self); |
| 133 | self.active_automations = records |
| 134 | .iter() |
| 135 | .filter(|record| { |
| 136 | matches!(record.status, AutomationStatus::Active) |
| 137 | && execution_scope |
| 138 | .is_none_or(|scope| record.execution_scope.as_deref() == Some(scope)) |
| 139 | }) |
| 140 | .count(); |
| 141 | self.live_run_ids = runs |
| 142 | .iter() |
| 143 | .filter(|run| { |
| 144 | matches!( |
| 145 | run.status, |
| 146 | AutomationRunStatus::Queued | AutomationRunStatus::Running |
| 147 | ) |
| 148 | }) |
| 149 | .map(|run| run.id.clone()) |
| 150 | .collect(); |
| 151 | self.live_run_owners = runs |
| 152 | .iter() |
| 153 | .filter(|run| self.live_run_ids.contains(&run.id)) |
| 154 | .map(|run| (run.id.clone(), run.automation_id.clone())) |
| 155 | .collect(); |
| 156 | self.live_runs = self.live_run_ids.len(); |
| 157 | let names: BTreeMap<&str, &str> = records |
| 158 | .iter() |
| 159 | .map(|record| (record.id.as_str(), record.name.as_str())) |
| 160 | .collect(); |
| 161 | let settled = |
| 162 | runs.iter() |
| 163 | .filter(|run| previous.live_run_ids.contains(&run.id)) |
| 164 | .filter_map(|run| { |
| 165 | let outcome = match run.status { |
| 166 | AutomationRunStatus::Completed => SettledOutcome::Completed, |
| 167 | AutomationRunStatus::Failed => SettledOutcome::Failed, |
| 168 | AutomationRunStatus::Canceled => SettledOutcome::Canceled, |
| 169 | AutomationRunStatus::Queued | AutomationRunStatus::Running => return None, |
| 170 | }; |
| 171 | Some(SettledRun { |
| 172 | automation_id: run.automation_id.clone(), |
| 173 | automation_name: names |
| 174 | .get(run.automation_id.as_str()) |
| 175 | .map_or_else(|| run.automation_id.clone(), |name| (*name).to_string()), |
| 176 | run_id: run.id.clone(), |
| 177 | outcome, |
| 178 | duration_ms: run.started_at.zip(run.ended_at).map(|(started, ended)| { |
| 179 | (ended - started).num_milliseconds().max(0) as u64 |
| 180 | }), |
| 181 | error: run.error.clone(), |
| 182 | }) |
| 183 | }) |
| 184 | .collect(); |
| 185 | // Runs of deleted automations drop out; the surviving ids keep their |
| 186 | // acknowledgement demand. The acknowledged watermark sheds deleted |
| 187 | // automations the same way so it cannot grow unbounded across a |
| 188 | // long session. |
| 189 | let automation_ids: BTreeSet<&str> = |
| 190 | records.iter().map(|record| record.id.as_str()).collect(); |
| 191 | let mut unacknowledged: BTreeSet<String> = previous |
| 192 | .unacknowledged_failures |
| 193 | .iter() |
| 194 | .filter(|key| { |
| 195 | key.split_once('/') |
| 196 | .is_some_and(|(automation_id, _)| automation_ids.contains(automation_id)) |
| 197 | }) |
| 198 | .cloned() |
| 199 | .collect(); |
| 200 | let acknowledged: BTreeSet<String> = previous |
| 201 | .acknowledged_failures |
| 202 | .iter() |
| 203 | .filter(|key| { |
| 204 | key.split_once('/') |
| 205 | .is_some_and(|(automation_id, _)| automation_ids.contains(automation_id)) |
| 206 | }) |
| 207 | .cloned() |
| 208 | .collect(); |
| 209 | self.acknowledged_failures = acknowledged; |
| 210 | for run in runs { |
| 211 | let finished_at = run.ended_at.unwrap_or(run.created_at); |
| 212 | if matches!(run.status, AutomationRunStatus::Failed) |
| 213 | && finished_at >= session_started_at |
| 214 | { |
| 215 | let key = format!("{}/{}", run.automation_id, run.id); |
| 216 | if !self.acknowledged_failures.contains(&key) { |
| 217 | unacknowledged.insert(key); |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | self.unacknowledged_failures = unacknowledged; |
| 222 | let changed = self.active_automations != previous.active_automations |
| 223 | || self.live_runs != previous.live_runs |
| 224 | || self.unacknowledged_failures != previous.unacknowledged_failures; |
| 225 | ScanDelta { changed, settled } |
| 226 | } |
| 227 | |
| 228 | /// The operator engaged with the automation surface (`/automation …`; |
| 229 | /// the Slice-2 panel hooks the same call): every failure observed so far |
| 230 | /// is acknowledged and the band ink settles. The acknowledgement rides |
| 231 | /// the watermark — the next fold re-sees the same persisted Failed runs |
| 232 | /// and must not re-light them. |
| 233 | pub fn acknowledge_failures(&mut self) { |
| 234 | self.acknowledged_failures |
| 235 | .extend(self.unacknowledged_failures.iter().cloned()); |
| 236 | self.unacknowledged_failures.clear(); |
| 237 | } |
| 238 | |
| 239 | #[must_use] |
| 240 | pub fn has_unacknowledged_failure(&self) -> bool { |
| 241 | !self.unacknowledged_failures.is_empty() |
| 242 | } |
| 243 | |
| 244 | /// Live runs this session is watching (`run_id -> automation_id`), so |
| 245 | /// the next scan can re-fetch them even after newer runs push them |
| 246 | /// past the newest-run window. |
| 247 | pub(crate) fn live_run_owners(&self) -> BTreeMap<String, String> { |
| 248 | self.live_run_owners.clone() |
| 249 | } |
| 250 | |
| 251 | /// Activity-band slot text: `⏱ N scheduled` while any automation is |
| 252 | /// Active, plus `· M running` while runs are Queued|Running. Pausing an |
| 253 | /// automation does not cancel its already-enqueued runs, so the slot |
| 254 | /// stays up while either count is nonzero and vanishes only at zero — |
| 255 | /// it never becomes permanent furniture (spec §7.2). |
| 256 | #[must_use] |
| 257 | pub fn activity_slot(&self, locale: Locale) -> Option<String> { |
| 258 | if self.active_automations == 0 && self.live_runs == 0 { |
| 259 | return None; |
| 260 | } |
| 261 | if self.active_automations == 0 { |
| 262 | // Runs outlive their paused automation: show the live work, |
| 263 | // not the (zero) scheduled count. |
| 264 | return Some(format!( |
| 265 | "{SLOT_GLYPH} {} {}", |
| 266 | self.live_runs, |
| 267 | tr(locale, MessageId::AutomationRunStatusRunning) |
| 268 | )); |
| 269 | } |
| 270 | let mut slot = format!( |
| 271 | "{SLOT_GLYPH} {} {}", |
| 272 | self.active_automations, |
| 273 | tr(locale, MessageId::AutomationBandScheduled) |
| 274 | ); |
| 275 | if self.live_runs > 0 { |
| 276 | slot.push_str(&format!( |
| 277 | " · {} {}", |
| 278 | self.live_runs, |
| 279 | tr(locale, MessageId::AutomationRunStatusRunning) |
| 280 | )); |
| 281 | } |
| 282 | Some(slot) |
| 283 | } |
| 284 | |
| 285 | /// Compact-tier form of the same fact: `⏱ 2·1` (scheduled·running). |
| 286 | /// Chrome sheds before content on narrow terminals, so the live-work |
| 287 | /// count abbreviates instead of vanishing; still zero-suppressed on |
| 288 | /// both counts. |
| 289 | #[must_use] |
| 290 | pub fn activity_slot_compact(&self) -> Option<String> { |
| 291 | if self.active_automations == 0 && self.live_runs == 0 { |
| 292 | return None; |
| 293 | } |
| 294 | Some(if self.live_runs > 0 { |
| 295 | if self.active_automations == 0 { |
| 296 | format!("{SLOT_GLYPH} ·{}", self.live_runs) |
| 297 | } else { |
| 298 | format!( |
| 299 | "{SLOT_GLYPH} {}·{}", |
| 300 | self.active_automations, self.live_runs |
| 301 | ) |
| 302 | } |
| 303 | } else { |
| 304 | format!("{SLOT_GLYPH} {}", self.active_automations) |
| 305 | }) |
| 306 | } |
| 307 | |
| 308 | /// Slot ink, the grammar table's existing Goal-chip rule: `Info` idle, |
| 309 | /// `Active` while a run is live, `Attention` when a run failed since last |
| 310 | /// acknowledgement. Never `Failure` — a failed report job is not a |
| 311 | /// product failure. |
| 312 | #[must_use] |
| 313 | pub fn activity_ink(&self) -> ChromeInk { |
| 314 | if self.has_unacknowledged_failure() { |
| 315 | ChromeInk::Attention |
| 316 | } else if self.live_runs > 0 { |
| 317 | ChromeInk::Active |
| 318 | } else { |
| 319 | ChromeInk::Info |
| 320 | } |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | #[must_use] |
| 325 | pub(crate) fn format_schedule_badge(rrule: &str, locale: Locale) -> String { |
| 326 | let trimmed = rrule.trim(); |
| 327 | if trimmed.is_empty() { |
| 328 | return "-".to_string(); |
| 329 | } |
| 330 | let mut freq: Option<&str> = None; |
| 331 | let mut interval: Option<u32> = None; |
| 332 | let mut byday: Option<&str> = None; |
| 333 | let mut byhour: Option<u32> = None; |
| 334 | let mut byminute: Option<u32> = None; |
| 335 | let mut expr: Option<&str> = None; |
| 336 | for part in trimmed.split(';') { |
| 337 | if let Some((key, value)) = part.split_once('=') { |
| 338 | match key.trim().to_ascii_uppercase().as_str() { |
| 339 | "FREQ" => freq = Some(value.trim()), |
| 340 | "INTERVAL" => interval = value.trim().parse().ok(), |
| 341 | "BYDAY" => byday = Some(value.trim()), |
| 342 | "BYHOUR" => byhour = value.trim().parse().ok(), |
| 343 | "BYMINUTE" => byminute = value.trim().parse().ok(), |
| 344 | "EXPR" => expr = Some(value.trim()), |
| 345 | _ => {} |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | let time = byhour.map(|h| format!("{h:02}:{:02}", byminute.unwrap_or(0))); |
| 350 | let label = |id| tr(locale, id).to_lowercase(); |
| 351 | let repeat = |id, n: u32| tr(locale, id).replace("{count}", &n.to_string()); |
| 352 | let with_time = |label: String, time: Option<String>| match time { |
| 353 | Some(time) => format!("{label} {time}"), |
| 354 | None => label, |
| 355 | }; |
| 356 | match freq.map(str::to_ascii_uppercase).as_deref() { |
| 357 | Some("CRON") => match expr { |
| 358 | Some(e) if !e.is_empty() => format!("cron {e}"), |
| 359 | _ => trimmed.to_string(), |
| 360 | }, |
| 361 | Some("MINUTELY") => repeat( |
| 362 | MessageId::AutomationScheduleMinutes, |
| 363 | interval.unwrap_or(1).max(1), |
| 364 | ), |
| 365 | Some("HOURLY") => match interval { |
| 366 | Some(n) if n > 1 => repeat(MessageId::AutomationScheduleHours, n), |
| 367 | _ => label(MessageId::AutomationEditorHourly), |
| 368 | }, |
| 369 | Some("DAILY") => with_time( |
| 370 | match interval { |
| 371 | Some(n) if n > 1 => repeat(MessageId::AutomationScheduleDays, n), |
| 372 | _ => label(MessageId::AutomationEditorDaily), |
| 373 | }, |
| 374 | time, |
| 375 | ), |
| 376 | Some("WEEKLY") => { |
| 377 | let mut label = match interval { |
| 378 | Some(n) if n > 1 => repeat(MessageId::AutomationScheduleWeeks, n), |
| 379 | _ => label(MessageId::AutomationEditorWeekly), |
| 380 | }; |
| 381 | if let Some(days) = byday.filter(|d| !d.is_empty()) { |
| 382 | label.push(' '); |
| 383 | label.push_str(days); |
| 384 | } |
| 385 | with_time(label, time) |
| 386 | } |
| 387 | Some("MONTHLY") => with_time(label(MessageId::AutomationScheduleMonthly), time), |
| 388 | _ => trimmed.to_string(), |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | #[cfg(test)] |
| 393 | mod tests { |
| 394 | use super::*; |
| 395 | |
| 396 | #[test] |
| 397 | fn schedule_badges_translate_labels_and_preserve_rule_values() { |
| 398 | let rrule = "FREQ=WEEKLY;INTERVAL=2;BYDAY=MO,WE;BYHOUR=9;BYMINUTE=5"; |
| 399 | assert_eq!( |
| 400 | format_schedule_badge(rrule, Locale::En), |
| 401 | "every 2w MO,WE 09:05" |
| 402 | ); |
| 403 | assert_eq!( |
| 404 | format_schedule_badge(rrule, Locale::Ja), |
| 405 | "2週間ごと MO,WE 09:05" |
| 406 | ); |
| 407 | } |
| 408 | |
| 409 | fn record(id: &str, status: AutomationStatus) -> AutomationRecord { |
| 410 | let now = Utc::now(); |
| 411 | AutomationRecord { |
| 412 | destination_thread_id: None, |
| 413 | schema_version: 1, |
| 414 | execution_scope: Some(codewhale_engine::task_manager::test_execution_scope("test")), |
| 415 | id: id.to_string(), |
| 416 | name: id.to_string(), |
| 417 | prompt: "prompt".to_string(), |
| 418 | rrule: "FREQ=DAILY".to_string(), |
| 419 | cwds: Vec::new(), |
| 420 | model: None, |
| 421 | model_provider: None, |
| 422 | model_provider_id: None, |
| 423 | mode: None, |
| 424 | allow_shell: None, |
| 425 | trust_mode: None, |
| 426 | auto_approve: None, |
| 427 | delivery_mode: None, |
| 428 | status, |
| 429 | created_at: now, |
| 430 | updated_at: now, |
| 431 | next_run_at: None, |
| 432 | last_run_at: None, |
| 433 | revision: 0, |
| 434 | disallowed_tools: Vec::new(), |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | fn run( |
| 439 | automation_id: &str, |
| 440 | id: &str, |
| 441 | status: AutomationRunStatus, |
| 442 | ended_at: Option<DateTime<Utc>>, |
| 443 | ) -> AutomationRunRecord { |
| 444 | let now = Utc::now(); |
| 445 | AutomationRunRecord { |
| 446 | schema_version: 1, |
| 447 | id: id.to_string(), |
| 448 | automation_id: automation_id.to_string(), |
| 449 | scheduled_for: now, |
| 450 | status, |
| 451 | created_at: now, |
| 452 | started_at: Some(now), |
| 453 | ended_at, |
| 454 | task_id: None, |
| 455 | thread_id: None, |
| 456 | turn_id: None, |
| 457 | error: None, |
| 458 | dispatch: None, |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | #[test] |
| 463 | fn activity_slot_counts_and_zero_suppression() { |
| 464 | let session_started_at = Utc::now(); |
| 465 | let mut panel = AutomationPanelState::default(); |
| 466 | assert_eq!(panel.activity_slot(Locale::En), None, "zero-suppressed"); |
| 467 | |
| 468 | panel.fold_scan( |
| 469 | &[ |
| 470 | record("a1", AutomationStatus::Active), |
| 471 | record("a2", AutomationStatus::Active), |
| 472 | record("a3", AutomationStatus::Paused), |
| 473 | ], |
| 474 | &[ |
| 475 | run("a1", "r1", AutomationRunStatus::Running, None), |
| 476 | run("a2", "r2", AutomationRunStatus::Completed, Some(Utc::now())), |
| 477 | ], |
| 478 | session_started_at, |
| 479 | ); |
| 480 | assert_eq!(panel.active_automations, 2, "paused automation excluded"); |
| 481 | assert_eq!(panel.live_runs, 1, "completed run excluded"); |
| 482 | assert_eq!( |
| 483 | panel.activity_slot(Locale::En).as_deref(), |
| 484 | Some("⏱ 2 scheduled · 1 running") |
| 485 | ); |
| 486 | assert_eq!(panel.activity_ink(), ChromeInk::Active); |
| 487 | |
| 488 | panel.fold_scan( |
| 489 | &[ |
| 490 | record("a1", AutomationStatus::Active), |
| 491 | record("a2", AutomationStatus::Active), |
| 492 | ], |
| 493 | &[], |
| 494 | session_started_at, |
| 495 | ); |
| 496 | assert_eq!( |
| 497 | panel.activity_slot(Locale::En).as_deref(), |
| 498 | Some("⏱ 2 scheduled"), |
| 499 | "no live runs: the running clause drops" |
| 500 | ); |
| 501 | assert_eq!(panel.activity_ink(), ChromeInk::Info); |
| 502 | } |
| 503 | |
| 504 | #[test] |
| 505 | fn failure_ink_holds_until_acknowledged_and_survives_the_scan_window() { |
| 506 | let session_started_at = Utc::now(); |
| 507 | let mut panel = AutomationPanelState::default(); |
| 508 | panel.fold_scan( |
| 509 | &[record("a1", AutomationStatus::Active)], |
| 510 | &[run( |
| 511 | "a1", |
| 512 | "r1", |
| 513 | AutomationRunStatus::Failed, |
| 514 | Some(Utc::now()), |
| 515 | )], |
| 516 | session_started_at, |
| 517 | ); |
| 518 | assert!(panel.has_unacknowledged_failure()); |
| 519 | assert_eq!(panel.activity_ink(), ChromeInk::Attention); |
| 520 | |
| 521 | // The failed run ages out of the scan window: the acknowledgement |
| 522 | // demand survives — a capped scan must not quietly settle the band. |
| 523 | panel.fold_scan( |
| 524 | &[record("a1", AutomationStatus::Active)], |
| 525 | &[], |
| 526 | session_started_at, |
| 527 | ); |
| 528 | assert_eq!(panel.activity_ink(), ChromeInk::Attention); |
| 529 | |
| 530 | panel.acknowledge_failures(); |
| 531 | assert_eq!(panel.activity_ink(), ChromeInk::Info); |
| 532 | |
| 533 | // The next fold re-sees the same persisted Failed run and must not |
| 534 | // re-light the acknowledged failure. |
| 535 | panel.fold_scan( |
| 536 | &[record("a1", AutomationStatus::Active)], |
| 537 | &[run( |
| 538 | "a1", |
| 539 | "r1", |
| 540 | AutomationRunStatus::Failed, |
| 541 | Some(Utc::now()), |
| 542 | )], |
| 543 | session_started_at, |
| 544 | ); |
| 545 | assert!( |
| 546 | !panel.has_unacknowledged_failure(), |
| 547 | "an acknowledged failure must not re-light on the next scan" |
| 548 | ); |
| 549 | assert_eq!(panel.activity_ink(), ChromeInk::Info); |
| 550 | |
| 551 | // A NEW failed run is still a fresh acknowledgement demand. |
| 552 | panel.fold_scan( |
| 553 | &[record("a1", AutomationStatus::Active)], |
| 554 | &[run( |
| 555 | "a1", |
| 556 | "r2", |
| 557 | AutomationRunStatus::Failed, |
| 558 | Some(Utc::now()), |
| 559 | )], |
| 560 | session_started_at, |
| 561 | ); |
| 562 | assert!(panel.has_unacknowledged_failure()); |
| 563 | } |
| 564 | |
| 565 | #[test] |
| 566 | fn live_runs_stay_visible_when_their_automation_is_paused() { |
| 567 | // Pausing prevents future scheduling; it does not cancel the |
| 568 | // already-enqueued run. The projection must stay up while either |
| 569 | // count is nonzero. |
| 570 | let session_started_at = Utc::now(); |
| 571 | let mut panel = AutomationPanelState::default(); |
| 572 | panel.fold_scan( |
| 573 | &[record("a1", AutomationStatus::Paused)], |
| 574 | &[run("a1", "r1", AutomationRunStatus::Running, None)], |
| 575 | session_started_at, |
| 576 | ); |
| 577 | assert_eq!(panel.active_automations, 0); |
| 578 | assert_eq!(panel.live_runs, 1); |
| 579 | assert_eq!( |
| 580 | panel.activity_slot(Locale::En).as_deref(), |
| 581 | Some("⏱ 1 running"), |
| 582 | "a paused automation's live run stays visible" |
| 583 | ); |
| 584 | assert_eq!(panel.activity_slot_compact().as_deref(), Some("⏱ ·1")); |
| 585 | assert_eq!(panel.activity_ink(), ChromeInk::Active); |
| 586 | |
| 587 | // Both counts at zero: the slot vanishes. |
| 588 | panel.fold_scan( |
| 589 | &[record("a1", AutomationStatus::Paused)], |
| 590 | &[], |
| 591 | session_started_at, |
| 592 | ); |
| 593 | assert_eq!(panel.activity_slot(Locale::En), None); |
| 594 | assert_eq!(panel.activity_slot_compact(), None); |
| 595 | } |
| 596 | |
| 597 | #[test] |
| 598 | fn pre_session_failures_do_not_light_the_band() { |
| 599 | let session_started_at = Utc::now(); |
| 600 | let old = session_started_at - chrono::Duration::hours(2); |
| 601 | let mut stale_run = run("a1", "r0", AutomationRunStatus::Failed, Some(old)); |
| 602 | stale_run.created_at = old; |
| 603 | let mut panel = AutomationPanelState::default(); |
| 604 | panel.fold_scan( |
| 605 | &[record("a1", AutomationStatus::Active)], |
| 606 | &[stale_run], |
| 607 | session_started_at, |
| 608 | ); |
| 609 | assert!(!panel.has_unacknowledged_failure()); |
| 610 | assert_eq!(panel.activity_ink(), ChromeInk::Info); |
| 611 | } |
| 612 | |
| 613 | #[test] |
| 614 | fn failures_of_deleted_automations_drop_out() { |
| 615 | let session_started_at = Utc::now(); |
| 616 | let mut panel = AutomationPanelState::default(); |
| 617 | panel.fold_scan( |
| 618 | &[record("a1", AutomationStatus::Active)], |
| 619 | &[run( |
| 620 | "a1", |
| 621 | "r1", |
| 622 | AutomationRunStatus::Failed, |
| 623 | Some(Utc::now()), |
| 624 | )], |
| 625 | session_started_at, |
| 626 | ); |
| 627 | assert!(panel.has_unacknowledged_failure()); |
| 628 | panel.fold_scan(&[], &[], session_started_at); |
| 629 | assert!( |
| 630 | !panel.has_unacknowledged_failure(), |
| 631 | "deleting the automation clears its failure demand" |
| 632 | ); |
| 633 | } |
| 634 | |
| 635 | #[test] |
| 636 | fn fold_scan_reports_only_visible_change() { |
| 637 | let session_started_at = Utc::now(); |
| 638 | let mut panel = AutomationPanelState::default(); |
| 639 | assert!( |
| 640 | panel |
| 641 | .fold_scan( |
| 642 | &[record("a1", AutomationStatus::Active)], |
| 643 | &[], |
| 644 | session_started_at |
| 645 | ) |
| 646 | .changed |
| 647 | ); |
| 648 | assert!( |
| 649 | !panel |
| 650 | .fold_scan( |
| 651 | &[record("a1", AutomationStatus::Active)], |
| 652 | &[], |
| 653 | session_started_at |
| 654 | ) |
| 655 | .changed, |
| 656 | "an unchanged scan must not force a redraw" |
| 657 | ); |
| 658 | } |
| 659 | |
| 660 | /// A run the session watched go live settles exactly once, carrying the |
| 661 | /// definition name and its wall-clock duration; runs that were already |
| 662 | /// finished before the session saw them never replay as receipts. |
| 663 | #[test] |
| 664 | fn runs_watched_live_settle_once_with_name_and_duration() { |
| 665 | let session_started_at = Utc::now(); |
| 666 | let started = Utc::now(); |
| 667 | let mut panel = AutomationPanelState::default(); |
| 668 | let mut docs = record("a1", AutomationStatus::Active); |
| 669 | docs.name = "Documentation".to_string(); |
| 670 | let mut finished_earlier = run("a1", "r0", AutomationRunStatus::Completed, Some(started)); |
| 671 | finished_earlier.started_at = Some(started); |
| 672 | |
| 673 | // First scan: one live run, one already-finished run. Nothing settles |
| 674 | // — the finished run was never seen live. |
| 675 | let mut live = run("a1", "r1", AutomationRunStatus::Running, None); |
| 676 | live.started_at = Some(started); |
| 677 | let delta = panel.fold_scan( |
| 678 | std::slice::from_ref(&docs), |
| 679 | &[live, finished_earlier.clone()], |
| 680 | session_started_at, |
| 681 | ); |
| 682 | assert!(delta.changed); |
| 683 | assert!(delta.settled.is_empty(), "{:?}", delta.settled); |
| 684 | assert_eq!(panel.live_runs, 1); |
| 685 | |
| 686 | // Second scan: the live run completed 42 s later. |
| 687 | let mut done = run( |
| 688 | "a1", |
| 689 | "r1", |
| 690 | AutomationRunStatus::Completed, |
| 691 | Some(started + chrono::Duration::seconds(42)), |
| 692 | ); |
| 693 | done.started_at = Some(started); |
| 694 | let delta = panel.fold_scan( |
| 695 | std::slice::from_ref(&docs), |
| 696 | &[done.clone(), finished_earlier.clone()], |
| 697 | session_started_at, |
| 698 | ); |
| 699 | assert_eq!( |
| 700 | delta.settled, |
| 701 | vec![SettledRun { |
| 702 | automation_id: "a1".to_string(), |
| 703 | automation_name: "Documentation".to_string(), |
| 704 | run_id: "r1".to_string(), |
| 705 | outcome: SettledOutcome::Completed, |
| 706 | duration_ms: Some(42_000), |
| 707 | error: None, |
| 708 | }] |
| 709 | ); |
| 710 | assert_eq!(panel.live_runs, 0); |
| 711 | assert_eq!(panel.activity_ink(), ChromeInk::Info); |
| 712 | |
| 713 | // Third scan, same picture: the settle is not reported twice. |
| 714 | let delta = panel.fold_scan( |
| 715 | std::slice::from_ref(&docs), |
| 716 | &[done, finished_earlier], |
| 717 | session_started_at, |
| 718 | ); |
| 719 | assert!(!delta.changed); |
| 720 | assert!(delta.settled.is_empty(), "{:?}", delta.settled); |
| 721 | } |
| 722 | |
| 723 | /// A watched run that fails settles as `Failed` with its error, and the |
| 724 | /// same fold lights the band's acknowledgement demand. |
| 725 | #[test] |
| 726 | fn a_watched_run_that_fails_settles_with_its_error_and_lights_the_band() { |
| 727 | let session_started_at = Utc::now(); |
| 728 | let mut panel = AutomationPanelState::default(); |
| 729 | let records = [record("a1", AutomationStatus::Active)]; |
| 730 | panel.fold_scan( |
| 731 | &records, |
| 732 | &[run("a1", "r1", AutomationRunStatus::Running, None)], |
| 733 | session_started_at, |
| 734 | ); |
| 735 | let mut failed = run("a1", "r1", AutomationRunStatus::Failed, Some(Utc::now())); |
| 736 | failed.error = Some("provider timeout".to_string()); |
| 737 | let delta = panel.fold_scan(&records, &[failed], session_started_at); |
| 738 | assert_eq!(delta.settled.len(), 1); |
| 739 | assert_eq!(delta.settled[0].outcome, SettledOutcome::Failed); |
| 740 | assert_eq!(delta.settled[0].error.as_deref(), Some("provider timeout")); |
| 741 | assert_eq!(panel.activity_ink(), ChromeInk::Attention); |
| 742 | |
| 743 | // A canceled run leaves the live set with a receipt that names the |
| 744 | // cancellation (#6162), without lighting the failure demand. |
| 745 | panel.acknowledge_failures(); |
| 746 | assert!(!panel.has_unacknowledged_failure()); |
| 747 | panel.fold_scan( |
| 748 | &records, |
| 749 | &[run("a1", "r2", AutomationRunStatus::Queued, None)], |
| 750 | session_started_at, |
| 751 | ); |
| 752 | let mut canceled = run("a1", "r2", AutomationRunStatus::Canceled, Some(Utc::now())); |
| 753 | canceled.error = Some("canceled by request".to_string()); |
| 754 | let delta = panel.fold_scan(&records, &[canceled.clone()], session_started_at); |
| 755 | assert_eq!(delta.settled.len(), 1, "{:?}", delta.settled); |
| 756 | assert_eq!(delta.settled[0].outcome, SettledOutcome::Canceled); |
| 757 | assert_eq!(delta.settled[0].run_id, "r2"); |
| 758 | assert_eq!( |
| 759 | delta.settled[0].error.as_deref(), |
| 760 | Some("canceled by request") |
| 761 | ); |
| 762 | assert!( |
| 763 | !panel.has_unacknowledged_failure(), |
| 764 | "a cancellation is not a failure" |
| 765 | ); |
| 766 | |
| 767 | // The receipt is posted once: the same picture settles nothing more. |
| 768 | let delta = panel.fold_scan(&records, &[canceled], session_started_at); |
| 769 | assert!(delta.settled.is_empty(), "{:?}", delta.settled); |
| 770 | } |
| 771 | |
| 772 | /// The spec's reservation check (§6 Slice 1 accept): no automation band |
| 773 | /// ink may resolve to the theme's failure color in any selectable preset. |
| 774 | #[test] |
| 775 | fn automation_band_ink_never_resolves_to_failure_red() { |
| 776 | for theme_id in codewhale_palette::SELECTABLE_THEMES { |
| 777 | let theme = theme_id.ui_theme(); |
| 778 | for ink in [ChromeInk::Info, ChromeInk::Active, ChromeInk::Attention] { |
| 779 | assert_ne!( |
| 780 | ink.color(&theme), |
| 781 | theme.error_fg, |
| 782 | "theme '{}' spends Failure red on the automation band ({ink:?})", |
| 783 | theme_id.name() |
| 784 | ); |
| 785 | } |
| 786 | } |
| 787 | } |
| 788 | } |
| 789 |