返回 CodeWhale
automations.rs
根目录 / crates / tui / src / tui / views / automations.rs
1 //! `/automation` — the scheduled-automation room.
2 //!
3 //! One list, one detail pane, one key grammar shared with the other rooms
4 //! (workflow runs, fleet, extensions): ↑↓ move, Enter opens the detail, Esc
5 //! backs out, Tab flips list ↔ detail. The actions an automation affords —
6 //! pause / resume, run now, cancel a live run, delete — are single keys and
7 //! every one of those actions goes through the same `/automation …` and `/task cancel`
8 //! commands the transcript already accepts, so a keypress here and a typed
9 //! command leave identical receipts.
10 //! Create/edit keep a local draft until Save calls the shared manager; Cancel
11 //! discards that draft. The room then shows the persisted definition and receipt.
12 //!
13 //! Automations are user-global (`~/.codewhale/automations`): they follow the
14 //! person into every repository, which is why the room says where each one
15 //! runs (`cwds`) rather than assuming this workspace.
16 //!
17 //! The view reads the shared [`AutomationManager`] with `try_lock`; a frame
18 //! that finds it busy keeps the last snapshot rather than blocking the UI.
19
20 use std::cell::Cell;
21 use std::time::{Duration, Instant};
22
23 use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
24 use ratatui::{
25 buffer::Buffer,
26 layout::{Constraint, Direction, Layout, Rect},
27 style::{Modifier, Style},
28 text::{Line, Span},
29 widgets::{Block, Clear, Paragraph, Widget, Wrap},
30 };
31
32 use super::{
33 ActionHint, CommandPaletteAction, ModalKind, ModalView, ViewAction, ViewEvent,
34 render_panel_scroll_rail,
35 };
36 use crate::tui::app::App;
37 use crate::tui::automation_panel::format_schedule_badge;
38 use crate::tui::views::rounded::{
39 pad_selected_line, render_hairline, render_rounded_footer, render_rounded_surface,
40 };
41 use codewhale_engine::automation_manager::{
42 AutomationExecutionOwnership, AutomationRecord, AutomationRunRecord, AutomationRunStatus,
43 AutomationStatus, SharedAutomationManager,
44 };
45 use codewhale_localization::{Locale, MessageId, tr};
46 use codewhale_palette as palette;
47 use codewhale_tui_kit::list_nav::wrap_index;
48 use codewhale_tui_kit::menu_style;
49 use unicode_width::UnicodeWidthStr;
50
51 mod editor;
52 use editor::{AutomationEditor, EditorAction};
53
54 /// Recent runs kept per automation in the detail pane.
55 const RECENT_RUNS: usize = 5;
56
57 /// One automation with the runs the detail pane and the cancel key need.
58 #[derive(Debug, Clone)]
59 pub(crate) struct AutomationRow {
60 pub(crate) record: AutomationRecord,
61 pub(crate) execution_ownership: Option<AutomationExecutionOwnership>,
62 /// Newest first.
63 pub(crate) runs: Vec<AutomationRunRecord>,
64 /// The run history could not be read. Painted instead of "no recorded
65 /// runs", which would claim an empty history nobody observed.
66 pub(crate) runs_error: Option<String>,
67 }
68
69 impl AutomationRow {
70 /// The run in flight, if any — the one `x` cancels.
71 fn live_run(&self) -> Option<&AutomationRunRecord> {
72 self.runs.iter().find(|run| {
73 matches!(
74 run.status,
75 AutomationRunStatus::Queued | AutomationRunStatus::Running
76 )
77 })
78 }
79 }
80
81 pub struct AutomationsView {
82 rows: Vec<AutomationRow>,
83 row: usize,
84 detail_open: bool,
85 detail_scroll: usize,
86 /// Largest useful detail scroll in rendered (wrapped) rows, from the last
87 /// paint; ↓ stops there instead of piling up invisible scroll.
88 detail_max_scroll: Cell<usize>,
89 locale: Locale,
90 manager: Option<SharedAutomationManager>,
91 /// Refreshes ride the modal tick, not every frame.
92 last_refresh_at: Instant,
93 /// A snapshot that could not be read: the manager is missing or its
94 /// store failed. Painted in place of the list.
95 problem: Option<String>,
96 /// Screen rect of the list body, recorded at render for mouse parity.
97 list_body: Cell<Rect>,
98 config: codewhale_runtime::config::Config,
99 workspace: std::path::PathBuf,
100 editor: Option<AutomationEditor>,
101 notice: Option<String>,
102 new_button: Cell<Rect>,
103 edit_button: Cell<Rect>,
104 }
105
106 impl AutomationsView {
107 /// Open the room, optionally focused on one automation id.
108 #[must_use]
109 pub fn new(app: &App, config: &codewhale_runtime::config::Config, focus: Option<&str>) -> Self {
110 let mut view = Self {
111 rows: Vec::new(),
112 row: 0,
113 detail_open: false,
114 detail_scroll: 0,
115 detail_max_scroll: Cell::new(usize::MAX),
116 locale: app.ui_locale,
117 manager: app.runtime_services.automations.clone(),
118 last_refresh_at: Instant::now(),
119 problem: None,
120 list_body: Cell::new(Rect::ZERO),
121 config: config.clone(),
122 workspace: app.workspace.clone(),
123 editor: None,
124 notice: None,
125 new_button: Cell::new(Rect::ZERO),
126 edit_button: Cell::new(Rect::ZERO),
127 };
128 view.refresh();
129 if let Some(focus) = focus
130 && let Some(index) = view.rows.iter().position(|row| row.record.id == focus)
131 {
132 view.row = index;
133 view.detail_open = true;
134 }
135 view
136 }
137
138 #[cfg(test)]
139 pub(crate) fn from_rows(rows: Vec<AutomationRow>, locale: Locale) -> Self {
140 Self {
141 rows,
142 row: 0,
143 detail_open: false,
144 detail_scroll: 0,
145 detail_max_scroll: Cell::new(usize::MAX),
146 locale,
147 manager: None,
148 last_refresh_at: Instant::now(),
149 problem: None,
150 list_body: Cell::new(Rect::ZERO),
151 config: codewhale_runtime::config::Config::default(),
152 workspace: std::env::temp_dir(),
153 editor: None,
154 notice: None,
155 new_button: Cell::new(Rect::ZERO),
156 edit_button: Cell::new(Rect::ZERO),
157 }
158 }
159
160 fn open_editor(&mut self, edit: bool) {
161 let original = if edit {
162 let Some(row) = self.selected() else {
163 return;
164 };
165 Some(row.record.clone())
166 } else {
167 None
168 };
169 self.notice = None;
170 self.editor = Some(AutomationEditor::new(
171 &self.config,
172 &self.workspace,
173 self.locale,
174 original,
175 ));
176 }
177
178 fn editor_action(&mut self, action: EditorAction) -> ViewAction {
179 match action {
180 EditorAction::Cancel => self.editor = None,
181 EditorAction::Save => {
182 let result = self
183 .manager
184 .as_ref()
185 .ok_or_else(|| {
186 tr(self.locale, MessageId::AutomationManagerUnavailable).into_owned()
187 })
188 .and_then(|manager| {
189 manager.try_lock().map_err(|_| {
190 tr(self.locale, MessageId::AutomationEditorBusy).into_owned()
191 })
192 })
193 .and_then(|manager| {
194 self.editor
195 .as_ref()
196 .unwrap()
197 .save(&manager)
198 .map_err(|error| error.to_string())
199 });
200 match result {
201 Ok(record) => {
202 self.editor = None;
203 self.refresh();
204 if let Some(index) =
205 self.rows.iter().position(|row| row.record.id == record.id)
206 {
207 self.row = index;
208 }
209 self.detail_open = true;
210 self.detail_scroll = 0;
211 self.notice = Some(
212 tr(self.locale, MessageId::AutomationEditorSaved)
213 .replace("{name}", &display_text(&record.name)),
214 );
215 }
216 Err(error) => {
217 self.editor.as_mut().unwrap().problem = Some(
218 tr(self.locale, MessageId::AutomationEditorSaveFailed)
219 .replace("{error}", &error),
220 )
221 }
222 }
223 }
224 EditorAction::None => {}
225 }
226 ViewAction::None
227 }
228
229 /// Re-read definitions and recent runs, keeping the selected id when the
230 /// list reorders. A busy manager keeps the previous snapshot.
231 fn refresh(&mut self) {
232 self.last_refresh_at = Instant::now();
233 let Some(manager) = self.manager.as_ref() else {
234 self.problem =
235 Some(tr(self.locale, MessageId::AutomationManagerUnavailable).into_owned());
236 return;
237 };
238 let Ok(manager) = manager.try_lock() else {
239 return;
240 };
241 let records = match manager.list_automation_views() {
242 Ok(records) => records,
243 Err(error) => {
244 self.problem = Some(
245 tr(self.locale, MessageId::AutomationListFailed)
246 .replace("{error}", &error.to_string()),
247 );
248 return;
249 }
250 };
251 let rows = records
252 .into_iter()
253 .map(|view| {
254 let (runs, runs_error) = match manager.list_runs(&view.record.id, Some(RECENT_RUNS))
255 {
256 Ok(runs) => (runs, None),
257 Err(error) => (Vec::new(), Some(error.to_string())),
258 };
259 AutomationRow {
260 record: view.record,
261 execution_ownership: Some(view.execution_ownership),
262 runs,
263 runs_error,
264 }
265 })
266 .collect();
267 drop(manager);
268 self.apply_rows(rows);
269 }
270
271 fn apply_rows(&mut self, rows: Vec<AutomationRow>) {
272 let selected_id = self.selected().map(|row| row.record.id.clone());
273 self.rows = rows;
274 self.problem = None;
275 let preserved = selected_id
276 .as_deref()
277 .and_then(|id| self.rows.iter().position(|row| row.record.id == id));
278 if let Some(index) = preserved {
279 self.row = index;
280 } else {
281 self.row = self.row.min(self.rows.len().saturating_sub(1));
282 self.detail_scroll = 0;
283 }
284 if self.rows.is_empty() {
285 self.detail_open = false;
286 self.detail_scroll = 0;
287 }
288 }
289
290 fn selected(&self) -> Option<&AutomationRow> {
291 self.rows.get(self.row)
292 }
293
294 pub(crate) fn show_action_receipt(&mut self, receipt: String) {
295 self.notice = Some(receipt);
296 self.refresh();
297 }
298
299 fn move_row(&mut self, delta: isize) {
300 if self.rows.is_empty() {
301 return;
302 }
303 self.row = wrap_index(self.row, self.rows.len(), delta);
304 self.detail_scroll = 0;
305 }
306
307 /// Every mutation is the typed command, so the receipt in the transcript
308 /// is the same one `/automation …` leaves; the next tick re-reads.
309 fn command(command: String) -> ViewAction {
310 ViewAction::Emit(ViewEvent::CommandPaletteSelected {
311 action: CommandPaletteAction::ExecuteCommand { command },
312 })
313 }
314
315 fn toggle_pause(&self) -> ViewAction {
316 let Some(row) = self.selected() else {
317 return ViewAction::None;
318 };
319 let verb = match row.record.status {
320 AutomationStatus::Active => "pause",
321 AutomationStatus::Paused => "resume",
322 };
323 Self::command(format!("/automation {verb} {}", row.record.id))
324 }
325
326 fn run_now(&self) -> ViewAction {
327 match self.selected() {
328 Some(row) => Self::command(format!("/automation run {}", row.record.id)),
329 None => ViewAction::None,
330 }
331 }
332
333 fn adopt(&self) -> ViewAction {
334 match self.selected() {
335 Some(row) => Self::command(format!("/automation adopt {}", row.record.id)),
336 None => ViewAction::None,
337 }
338 }
339
340 /// Cancel the live run: an automation run is a durable task, so the
341 /// task's own cancel is the one path.
342 fn cancel_live_run(&self) -> ViewAction {
343 match self
344 .selected()
345 .and_then(AutomationRow::live_run)
346 .and_then(|run| run.task_id.as_deref())
347 {
348 Some(task_id) => Self::command(format!("/task cancel {task_id}")),
349 None => ViewAction::None,
350 }
351 }
352
353 /// Delete opens the shared review control with the exact snapshot token.
354 fn delete(&self) -> ViewAction {
355 match self.selected() {
356 Some(row) => Self::command(format!("/automation delete {}", row.record.id)),
357 None => ViewAction::None,
358 }
359 }
360
361 fn footer_hints(&self) -> Vec<ActionHint> {
362 let locale = self.locale;
363 let mut hints = vec![ActionHint::new("↑↓", tr(locale, MessageId::LaunchHintMove))];
364 if self.detail_open {
365 hints.push(ActionHint::new(
366 "Tab",
367 tr(locale, MessageId::AutomationListHeading),
368 ));
369 } else {
370 hints.push(ActionHint::new(
371 "Enter",
372 tr(locale, MessageId::AutomationActionInspect),
373 ));
374 }
375 if let Some(row) = self.selected() {
376 hints.push(ActionHint::new(
377 "p",
378 match row.record.status {
379 AutomationStatus::Active => tr(locale, MessageId::AutomationActionPause),
380 AutomationStatus::Paused => tr(locale, MessageId::AutomationActionResume),
381 },
382 ));
383 hints.push(ActionHint::new(
384 "r",
385 tr(locale, MessageId::AutomationActionRun),
386 ));
387 if matches!(
388 row.execution_ownership,
389 Some(
390 AutomationExecutionOwnership::OtherRuntime
391 | AutomationExecutionOwnership::Unbound
392 )
393 ) {
394 hints.push(ActionHint::new(
395 "a",
396 tr(locale, MessageId::AutomationActionAdopt),
397 ));
398 }
399 if row.live_run().is_some() {
400 hints.push(ActionHint::new(
401 "x",
402 tr(locale, MessageId::AutomationActionCancel),
403 ));
404 }
405 hints.push(ActionHint::new(
406 "d",
407 tr(locale, MessageId::AutomationActionDelete),
408 ));
409 }
410 hints.push(ActionHint::new(
411 "Esc",
412 tr(locale, MessageId::SessionsActionClose),
413 ));
414 hints
415 }
416
417 fn summary_meta(&self) -> String {
418 let active = self
419 .rows
420 .iter()
421 .filter(|row| {
422 row.record.status == AutomationStatus::Active
423 && row
424 .execution_ownership
425 .is_none_or(|ownership| ownership == AutomationExecutionOwnership::Owned)
426 })
427 .count();
428 let live = self
429 .rows
430 .iter()
431 .filter(|row| row.live_run().is_some())
432 .count();
433 format!(
434 "{active} {} · {live} {}",
435 tr(self.locale, MessageId::AutomationStatusActive),
436 tr(self.locale, MessageId::AutomationRunStatusRunning)
437 )
438 }
439
440 fn header_lines(&self) -> Vec<Line<'static>> {
441 let mut lines = vec![Line::from(Span::styled(
442 tr(self.locale, MessageId::AutomationScopeNote).into_owned(),
443 Style::default().fg(palette::TEXT_MUTED),
444 ))];
445 if let Some(notice) = self.notice.as_deref().filter(|n| !n.is_empty()) {
446 lines.push(Line::from(Span::styled(
447 notice.to_string(),
448 Style::default()
449 .fg(palette::WHALE_ACTION)
450 .add_modifier(Modifier::BOLD),
451 )));
452 }
453 lines
454 }
455
456 fn render_list(&self, area: Rect, buf: &mut Buffer) {
457 self.list_body.set(area);
458 if area.is_empty() {
459 return;
460 }
461 if let Some(problem) = self.problem.as_deref() {
462 Paragraph::new(Line::from(Span::styled(
463 problem.to_string(),
464 Style::default().fg(palette::STATUS_ERROR),
465 )))
466 .wrap(Wrap { trim: false })
467 .render(area, buf);
468 return;
469 }
470 if self.rows.is_empty() {
471 Paragraph::new(Line::from(Span::styled(
472 tr(self.locale, MessageId::AutomationEmpty).into_owned(),
473 Style::default().fg(palette::TEXT_MUTED),
474 )))
475 .wrap(Wrap { trim: false })
476 .render(area, buf);
477 return;
478 }
479 let rows_visible = usize::from(area.height).max(1);
480 let scroll = self.row.saturating_sub(rows_visible.saturating_sub(1));
481 let list_area =
482 render_panel_scroll_rail(area, buf, self.rows.len(), scroll, rows_visible, true);
483 self.list_body.set(list_area);
484 let ascii = crate::tui::color_compat::ascii_safe_enabled();
485 let sep = if ascii { " | " } else { " · " };
486 let width = usize::from(list_area.width);
487 for (idx, row) in self.rows.iter().enumerate().skip(scroll).take(rows_visible) {
488 let y = list_area.y + u16::try_from(idx - scroll).unwrap_or(u16::MAX);
489 let selected = idx == self.row;
490 let (mark, mark_color) = match (row.live_run(), row.record.status) {
491 (Some(_), _) => (if ascii { "*" } else { "●" }, palette::STATUS_WARNING),
492 (None, AutomationStatus::Active) => {
493 (if ascii { "o" } else { "○" }, palette::STATUS_SUCCESS)
494 }
495 (None, AutomationStatus::Paused) => {
496 (if ascii { "=" } else { "‖" }, palette::TEXT_MUTED)
497 }
498 };
499 let state = match (row.live_run(), row.record.status) {
500 (Some(_), _) => tr(self.locale, MessageId::AutomationRunStatusRunning),
501 (None, AutomationStatus::Active) => {
502 tr(self.locale, MessageId::AutomationStatusActive)
503 }
504 (None, AutomationStatus::Paused) => {
505 tr(self.locale, MessageId::AutomationStatusPaused)
506 }
507 };
508 let name = display_text(&row.record.name);
509 let schedule = format_schedule_badge(&row.record.rrule, self.locale);
510 let next_label = tr(self.locale, MessageId::AutomationNextLabel);
511 let next_run = self.next_run_text(row);
512 let pointer = codewhale_tui_kit::glyphs::selection_marker(selected);
513 let unowned_active = row.record.status == AutomationStatus::Active
514 && row
515 .execution_ownership
516 .is_some_and(|ownership| ownership != AutomationExecutionOwnership::Owned);
517
518 let with_schedule = format!(
519 "{pointer} {mark} {name}{sep}{state}{sep}{schedule}{sep}{next_label}: {next_run}"
520 );
521 let include_schedule = with_schedule.width() <= width;
522
523 let line = if selected {
524 let raw = if include_schedule {
525 with_schedule
526 } else {
527 format!("{pointer} {mark} {name}{sep}{state}{sep}{next_label}: {next_run}")
528 };
529 let clipped = codewhale_tui_kit::ui_text::truncate_line_to_width(&raw, width);
530 let sel_style = menu_style::selected_row_style();
531 pad_selected_line(
532 Line::from(Span::styled(clipped, sel_style)),
533 width,
534 sel_style,
535 )
536 } else {
537 let sep_style = Style::default().fg(palette::BORDER_COLOR);
538 let mut spans = vec![
539 Span::styled(
540 format!("{pointer} "),
541 Style::default().fg(palette::TEXT_MUTED),
542 ),
543 Span::styled(
544 format!("{mark} "),
545 Style::default()
546 .fg(mark_color)
547 .add_modifier(if row.live_run().is_some() {
548 Modifier::BOLD
549 } else {
550 Modifier::empty()
551 }),
552 ),
553 Span::styled(
554 name,
555 Style::default()
556 .fg(if row.record.status == AutomationStatus::Paused {
557 palette::TEXT_MUTED
558 } else {
559 palette::TEXT_PRIMARY
560 })
561 .add_modifier(if row.live_run().is_some() {
562 Modifier::BOLD
563 } else {
564 Modifier::empty()
565 }),
566 ),
567 Span::styled(sep, sep_style),
568 Span::styled(state.into_owned(), Style::default().fg(mark_color)),
569 ];
570 if include_schedule {
571 spans.push(Span::styled(sep, sep_style));
572 spans.push(Span::styled(
573 schedule,
574 Style::default().fg(palette::TEXT_SOFT),
575 ));
576 }
577 spans.push(Span::styled(sep, sep_style));
578 spans.push(Span::styled(
579 format!("{next_label}: "),
580 Style::default().fg(palette::TEXT_MUTED),
581 ));
582 spans.push(Span::styled(
583 next_run,
584 Style::default().fg(if unowned_active {
585 palette::STATUS_WARNING
586 } else {
587 palette::TEXT_MUTED
588 }),
589 ));
590 Line::from(spans)
591 };
592 Paragraph::new(line).render(Rect::new(list_area.x, y, list_area.width, 1), buf);
593 }
594 }
595
596 fn detail_lines(&self, row: &AutomationRow) -> Vec<Line<'static>> {
597 let locale = self.locale;
598 let ascii = crate::tui::color_compat::ascii_safe_enabled();
599 let rule = if ascii { "-" } else { "─" };
600 let sep = if ascii { " | " } else { " · " };
601 let label = |id: MessageId| {
602 Span::styled(
603 format!("{:<12} ", tr(locale, id)),
604 Style::default().fg(palette::TEXT_MUTED).bold(),
605 )
606 };
607 let value = |text: String| Span::styled(text, Style::default().fg(palette::TEXT_PRIMARY));
608 let record = &row.record;
609 let (status_glyph, status_color, status_text) = match (row.live_run(), record.status) {
610 (Some(_), _) => (
611 if ascii { "*" } else { "●" },
612 palette::STATUS_WARNING,
613 tr(locale, MessageId::AutomationRunStatusRunning),
614 ),
615 (None, AutomationStatus::Active) => (
616 if ascii { "o" } else { "○" },
617 palette::STATUS_SUCCESS,
618 tr(locale, MessageId::AutomationStatusActive),
619 ),
620 (None, AutomationStatus::Paused) => (
621 if ascii { "=" } else { "‖" },
622 palette::TEXT_MUTED,
623 tr(locale, MessageId::AutomationStatusPaused),
624 ),
625 };
626 let mut lines = vec![
627 Line::from(vec![
628 Span::styled(
629 format!("{status_glyph} "),
630 Style::default().fg(status_color).bold(),
631 ),
632 Span::styled(
633 display_text(&record.name),
634 Style::default().fg(palette::TEXT_PRIMARY).bold(),
635 ),
636 Span::styled(sep, Style::default().fg(palette::BORDER_COLOR)),
637 Span::styled(
638 status_text.into_owned(),
639 Style::default().fg(status_color).bold(),
640 ),
641 Span::styled(sep, Style::default().fg(palette::BORDER_COLOR)),
642 Span::styled(
643 format_schedule_badge(&record.rrule, self.locale),
644 Style::default().fg(palette::TEXT_SOFT),
645 ),
646 ]),
647 Line::from(Span::styled(
648 record.id.clone(),
649 Style::default().fg(palette::TEXT_MUTED),
650 )),
651 Line::from(Span::styled(
652 rule.repeat(36),
653 Style::default().fg(palette::BORDER_COLOR),
654 )),
655 Line::from(vec![
656 label(MessageId::AutomationRruleLabel),
657 value(record.rrule.clone()),
658 ]),
659 Line::from(vec![
660 label(MessageId::AutomationNextLabel),
661 value(self.next_run_text(row)),
662 ]),
663 ];
664 if let Some(reason) = record.elevated_pause_reason() {
665 lines.insert(
666 2,
667 Line::from(Span::styled(
668 reason,
669 Style::default().fg(palette::STATUS_WARNING),
670 )),
671 );
672 }
673 if !record.cwds.is_empty() {
674 lines.push(Line::from(vec![
675 label(MessageId::AutomationCwdLabel),
676 value(
677 record
678 .cwds
679 .iter()
680 .map(|cwd| cwd.display().to_string())
681 .collect::<Vec<_>>()
682 .join(", "),
683 ),
684 ]));
685 }
686 if let Some(model) = record.model.as_deref() {
687 lines.push(Line::from(vec![
688 label(MessageId::SetupCardModelLabel),
689 value(
690 record
691 .model_provider_id
692 .as_ref()
693 .or(record.model_provider.as_ref())
694 .map_or_else(
695 || model.to_string(),
696 |provider| format!("{provider} / {model}"),
697 ),
698 ),
699 ]));
700 }
701 lines.push(Line::from(""));
702 lines.push(Line::from(Span::styled(
703 tr(locale, MessageId::AutomationPromptLabel).into_owned(),
704 Style::default().fg(palette::WHALE_ACTION).bold(),
705 )));
706 for line in display_text(&record.prompt).lines().take(12) {
707 lines.push(Line::from(Span::styled(
708 format!(" {line}"),
709 Style::default().fg(palette::TEXT_SOFT),
710 )));
711 }
712 lines.push(Line::from(""));
713 lines.push(Line::from(Span::styled(
714 tr(locale, MessageId::AutomationRecentRunsLabel).into_owned(),
715 Style::default().fg(palette::WHALE_ACTION).bold(),
716 )));
717 if let Some(error) = row.runs_error.as_deref() {
718 lines.push(Line::from(Span::styled(
719 format!(
720 " {}{sep}{}",
721 tr(locale, MessageId::AutomationRunsUnavailable),
722 display_text(error)
723 ),
724 Style::default().fg(palette::STATUS_ERROR),
725 )));
726 } else if row.runs.is_empty() {
727 lines.push(Line::from(Span::styled(
728 format!(" {}", tr(locale, MessageId::AutomationNoRuns)),
729 Style::default().fg(palette::TEXT_MUTED),
730 )));
731 }
732 for run in &row.runs {
733 let (glyph, style) = match run.status {
734 AutomationRunStatus::Queued | AutomationRunStatus::Running => (
735 if ascii { "*" } else { "●" },
736 Style::default().fg(palette::STATUS_WARNING).bold(),
737 ),
738 AutomationRunStatus::Completed => (
739 if ascii { "+" } else { "✓" },
740 Style::default().fg(palette::STATUS_SUCCESS),
741 ),
742 AutomationRunStatus::Failed => (
743 if ascii { "x" } else { "✗" },
744 Style::default().fg(palette::STATUS_ERROR).bold(),
745 ),
746 AutomationRunStatus::Canceled => (
747 if ascii { "-" } else { "–" },
748 Style::default().fg(palette::TEXT_MUTED),
749 ),
750 };
751 let mut spans = vec![
752 Span::styled(format!(" {glyph} "), style),
753 Span::styled(
754 run.scheduled_for.format("%Y-%m-%d %H:%M UTC").to_string(),
755 Style::default().fg(palette::TEXT_PRIMARY),
756 ),
757 ];
758 if let Some(task) = run.task_id.as_deref() {
759 spans.push(Span::styled(
760 format!("{sep}{} {task}", tr(locale, MessageId::AutomationTaskLabel)),
761 Style::default().fg(palette::TEXT_MUTED),
762 ));
763 }
764 if let Some(error) = run.error.as_deref() {
765 spans.push(Span::styled(
766 format!("{sep}{error}"),
767 Style::default().fg(palette::STATUS_ERROR),
768 ));
769 }
770 lines.push(Line::from(spans));
771 }
772 lines
773 }
774
775 fn render_detail(&self, area: Rect, buf: &mut Buffer) {
776 let Some(row) = self.selected() else {
777 self.render_list(area, buf);
778 return;
779 };
780 let lines = self.detail_lines(row);
781 self.detail_max_scroll.set(super::render_wrapped_detail(
782 lines,
783 area,
784 buf,
785 self.detail_scroll,
786 ));
787 }
788 fn next_run_text(&self, row: &AutomationRow) -> String {
789 if row.record.status == AutomationStatus::Active
790 && let Some(ownership) = row.execution_ownership
791 && ownership != AutomationExecutionOwnership::Owned
792 {
793 let id = match ownership {
794 AutomationExecutionOwnership::OtherRuntime => {
795 MessageId::AutomationNotScheduledOtherRuntime
796 }
797 AutomationExecutionOwnership::Unbound => MessageId::AutomationNotScheduledUnbound,
798 AutomationExecutionOwnership::HostUnattached => {
799 MessageId::AutomationNotScheduledUnattached
800 }
801 AutomationExecutionOwnership::Owned => {
802 return next_run_label(row.record.next_run_at);
803 }
804 };
805 return tr(self.locale, id).into_owned();
806 }
807 next_run_label(row.record.next_run_at)
808 }
809 }
810
811 fn next_run_label(value: Option<chrono::DateTime<chrono::Utc>>) -> String {
812 value.map_or_else(
813 || "-".to_string(),
814 |at| at.format("%Y-%m-%d %H:%M UTC").to_string(),
815 )
816 }
817
818 /// Stored names and prompts are untrusted text: one line, no control
819 /// characters, so a name cannot reflow the room.
820 fn display_text(value: &str) -> String {
821 value
822 .chars()
823 .map(|ch| {
824 if ch.is_control() && ch != '\n' {
825 ' '
826 } else {
827 ch
828 }
829 })
830 .collect::<String>()
831 .trim()
832 .to_string()
833 }
834
835 impl ModalView for AutomationsView {
836 fn kind(&self) -> ModalKind {
837 ModalKind::Automations
838 }
839
840 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
841 self
842 }
843
844 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
845 if let Some(editor) = self.editor.as_mut() {
846 let action = editor.key(key);
847 return self.editor_action(action);
848 }
849 match key.code {
850 KeyCode::Char('n') => {
851 self.open_editor(false);
852 ViewAction::None
853 }
854 KeyCode::Char('e') => {
855 self.open_editor(true);
856 ViewAction::None
857 }
858 KeyCode::Esc => {
859 if self.detail_open {
860 self.detail_open = false;
861 self.detail_scroll = 0;
862 ViewAction::None
863 } else {
864 ViewAction::Close
865 }
866 }
867 KeyCode::Char('q') => ViewAction::Close,
868 KeyCode::Up | KeyCode::Char('k') => {
869 if self.detail_open {
870 self.detail_scroll = self.detail_scroll.saturating_sub(1);
871 } else {
872 self.move_row(-1);
873 }
874 ViewAction::None
875 }
876 KeyCode::Down | KeyCode::Char('j') => {
877 if self.detail_open {
878 self.detail_scroll = self
879 .detail_scroll
880 .saturating_add(1)
881 .min(self.detail_max_scroll.get());
882 } else {
883 self.move_row(1);
884 }
885 ViewAction::None
886 }
887 KeyCode::Enter | KeyCode::Right | KeyCode::Char('l') => {
888 if !self.rows.is_empty() {
889 self.detail_open = true;
890 }
891 ViewAction::None
892 }
893 KeyCode::Left | KeyCode::Char('h') => {
894 self.detail_open = false;
895 self.detail_scroll = 0;
896 ViewAction::None
897 }
898 KeyCode::Tab | KeyCode::BackTab => {
899 if !self.rows.is_empty() {
900 self.detail_open = !self.detail_open;
901 self.detail_scroll = 0;
902 }
903 ViewAction::None
904 }
905 KeyCode::Char('p') | KeyCode::Char(' ') => self.toggle_pause(),
906 KeyCode::Char('r') => self.run_now(),
907 KeyCode::Char('a') => self.adopt(),
908 KeyCode::Char('x') | KeyCode::Char('c') => self.cancel_live_run(),
909 KeyCode::Char('d') => self.delete(),
910 _ => ViewAction::None,
911 }
912 }
913
914 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
915 if let Some(editor) = self.editor.as_mut() {
916 let action = editor.mouse(mouse);
917 return self.editor_action(action);
918 }
919 // The wheel moves this list, not the transcript behind it.
920 match mouse.kind {
921 MouseEventKind::ScrollUp => {
922 if self.detail_open {
923 self.detail_scroll = self.detail_scroll.saturating_sub(1);
924 } else {
925 self.move_row(-1);
926 }
927 return ViewAction::None;
928 }
929 MouseEventKind::ScrollDown => {
930 if self.detail_open {
931 self.detail_scroll = self
932 .detail_scroll
933 .saturating_add(1)
934 .min(self.detail_max_scroll.get());
935 } else {
936 self.move_row(1);
937 }
938 return ViewAction::None;
939 }
940 _ => {}
941 }
942 if mouse.kind == MouseEventKind::Down(MouseButton::Left) {
943 let point = (mouse.column, mouse.row).into();
944 if self.new_button.get().contains(point) {
945 self.open_editor(false);
946 return ViewAction::None;
947 }
948 if self.edit_button.get().contains(point) {
949 self.open_editor(true);
950 return ViewAction::None;
951 }
952 }
953 if self.detail_open {
954 return ViewAction::None;
955 }
956 if let MouseEventKind::Down(MouseButton::Left) = mouse.kind {
957 let body = self.list_body.get();
958 if body.width > 0 && body.contains((mouse.column, mouse.row).into()) {
959 let offset = usize::from(mouse.row - body.y);
960 let scroll = self
961 .row
962 .saturating_sub(usize::from(body.height).saturating_sub(1));
963 let idx = scroll + offset;
964 if idx < self.rows.len() {
965 if self.row == idx {
966 self.detail_open = true;
967 }
968 self.row = idx;
969 }
970 }
971 }
972 ViewAction::None
973 }
974
975 fn handle_paste(&mut self, text: &str) -> bool {
976 if let Some(editor) = self.editor.as_mut() {
977 editor.paste(text);
978 return true;
979 }
980 false
981 }
982
983 fn tick(&mut self) -> ViewAction {
984 let interval = if self.rows.iter().any(|row| row.live_run().is_some()) {
985 Duration::from_millis(500)
986 } else {
987 Duration::from_secs(2)
988 };
989 if self.last_refresh_at.elapsed() >= interval {
990 self.refresh();
991 }
992 ViewAction::None
993 }
994
995 fn render(&self, area: Rect, buf: &mut Buffer) {
996 let area = area.intersection(buf.area);
997 self.new_button.set(Rect::ZERO);
998 self.edit_button.set(Rect::ZERO);
999 self.list_body.set(Rect::ZERO);
1000 if let Some(editor) = &self.editor {
1001 Clear.render(area, buf);
1002 Block::default()
1003 .style(
1004 Style::default()
1005 .fg(palette::TEXT_PRIMARY)
1006 .bg(palette::COMPOSER_BG),
1007 )
1008 .render(area, buf);
1009 editor.render(area, buf);
1010 return;
1011 }
1012 let surface = render_rounded_surface(
1013 area,
1014 buf,
1015 tr(self.locale, MessageId::AutomationListHeading),
1016 Some(self.summary_meta()),
1017 self.rows.iter().any(|row| row.live_run().is_some()),
1018 );
1019 let hints = self.footer_hints();
1020 let content = render_rounded_footer(surface, buf, &hints);
1021 let header = Paragraph::new(self.header_lines()).wrap(Wrap { trim: false });
1022 let header_rows = u16::try_from(header.line_count(content.width))
1023 .unwrap_or(u16::MAX)
1024 .min(content.height.saturating_sub(2));
1025 let show_divider = content.height >= header_rows.saturating_add(4);
1026 let header_height = header_rows
1027 .saturating_add(1)
1028 .saturating_add(u16::from(show_divider));
1029 let chunks = Layout::default()
1030 .direction(Direction::Vertical)
1031 .constraints([Constraint::Length(header_height), Constraint::Min(1)])
1032 .split(content);
1033 let header_area = Rect::new(chunks[0].x, chunks[0].y, chunks[0].width, header_rows)
1034 .intersection(chunks[0]);
1035 header.render(header_area, buf);
1036 let button_y = header_area.bottom();
1037 let mut x = chunks[0].x;
1038 for (key, label, hit) in [
1039 ("n", MessageId::AutomationEditorNew, &self.new_button),
1040 ("e", MessageId::AutomationEditorEdit, &self.edit_button),
1041 ] {
1042 if key == "e" && self.selected().is_none() {
1043 continue;
1044 }
1045 let text = format!("[{key} {}]", tr(self.locale, label));
1046 let width = u16::try_from(codewhale_tui_kit::ui_text::text_display_width(&text))
1047 .unwrap_or(u16::MAX)
1048 .min(chunks[0].right().saturating_sub(x));
1049 let rect = Rect::new(x, button_y, width, 1).intersection(chunks[0]);
1050 Paragraph::new(Line::from(vec![
1051 Span::styled(
1052 format!("[{key} "),
1053 Style::default()
1054 .fg(palette::WHALE_ACTION)
1055 .bg(palette::SURFACE_ELEVATED)
1056 .add_modifier(Modifier::BOLD),
1057 ),
1058 Span::styled(
1059 format!("{}]", tr(self.locale, label)),
1060 Style::default()
1061 .fg(palette::TEXT_PRIMARY)
1062 .bg(palette::SURFACE_ELEVATED),
1063 ),
1064 ]))
1065 .render(rect, buf);
1066 hit.set(rect);
1067 x = x.saturating_add(width).saturating_add(1);
1068 }
1069 if show_divider {
1070 render_hairline(
1071 Rect::new(chunks[0].x, button_y.saturating_add(1), chunks[0].width, 1),
1072 buf,
1073 palette::BORDER_COLOR,
1074 palette::COMPOSER_BG,
1075 );
1076 }
1077 if self.detail_open {
1078 self.render_detail(chunks[1], buf);
1079 } else {
1080 self.render_list(chunks[1], buf);
1081 }
1082 }
1083 }
1084
1085 #[cfg(test)]
1086 mod tests {
1087 use super::*;
1088 use chrono::{TimeZone, Utc};
1089 use crossterm::event::KeyModifiers;
1090
1091 fn record(id: &str, status: AutomationStatus) -> AutomationRecord {
1092 let at = Utc.with_ymd_and_hms(2026, 9, 4, 17, 0, 0).unwrap();
1093 AutomationRecord {
1094 destination_thread_id: None,
1095 schema_version: 1,
1096 execution_scope: Some(codewhale_engine::task_manager::test_execution_scope("test")),
1097 id: id.to_string(),
1098 name: format!("cwc daily {id}"),
1099 prompt: "patrol".to_string(),
1100 rrule: "FREQ=DAILY;BYHOUR=17".to_string(),
1101 cwds: vec![std::path::PathBuf::from("/tmp/cwc")],
1102 model: None,
1103 model_provider: None,
1104 model_provider_id: None,
1105 mode: None,
1106 allow_shell: None,
1107 trust_mode: None,
1108 auto_approve: None,
1109 delivery_mode: None,
1110 status,
1111 created_at: at,
1112 updated_at: at,
1113 next_run_at: Some(at),
1114 last_run_at: None,
1115 revision: 0,
1116 disallowed_tools: Vec::new(),
1117 }
1118 }
1119
1120 fn run(automation_id: &str, status: AutomationRunStatus) -> AutomationRunRecord {
1121 let at = Utc.with_ymd_and_hms(2026, 9, 3, 17, 0, 0).unwrap();
1122 AutomationRunRecord {
1123 schema_version: 1,
1124 id: format!("run-{automation_id}"),
1125 automation_id: automation_id.to_string(),
1126 scheduled_for: at,
1127 status,
1128 created_at: at,
1129 started_at: Some(at),
1130 ended_at: None,
1131 task_id: Some(format!("task-{automation_id}")),
1132 thread_id: None,
1133 turn_id: None,
1134 error: None,
1135 dispatch: None,
1136 }
1137 }
1138
1139 fn view() -> AutomationsView {
1140 AutomationsView::from_rows(
1141 vec![
1142 AutomationRow {
1143 record: record("vision", AutomationStatus::Active),
1144 execution_ownership: None,
1145 runs: vec![run("vision", AutomationRunStatus::Running)],
1146 runs_error: None,
1147 },
1148 AutomationRow {
1149 record: record("infra", AutomationStatus::Paused),
1150 execution_ownership: None,
1151 runs: Vec::new(),
1152 runs_error: None,
1153 },
1154 ],
1155 Locale::En,
1156 )
1157 }
1158
1159 fn key(code: KeyCode) -> KeyEvent {
1160 KeyEvent::new(code, KeyModifiers::NONE)
1161 }
1162
1163 fn command_of(action: ViewAction) -> String {
1164 match action {
1165 ViewAction::Emit(ViewEvent::CommandPaletteSelected {
1166 action: CommandPaletteAction::ExecuteCommand { command },
1167 }) => command,
1168 other => panic!("expected a command, got {other:?}"),
1169 }
1170 }
1171
1172 #[test]
1173 fn every_affordance_is_the_typed_command() {
1174 let mut view = view();
1175 assert_eq!(
1176 command_of(view.handle_key(key(KeyCode::Char('p')))),
1177 "/automation pause vision"
1178 );
1179 assert_eq!(
1180 command_of(view.handle_key(key(KeyCode::Char('r')))),
1181 "/automation run vision"
1182 );
1183 assert_eq!(
1184 command_of(view.handle_key(key(KeyCode::Char('x')))),
1185 "/task cancel task-vision"
1186 );
1187 assert_eq!(
1188 command_of(view.handle_key(key(KeyCode::Char('d')))),
1189 "/automation delete vision"
1190 );
1191
1192 view.handle_key(key(KeyCode::Down));
1193 assert_eq!(
1194 command_of(view.handle_key(key(KeyCode::Char('p')))),
1195 "/automation resume infra"
1196 );
1197 // Nothing live to cancel on the paused row.
1198 assert!(matches!(
1199 view.handle_key(key(KeyCode::Char('x'))),
1200 ViewAction::None
1201 ));
1202 }
1203
1204 #[test]
1205 fn tab_flips_list_and_detail_and_esc_backs_out() {
1206 let mut view = view();
1207 assert!(!view.detail_open);
1208 view.handle_key(key(KeyCode::Tab));
1209 assert!(view.detail_open);
1210 assert!(matches!(
1211 view.handle_key(key(KeyCode::Esc)),
1212 ViewAction::None
1213 ));
1214 assert!(!view.detail_open);
1215 assert!(matches!(
1216 view.handle_key(key(KeyCode::Esc)),
1217 ViewAction::Close
1218 ));
1219 }
1220
1221 #[test]
1222 fn editor_save_and_cancel_require_explicit_room_actions() {
1223 let _env = crate::test_support::lock_test_env();
1224 let root = tempfile::tempdir().unwrap();
1225 let manager = std::sync::Arc::new(tokio::sync::Mutex::new(
1226 codewhale_engine::automation_manager::AutomationManager::open_for_test(
1227 root.path().join("store"),
1228 )
1229 .unwrap(),
1230 ));
1231 let mut view = AutomationsView::from_rows(Vec::new(), Locale::En);
1232 view.workspace = root.path().to_path_buf();
1233 view.manager = Some(manager.clone());
1234 view.handle_key(key(KeyCode::Char('n')));
1235 assert!(view.handle_paste("draft"));
1236 view.handle_key(key(KeyCode::Tab));
1237 view.handle_paste("line one\nline two");
1238 assert!(
1239 manager
1240 .try_lock()
1241 .unwrap()
1242 .list_automations()
1243 .unwrap()
1244 .is_empty()
1245 );
1246 let area = Rect::new(0, 0, 40, 12);
1247 let mut buffer = Buffer::empty(area);
1248 view.render(area, &mut buffer);
1249 let cancel = MouseEvent {
1250 kind: MouseEventKind::Down(MouseButton::Left),
1251 column: 17,
1252 row: 11,
1253 modifiers: KeyModifiers::NONE,
1254 };
1255 view.handle_mouse(cancel);
1256 assert!(view.editor.is_none());
1257 assert!(
1258 manager
1259 .try_lock()
1260 .unwrap()
1261 .list_automations()
1262 .unwrap()
1263 .is_empty()
1264 );
1265
1266 view.handle_key(key(KeyCode::Char('n')));
1267 view.handle_paste("saved");
1268 view.handle_key(key(KeyCode::Tab));
1269 view.handle_paste("prompt");
1270 view.render(area, &mut buffer);
1271 view.handle_mouse(MouseEvent {
1272 column: 2,
1273 ..cancel
1274 });
1275 assert!(view.editor.is_none());
1276 assert_eq!(
1277 manager
1278 .try_lock()
1279 .unwrap()
1280 .list_automations()
1281 .unwrap()
1282 .len(),
1283 1
1284 );
1285 view.render(area, &mut buffer);
1286 let receipt = rendered_text(area, &buffer);
1287 assert!(
1288 receipt.contains("Saved saved"),
1289 "compact receipt: {receipt}"
1290 );
1291 }
1292
1293 fn rendered_text(area: Rect, buffer: &Buffer) -> String {
1294 (0..area.height)
1295 .map(|y| {
1296 (0..area.width)
1297 .map(|x| buffer[(x, y)].symbol())
1298 .collect::<String>()
1299 })
1300 .collect::<Vec<_>>()
1301 .join("\n")
1302 }
1303
1304 #[test]
1305 fn refused_action_stays_visible_in_list_and_detail_after_refresh() {
1306 for (locale, receipt) in [
1307 (
1308 Locale::En,
1309 "Could not run automation: Automation belongs to another Runtime execution scope",
1310 ),
1311 (
1312 Locale::ZhHans,
1313 "无法运行此自动化:它属于另一会话,请返回原会话后重试。",
1314 ),
1315 ] {
1316 for width in [40, 80, 120] {
1317 for detail in [false, true] {
1318 let mut view = view();
1319 view.locale = locale;
1320 view.detail_open = detail;
1321 view.show_action_receipt(receipt.to_string());
1322 view.refresh();
1323 let area = Rect::new(0, 0, width, 20);
1324 let mut buffer = Buffer::empty(area);
1325 view.render(area, &mut buffer);
1326 let text = rendered_text(area, &buffer);
1327 let compact = |s: &str| {
1328 s.chars()
1329 .filter(|c| !c.is_whitespace() && *c != '│')
1330 .collect::<String>()
1331 };
1332 assert!(
1333 compact(&text).contains(&compact(receipt)),
1334 "{locale:?}/{width}/{detail}: {text}"
1335 );
1336 assert!(!view.new_button.get().is_empty(), "New remains accessible");
1337 assert_eq!(view.rows.len(), 2, "feedback preserves definitions");
1338 }
1339 }
1340 }
1341 }
1342
1343 #[test]
1344 fn long_receipts_keep_content_and_controls_inside_the_modal() {
1345 let _env = crate::test_support::lock_test_env();
1346 for (width, height) in [(40, 12), (60, 16), (80, 24), (100, 32), (140, 40)] {
1347 for locale in [Locale::En, Locale::ZhHans] {
1348 for detail in [false, true] {
1349 let area = Rect::new(3, 2, width, height);
1350 let canvas = Rect::new(0, 0, width + 6, height + 4);
1351 let mut view = view();
1352 view.locale = locale;
1353 view.detail_open = detail;
1354 view.show_action_receipt("Long action receipt 自动化操作结果 ".repeat(100));
1355 let mut expected = Buffer::empty(canvas);
1356 let surface = render_rounded_surface(
1357 area,
1358 &mut expected,
1359 tr(locale, MessageId::AutomationListHeading),
1360 Some(view.summary_meta()),
1361 true,
1362 );
1363 let content =
1364 render_rounded_footer(surface, &mut expected, &view.footer_hints());
1365 let mut actual = Buffer::empty(canvas);
1366 view.render(area, &mut actual);
1367 for y in canvas.y..canvas.bottom() {
1368 for x in canvas.x..canvas.right() {
1369 if !content.contains((x, y).into()) {
1370 assert_eq!(
1371 actual[(x, y)],
1372 expected[(x, y)],
1373 "{area:?}/{locale:?}/{detail} at {x},{y}"
1374 );
1375 }
1376 }
1377 }
1378 for (code, button) in
1379 [('n', view.new_button.get()), ('e', view.edit_button.get())]
1380 {
1381 assert!(!button.is_empty(), "{area:?}/{locale:?}/{detail}");
1382 assert_eq!(button.intersection(content), button);
1383 assert_eq!(actual[(button.x, button.y)].symbol(), "[");
1384 view.handle_mouse(MouseEvent {
1385 kind: MouseEventKind::Down(MouseButton::Left),
1386 column: button.x,
1387 row: button.y,
1388 modifiers: KeyModifiers::NONE,
1389 });
1390 assert!(view.editor.is_some());
1391 view.handle_key(key(KeyCode::Esc));
1392 assert!(view.editor.is_none());
1393 view.handle_key(key(KeyCode::Char(code)));
1394 assert!(view.editor.is_some());
1395 view.handle_key(key(KeyCode::Esc));
1396 assert!(view.editor.is_none());
1397 }
1398 }
1399 }
1400 }
1401 }
1402
1403 #[test]
1404 fn renders_state_next_run_and_the_live_cancel_hint() {
1405 let view = view();
1406 let area = Rect::new(0, 0, 100, 16);
1407 let mut buf = Buffer::empty(area);
1408 view.render(area, &mut buf);
1409 let text = (0..area.height)
1410 .map(|y| {
1411 (0..area.width)
1412 .map(|x| buf[(x, y)].symbol())
1413 .collect::<String>()
1414 })
1415 .collect::<Vec<_>>()
1416 .join("\n");
1417 assert!(text.contains("cwc daily vision"), "{text}");
1418 assert!(text.contains("running"), "{text}");
1419 assert!(text.contains("2026-09-04 17:00 UTC"), "{text}");
1420 assert!(text.contains("x cancel"), "{text}");
1421 assert!(text.contains("p pause"), "{text}");
1422 assert!(text.contains("follow you into every repository"), "{text}");
1423 }
1424
1425 /// U09-m3: a run history that could not be read is reported as such,
1426 /// never painted as "no recorded runs".
1427 #[test]
1428 fn unreadable_run_history_is_not_shown_as_empty() {
1429 let view = AutomationsView::from_rows(
1430 vec![AutomationRow {
1431 record: record("vision", AutomationStatus::Active),
1432 execution_ownership: None,
1433 runs: Vec::new(),
1434 runs_error: Some("run store unreadable".to_string()),
1435 }],
1436 Locale::En,
1437 );
1438 let text = view
1439 .detail_lines(&view.rows[0])
1440 .iter()
1441 .map(|line| {
1442 line.spans
1443 .iter()
1444 .map(|span| span.content.as_ref())
1445 .collect::<String>()
1446 })
1447 .collect::<Vec<_>>()
1448 .join("\n");
1449 assert!(text.contains("runs unavailable"), "{text}");
1450 assert!(text.contains("run store unreadable"), "{text}");
1451 assert!(!text.contains("no recorded runs"), "{text}");
1452 }
1453
1454 #[test]
1455 fn detail_states_why_an_elevated_automation_is_paused() {
1456 let mut elevated = record("elevated", AutomationStatus::Paused);
1457 elevated.allow_shell = Some(true);
1458 let view = AutomationsView::from_rows(
1459 vec![
1460 AutomationRow {
1461 record: elevated,
1462 execution_ownership: None,
1463 runs: Vec::new(),
1464 runs_error: None,
1465 },
1466 AutomationRow {
1467 record: record("plain", AutomationStatus::Paused),
1468 execution_ownership: None,
1469 runs: Vec::new(),
1470 runs_error: None,
1471 },
1472 ],
1473 Locale::En,
1474 );
1475 let text_of = |row: &AutomationRow| {
1476 view.detail_lines(row)
1477 .iter()
1478 .map(|line| {
1479 line.spans
1480 .iter()
1481 .map(|span| span.content.as_ref())
1482 .collect::<String>()
1483 })
1484 .collect::<Vec<_>>()
1485 .join("\n")
1486 };
1487 assert!(
1488 text_of(&view.rows[0]).contains("Remove those settings, then resume it."),
1489 "{}",
1490 text_of(&view.rows[0])
1491 );
1492 assert!(!text_of(&view.rows[1]).contains("Full Access"));
1493 }
1494
1495 /// U09-m6: detail scroll counts wrapped rows, so a long prompt's tail is
1496 /// reachable and ↓ stops at the real end instead of piling up scroll.
1497 #[test]
1498 fn detail_scroll_reaches_the_wrapped_tail() {
1499 let mut long = record("long", AutomationStatus::Active);
1500 long.prompt = format!("{}TAILMARK", "word ".repeat(80));
1501 let mut view = AutomationsView::from_rows(
1502 vec![AutomationRow {
1503 record: long,
1504 execution_ownership: None,
1505 runs: Vec::new(),
1506 runs_error: None,
1507 }],
1508 Locale::En,
1509 );
1510 view.detail_open = true;
1511 let area = Rect::new(0, 0, 30, 8);
1512 let mut buf = Buffer::empty(area);
1513 view.render_detail(area, &mut buf);
1514 for _ in 0..200 {
1515 view.handle_key(key(KeyCode::Down));
1516 }
1517 assert_eq!(view.detail_scroll, view.detail_max_scroll.get());
1518 let mut buf = Buffer::empty(area);
1519 view.render_detail(area, &mut buf);
1520 let text = rendered_text(area, &buf);
1521 assert!(text.contains("TAILMARK"), "{text}");
1522 }
1523
1524 #[test]
1525 fn mouse_wheel_in_detail_scrolls_detail_without_switching_rows() {
1526 let mut long = record("long", AutomationStatus::Active);
1527 long.prompt = format!("{}TAILMARK", "word ".repeat(80));
1528 let mut view = AutomationsView::from_rows(
1529 vec![
1530 AutomationRow {
1531 record: long,
1532 execution_ownership: None,
1533 runs: Vec::new(),
1534 runs_error: None,
1535 },
1536 AutomationRow {
1537 record: record("second", AutomationStatus::Active),
1538 execution_ownership: None,
1539 runs: Vec::new(),
1540 runs_error: None,
1541 },
1542 ],
1543 Locale::En,
1544 );
1545 view.detail_open = true;
1546 let area = Rect::new(0, 0, 30, 8);
1547 let mut buf = Buffer::empty(area);
1548 view.render_detail(area, &mut buf);
1549
1550 let wheel = |kind| MouseEvent {
1551 kind,
1552 column: 1,
1553 row: 1,
1554 modifiers: crossterm::event::KeyModifiers::NONE,
1555 };
1556 for _ in 0..200 {
1557 view.handle_mouse(wheel(MouseEventKind::ScrollDown));
1558 }
1559 assert_eq!(view.row, 0);
1560 assert_eq!(view.detail_scroll, view.detail_max_scroll.get());
1561 view.handle_mouse(wheel(MouseEventKind::ScrollUp));
1562 assert_eq!(view.row, 0);
1563 assert_eq!(
1564 view.detail_scroll,
1565 view.detail_max_scroll.get().saturating_sub(1)
1566 );
1567 }
1568
1569 #[test]
1570 fn refresh_clears_stale_detail_state_when_rows_change_or_empty() {
1571 let mut view = AutomationsView::from_rows(
1572 vec![
1573 AutomationRow {
1574 record: record("first", AutomationStatus::Active),
1575 execution_ownership: None,
1576 runs: Vec::new(),
1577 runs_error: None,
1578 },
1579 AutomationRow {
1580 record: record("second", AutomationStatus::Active),
1581 execution_ownership: None,
1582 runs: Vec::new(),
1583 runs_error: None,
1584 },
1585 ],
1586 Locale::En,
1587 );
1588 view.detail_open = true;
1589 view.detail_scroll = 5;
1590
1591 view.apply_rows(vec![AutomationRow {
1592 record: record("second", AutomationStatus::Active),
1593 execution_ownership: None,
1594 runs: Vec::new(),
1595 runs_error: None,
1596 }]);
1597 assert!(view.detail_open);
1598 assert_eq!(view.row, 0);
1599 assert_eq!(view.detail_scroll, 0);
1600
1601 view.detail_scroll = 3;
1602 view.apply_rows(Vec::new());
1603 assert!(!view.detail_open);
1604 assert_eq!(view.detail_scroll, 0);
1605 }
1606 }
1607
1607 lines RUST