| 1 | //! Durable automation formatting and operator actions. |
| 2 | //! |
| 3 | //! Receipts for run/definition events are typed `HistoryCell::Automation` |
| 4 | //! cards (AUTOMATION-VISIBILITY-SPEC §2.2). Deletion uses the shared pager |
| 5 | //! review control; query responses (list/show) retain their text receipts. |
| 6 | |
| 7 | use crate::automation_manager::{ |
| 8 | AutomationRecord, AutomationRunRecord, AutomationRunStatus, AutomationStatus, |
| 9 | SharedAutomationManager, run_now_shared, |
| 10 | }; |
| 11 | use crate::task_manager::SharedTaskManager; |
| 12 | use crate::tui::app::{App, AutomationAction}; |
| 13 | use crate::tui::automation_panel::{SettledOutcome, SettledRun}; |
| 14 | use crate::tui::history::{AutomationCell, AutomationCellKind, HistoryCell}; |
| 15 | use codewhale_localization::{Locale, MessageId, tr}; |
| 16 | |
| 17 | pub(super) async fn handle_action( |
| 18 | app: &mut App, |
| 19 | config: &crate::config::Config, |
| 20 | action: AutomationAction, |
| 21 | task_manager: &SharedTaskManager, |
| 22 | ) { |
| 23 | let locale = app.ui_locale; |
| 24 | // Engaging the automation surface acknowledges the failures the activity |
| 25 | // band is demanding attention for (spec §2.1). |
| 26 | app.automation_panel.acknowledge_failures(); |
| 27 | let Some(automations) = app.runtime_services.automations.clone() else { |
| 28 | add_message( |
| 29 | app, |
| 30 | tr(locale, MessageId::AutomationManagerUnavailable).into_owned(), |
| 31 | ); |
| 32 | return; |
| 33 | }; |
| 34 | |
| 35 | let cell = match action { |
| 36 | AutomationAction::Open { focus } => { |
| 37 | // The room, not a receipt: the one place to see, pause, run, |
| 38 | // cancel, and delete automations (0.9.12 defect #14). |
| 39 | if app.view_stack.top_kind() == Some(crate::tui::views::ModalKind::Automations) { |
| 40 | app.view_stack.pop(); |
| 41 | } |
| 42 | app.view_stack |
| 43 | .push(crate::tui::views::automations::AutomationsView::new( |
| 44 | app, |
| 45 | config, |
| 46 | focus.as_deref(), |
| 47 | )); |
| 48 | app.needs_redraw = true; |
| 49 | return; |
| 50 | } |
| 51 | AutomationAction::List => HistoryCell::System { |
| 52 | content: list(locale, &automations).await, |
| 53 | }, |
| 54 | AutomationAction::Show(id) => HistoryCell::System { |
| 55 | content: show(locale, &automations, &id).await, |
| 56 | }, |
| 57 | AutomationAction::Pause(id) => mutate(locale, &automations, &id, Mutation::Pause).await, |
| 58 | AutomationAction::Resume(id) => mutate(locale, &automations, &id, Mutation::Resume).await, |
| 59 | AutomationAction::Delete { id, confirmation } => { |
| 60 | let (cell, command) = delete(locale, &automations, &id, confirmation.as_deref()).await; |
| 61 | if let Some(command) = command { |
| 62 | if let HistoryCell::System { content } = cell { |
| 63 | let width = app |
| 64 | .viewport |
| 65 | .last_transcript_area |
| 66 | .map_or(80, |area| area.width); |
| 67 | app.view_stack |
| 68 | .push(crate::tui::pager::PagerView::command_review( |
| 69 | tr(locale, MessageId::AutomationActionDelete), |
| 70 | &content, |
| 71 | width.saturating_sub(2), |
| 72 | command, |
| 73 | locale, |
| 74 | )); |
| 75 | app.needs_redraw = true; |
| 76 | } |
| 77 | return; |
| 78 | } |
| 79 | cell |
| 80 | } |
| 81 | AutomationAction::Run(id) => run_now(locale, &automations, &id, task_manager).await, |
| 82 | }; |
| 83 | present_receipt(app, cell); |
| 84 | } |
| 85 | |
| 86 | fn present_receipt(app: &mut App, cell: HistoryCell) { |
| 87 | // The automation room covers the transcript. A refused action still needs |
| 88 | // an immediate visible receipt there, even when no run record was created. |
| 89 | if app.view_stack.top_kind() == Some(crate::tui::views::ModalKind::Automations) |
| 90 | && let Some(mut view) = app.view_stack.pop() |
| 91 | { |
| 92 | if let Some(automations_view) = |
| 93 | view.as_any_mut() |
| 94 | .downcast_mut::<crate::tui::views::automations::AutomationsView>() |
| 95 | { |
| 96 | let receipt = match &cell { |
| 97 | HistoryCell::Automation(receipt) => receipt.plain_summary(), |
| 98 | HistoryCell::System { content } => content.clone(), |
| 99 | _ => String::new(), |
| 100 | }; |
| 101 | automations_view.show_action_receipt(receipt); |
| 102 | } |
| 103 | app.view_stack.push_boxed(view); |
| 104 | app.needs_redraw = true; |
| 105 | } |
| 106 | app.add_message(cell); |
| 107 | } |
| 108 | |
| 109 | async fn list(locale: Locale, automations: &SharedAutomationManager) -> String { |
| 110 | match automations.lock().await.list_automations() { |
| 111 | Ok(records) => format_list(locale, &records), |
| 112 | Err(error) => { |
| 113 | tr(locale, MessageId::AutomationListFailed).replace("{error}", &error.to_string()) |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | async fn show(locale: Locale, automations: &SharedAutomationManager, id: &str) -> String { |
| 119 | let manager = automations.lock().await; |
| 120 | match manager.get_automation(id) { |
| 121 | Ok(record) => { |
| 122 | let runs = manager.list_runs(id, Some(5)).ok(); |
| 123 | format_detail(locale, &record, runs.as_deref()) |
| 124 | } |
| 125 | Err(error) => action_failed(locale, MessageId::AutomationActionInspect, id, &error), |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | #[derive(Clone, Copy)] |
| 130 | enum Mutation { |
| 131 | Pause, |
| 132 | Resume, |
| 133 | } |
| 134 | |
| 135 | impl Mutation { |
| 136 | const fn action_id(self) -> MessageId { |
| 137 | match self { |
| 138 | Self::Pause => MessageId::AutomationActionPause, |
| 139 | Self::Resume => MessageId::AutomationActionResume, |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | const fn receipt_id(self) -> MessageId { |
| 144 | match self { |
| 145 | Self::Pause => MessageId::AutomationActionPaused, |
| 146 | Self::Resume => MessageId::AutomationActionResumed, |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | async fn mutate( |
| 152 | locale: Locale, |
| 153 | automations: &SharedAutomationManager, |
| 154 | id: &str, |
| 155 | mutation: Mutation, |
| 156 | ) -> HistoryCell { |
| 157 | let manager = automations.lock().await; |
| 158 | let result = match mutation { |
| 159 | Mutation::Pause => manager.pause_automation(id), |
| 160 | Mutation::Resume => manager.resume_automation(id), |
| 161 | }; |
| 162 | |
| 163 | match result { |
| 164 | Ok(record) => HistoryCell::Automation(AutomationCell::mutated( |
| 165 | display_text(&record.name), |
| 166 | tr(locale, mutation.receipt_id()).into_owned(), |
| 167 | )), |
| 168 | Err(error) => HistoryCell::System { |
| 169 | content: action_failed(locale, mutation.action_id(), id, &error), |
| 170 | }, |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | async fn delete( |
| 175 | locale: Locale, |
| 176 | automations: &SharedAutomationManager, |
| 177 | id: &str, |
| 178 | confirmation: Option<&str>, |
| 179 | ) -> (HistoryCell, Option<String>) { |
| 180 | let manager = automations.lock().await; |
| 181 | let record = match manager.get_automation(id) { |
| 182 | Ok(record) => record, |
| 183 | Err(error) => { |
| 184 | return ( |
| 185 | system(action_failed( |
| 186 | locale, |
| 187 | MessageId::AutomationActionDelete, |
| 188 | id, |
| 189 | &error, |
| 190 | )), |
| 191 | None, |
| 192 | ); |
| 193 | } |
| 194 | }; |
| 195 | let runs = match manager.list_runs(id, None) { |
| 196 | Ok(runs) => runs, |
| 197 | Err(error) => { |
| 198 | return ( |
| 199 | system(action_failed( |
| 200 | locale, |
| 201 | MessageId::AutomationActionDelete, |
| 202 | id, |
| 203 | &error, |
| 204 | )), |
| 205 | None, |
| 206 | ); |
| 207 | } |
| 208 | }; |
| 209 | let token = match deletion_token(&record, &runs) { |
| 210 | Ok(token) => token, |
| 211 | Err(error) => { |
| 212 | return ( |
| 213 | system(action_failed( |
| 214 | locale, |
| 215 | MessageId::AutomationActionDelete, |
| 216 | id, |
| 217 | &error, |
| 218 | )), |
| 219 | None, |
| 220 | ); |
| 221 | } |
| 222 | }; |
| 223 | |
| 224 | let Some(confirmation) = confirmation else { |
| 225 | let command = format!("/automation delete {id} --confirm {token}"); |
| 226 | let recent_len = runs.len().min(5); |
| 227 | let detail = format_detail(locale, &record, Some(&runs[..recent_len])); |
| 228 | let preview = tr(locale, MessageId::AutomationDeletePreview) |
| 229 | .replace("{id}", id) |
| 230 | .replace("{name}", &display_text(&record.name)) |
| 231 | .replace("{run_count}", &runs.len().to_string()) |
| 232 | .replace("{command}", "y → Enter"); |
| 233 | return (system(format!("{detail}\n\n{preview}")), Some(command)); |
| 234 | }; |
| 235 | |
| 236 | if confirmation != token { |
| 237 | let command = format!("/automation delete {id}"); |
| 238 | return ( |
| 239 | system( |
| 240 | tr(locale, MessageId::AutomationDeleteConfirmationStale) |
| 241 | .replace("{id}", id) |
| 242 | .replace("{command}", &command), |
| 243 | ), |
| 244 | None, |
| 245 | ); |
| 246 | } |
| 247 | |
| 248 | let receipt = match manager.delete_automation(id) { |
| 249 | Ok(record) => HistoryCell::Automation( |
| 250 | AutomationCell::mutated( |
| 251 | display_text(&record.name), |
| 252 | tr(locale, MessageId::AutomationReceiptDeleted).into_owned(), |
| 253 | ) |
| 254 | .with_detail(Some( |
| 255 | tr(locale, MessageId::AutomationDeletedRunsDetail) |
| 256 | .replace("{run_count}", &runs.len().to_string()), |
| 257 | )), |
| 258 | ), |
| 259 | Err(error) => system(action_failed( |
| 260 | locale, |
| 261 | MessageId::AutomationActionDelete, |
| 262 | id, |
| 263 | &error, |
| 264 | )), |
| 265 | }; |
| 266 | (receipt, None) |
| 267 | } |
| 268 | |
| 269 | fn system(content: String) -> HistoryCell { |
| 270 | HistoryCell::System { content } |
| 271 | } |
| 272 | |
| 273 | fn deletion_token( |
| 274 | record: &AutomationRecord, |
| 275 | runs: &[AutomationRunRecord], |
| 276 | ) -> Result<String, serde_json::Error> { |
| 277 | let mut canonical_runs = runs.iter().collect::<Vec<_>>(); |
| 278 | canonical_runs.sort_by(|left, right| left.id.cmp(&right.id)); |
| 279 | serde_json::to_vec(&(record, canonical_runs)).map(crate::hashing::sha256_hex) |
| 280 | } |
| 281 | |
| 282 | fn action_failed( |
| 283 | locale: Locale, |
| 284 | action_id: MessageId, |
| 285 | id: &str, |
| 286 | error: &impl std::fmt::Display, |
| 287 | ) -> String { |
| 288 | tr(locale, MessageId::AutomationActionFailed) |
| 289 | .replace("{action}", &tr(locale, action_id)) |
| 290 | .replace("{id}", id) |
| 291 | .replace("{error}", &error.to_string()) |
| 292 | } |
| 293 | |
| 294 | fn format_list(locale: Locale, records: &[AutomationRecord]) -> String { |
| 295 | if records.is_empty() { |
| 296 | return tr(locale, MessageId::AutomationEmpty).into_owned(); |
| 297 | } |
| 298 | |
| 299 | let lines = records |
| 300 | .iter() |
| 301 | .map(|record| { |
| 302 | format!( |
| 303 | "{} [{}] {} ({}; {}: {})", |
| 304 | record.id, |
| 305 | status_label(locale, record.status), |
| 306 | display_text(&record.name), |
| 307 | delivery_mode_label(record), |
| 308 | tr(locale, MessageId::AutomationNextLabel), |
| 309 | timestamp(record.next_run_at) |
| 310 | ) |
| 311 | }) |
| 312 | .collect::<Vec<_>>() |
| 313 | .join("\n"); |
| 314 | format!("{}:\n{lines}", tr(locale, MessageId::AutomationListHeading)) |
| 315 | } |
| 316 | |
| 317 | fn format_detail( |
| 318 | locale: Locale, |
| 319 | record: &AutomationRecord, |
| 320 | runs: Option<&[AutomationRunRecord]>, |
| 321 | ) -> String { |
| 322 | let runs = match runs { |
| 323 | Some([]) => format!(" {}", tr(locale, MessageId::AutomationNoRuns)), |
| 324 | Some(runs) => runs |
| 325 | .iter() |
| 326 | .map(|run| { |
| 327 | format!( |
| 328 | " {} {} ({} {})", |
| 329 | run_status_label(locale, run.status), |
| 330 | run.scheduled_for.to_rfc3339(), |
| 331 | tr(locale, MessageId::AutomationTaskLabel), |
| 332 | run.task_id.as_deref().unwrap_or("-") |
| 333 | ) |
| 334 | }) |
| 335 | .collect::<Vec<_>>() |
| 336 | .join("\n"), |
| 337 | None => format!(" {}", tr(locale, MessageId::AutomationRunsUnavailable)), |
| 338 | }; |
| 339 | let mut lines = vec![ |
| 340 | format!( |
| 341 | "{} {} [{}]", |
| 342 | tr(locale, MessageId::AutomationNoun), |
| 343 | record.id, |
| 344 | status_label(locale, record.status) |
| 345 | ), |
| 346 | field( |
| 347 | locale, |
| 348 | MessageId::AutomationNameLabel, |
| 349 | &display_text(&record.name), |
| 350 | ), |
| 351 | format!(" {}:", tr(locale, MessageId::AutomationPromptLabel)), |
| 352 | ]; |
| 353 | lines.extend( |
| 354 | display_text(&record.prompt) |
| 355 | .lines() |
| 356 | .map(|line| format!(" {line}")), |
| 357 | ); |
| 358 | lines.extend(record.cwds.iter().map(|cwd| { |
| 359 | field( |
| 360 | locale, |
| 361 | MessageId::AutomationCwdLabel, |
| 362 | &display_text(&crate::utils::display_path(cwd)), |
| 363 | ) |
| 364 | })); |
| 365 | if let Some(mode) = record.mode.as_deref() { |
| 366 | lines.push(field( |
| 367 | locale, |
| 368 | MessageId::AutomationModeLabel, |
| 369 | &display_text(mode), |
| 370 | )); |
| 371 | } |
| 372 | if let Some(model) = record.model.as_deref() { |
| 373 | let route = record |
| 374 | .model_provider_id |
| 375 | .as_ref() |
| 376 | .or(record.model_provider.as_ref()) |
| 377 | .map_or_else( |
| 378 | || model.to_string(), |
| 379 | |provider| format!("{provider} / {model}"), |
| 380 | ); |
| 381 | lines.push(field( |
| 382 | locale, |
| 383 | MessageId::SetupCardModelLabel, |
| 384 | &display_text(&route), |
| 385 | )); |
| 386 | } |
| 387 | if let Some(allow_shell) = record.allow_shell { |
| 388 | lines.push(field( |
| 389 | locale, |
| 390 | MessageId::AutomationAllowShellLabel, |
| 391 | &allow_shell.to_string(), |
| 392 | )); |
| 393 | } |
| 394 | if let Some(trust_mode) = record.trust_mode { |
| 395 | lines.push(field( |
| 396 | locale, |
| 397 | MessageId::AutomationTrustModeLabel, |
| 398 | &trust_mode.to_string(), |
| 399 | )); |
| 400 | } |
| 401 | if let Some(auto_approve) = record.auto_approve { |
| 402 | lines.push(field( |
| 403 | locale, |
| 404 | MessageId::AutomationAutoApproveLabel, |
| 405 | &auto_approve.to_string(), |
| 406 | )); |
| 407 | } |
| 408 | lines.extend([ |
| 409 | field(locale, MessageId::AutomationRruleLabel, &record.rrule), |
| 410 | field( |
| 411 | locale, |
| 412 | MessageId::AutomationDeliveryLabel, |
| 413 | &delivery_mode_label(record), |
| 414 | ), |
| 415 | field( |
| 416 | locale, |
| 417 | MessageId::AutomationNextLabel, |
| 418 | ×tamp(record.next_run_at), |
| 419 | ), |
| 420 | field( |
| 421 | locale, |
| 422 | MessageId::AutomationLastLabel, |
| 423 | ×tamp(record.last_run_at), |
| 424 | ), |
| 425 | format!( |
| 426 | "{}:\n{runs}", |
| 427 | tr(locale, MessageId::AutomationRecentRunsLabel) |
| 428 | ), |
| 429 | ]); |
| 430 | lines.join("\n") |
| 431 | } |
| 432 | |
| 433 | fn field(locale: Locale, label: MessageId, value: &str) -> String { |
| 434 | format!(" {}: {value}", tr(locale, label)) |
| 435 | } |
| 436 | |
| 437 | fn display_text(value: &str) -> String { |
| 438 | let mut visible = String::with_capacity(value.len()); |
| 439 | crate::tui::osc8::strip_ansi_into(value, &mut visible); |
| 440 | codewhale_config::persistence::redact_secrets(&visible) |
| 441 | } |
| 442 | |
| 443 | /// `run <id>`: enqueue immediately and acknowledge with a typed `Started` |
| 444 | /// receipt — the `${subject} started in background` line, promoted from tip |
| 445 | /// to receipt (spec §2.2). |
| 446 | async fn run_now( |
| 447 | locale: Locale, |
| 448 | automations: &SharedAutomationManager, |
| 449 | id: &str, |
| 450 | task_manager: &SharedTaskManager, |
| 451 | ) -> HistoryCell { |
| 452 | let name = automations |
| 453 | .lock() |
| 454 | .await |
| 455 | .get_automation(id) |
| 456 | .ok() |
| 457 | .map(|record| display_text(&record.name)); |
| 458 | match run_now_shared(automations, id, task_manager).await { |
| 459 | Ok(run) => { |
| 460 | // The run record can come back already settled: a refused |
| 461 | // enqueue returns Ok with status Failed, and a "started in |
| 462 | // background" receipt would then be a lie. Branch the receipt |
| 463 | // on the record's own status. Running/Queued are the live |
| 464 | // states; Completed/Canceled cannot occur this soon after |
| 465 | // enqueue, but if one ever does, "started" would be false — |
| 466 | // report the settled verb instead. |
| 467 | let kind = match run.status { |
| 468 | AutomationRunStatus::Failed => AutomationCellKind::Failed, |
| 469 | AutomationRunStatus::Queued | AutomationRunStatus::Running => { |
| 470 | AutomationCellKind::Started |
| 471 | } |
| 472 | AutomationRunStatus::Completed => AutomationCellKind::Completed, |
| 473 | AutomationRunStatus::Canceled => AutomationCellKind::Canceled, |
| 474 | }; |
| 475 | // The operator asked for this run by hand: echo its full id so |
| 476 | // it can be copied straight from the receipt. |
| 477 | let mut detail = format!( |
| 478 | "{} {} · {} {}", |
| 479 | tr(locale, MessageId::AutomationRunLabel), |
| 480 | run.id, |
| 481 | tr(locale, MessageId::AutomationTaskLabel), |
| 482 | run.task_id.as_deref().map(short_id).unwrap_or("-") |
| 483 | ); |
| 484 | if let Some(error) = run.error.as_deref() { |
| 485 | detail.push_str(" · "); |
| 486 | detail.push_str(&display_text(error)); |
| 487 | } |
| 488 | let name = name.unwrap_or_else(|| id.to_string()); |
| 489 | HistoryCell::Automation( |
| 490 | AutomationCell::event(kind, name, locale).with_detail(Some(detail)), |
| 491 | ) |
| 492 | } |
| 493 | Err(error) => system(action_failed( |
| 494 | locale, |
| 495 | MessageId::AutomationActionRun, |
| 496 | id, |
| 497 | &error, |
| 498 | )), |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | /// Receipt for a run the projection watched go live and settle (spec §2.2: |
| 503 | /// `Documentation completed in background 42s · run r-8f19`). `Completed` |
| 504 | /// wears Outcome ink; a genuinely failed run is the one receipt that wears |
| 505 | /// Failure, and its detail leads with the (redacted) error. |
| 506 | /// A canceled run (#6162) wears Attention ink and its detail leads with the |
| 507 | /// cancellation reason, so a stopped run is never silent and never red. |
| 508 | pub(super) fn settled_run_receipt(locale: Locale, run: &SettledRun) -> HistoryCell { |
| 509 | let kind = match run.outcome { |
| 510 | SettledOutcome::Completed => AutomationCellKind::Completed, |
| 511 | SettledOutcome::Failed => AutomationCellKind::Failed, |
| 512 | SettledOutcome::Canceled => AutomationCellKind::Canceled, |
| 513 | }; |
| 514 | let mut parts = Vec::new(); |
| 515 | if let Some(error) = run |
| 516 | .error |
| 517 | .as_deref() |
| 518 | .map(display_text) |
| 519 | .filter(|error| !error.is_empty()) |
| 520 | { |
| 521 | parts.push(error); |
| 522 | } |
| 523 | if let Some(duration_ms) = run.duration_ms { |
| 524 | parts.push(crate::elapsed::format_elapsed_ms(duration_ms)); |
| 525 | } |
| 526 | parts.push(format!( |
| 527 | "{} {}", |
| 528 | tr(locale, MessageId::AutomationRunLabel), |
| 529 | short_id(&run.run_id) |
| 530 | )); |
| 531 | HistoryCell::Automation( |
| 532 | AutomationCell::event(kind, display_text(&run.automation_name), locale) |
| 533 | .with_detail(Some(parts.join(" · "))), |
| 534 | ) |
| 535 | } |
| 536 | |
| 537 | /// Background receipts name a run/task by prefix — full UUIDs would eat the |
| 538 | /// card's one line. The complete ids stay on the records for |
| 539 | /// `/automation show`; only the operator-driven `/automation run` echo |
| 540 | /// carries the whole run id. |
| 541 | fn short_id(id: &str) -> &str { |
| 542 | id.get(..12).unwrap_or(id) |
| 543 | } |
| 544 | |
| 545 | fn status_label(locale: Locale, status: AutomationStatus) -> String { |
| 546 | let id = match status { |
| 547 | AutomationStatus::Active => MessageId::AutomationStatusActive, |
| 548 | AutomationStatus::Paused => MessageId::AutomationStatusPaused, |
| 549 | }; |
| 550 | tr(locale, id).into_owned() |
| 551 | } |
| 552 | |
| 553 | fn run_status_label(locale: Locale, status: AutomationRunStatus) -> String { |
| 554 | let id = match status { |
| 555 | AutomationRunStatus::Queued => MessageId::AutomationRunStatusQueued, |
| 556 | AutomationRunStatus::Running => MessageId::AutomationRunStatusRunning, |
| 557 | AutomationRunStatus::Completed => MessageId::AutomationRunStatusCompleted, |
| 558 | AutomationRunStatus::Failed => MessageId::AutomationRunStatusFailed, |
| 559 | AutomationRunStatus::Canceled => MessageId::AutomationRunStatusCanceled, |
| 560 | }; |
| 561 | tr(locale, id).into_owned() |
| 562 | } |
| 563 | |
| 564 | fn timestamp(value: Option<chrono::DateTime<chrono::Utc>>) -> String { |
| 565 | value |
| 566 | .map(|timestamp| timestamp.to_rfc3339()) |
| 567 | .unwrap_or_else(|| "-".to_string()) |
| 568 | } |
| 569 | |
| 570 | /// Delivery mode is a stored enum value, not prose — render it raw like |
| 571 | /// `mode`/`rrule` rather than translating it. Unset means the default `task`. |
| 572 | fn delivery_mode_label(record: &AutomationRecord) -> String { |
| 573 | format!("{:?}", record.delivery_mode.unwrap_or_default()).to_ascii_lowercase() |
| 574 | } |
| 575 | |
| 576 | fn add_message(app: &mut App, content: String) { |
| 577 | present_receipt(app, HistoryCell::System { content }); |
| 578 | } |
| 579 | |
| 580 | #[cfg(test)] |
| 581 | mod tests { |
| 582 | use std::fs; |
| 583 | use std::sync::Arc; |
| 584 | |
| 585 | use super::*; |
| 586 | use crate::automation_manager::{ |
| 587 | AutomationDeliveryMode, AutomationManager, CreateAutomationRequest, |
| 588 | }; |
| 589 | use chrono::Utc; |
| 590 | use tempfile::TempDir; |
| 591 | use tokio::sync::Mutex; |
| 592 | |
| 593 | fn record(status: AutomationStatus) -> AutomationRecord { |
| 594 | let now = Utc::now(); |
| 595 | AutomationRecord { |
| 596 | schema_version: 1, |
| 597 | execution_scope: Some(crate::task_manager::test_execution_scope("test")), |
| 598 | id: "auto_1".to_string(), |
| 599 | name: "Nightly checks".to_string(), |
| 600 | prompt: "Run checks".to_string(), |
| 601 | rrule: "FREQ=DAILY".to_string(), |
| 602 | cwds: Vec::new(), |
| 603 | model: None, |
| 604 | model_provider: None, |
| 605 | model_provider_id: None, |
| 606 | mode: None, |
| 607 | allow_shell: None, |
| 608 | trust_mode: None, |
| 609 | auto_approve: None, |
| 610 | delivery_mode: None, |
| 611 | status, |
| 612 | created_at: now, |
| 613 | updated_at: now, |
| 614 | next_run_at: None, |
| 615 | last_run_at: None, |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | #[test] |
| 620 | fn action_receipts_reach_the_open_room_and_remain_in_history() { |
| 621 | use crate::tui::views::{ModalKind, automations::AutomationsView}; |
| 622 | use ratatui::{buffer::Buffer, layout::Rect}; |
| 623 | |
| 624 | let root = TempDir::new().unwrap(); |
| 625 | let mut app = crate::test_support::test_app_with_options( |
| 626 | crate::test_support::test_tui_options(root.path()), |
| 627 | ); |
| 628 | app.view_stack |
| 629 | .push(AutomationsView::from_rows(Vec::new(), Locale::En)); |
| 630 | for cell in [ |
| 631 | system( |
| 632 | "Could not run automation: Automation belongs to another Runtime execution scope" |
| 633 | .to_string(), |
| 634 | ), |
| 635 | HistoryCell::Automation(AutomationCell::mutated( |
| 636 | "Nightly checks".into(), |
| 637 | "paused".into(), |
| 638 | )), |
| 639 | ] { |
| 640 | let expected = match &cell { |
| 641 | HistoryCell::System { content } => content.clone(), |
| 642 | HistoryCell::Automation(receipt) => receipt.plain_summary(), |
| 643 | _ => unreachable!(), |
| 644 | }; |
| 645 | let before = app.history.len(); |
| 646 | present_receipt(&mut app, cell); |
| 647 | assert_eq!(app.history.len(), before + 1); |
| 648 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::Automations)); |
| 649 | let view = app.view_stack.pop().unwrap(); |
| 650 | let area = Rect::new(0, 0, 120, 20); |
| 651 | let mut buffer = Buffer::empty(area); |
| 652 | view.render(area, &mut buffer); |
| 653 | let text = (0..area.height) |
| 654 | .map(|y| { |
| 655 | (0..area.width) |
| 656 | .map(|x| buffer[(x, y)].symbol()) |
| 657 | .collect::<String>() |
| 658 | }) |
| 659 | .collect::<Vec<_>>() |
| 660 | .join("\n"); |
| 661 | assert!(text.contains(&expected), "{text}"); |
| 662 | app.view_stack.push_boxed(view); |
| 663 | } |
| 664 | // The missing-manager early return uses this same path. |
| 665 | add_message(&mut app, "Automation manager unavailable".into()); |
| 666 | let view = app.view_stack.pop().unwrap(); |
| 667 | let area = Rect::new(0, 0, 80, 20); |
| 668 | let mut buffer = Buffer::empty(area); |
| 669 | view.render(area, &mut buffer); |
| 670 | let text = buffer |
| 671 | .content() |
| 672 | .iter() |
| 673 | .map(|cell| cell.symbol()) |
| 674 | .collect::<String>(); |
| 675 | assert!(text.contains("Automation manager unavailable")); |
| 676 | } |
| 677 | |
| 678 | #[test] |
| 679 | fn list_explains_empty_state_and_operator_controls() { |
| 680 | assert!(format_list(Locale::En, &[]).contains("Choose New automation")); |
| 681 | let text = format_list(Locale::En, &[record(AutomationStatus::Paused)]); |
| 682 | assert!(text.contains("auto_1 [paused] Nightly checks")); |
| 683 | assert!(text.contains("next: -")); |
| 684 | } |
| 685 | |
| 686 | #[test] |
| 687 | fn detail_keeps_schedule_and_recent_run_shape() { |
| 688 | let text = format_detail(Locale::En, &record(AutomationStatus::Active), Some(&[])); |
| 689 | assert!(text.contains("Automation auto_1 [active]")); |
| 690 | assert!(text.contains("rrule: FREQ=DAILY")); |
| 691 | assert!(text.contains("recent runs:")); |
| 692 | } |
| 693 | |
| 694 | #[test] |
| 695 | fn list_and_detail_surface_delivery_mode() { |
| 696 | let mut automation = record(AutomationStatus::Active); |
| 697 | automation.delivery_mode = Some(AutomationDeliveryMode::Watcher); |
| 698 | |
| 699 | let list = format_list(Locale::En, std::slice::from_ref(&automation)); |
| 700 | assert!(list.contains("(watcher; next:")); |
| 701 | |
| 702 | let detail = format_detail(Locale::En, &automation, Some(&[])); |
| 703 | assert!(detail.contains(" delivery: watcher")); |
| 704 | |
| 705 | let default_detail = |
| 706 | format_detail(Locale::En, &record(AutomationStatus::Active), Some(&[])); |
| 707 | assert!(default_detail.contains(" delivery: task")); |
| 708 | } |
| 709 | |
| 710 | #[test] |
| 711 | fn detail_exposes_configured_execution_contract_and_redacts_prompt() { |
| 712 | let mut automation = record(AutomationStatus::Active); |
| 713 | automation.prompt = "Run release checks\napi_key = \"sk-audit-secret-value\"".to_string(); |
| 714 | automation.cwds = vec!["release-workspace".into()]; |
| 715 | automation.mode = Some("agent".to_string()); |
| 716 | automation.allow_shell = Some(true); |
| 717 | automation.trust_mode = Some(false); |
| 718 | automation.auto_approve = Some(true); |
| 719 | |
| 720 | let text = format_detail(Locale::En, &automation, Some(&[])); |
| 721 | |
| 722 | assert!(text.contains(" prompt:\n Run release checks")); |
| 723 | assert!(text.contains("[redacted]")); |
| 724 | assert!(!text.contains("sk-audit-secret-value")); |
| 725 | assert!(text.contains(" cwd: release-workspace")); |
| 726 | assert!(text.contains(" mode: agent")); |
| 727 | assert!(text.contains(" allow_shell: true")); |
| 728 | assert!(text.contains(" trust_mode: false")); |
| 729 | assert!(text.contains(" auto_approve: true")); |
| 730 | } |
| 731 | |
| 732 | #[test] |
| 733 | fn list_stays_compact_and_detail_omits_unset_execution_overrides() { |
| 734 | let automation = record(AutomationStatus::Paused); |
| 735 | |
| 736 | let list = format_list(Locale::En, std::slice::from_ref(&automation)); |
| 737 | assert!(!list.contains(&automation.prompt)); |
| 738 | assert!(!list.contains("prompt:")); |
| 739 | assert!(!list.contains("cwd:")); |
| 740 | assert!(!list.contains("mode:")); |
| 741 | assert!(!list.contains("allow_shell:")); |
| 742 | assert!(!list.contains("trust_mode:")); |
| 743 | assert!(!list.contains("auto_approve:")); |
| 744 | |
| 745 | let detail = format_detail(Locale::En, &automation, Some(&[])); |
| 746 | assert!(!detail.contains("cwd:")); |
| 747 | assert!(!detail.contains("mode:")); |
| 748 | assert!(!detail.contains("allow_shell:")); |
| 749 | assert!(!detail.contains("trust_mode:")); |
| 750 | assert!(!detail.contains("auto_approve:")); |
| 751 | } |
| 752 | |
| 753 | #[test] |
| 754 | fn automation_output_routes_through_the_selected_locale() { |
| 755 | let french = format_list(Locale::Fr, &[record(AutomationStatus::Paused)]); |
| 756 | assert!(french.starts_with(tr(Locale::Fr, MessageId::AutomationListHeading).as_ref())); |
| 757 | assert!(french.contains(tr(Locale::Fr, MessageId::AutomationStatusPaused).as_ref())); |
| 758 | assert!(!french.starts_with(tr(Locale::En, MessageId::AutomationListHeading).as_ref())); |
| 759 | |
| 760 | for locale in Locale::shipped_complete() { |
| 761 | for id in [ |
| 762 | MessageId::AutomationManagerUnavailable, |
| 763 | MessageId::AutomationDeletePreview, |
| 764 | MessageId::AutomationReceiptDeleted, |
| 765 | MessageId::AutomationDeletedRunsDetail, |
| 766 | MessageId::AutomationReceiptStarted, |
| 767 | MessageId::AutomationRunLabel, |
| 768 | MessageId::AutomationBandScheduled, |
| 769 | ] { |
| 770 | assert_ne!(tr(*locale, id).as_ref(), format!("{id:?}"), "{locale:?}"); |
| 771 | } |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | /// #6162: a canceled run gets a receipt of its own — attention ink, the |
| 776 | /// `canceled` verb, and the cancellation reason leading the detail — so a |
| 777 | /// stopped run is never silent and never dressed as a crash. |
| 778 | #[test] |
| 779 | fn a_canceled_run_settles_with_a_canceled_receipt() { |
| 780 | let canceled = settled_run_receipt( |
| 781 | Locale::En, |
| 782 | &SettledRun { |
| 783 | automation_id: "auto_1".to_string(), |
| 784 | automation_name: "Documentation".to_string(), |
| 785 | run_id: "r-8f21deadbeef-0000".to_string(), |
| 786 | outcome: SettledOutcome::Canceled, |
| 787 | duration_ms: Some(3_000), |
| 788 | error: Some("canceled by request".to_string()), |
| 789 | }, |
| 790 | ); |
| 791 | let HistoryCell::Automation(cell) = canceled else { |
| 792 | panic!("a settled run is a typed Automation receipt"); |
| 793 | }; |
| 794 | assert_eq!(cell.kind, AutomationCellKind::Canceled); |
| 795 | assert_eq!( |
| 796 | cell.kind.chrome_ink(), |
| 797 | codewhale_palette::ChromeInk::Attention |
| 798 | ); |
| 799 | assert_eq!(cell.name, "Documentation"); |
| 800 | assert_eq!(cell.verb, "canceled"); |
| 801 | assert_eq!( |
| 802 | cell.detail.as_deref(), |
| 803 | Some("canceled by request · 3s · run r-8f21deadbe") |
| 804 | ); |
| 805 | } |
| 806 | |
| 807 | #[test] |
| 808 | fn settled_runs_become_completed_or_failed_receipts() { |
| 809 | let completed = settled_run_receipt( |
| 810 | Locale::En, |
| 811 | &SettledRun { |
| 812 | automation_id: "auto_1".to_string(), |
| 813 | automation_name: "Documentation".to_string(), |
| 814 | run_id: "r-8f19deadbeef-0000".to_string(), |
| 815 | outcome: SettledOutcome::Completed, |
| 816 | duration_ms: Some(42_000), |
| 817 | error: None, |
| 818 | }, |
| 819 | ); |
| 820 | let HistoryCell::Automation(cell) = completed else { |
| 821 | panic!("a settled run is a typed Automation receipt"); |
| 822 | }; |
| 823 | assert_eq!(cell.kind, AutomationCellKind::Completed); |
| 824 | assert_eq!(cell.name, "Documentation"); |
| 825 | assert_eq!(cell.verb, "completed in background"); |
| 826 | assert_eq!(cell.detail.as_deref(), Some("42s · run r-8f19deadbe")); |
| 827 | |
| 828 | let failed = settled_run_receipt( |
| 829 | Locale::En, |
| 830 | &SettledRun { |
| 831 | automation_id: "auto_1".to_string(), |
| 832 | automation_name: "Documentation".to_string(), |
| 833 | run_id: "r-8f20".to_string(), |
| 834 | outcome: SettledOutcome::Failed, |
| 835 | duration_ms: None, |
| 836 | error: Some( |
| 837 | "provider timeout\u{1b}[31m token=sk-abcdefghijklmnopqrstuvwxyz0123456789" |
| 838 | .to_string(), |
| 839 | ), |
| 840 | }, |
| 841 | ); |
| 842 | let HistoryCell::Automation(cell) = failed else { |
| 843 | panic!("a failed run is a typed Automation receipt"); |
| 844 | }; |
| 845 | assert_eq!(cell.kind, AutomationCellKind::Failed); |
| 846 | assert_eq!(cell.verb, "failed"); |
| 847 | let detail = cell.detail.expect("failure detail"); |
| 848 | assert!(detail.starts_with("provider timeout"), "{detail}"); |
| 849 | assert!(!detail.contains("\u{1b}"), "ANSI stripped: {detail}"); |
| 850 | assert!( |
| 851 | !detail.contains("abcdefghijklmnopqrstuvwxyz0123456789"), |
| 852 | "secrets redacted: {detail}" |
| 853 | ); |
| 854 | assert!(detail.ends_with("· run r-8f20"), "{detail}"); |
| 855 | } |
| 856 | |
| 857 | #[tokio::test] |
| 858 | async fn pause_and_resume_emit_typed_mutation_receipts() { |
| 859 | let temp = TempDir::new().expect("temp dir"); |
| 860 | let manager = AutomationManager::open_for_test(temp.path().to_path_buf()).expect("manager"); |
| 861 | let automation = manager |
| 862 | .create_automation(CreateAutomationRequest { |
| 863 | name: "Nightly checks".to_string(), |
| 864 | prompt: "Run checks".to_string(), |
| 865 | rrule: "FREQ=HOURLY;INTERVAL=1".to_string(), |
| 866 | cwds: Vec::new(), |
| 867 | model: None, |
| 868 | model_provider: None, |
| 869 | model_provider_id: None, |
| 870 | mode: None, |
| 871 | allow_shell: None, |
| 872 | trust_mode: None, |
| 873 | auto_approve: None, |
| 874 | delivery_mode: None, |
| 875 | status: Some(AutomationStatus::Active), |
| 876 | }) |
| 877 | .expect("automation"); |
| 878 | let manager = Arc::new(Mutex::new(manager)); |
| 879 | |
| 880 | let HistoryCell::Automation(paused) = |
| 881 | mutate(Locale::En, &manager, &automation.id, Mutation::Pause).await |
| 882 | else { |
| 883 | panic!("pause emits a typed Automation receipt"); |
| 884 | }; |
| 885 | assert_eq!(paused.kind, AutomationCellKind::Mutated); |
| 886 | assert_eq!(paused.verb, "paused"); |
| 887 | assert_eq!(paused.name, "Nightly checks"); |
| 888 | assert_eq!(paused.detail, None); |
| 889 | |
| 890 | let HistoryCell::Automation(resumed) = |
| 891 | mutate(Locale::En, &manager, &automation.id, Mutation::Resume).await |
| 892 | else { |
| 893 | panic!("resume emits a typed Automation receipt"); |
| 894 | }; |
| 895 | assert_eq!(resumed.verb, "resumed"); |
| 896 | |
| 897 | // A failed action keeps the System error path. |
| 898 | let HistoryCell::System { content } = |
| 899 | mutate(Locale::En, &manager, "missing", Mutation::Pause).await |
| 900 | else { |
| 901 | panic!("a failed mutation stays a System error"); |
| 902 | }; |
| 903 | assert!(content.contains("missing"), "{content}"); |
| 904 | } |
| 905 | |
| 906 | #[tokio::test] |
| 907 | async fn delete_is_a_noop_until_snapshot_confirmation_then_removes_definition_and_runs() { |
| 908 | let temp = TempDir::new().expect("temp dir"); |
| 909 | let manager = AutomationManager::open_for_test(temp.path().to_path_buf()).expect("manager"); |
| 910 | let automation = manager |
| 911 | .create_automation(CreateAutomationRequest { |
| 912 | name: "Nightly checks".to_string(), |
| 913 | prompt: "Run checks".to_string(), |
| 914 | rrule: "FREQ=HOURLY;INTERVAL=1".to_string(), |
| 915 | cwds: Vec::new(), |
| 916 | model: None, |
| 917 | model_provider: None, |
| 918 | model_provider_id: None, |
| 919 | mode: None, |
| 920 | allow_shell: None, |
| 921 | trust_mode: None, |
| 922 | auto_approve: None, |
| 923 | delivery_mode: None, |
| 924 | status: Some(AutomationStatus::Paused), |
| 925 | }) |
| 926 | .expect("automation"); |
| 927 | let now = Utc::now(); |
| 928 | let run = AutomationRunRecord { |
| 929 | schema_version: 1, |
| 930 | id: "run_1".to_string(), |
| 931 | automation_id: automation.id.clone(), |
| 932 | scheduled_for: now, |
| 933 | status: AutomationRunStatus::Completed, |
| 934 | created_at: now, |
| 935 | started_at: Some(now), |
| 936 | ended_at: Some(now), |
| 937 | task_id: Some("task_1".to_string()), |
| 938 | thread_id: None, |
| 939 | turn_id: None, |
| 940 | error: None, |
| 941 | dispatch: None, |
| 942 | }; |
| 943 | let runs_dir = temp.path().join("runs").join(&automation.id); |
| 944 | fs::create_dir_all(&runs_dir).expect("runs dir"); |
| 945 | fs::write( |
| 946 | runs_dir.join("run_1.json"), |
| 947 | serde_json::to_vec_pretty(&run).expect("serialize run"), |
| 948 | ) |
| 949 | .expect("write run"); |
| 950 | let manager = Arc::new(Mutex::new(manager)); |
| 951 | |
| 952 | let (HistoryCell::System { content: preview }, Some(command)) = |
| 953 | delete(Locale::En, &manager, &automation.id, None).await |
| 954 | else { |
| 955 | panic!("delete preview carries a separate confirmation command"); |
| 956 | }; |
| 957 | assert!(preview.contains("Nothing was deleted"), "{preview}"); |
| 958 | assert!(preview.contains("Recorded runs: 1"), "{preview}"); |
| 959 | assert!( |
| 960 | !preview.contains("--confirm"), |
| 961 | "the token stays in the control" |
| 962 | ); |
| 963 | assert!( |
| 964 | manager.lock().await.get_automation(&automation.id).is_ok(), |
| 965 | "preview must preserve the definition" |
| 966 | ); |
| 967 | assert_eq!( |
| 968 | manager |
| 969 | .lock() |
| 970 | .await |
| 971 | .list_runs(&automation.id, None) |
| 972 | .expect("runs after preview") |
| 973 | .len(), |
| 974 | 1, |
| 975 | "preview must preserve run history" |
| 976 | ); |
| 977 | |
| 978 | let (HistoryCell::System { content: stale }, None) = |
| 979 | delete(Locale::En, &manager, &automation.id, Some("wrong-receipt")).await |
| 980 | else { |
| 981 | panic!("stale confirmation stays a System text report"); |
| 982 | }; |
| 983 | assert!(stale.contains("no longer matches"), "{stale}"); |
| 984 | assert!( |
| 985 | manager.lock().await.get_automation(&automation.id).is_ok(), |
| 986 | "a mismatched receipt must not delete" |
| 987 | ); |
| 988 | |
| 989 | let token = command.split_whitespace().last().expect("reviewed token"); |
| 990 | manager |
| 991 | .lock() |
| 992 | .await |
| 993 | .resume_automation(&automation.id) |
| 994 | .unwrap(); |
| 995 | let (HistoryCell::System { content: changed }, None) = |
| 996 | delete(Locale::En, &manager, &automation.id, Some(token)).await |
| 997 | else { |
| 998 | panic!("changed definition refuses the old confirmation"); |
| 999 | }; |
| 1000 | assert!(changed.contains("no longer matches")); |
| 1001 | assert!(manager.lock().await.get_automation(&automation.id).is_ok()); |
| 1002 | let (_, Some(command)) = delete(Locale::En, &manager, &automation.id, None).await else { |
| 1003 | panic!("fresh review"); |
| 1004 | }; |
| 1005 | use crate::tui::views::{CommandPaletteAction, ModalView, ViewAction, ViewEvent}; |
| 1006 | use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; |
| 1007 | let mut pager = crate::tui::pager::PagerView::command_review( |
| 1008 | "Delete", |
| 1009 | &preview, |
| 1010 | 78, |
| 1011 | command.clone(), |
| 1012 | Locale::En, |
| 1013 | ); |
| 1014 | assert!(matches!( |
| 1015 | pager.handle_key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)), |
| 1016 | ViewAction::None |
| 1017 | )); |
| 1018 | let ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected { |
| 1019 | action: CommandPaletteAction::ExecuteCommand { command: confirmed }, |
| 1020 | }) = pager.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)) |
| 1021 | else { |
| 1022 | panic!("confirmed control dispatches the exact reviewed command"); |
| 1023 | }; |
| 1024 | assert_eq!(confirmed, command); |
| 1025 | let token = confirmed.split_whitespace().last().unwrap(); |
| 1026 | let (HistoryCell::Automation(deleted), None) = |
| 1027 | delete(Locale::En, &manager, &automation.id, Some(token)).await |
| 1028 | else { |
| 1029 | panic!("confirmed deletion is a typed Automation receipt"); |
| 1030 | }; |
| 1031 | assert_eq!(deleted.kind, AutomationCellKind::Mutated); |
| 1032 | assert_eq!(deleted.verb, "deleted"); |
| 1033 | assert_eq!(deleted.name, "Nightly checks"); |
| 1034 | assert!( |
| 1035 | deleted |
| 1036 | .detail |
| 1037 | .as_deref() |
| 1038 | .is_some_and(|detail| detail.contains('1')), |
| 1039 | "the run count rides the receipt detail: {deleted:?}" |
| 1040 | ); |
| 1041 | assert!( |
| 1042 | manager.lock().await.get_automation(&automation.id).is_err(), |
| 1043 | "confirmed deletion removes definition" |
| 1044 | ); |
| 1045 | assert!(!runs_dir.exists(), "confirmed deletion removes run history"); |
| 1046 | } |
| 1047 | } |
| 1048 |