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