返回 CodeWhale
automation.rs
根目录 / crates / tui / src / tui / history / automation.rs
1 //! Typed transcript receipt for durable scheduled automations
2 //! (AUTOMATION-VISIBILITY-SPEC §2.2).
3 //!
4 //! One-line bulleted card, mirroring kimi's `CronMessageComponent`:
5 //! `● {name} {verb}` plus an optional dim detail segment. Replaces the
6 //! bare-String `HistoryCell::System` receipts `automation_routing.rs` used to
7 //! emit, so the palette can color the event and the pager can navigate it.
8 //! Later slices add producers (engine fire/complete/coalesce/miss/expire
9 //! events); the kind vocabulary is the spec's full set.
10
11 use ratatui::style::{Modifier, Style};
12 use ratatui::text::{Line, Span};
13
14 use codewhale_localization::{Locale, MessageId, tr};
15 use codewhale_palette::ChromeInk;
16 use codewhale_tui_kit::glyphs;
17
18 /// What happened to the automation or its run. Drives the card's ink; the
19 /// visible verb phrase comes from the producer (localized at construction).
20 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
21 pub enum AutomationCellKind {
22 /// The schedule fired and a run was enqueued.
23 #[cfg(test)]
24 Fired,
25 /// A run started in the background.
26 Started,
27 /// A run completed in the background.
28 Completed,
29 /// A run genuinely crashed — the only kind that may wear Failure red.
30 Failed,
31 /// A run was canceled by the operator, a cancel timeout or shutdown
32 /// (#6162). Consequential enough to see, never a failure.
33 Canceled,
34 /// Missed slots collapsed into a single delivery.
35 #[cfg(test)]
36 Coalesced,
37 /// A scheduled run was missed while the app was down.
38 #[cfg(test)]
39 Missed,
40 /// An idle automation expired (paused, never deleted).
41 #[cfg(test)]
42 Expired,
43 /// The definition changed (pause / resume / delete).
44 Mutated,
45 }
46
47 impl AutomationCellKind {
48 /// Status-bar grammar ink (docs/design/STATUS_BAR_COLOR_GRAMMAR.md):
49 /// Fired/Started → Active, Completed → Outcome, Coalesced/Missed/Expired
50 /// → Attention ("consequential, needs your eye"), Mutated → Info. Only a
51 /// genuinely crashed run takes Failure — a failed report job is not a
52 /// product failure.
53 #[must_use]
54 pub const fn chrome_ink(self) -> ChromeInk {
55 match self {
56 #[cfg(test)]
57 Self::Fired => ChromeInk::Active,
58 Self::Started => ChromeInk::Active,
59 Self::Completed => ChromeInk::Outcome,
60 Self::Failed => ChromeInk::Failure,
61 #[cfg(test)]
62 Self::Coalesced | Self::Missed | Self::Expired => ChromeInk::Attention,
63 Self::Canceled => ChromeInk::Attention,
64 Self::Mutated => ChromeInk::Info,
65 }
66 }
67
68 /// Canonical verb phrase for run-lifecycle kinds. `Mutated` has none —
69 /// the producer supplies the concrete word (`paused` / `resumed` /
70 /// `deleted`) via [`AutomationCell::mutated`].
71 #[must_use]
72 pub fn canonical_verb(self, locale: Locale) -> Option<String> {
73 let id = match self {
74 #[cfg(test)]
75 Self::Fired => MessageId::AutomationReceiptFired,
76 Self::Started => MessageId::AutomationReceiptStarted,
77 Self::Completed => MessageId::AutomationReceiptCompleted,
78 Self::Failed => MessageId::AutomationRunStatusFailed,
79 Self::Canceled => MessageId::AutomationRunStatusCanceled,
80 #[cfg(test)]
81 Self::Coalesced => MessageId::AutomationReceiptCoalesced,
82 #[cfg(test)]
83 Self::Missed => MessageId::AutomationReceiptMissed,
84 #[cfg(test)]
85 Self::Expired => MessageId::AutomationReceiptExpired,
86 Self::Mutated => return None,
87 };
88 Some(tr(locale, id).into_owned())
89 }
90 }
91
92 /// One-line automation receipt card. `name`, `verb`, and `detail` arrive
93 /// display-safe (ANSI-stripped, secret-redacted) and localized; the renderer
94 /// only truncates.
95 #[derive(Debug, Clone, PartialEq, Eq)]
96 pub struct AutomationCell {
97 pub kind: AutomationCellKind,
98 pub name: String,
99 pub verb: String,
100 pub detail: Option<String>,
101 }
102
103 impl AutomationCell {
104 /// Receipt for a run-lifecycle event; the kind supplies the verb.
105 /// `Mutated` is not a run-lifecycle kind — use [`Self::mutated`].
106 #[must_use]
107 pub fn event(kind: AutomationCellKind, name: String, locale: Locale) -> Self {
108 debug_assert!(
109 !matches!(kind, AutomationCellKind::Mutated),
110 "Mutated receipts name their mutation; use AutomationCell::mutated"
111 );
112 Self {
113 kind,
114 name,
115 verb: kind.canonical_verb(locale).unwrap_or_default(),
116 detail: None,
117 }
118 }
119
120 /// Receipt for a definition change; `verb` is the concrete mutation word
121 /// (already localized by the producer).
122 #[must_use]
123 pub fn mutated(name: String, verb: String) -> Self {
124 Self {
125 kind: AutomationCellKind::Mutated,
126 name,
127 verb,
128 detail: None,
129 }
130 }
131
132 #[must_use]
133 pub fn with_detail(mut self, detail: Option<String>) -> Self {
134 self.detail = detail.filter(|detail| !detail.trim().is_empty());
135 self
136 }
137
138 /// Plain-text form for the pager/clipboard/inspection surfaces — the same
139 /// line the card paints, minus ink.
140 #[must_use]
141 pub fn plain_summary(&self) -> String {
142 let mut line = format!("{} {}", self.name, self.verb);
143 if let Some(detail) = &self.detail {
144 line.push_str(" ");
145 line.push_str(detail);
146 }
147 line.trim_end().to_string()
148 }
149
150 /// Render the one-line card at `width`. The card never wraps: the detail
151 /// segment sheds first, then the name/verb truncate.
152 pub(crate) fn render(&self, width: u16) -> Vec<Line<'static>> {
153 let color = self.kind.chrome_ink().color(&codewhale_palette::UI_THEME);
154 let bullet_width = 2usize; // `● ` — the charter's current marker + space
155 let budget = usize::from(width).saturating_sub(bullet_width);
156 let mut text = self.name.clone();
157 if !self.verb.is_empty() {
158 text.push(' ');
159 text.push_str(&self.verb);
160 }
161 let text = codewhale_localization::truncate_to_width(&text, budget);
162 let used = unicode_width::UnicodeWidthStr::width(text.as_str());
163 let detail = self.detail.as_deref().and_then(|detail| {
164 let remaining = budget.saturating_sub(used + 2);
165 (remaining > 0).then(|| codewhale_localization::truncate_to_width(detail, remaining))
166 });
167 let mut spans = vec![
168 Span::styled(
169 format!("{} ", glyphs::CURRENT),
170 Style::default().fg(color).add_modifier(Modifier::BOLD),
171 ),
172 Span::styled(text, Style::default().fg(color)),
173 ];
174 if let Some(detail) = detail {
175 spans.push(Span::styled(
176 format!(" {detail}"),
177 Style::default().fg(codewhale_palette::TEXT_DIM),
178 ));
179 }
180 vec![Line::from(spans)]
181 }
182 }
183
184 #[cfg(test)]
185 mod tests {
186 use super::*;
187 use crate::tui::golden_harness::{assert_matches_golden, render_golden_text};
188
189 fn cell_text(cell: &AutomationCell, width: u16) -> String {
190 cell.render(width)
191 .into_iter()
192 .map(|line| {
193 line.spans
194 .iter()
195 .map(|span| span.content.to_string())
196 .collect::<String>()
197 })
198 .collect::<Vec<_>>()
199 .join("\n")
200 }
201
202 #[test]
203 fn receipt_kinds_follow_the_color_grammar() {
204 assert_eq!(AutomationCellKind::Fired.chrome_ink(), ChromeInk::Active);
205 assert_eq!(AutomationCellKind::Started.chrome_ink(), ChromeInk::Active);
206 assert_eq!(
207 AutomationCellKind::Completed.chrome_ink(),
208 ChromeInk::Outcome
209 );
210 assert_eq!(AutomationCellKind::Failed.chrome_ink(), ChromeInk::Failure);
211 for kind in [
212 AutomationCellKind::Canceled,
213 AutomationCellKind::Coalesced,
214 AutomationCellKind::Missed,
215 AutomationCellKind::Expired,
216 ] {
217 assert_eq!(kind.chrome_ink(), ChromeInk::Attention, "{kind:?}");
218 }
219 assert_eq!(AutomationCellKind::Mutated.chrome_ink(), ChromeInk::Info);
220 }
221
222 /// The spec's reservation check (§6 Slice 1 accept): no automation
223 /// receipt ink resolves to the failure color in any selectable preset —
224 /// except `Failed`, which pins Failure deliberately and is reserved for a
225 /// genuinely crashed run, never a report job.
226 #[test]
227 fn no_automation_receipt_ink_spends_failure_red_but_the_crashed_run() {
228 for theme_id in codewhale_palette::SELECTABLE_THEMES {
229 let theme = theme_id.ui_theme();
230 for kind in [
231 AutomationCellKind::Fired,
232 AutomationCellKind::Started,
233 AutomationCellKind::Completed,
234 AutomationCellKind::Canceled,
235 AutomationCellKind::Coalesced,
236 AutomationCellKind::Missed,
237 AutomationCellKind::Expired,
238 AutomationCellKind::Mutated,
239 ] {
240 assert_ne!(
241 kind.chrome_ink().color(&theme),
242 theme.error_fg,
243 "theme '{}' spends Failure red on automation receipt {kind:?}",
244 theme_id.name()
245 );
246 }
247 }
248 }
249
250 #[test]
251 fn cards_are_one_line_and_shed_detail_before_the_name() {
252 let cell = AutomationCell::event(
253 AutomationCellKind::Fired,
254 "Release Manager".to_string(),
255 Locale::En,
256 )
257 .with_detail(Some("run r-8f21 · task t-9de".to_string()));
258 let full = cell_text(&cell, 80);
259 assert_eq!(full, "● Release Manager fired run r-8f21 · task t-9de");
260 let narrow = cell_text(&cell, 24);
261 assert!(
262 !narrow.contains("run r-8f21"),
263 "detail sheds first: {narrow}"
264 );
265 assert!(narrow.starts_with("● "), "{narrow}");
266 assert_eq!(narrow.lines().count(), 1, "the card never wraps");
267 }
268
269 /// Golden contract for the fired/completed cards (spec §6 Slice 1
270 /// accept), following `golden_harness.rs`. Re-bless with
271 /// `CODEWHALE_BLESS_GOLDENS=1`.
272 #[test]
273 fn receipt_cards_match_goldens() {
274 let fired = AutomationCell::event(
275 AutomationCellKind::Fired,
276 "Release Manager".to_string(),
277 Locale::En,
278 )
279 .with_detail(Some("run r-8f21 · task t-9de".to_string()));
280 let completed = AutomationCell::event(
281 AutomationCellKind::Completed,
282 "Documentation".to_string(),
283 Locale::En,
284 )
285 .with_detail(Some("42s · run r-8f19".to_string()));
286 let mutated =
287 AutomationCell::mutated("Market Intelligence".to_string(), "paused".to_string());
288 for (w, h) in [(80u16, 3u16), (40, 3)] {
289 let rendered = render_golden_text(w, h, |buf| {
290 for (y, cell) in [&fired, &completed, &mutated].into_iter().enumerate() {
291 for line in cell.render(w) {
292 buf.set_line(0, y as u16, &line, w);
293 }
294 }
295 });
296 assert_matches_golden(&format!("automation_receipts_{w}x{h}"), &rendered);
297 }
298 }
299 }
300
300 lines RUST