返回 CodeWhale
approval.rs
1 //! Package Approval: the approval card and the review verdict.
2 //!
3 //! This is what a person reads before letting an agent run a command or change
4 //! files, so it follows a few rules that nothing else in the kit needs:
5 //!
6 //! - **The subject is verbatim.** The command or target is never elided in the
7 //! middle. It wraps; if the card cannot show all of it, the card says how many
8 //! characters and lines are not shown and offers the binding that reveals
9 //! them, and [`ApprovalPaint`] tells the caller so it can refuse a blind
10 //! approval.
11 //! - **What is shown is what will run.** Every control character, escape
12 //! sequence, bidi override, zero-width or otherwise invisible character is
13 //! drawn as a named token (`‹ESC›`, `‹RLO›`, `‹ZWJ›`, `‹LF›`, `‹HT›`), styled
14 //! reversed and bold so it cannot be mistaken for text. Leading and trailing
15 //! spaces are drawn too (`‹SP×3›`). A literal `‹` that could be mistaken for
16 //! the start of a token is itself drawn as a token (`‹U+2039›`), so the
17 //! display decodes to exactly one subject. [`visible_text`] is that encoding.
18 //! - **Nothing is decided by color, and nothing is preselected.** "Outside this
19 //! project" and elevation carry a mark and words. The choices come from the
20 //! caller with their key chords; the card never invents one, and the default
21 //! focus is the first choice that does not grant anything.
22 //! - **Displayed chords are handled chords.** [`ApprovalState`] owns the
23 //! choices, so the keys the card advertises are the keys `handle_key`
24 //! accepts.
25 //!
26 //! The host owns policy and input guards. A key that arrives before the card
27 //! was drawn should not count; [`ApprovalState::unarmed`] and
28 //! [`ApprovalState::arm`] are the hooks for that.
29
30 use std::borrow::Cow;
31
32 use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
33 use ratatui::{
34 buffer::Buffer,
35 layout::Rect,
36 style::{Modifier, Style},
37 text::{Line, Span},
38 };
39 use unicode_segmentation::UnicodeSegmentation;
40 use unicode_width::UnicodeWidthChar;
41
42 use crate::{
43 Depth, KeyHint, KeyHints, Paint, Panel, Role, State, StateWords, Theme, glyphs,
44 keys::{self, Platform},
45 text,
46 };
47
48 // ---------------------------------------------------------------------------
49 // Words
50 // ---------------------------------------------------------------------------
51
52 /// A phrase with a singular and a plural form. `{n}` is replaced by the count.
53 #[derive(Clone, Debug, PartialEq, Eq)]
54 pub struct ApprovalCountWords {
55 pub one: Cow<'static, str>,
56 pub many: Cow<'static, str>,
57 }
58
59 impl ApprovalCountWords {
60 #[must_use]
61 pub fn new(one: impl Into<Cow<'static, str>>, many: impl Into<Cow<'static, str>>) -> Self {
62 Self {
63 one: one.into(),
64 many: many.into(),
65 }
66 }
67
68 /// The phrase for `n`.
69 #[must_use]
70 pub fn render(&self, n: usize) -> String {
71 let phrase = if n == 1 { &self.one } else { &self.many };
72 phrase.replace("{n}", &n.to_string())
73 }
74 }
75
76 /// The words of the "not shown" notice, shared by the card and the verdict.
77 #[derive(Clone, Debug, PartialEq, Eq)]
78 pub struct ApprovalClipWords {
79 pub hidden_chars: ApprovalCountWords,
80 pub hidden_lines: ApprovalCountWords,
81 pub hidden_preview: ApprovalCountWords,
82 pub hidden_details: ApprovalCountWords,
83 pub hidden_choices: ApprovalCountWords,
84 /// Verb beside the reveal binding: `o show all`.
85 pub reveal: Cow<'static, str>,
86 /// Shown for a subject with no characters.
87 pub empty: Cow<'static, str>,
88 }
89
90 impl Default for ApprovalClipWords {
91 fn default() -> Self {
92 Self {
93 hidden_chars: ApprovalCountWords::new(
94 "{n} character not shown",
95 "{n} characters not shown",
96 ),
97 hidden_lines: ApprovalCountWords::new("{n} line", "{n} lines"),
98 hidden_preview: ApprovalCountWords::new(
99 "{n} preview line not shown",
100 "{n} preview lines not shown",
101 ),
102 hidden_details: ApprovalCountWords::new(
103 "{n} detail line not shown",
104 "{n} detail lines not shown",
105 ),
106 hidden_choices: ApprovalCountWords::new(
107 "{n} choice not shown",
108 "{n} choices not shown",
109 ),
110 reveal: "show all".into(),
111 empty: "(empty)".into(),
112 }
113 }
114 }
115
116 /// Every word the approval card shows. The kit owns no copy beyond this
117 /// English default: a host fills one per locale and passes it in.
118 #[derive(Clone, Debug, PartialEq, Eq)]
119 pub struct ApprovalWords {
120 pub needs_you: Cow<'static, str>,
121 pub command: Cow<'static, str>,
122 pub file_change: Cow<'static, str>,
123 pub network: Cow<'static, str>,
124 pub tool_call: Cow<'static, str>,
125 pub elevation: Cow<'static, str>,
126 /// `In /path/to/dir`
127 pub in_dir: Cow<'static, str>,
128 pub inside: Cow<'static, str>,
129 pub outside: Cow<'static, str>,
130 pub unchecked: Cow<'static, str>,
131 pub elevated: Cow<'static, str>,
132 pub requested_by: Cow<'static, str>,
133 pub sub_agent: Cow<'static, str>,
134 pub risk: Cow<'static, str>,
135 pub preview: Cow<'static, str>,
136 pub non_ascii: ApprovalCountWords,
137 /// Key-hint verbs for the rail under the card.
138 pub move_focus: Cow<'static, str>,
139 pub choose_focused: Cow<'static, str>,
140 pub cancel: Cow<'static, str>,
141 pub clip: ApprovalClipWords,
142 }
143
144 impl Default for ApprovalWords {
145 fn default() -> Self {
146 Self {
147 needs_you: Cow::Borrowed(StateWords::english(State::NeedsYou)),
148 command: "Run a command".into(),
149 file_change: "Change files".into(),
150 network: "Use the network".into(),
151 tool_call: "Call a tool".into(),
152 elevation: "Raise access".into(),
153 in_dir: "In".into(),
154 inside: "Inside this project".into(),
155 outside: "Outside this project".into(),
156 unchecked: "Not checked against the project".into(),
157 elevated: "Runs with elevated access".into(),
158 requested_by: "Requested by".into(),
159 sub_agent: "sub-agent".into(),
160 risk: "Risk".into(),
161 preview: "Preview".into(),
162 non_ascii: ApprovalCountWords::new(
163 "Contains {n} non-ASCII character: check it",
164 "Contains {n} non-ASCII characters: check them",
165 ),
166 move_focus: "move".into(),
167 choose_focused: "choose".into(),
168 cancel: "cancel".into(),
169 clip: ApprovalClipWords::default(),
170 }
171 }
172 }
173
174 impl ApprovalWords {
175 fn kind(&self, kind: ApprovalKind) -> &str {
176 match kind {
177 ApprovalKind::Command => &self.command,
178 ApprovalKind::FileChange => &self.file_change,
179 ApprovalKind::Network => &self.network,
180 ApprovalKind::ToolCall => &self.tool_call,
181 ApprovalKind::Elevation => &self.elevation,
182 }
183 }
184 }
185
186 // ---------------------------------------------------------------------------
187 // The subject
188 // ---------------------------------------------------------------------------
189
190 /// What the agent wants to do.
191 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
192 pub enum ApprovalKind {
193 /// Run a shell command.
194 Command,
195 /// Write or patch files.
196 FileChange,
197 /// Reach the network.
198 Network,
199 /// Call a tool or connected app.
200 ToolCall,
201 /// Run with more access than the sandbox gives.
202 Elevation,
203 }
204
205 /// Where the action lands relative to the project. Never assumed: the default
206 /// is [`ApprovalScope::Unchecked`].
207 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
208 pub enum ApprovalScope {
209 Inside,
210 Outside,
211 #[default]
212 Unchecked,
213 }
214
215 /// The agent that is asking.
216 #[derive(Clone, Debug, PartialEq, Eq)]
217 pub struct ApprovalAgent<'a> {
218 pub name: Cow<'a, str>,
219 pub sub_agent: bool,
220 }
221
222 /// Plain data the caller fills. Every string may come from a model or a file:
223 /// the card draws all of it through [`visible_text`].
224 #[derive(Clone, Debug, PartialEq, Eq)]
225 pub struct ApprovalSubject<'a> {
226 pub kind: ApprovalKind,
227 /// The exact command, path, URL or tool call.
228 pub target: Cow<'a, str>,
229 pub cwd: Option<Cow<'a, str>>,
230 /// Optional target file or directory path affected by this approval.
231 pub path: Option<Cow<'a, str>>,
232 pub scope: ApprovalScope,
233 pub agent: Option<ApprovalAgent<'a>>,
234 /// Risk notes the caller supplies, one per row.
235 pub risk_notes: Vec<Cow<'a, str>>,
236 /// A patch or file preview, one line per entry.
237 pub preview: Vec<Cow<'a, str>>,
238 }
239
240 impl<'a> ApprovalSubject<'a> {
241 #[must_use]
242 pub fn new(kind: ApprovalKind, target: impl Into<Cow<'a, str>>) -> Self {
243 Self {
244 kind,
245 target: target.into(),
246 cwd: None,
247 path: None,
248 scope: ApprovalScope::Unchecked,
249 agent: None,
250 risk_notes: Vec::new(),
251 preview: Vec::new(),
252 }
253 }
254
255 #[must_use]
256 pub fn cwd(mut self, cwd: impl Into<Cow<'a, str>>) -> Self {
257 self.cwd = Some(cwd.into());
258 self
259 }
260
261 /// Attach the file or directory path affected by this approval.
262 ///
263 /// Used as the fallback subject when [`Self::target`] is empty, and shown
264 /// in the details section when both are present.
265 #[must_use]
266 pub fn path(mut self, path: impl Into<Cow<'a, str>>) -> Self {
267 self.path = Some(path.into());
268 self
269 }
270
271 #[must_use]
272 pub fn scope(mut self, scope: ApprovalScope) -> Self {
273 self.scope = scope;
274 self
275 }
276
277 #[must_use]
278 pub fn agent(mut self, name: impl Into<Cow<'a, str>>, sub_agent: bool) -> Self {
279 self.agent = Some(ApprovalAgent {
280 name: name.into(),
281 sub_agent,
282 });
283 self
284 }
285
286 #[must_use]
287 pub fn risk_note(mut self, note: impl Into<Cow<'a, str>>) -> Self {
288 self.risk_notes.push(note.into());
289 self
290 }
291
292 #[must_use]
293 pub fn preview_line(mut self, line: impl Into<Cow<'a, str>>) -> Self {
294 self.preview.push(line.into());
295 self
296 }
297 }
298
299 // ---------------------------------------------------------------------------
300 // Visible text: the one encoding of "what will run"
301 // ---------------------------------------------------------------------------
302
303 /// How tokens are spelled. Unicode terminals get `‹ESC›`; ASCII-safe ones
304 /// get `<ESC>` (the glyph charter's own fallback for the guillemets).
305 #[derive(Clone, Copy)]
306 struct Marks {
307 open: &'static str,
308 close: &'static str,
309 times: &'static str,
310 }
311
312 impl Marks {
313 fn new(ascii: bool) -> Self {
314 Self {
315 open: glyphs::pick("‹", ascii),
316 close: glyphs::pick("›", ascii),
317 times: if ascii { "x" } else { "×" },
318 }
319 }
320
321 fn token(self, name: &str) -> String {
322 format!("{}{name}{}", self.open, self.close)
323 }
324
325 fn spaces(self, n: usize) -> String {
326 if n == 1 {
327 self.token("SP")
328 } else {
329 self.token(&format!("SP{}{n}", self.times))
330 }
331 }
332
333 /// Whether `rest` (the source after an opener) would read as the rest of
334 /// a token: name characters, then the closer. Such an opener is itself
335 /// drawn as a token, which keeps the encoding one-to-one.
336 fn looks_like_token(self, rest: &str) -> bool {
337 let mut names = 0;
338 for c in rest.chars() {
339 if c.is_ascii_uppercase() || c.is_ascii_digit() || matches!(c, '+' | 'x' | '×') {
340 names += 1;
341 } else {
342 return names > 0 && self.close.starts_with(c);
343 }
344 }
345 false
346 }
347 }
348
349 /// A character that is drawn as a token rather than as itself: control
350 /// characters, bidi controls, zero-width and invisible characters, and every
351 /// space except the ordinary one.
352 fn is_flagged(c: char) -> bool {
353 c.is_control()
354 || matches!(c,
355 '\u{00A0}' | '\u{00AD}' | '\u{034F}' | '\u{061C}' | '\u{115F}' | '\u{1160}'
356 | '\u{1680}' | '\u{17B4}' | '\u{17B5}' | '\u{180B}'..='\u{180F}'
357 | '\u{2000}'..='\u{200F}' | '\u{2028}'..='\u{202F}' | '\u{205F}'..='\u{206F}'
358 | '\u{2800}' | '\u{3000}' | '\u{3164}' | '\u{FE00}'..='\u{FE0F}' | '\u{FEFF}'
359 | '\u{FFA0}' | '\u{FFF9}'..='\u{FFFC}' | '\u{1D173}'..='\u{1D17A}'
360 | '\u{E0000}'..='\u{E01EF}')
361 }
362
363 fn char_name(c: char) -> String {
364 let name = match c {
365 '\0' => "NUL",
366 '\u{7}' => "BEL",
367 '\u{8}' => "BS",
368 '\t' => "HT",
369 '\n' => "LF",
370 '\u{B}' => "VT",
371 '\u{C}' => "FF",
372 '\r' => "CR",
373 '\u{1B}' => "ESC",
374 '\u{7F}' => "DEL",
375 '\u{A0}' => "NBSP",
376 '\u{AD}' => "SHY",
377 '\u{61C}' => "ALM",
378 '\u{200B}' => "ZWSP",
379 '\u{200C}' => "ZWNJ",
380 '\u{200D}' => "ZWJ",
381 '\u{200E}' => "LRM",
382 '\u{200F}' => "RLM",
383 '\u{202A}' => "LRE",
384 '\u{202B}' => "RLE",
385 '\u{202C}' => "PDF",
386 '\u{202D}' => "LRO",
387 '\u{202E}' => "RLO",
388 '\u{2060}' => "WJ",
389 '\u{2066}' => "LRI",
390 '\u{2067}' => "RLI",
391 '\u{2068}' => "FSI",
392 '\u{2069}' => "PDI",
393 '\u{FEFF}' => "BOM",
394 _ => return format!("U+{:04X}", c as u32),
395 };
396 name.to_owned()
397 }
398
399 /// One drawn piece of text: a grapheme, or a token standing for characters.
400 #[derive(Clone)]
401 struct Unit<'a> {
402 text: Cow<'a, str>,
403 width: usize,
404 /// Source characters this unit stands for (0 for the card's own words).
405 chars: usize,
406 style: Style,
407 /// An ordinary space: a place where a row may break.
408 space: bool,
409 }
410
411 struct Looks {
412 plain: Style,
413 token: Style,
414 }
415
416 /// Visit `src` as the units it is drawn with. Returns how many ordinary
417 /// (non-flagged) non-ASCII characters it holds.
418 fn escape<'a>(
419 src: &'a str,
420 ascii: bool,
421 edges: bool,
422 looks: &Looks,
423 mut visit: impl FnMut(Unit<'a>),
424 ) -> usize {
425 let marks = Marks::new(ascii);
426 let token_unit = |name: String, chars: usize| Unit {
427 width: text::width(&name),
428 text: Cow::Owned(name),
429 chars,
430 style: looks.token,
431 space: false,
432 };
433 // Leading and trailing spaces are drawn for anything that is run or
434 // named; prose and previews (indented code, diff context) keep theirs.
435 let lead = if edges {
436 src.len() - src.trim_start_matches(' ').len()
437 } else {
438 0
439 };
440 let trail = if !edges || lead == src.len() {
441 0
442 } else {
443 src.len() - src.trim_end_matches(' ').len()
444 };
445 let mid = &src[lead..src.len() - trail];
446 let mut non_ascii = 0;
447 if lead > 0 {
448 visit(token_unit(marks.spaces(lead), lead));
449 }
450 for (at, g) in mid.grapheme_indices(true) {
451 if !g.chars().any(is_flagged) && text::width(g) > 0 {
452 if g == marks.open && marks.looks_like_token(&mid[at + g.len()..]) {
453 let opener = marks.open.chars().next().unwrap_or('<');
454 visit(token_unit(marks.token(&char_name(opener)), 1));
455 continue;
456 }
457 non_ascii += g.chars().filter(|c| !c.is_ascii()).count();
458 visit(Unit {
459 text: Cow::Borrowed(g),
460 width: text::width(g),
461 chars: g.chars().count(),
462 style: looks.plain,
463 space: g == " ",
464 });
465 continue;
466 }
467 // A cluster with something invisible in it: draw each invisible
468 // character as a token and keep the visible runs between them.
469 let mut run: Option<usize> = None;
470 let mut flush = |end: usize, run: &mut Option<usize>, visit: &mut dyn FnMut(Unit<'a>)| {
471 if let Some(start) = run.take() {
472 let piece = &g[start..end];
473 if text::width(piece) > 0 {
474 non_ascii += piece.chars().filter(|c| !c.is_ascii()).count();
475 visit(Unit {
476 text: Cow::Borrowed(piece),
477 width: text::width(piece),
478 chars: piece.chars().count(),
479 style: looks.plain,
480 space: false,
481 });
482 } else {
483 for c in piece.chars() {
484 visit(token_unit(marks.token(&char_name(c)), 1));
485 }
486 }
487 }
488 };
489 for (off, c) in g.char_indices() {
490 if is_flagged(c) {
491 flush(off, &mut run, &mut visit);
492 visit(token_unit(marks.token(&char_name(c)), 1));
493 } else if run.is_none() {
494 run = Some(off);
495 }
496 }
497 flush(g.len(), &mut run, &mut visit);
498 }
499 if trail > 0 {
500 visit(token_unit(marks.spaces(trail), trail));
501 }
502 non_ascii
503 }
504
505 /// `src` as the card draws it: every invisible, control or direction-changing
506 /// character as a named token, leading and trailing spaces as `SP` tokens.
507 /// This is the text a test or a host can compare with what was painted.
508 #[must_use]
509 pub fn visible_text(src: &str, ascii: bool) -> String {
510 let looks = Looks {
511 plain: Style::default(),
512 token: Style::default(),
513 };
514 let mut out = String::new();
515 escape(src, ascii, true, &looks, |u| out.push_str(&u.text));
516 out
517 }
518
519 // ---------------------------------------------------------------------------
520 // Rows and wrapping
521 // ---------------------------------------------------------------------------
522
523 /// One painted row, with the source characters (or choices) it carries.
524 #[derive(Clone)]
525 struct Row {
526 spans: Vec<Span<'static>>,
527 units: usize,
528 }
529
530 fn spans_of(units: &[Unit<'_>]) -> Vec<Span<'static>> {
531 let mut spans = Vec::new();
532 let mut buf = String::new();
533 let mut style: Option<Style> = None;
534 for u in units {
535 if style != Some(u.style) {
536 if let Some(s) = style {
537 spans.push(Span::styled(std::mem::take(&mut buf), s));
538 }
539 style = Some(u.style);
540 }
541 buf.push_str(&u.text);
542 }
543 if let Some(s) = style {
544 spans.push(Span::styled(buf, s));
545 }
546 spans
547 }
548
549 #[derive(Default)]
550 struct Wrapped {
551 rows: Vec<Row>,
552 total_rows: usize,
553 total_chars: usize,
554 }
555
556 /// Greedy wrapping that never drops or rewrites a character: a row breaks
557 /// after an ordinary space when that leaves the row at least half full, and
558 /// otherwise at the cell where it runs out. The rows, read in order, are the
559 /// text.
560 struct Wrapper<'a> {
561 width: usize,
562 cap: usize,
563 cur: Vec<Unit<'a>>,
564 cur_w: usize,
565 last_break: Option<usize>,
566 any: bool,
567 out: Wrapped,
568 }
569
570 impl<'a> Wrapper<'a> {
571 fn new(width: usize, cap: usize) -> Self {
572 Self {
573 width,
574 cap,
575 cur: Vec::new(),
576 cur_w: 0,
577 last_break: None,
578 any: false,
579 out: Wrapped::default(),
580 }
581 }
582
583 fn emit(&mut self, spans: Vec<Span<'static>>, units: usize) {
584 self.out.total_rows += 1;
585 if self.out.rows.len() < self.cap {
586 self.out.rows.push(Row { spans, units });
587 }
588 }
589
590 fn flush(&mut self) {
591 if self.cur.is_empty() {
592 return;
593 }
594 let units = self.cur.iter().map(|u| u.chars).sum();
595 let spans = spans_of(&self.cur);
596 self.emit(spans, units);
597 self.cur.clear();
598 self.cur_w = 0;
599 self.last_break = None;
600 }
601
602 fn push(&mut self, u: Unit<'a>) {
603 self.any = true;
604 self.out.total_chars += u.chars;
605 if self.width == 0 {
606 return;
607 }
608 if u.width > self.width {
609 self.flush();
610 self.overwide(&u);
611 return;
612 }
613 if self.cur_w + u.width > self.width {
614 let split = match self.last_break {
615 Some(b)
616 if b < self.cur.len()
617 && self.cur[..b].iter().map(|u| u.width).sum::<usize>() * 2
618 >= self.width =>
619 {
620 b
621 }
622 _ => self.cur.len(),
623 };
624 let carry = self.cur.split_off(split);
625 self.flush();
626 self.cur_w = carry.iter().map(|u| u.width).sum();
627 self.cur = carry;
628 if self.cur_w + u.width > self.width {
629 self.flush();
630 }
631 }
632 self.cur_w += u.width;
633 let space = u.space;
634 self.cur.push(u);
635 if space {
636 self.last_break = Some(self.cur.len());
637 }
638 }
639
640 /// A unit wider than a whole row (a token at a tiny width): split it
641 /// across rows by character. A single character wider than the row has
642 /// nowhere to go and counts as not shown.
643 fn overwide(&mut self, u: &Unit<'_>) {
644 let mut piece = String::new();
645 let mut used = 0;
646 for c in u.text.chars() {
647 let w = c.width().unwrap_or(0);
648 if w > self.width {
649 if !piece.is_empty() {
650 self.emit(vec![Span::styled(std::mem::take(&mut piece), u.style)], 0);
651 used = 0;
652 }
653 self.emit(Vec::new(), 0);
654 continue;
655 }
656 if used + w > self.width {
657 self.emit(vec![Span::styled(std::mem::take(&mut piece), u.style)], 0);
658 used = 0;
659 }
660 piece.push(c);
661 used += w;
662 }
663 if !piece.is_empty() {
664 // The characters count as shown only once the last piece is.
665 self.emit(vec![Span::styled(piece, u.style)], u.chars);
666 }
667 }
668
669 fn finish(mut self) -> Wrapped {
670 self.flush();
671 if self.out.total_rows == 0 {
672 // A blank line still takes a row.
673 self.emit(Vec::new(), 0);
674 }
675 self.out
676 }
677
678 /// Push the card's own words (no source characters).
679 fn words(&mut self, words: &str, style: Style) {
680 for g in text::display_safe(words).graphemes(true) {
681 self.push(Unit {
682 text: Cow::Owned(g.to_owned()),
683 width: text::width(g),
684 chars: 0,
685 style,
686 space: g == " ",
687 });
688 }
689 }
690
691 /// Push caller text through [`escape`]; returns its non-ASCII count.
692 fn subject(&mut self, src: &'a str, ascii: bool, looks: &Looks) -> usize {
693 escape(src, ascii, true, looks, |u| self.push(u))
694 }
695
696 /// Like [`Wrapper::subject`] for prose and previews: control characters
697 /// and invisible characters are drawn, edge spaces are left alone.
698 fn prose(&mut self, src: &'a str, ascii: bool, looks: &Looks) -> usize {
699 escape(src, ascii, false, looks, |u| self.push(u))
700 }
701 }
702
703 /// Rows of one part of the card, with what did not fit.
704 struct Section {
705 rows: Vec<Row>,
706 total_rows: usize,
707 total_chars: usize,
708 cap: usize,
709 }
710
711 impl Section {
712 fn new(cap: usize) -> Self {
713 Self {
714 rows: Vec::new(),
715 total_rows: 0,
716 total_chars: 0,
717 cap,
718 }
719 }
720
721 fn absorb(&mut self, wrapped: Wrapped) {
722 self.total_rows += wrapped.total_rows;
723 self.total_chars += wrapped.total_chars;
724 for row in wrapped.rows {
725 if self.rows.len() < self.cap {
726 self.rows.push(row);
727 }
728 }
729 }
730
731 /// One logical line, wrapped into `width`, with a hanging gutter.
732 fn line<'a>(
733 &mut self,
734 width: usize,
735 gutter: Option<(&str, Style, &str, Style)>,
736 build: impl FnOnce(&mut Wrapper<'a>),
737 ) {
738 let gutter_w = gutter.map_or(0, |g| text::width(g.0));
739 let mut wrapper = Wrapper::new(width.saturating_sub(gutter_w), self.cap);
740 build(&mut wrapper);
741 let mut wrapped = wrapper.finish();
742 if let Some((first, first_style, rest, rest_style)) = gutter {
743 for (i, row) in wrapped.rows.iter_mut().enumerate() {
744 let (g, s) = if i == 0 {
745 (first, first_style)
746 } else {
747 (rest, rest_style)
748 };
749 row.spans.insert(0, Span::styled(g.to_owned(), s));
750 }
751 }
752 self.absorb(wrapped);
753 }
754
755 fn hidden(&self, shown: usize) -> ApprovalHidden {
756 let shown = shown.min(self.rows.len());
757 let shown_chars: usize = self.rows[..shown].iter().map(|r| r.units).sum();
758 ApprovalHidden {
759 chars: self.total_chars.saturating_sub(shown_chars),
760 lines: self.total_rows.saturating_sub(shown),
761 }
762 }
763 }
764
765 /// Pack unbreakable items into rows, `sep` between them on a row; an item
766 /// wider than a row wraps. Row units count the items that end in the row: an
767 /// item counts as shown only once its last row is, so a choice cut off after
768 /// its key is reported as cut.
769 fn pack(
770 items: Vec<Vec<Unit<'static>>>,
771 sep: &[Unit<'static>],
772 width: usize,
773 cap: usize,
774 ) -> Section {
775 let sep_w: usize = sep.iter().map(|u| u.width).sum();
776 let mut sec = Section::new(cap);
777 let mut cur: Vec<Unit<'static>> = Vec::new();
778 let mut cur_items = 0;
779 let mut used = 0;
780 let flush = |sec: &mut Section, cur: &mut Vec<Unit<'static>>, n: &mut usize| {
781 if !cur.is_empty() {
782 sec.total_rows += 1;
783 if sec.rows.len() < sec.cap {
784 sec.rows.push(Row {
785 spans: spans_of(cur),
786 units: *n,
787 });
788 }
789 cur.clear();
790 *n = 0;
791 }
792 };
793 for item in items {
794 sec.total_chars += 1;
795 let w: usize = item.iter().map(|u| u.width).sum();
796 if w > width {
797 flush(&mut sec, &mut cur, &mut cur_items);
798 used = 0;
799 let mut wrapper = Wrapper::new(width, cap);
800 for u in item {
801 wrapper.push(u);
802 }
803 let mut wrapped = wrapper.finish();
804 // The last row only counts if it was kept: rows past the cap are
805 // dropped, and an item whose tail is dropped is not shown.
806 if wrapped.rows.len() == wrapped.total_rows
807 && let Some(last) = wrapped.rows.last_mut()
808 {
809 last.units = 1;
810 }
811 wrapped.total_chars = 0;
812 sec.absorb(wrapped);
813 continue;
814 }
815 if !cur.is_empty() && used + sep_w + w > width {
816 flush(&mut sec, &mut cur, &mut cur_items);
817 used = 0;
818 }
819 if !cur.is_empty() {
820 cur.extend(sep.iter().cloned());
821 used += sep_w;
822 }
823 used += w;
824 cur.extend(item);
825 cur_items += 1;
826 }
827 flush(&mut sec, &mut cur, &mut cur_items);
828 sec
829 }
830
831 fn trusted(text: &str, style: Style) -> Vec<Unit<'static>> {
832 text::display_safe(text)
833 .graphemes(true)
834 .map(|g| Unit {
835 text: Cow::Owned(g.to_owned()),
836 width: text::width(g),
837 chars: 0,
838 style,
839 space: g == " ",
840 })
841 .collect()
842 }
843
844 // ---------------------------------------------------------------------------
845 // What a paint reports
846 // ---------------------------------------------------------------------------
847
848 /// What one part of a card did not show.
849 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
850 pub struct ApprovalHidden {
851 /// Source characters not shown.
852 pub chars: usize,
853 /// Rows not shown.
854 pub lines: usize,
855 }
856
857 impl ApprovalHidden {
858 #[must_use]
859 pub const fn any(self) -> bool {
860 self.chars > 0 || self.lines > 0
861 }
862
863 const fn plus(self, other: Self) -> Self {
864 Self {
865 chars: self.chars + other.chars,
866 lines: self.lines + other.lines,
867 }
868 }
869 }
870
871 /// What a paint showed and did not show. The caller reads [`clipped`] to
872 /// refuse a blind approval.
873 ///
874 /// [`clipped`]: ApprovalPaint::clipped
875 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
876 pub struct ApprovalPaint {
877 /// The exact command or target.
878 pub subject: ApprovalHidden,
879 /// The preview.
880 pub preview: ApprovalHidden,
881 /// Agent, location, elevation, risk notes and the non-ASCII note.
882 pub details: ApprovalHidden,
883 /// Choices that did not fit and so cannot be seen.
884 pub choices: usize,
885 /// Non-ASCII characters in the subject, location and agent name (the
886 /// card says so when there are any; this is how many).
887 pub non_ascii: usize,
888 }
889
890 impl ApprovalPaint {
891 /// Whether anything the person should read before deciding was not shown.
892 #[must_use]
893 pub const fn clipped(&self) -> bool {
894 self.subject.any() || self.preview.any() || self.details.any() || self.choices > 0
895 }
896 }
897
898 // ---------------------------------------------------------------------------
899 // Choices and keys
900 // ---------------------------------------------------------------------------
901
902 /// A caller-defined name for a choice. The kit never interprets it.
903 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
904 pub struct ChoiceId(pub u32);
905
906 /// What choosing does to the action. The card uses it for one thing: the
907 /// default focus is never a choice that grants.
908 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
909 pub enum ApprovalEffect {
910 /// The action may proceed.
911 Grants,
912 /// The action does not proceed.
913 Refuses,
914 /// Neither: "deny and say why" (it refuses, then asks), "open details".
915 Other,
916 }
917
918 /// A key and its modifiers, matched exactly: `y` is not `Y`, and `Ctrl+Y` is
919 /// neither.
920 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
921 pub struct ApprovalKey {
922 pub code: KeyCode,
923 pub modifiers: KeyModifiers,
924 }
925
926 impl ApprovalKey {
927 #[must_use]
928 pub const fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
929 Self { code, modifiers }
930 }
931
932 /// A character with no modifier.
933 #[must_use]
934 pub const fn char(c: char) -> Self {
935 Self::new(KeyCode::Char(c), KeyModifiers::NONE)
936 }
937
938 /// `Ctrl` plus a character.
939 #[must_use]
940 pub const fn ctrl(c: char) -> Self {
941 Self::new(KeyCode::Char(c), KeyModifiers::CONTROL)
942 }
943
944 /// The label the card shows, spelled as every other key in the kit.
945 #[must_use]
946 pub fn label(&self, platform: Platform) -> String {
947 keys::chord_label(&KeyEvent::new(self.code, self.modifiers), platform)
948 }
949
950 fn matches(&self, key: &KeyEvent) -> bool {
951 key.code == self.code && key.modifiers == self.modifiers
952 }
953
954 /// Keys that move focus, confirm or cancel are the card's own.
955 const fn reserved(&self) -> bool {
956 matches!(
957 self.code,
958 KeyCode::Enter
959 | KeyCode::Esc
960 | KeyCode::Tab
961 | KeyCode::BackTab
962 | KeyCode::Left
963 | KeyCode::Right
964 | KeyCode::Up
965 | KeyCode::Down
966 )
967 }
968 }
969
970 /// One thing the person can choose.
971 #[derive(Clone, Debug, PartialEq, Eq)]
972 pub struct ApprovalChoice {
973 pub id: ChoiceId,
974 pub label: Cow<'static, str>,
975 pub effect: ApprovalEffect,
976 /// Chords that choose directly. The first is the one shown. A chord an
977 /// earlier choice already has, or one the card owns, is dropped by
978 /// [`ApprovalState::new`].
979 pub keys: Vec<ApprovalKey>,
980 }
981
982 impl ApprovalChoice {
983 #[must_use]
984 pub fn new(id: ChoiceId, label: impl Into<Cow<'static, str>>, effect: ApprovalEffect) -> Self {
985 Self {
986 id,
987 label: label.into(),
988 effect,
989 keys: Vec::new(),
990 }
991 }
992
993 /// Convenience constructor for a session-scoped grant choice.
994 #[must_use]
995 pub fn allow_session(id: ChoiceId, label: impl Into<Cow<'static, str>>) -> Self {
996 Self::new(id, label, ApprovalEffect::Grants)
997 }
998
999 #[must_use]
1000 pub fn key(mut self, key: ApprovalKey) -> Self {
1001 self.keys.push(key);
1002 self
1003 }
1004
1005 /// A plain character chord.
1006 #[must_use]
1007 pub fn char_key(self, c: char) -> Self {
1008 self.key(ApprovalKey::char(c))
1009 }
1010 }
1011
1012 /// What a key did to an [`ApprovalState`]: the message a host reacts to.
1013 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1014 pub enum ApprovalOutcome {
1015 /// The key means nothing to the card; the host may use it.
1016 Ignored,
1017 /// Focus moved; repaint.
1018 Moved,
1019 /// A choice was made: Enter on the focused choice, or its chord.
1020 Chose(ChoiceId),
1021 /// The reveal chord: show the whole subject.
1022 Reveal,
1023 /// Esc. The caller decides whether that denies.
1024 Cancelled,
1025 }
1026
1027 /// The choices, which one has focus, and the keys. The card paints from this,
1028 /// so the chords it shows are the chords [`ApprovalState::handle_key`] takes.
1029 #[derive(Clone, Debug, PartialEq, Eq)]
1030 pub struct ApprovalState {
1031 choices: Vec<ApprovalChoice>,
1032 focus: Option<usize>,
1033 reveal: Option<ApprovalKey>,
1034 armed: bool,
1035 }
1036
1037 impl ApprovalState {
1038 /// Focus starts on the first choice that refuses, else the first that is
1039 /// neither, else nowhere: a card of only grants has no default, and Enter
1040 /// then chooses nothing.
1041 #[must_use]
1042 pub fn new(choices: Vec<ApprovalChoice>) -> Self {
1043 let mut state = Self {
1044 choices,
1045 focus: None,
1046 reveal: None,
1047 armed: true,
1048 };
1049 state.sanitize();
1050 state.focus = [ApprovalEffect::Refuses, ApprovalEffect::Other]
1051 .into_iter()
1052 .find_map(|effect| state.choices.iter().position(|c| c.effect == effect));
1053 state
1054 }
1055
1056 /// Bind the key that reveals the whole subject.
1057 #[must_use]
1058 pub fn reveal(mut self, key: ApprovalKey) -> Self {
1059 self.reveal = (!key.reserved()).then_some(key);
1060 self.sanitize();
1061 self
1062 }
1063
1064 /// Ignore every key until [`ApprovalState::arm`]: the host arms the state
1065 /// after the card was drawn, so keys typed ahead cannot answer it.
1066 #[must_use]
1067 pub fn unarmed(mut self) -> Self {
1068 self.armed = false;
1069 self
1070 }
1071
1072 pub fn arm(&mut self) {
1073 self.armed = true;
1074 }
1075
1076 #[must_use]
1077 pub fn choices(&self) -> &[ApprovalChoice] {
1078 &self.choices
1079 }
1080
1081 #[must_use]
1082 pub fn reveal_key(&self) -> Option<ApprovalKey> {
1083 self.reveal
1084 }
1085
1086 /// The index of the focused choice.
1087 #[must_use]
1088 pub fn focus(&self) -> Option<usize> {
1089 self.focus
1090 }
1091
1092 #[must_use]
1093 pub fn focused(&self) -> Option<ChoiceId> {
1094 self.focus.map(|i| self.choices[i].id)
1095 }
1096
1097 /// Whether choosing `id` lets the action proceed. A host that refuses a
1098 /// blind approval asks this of a [`ApprovalOutcome::Chose`] while the last
1099 /// paint [`ApprovalPaint::clipped`].
1100 #[must_use]
1101 pub fn grants(&self, id: ChoiceId) -> bool {
1102 self.choices
1103 .iter()
1104 .any(|c| c.id == id && c.effect == ApprovalEffect::Grants)
1105 }
1106
1107 /// Drop chords the card owns (navigation, Enter, Esc, the reveal key) and
1108 /// chords an earlier choice already has, so the card never advertises a
1109 /// key that does something else.
1110 fn sanitize(&mut self) {
1111 let reveal = self.reveal;
1112 let mut taken: Vec<ApprovalKey> = Vec::new();
1113 for choice in &mut self.choices {
1114 choice
1115 .keys
1116 .retain(|k| !k.reserved() && Some(*k) != reveal && !taken.contains(k));
1117 taken.extend(choice.keys.iter().copied());
1118 }
1119 }
1120
1121 fn step(&mut self, forward: bool) -> ApprovalOutcome {
1122 let len = self.choices.len();
1123 if len == 0 {
1124 return ApprovalOutcome::Ignored;
1125 }
1126 self.focus = Some(match (self.focus, forward) {
1127 (None, true) => 0,
1128 (None, false) => len - 1,
1129 (Some(i), true) => (i + 1) % len,
1130 (Some(i), false) => (i + len - 1) % len,
1131 });
1132 ApprovalOutcome::Moved
1133 }
1134
1135 /// Apply a key press. `Enter` chooses the focused choice and nothing
1136 /// else; a choice's chord chooses it directly; arrows and `Tab` move
1137 /// focus; `Esc` is [`ApprovalOutcome::Cancelled`]. Releases, held-key
1138 /// repeats (for everything but moving), modified Enter/Esc/arrows and
1139 /// every other key are [`ApprovalOutcome::Ignored`].
1140 pub fn handle_key(&mut self, key: KeyEvent) -> ApprovalOutcome {
1141 if key.kind == KeyEventKind::Release || !self.armed {
1142 return ApprovalOutcome::Ignored;
1143 }
1144 let repeat = key.kind == KeyEventKind::Repeat;
1145 let plain = key.modifiers.is_empty();
1146 match key.code {
1147 KeyCode::Right | KeyCode::Down | KeyCode::Tab if plain => return self.step(true),
1148 KeyCode::Left | KeyCode::Up if plain => return self.step(false),
1149 KeyCode::BackTab
1150 if key.modifiers.is_empty() || key.modifiers == KeyModifiers::SHIFT =>
1151 {
1152 return self.step(false);
1153 }
1154 _ => {}
1155 }
1156 // A held key must never answer the card.
1157 if repeat {
1158 return ApprovalOutcome::Ignored;
1159 }
1160 match key.code {
1161 KeyCode::Esc if plain => return ApprovalOutcome::Cancelled,
1162 KeyCode::Enter if plain => {
1163 return self
1164 .focused()
1165 .map_or(ApprovalOutcome::Ignored, ApprovalOutcome::Chose);
1166 }
1167 _ => {}
1168 }
1169 if self.reveal.is_some_and(|k| k.matches(&key)) {
1170 return ApprovalOutcome::Reveal;
1171 }
1172 self.choices
1173 .iter()
1174 .find(|c| c.keys.iter().any(|k| k.matches(&key)))
1175 .map_or(ApprovalOutcome::Ignored, |c| ApprovalOutcome::Chose(c.id))
1176 }
1177 }
1178
1179 // ---------------------------------------------------------------------------
1180 // The card
1181 // ---------------------------------------------------------------------------
1182
1183 struct Styles {
1184 plain: Style,
1185 strong: Style,
1186 muted: Style,
1187 hint: Style,
1188 border: Style,
1189 attention: Style,
1190 danger: Style,
1191 live: Style,
1192 diff_remove: Style,
1193 primary: Style,
1194 token: Style,
1195 }
1196
1197 impl Styles {
1198 fn new(theme: &Theme) -> Self {
1199 let bold = Modifier::BOLD;
1200 Self {
1201 plain: theme.fg(Role::Foreground),
1202 strong: theme.fg(Role::Foreground).add_modifier(bold),
1203 muted: theme.fg(Role::Muted),
1204 hint: theme.fg(Role::Hint),
1205 border: theme.fg(Role::Border),
1206 attention: theme.fg(Role::Attention).add_modifier(bold),
1207 danger: theme.fg(Role::Danger).add_modifier(bold),
1208 live: theme.fg(Role::Live),
1209 diff_remove: theme.fg(Role::Danger),
1210 primary: theme.fg(Role::Accent).add_modifier(bold),
1211 // Reversed and bold: a token is told from text by shape and
1212 // video, not hue, so it reads at 16 colors and under NO_COLOR.
1213 token: theme
1214 .fg(Role::Attention)
1215 .add_modifier(bold | Modifier::REVERSED),
1216 }
1217 }
1218
1219 fn looks(&self, plain: Style) -> Looks {
1220 Looks {
1221 plain,
1222 token: self.token,
1223 }
1224 }
1225 }
1226
1227 const MAX_ROWS: usize = 2048;
1228
1229 /// Between the parts of a line: ` · `, or ` - ` where marks are ASCII-safe
1230 /// (the ASCII form of `·` is `.`, which reads as punctuation).
1231 const fn dot(ascii: bool) -> &'static str {
1232 if ascii { " - " } else { " · " }
1233 }
1234
1235 /// The "not shown" notice for `report`, wrapped into `width`, and whether it
1236 /// is the whole notice. Given only `max_rows` rows it says less rather than run
1237 /// off the end: first the later counts go, then the line count, then the
1238 /// reveal key; the first count never does. `reveal` is the label of the key
1239 /// that shows everything, when the host has one.
1240 fn clip_notice(
1241 clip: &ApprovalClipWords,
1242 report: &ApprovalPaint,
1243 reveal: Option<String>,
1244 width: usize,
1245 max_rows: usize,
1246 theme: &Theme,
1247 st: &Styles,
1248 ) -> (Section, bool) {
1249 let mut first = None;
1250 let mut parts = Vec::new();
1251 if report.subject.any() {
1252 // `760 characters not shown (11 lines)`
1253 let chars = clip.hidden_chars.render(report.subject.chars);
1254 let mut part = chars.clone();
1255 if report.subject.lines > 0 {
1256 part.push_str(&format!(
1257 " ({})",
1258 clip.hidden_lines.render(report.subject.lines)
1259 ));
1260 }
1261 first = Some(chars);
1262 parts.push(part);
1263 }
1264 if report.preview.lines > 0 {
1265 parts.push(clip.hidden_preview.render(report.preview.lines));
1266 }
1267 if report.details.lines > 0 {
1268 parts.push(clip.hidden_details.render(report.details.lines));
1269 }
1270 if report.choices > 0 {
1271 parts.push(clip.hidden_choices.render(report.choices));
1272 }
1273 if parts.is_empty() {
1274 return (Section::new(0), true);
1275 }
1276 let reveal =
1277 reveal.filter(|_| report.subject.any() || report.preview.any() || report.details.any());
1278 let ascii = theme.ascii();
1279 let build = |parts: &[String], with_reveal: bool| {
1280 let mut sec = Section::new(MAX_ROWS);
1281 sec.line(width, None, |w| {
1282 w.words(&format!("{} ", glyphs::pick("⚠", ascii)), st.attention);
1283 for (i, part) in parts.iter().enumerate() {
1284 if i > 0 {
1285 w.words(dot(ascii), st.border);
1286 }
1287 w.words(part, st.strong);
1288 // The binding sits beside the first count, where a one-row
1289 // notice still shows it.
1290 if let (0, Some(key), true) = (i, &reveal, with_reveal) {
1291 w.words(dot(ascii), st.border);
1292 w.words(key, st.strong);
1293 w.words(&format!(" {}", clip.reveal), st.muted);
1294 }
1295 }
1296 });
1297 sec
1298 };
1299 let want_reveal = reveal.is_some();
1300 let mut variants: Vec<(Vec<String>, bool)> = (1..=parts.len())
1301 .rev()
1302 .map(|n| (parts[..n].to_vec(), want_reveal))
1303 .collect();
1304 if let Some(chars) = first {
1305 variants.push((vec![chars.clone()], want_reveal));
1306 variants.push((vec![chars], false));
1307 }
1308 let last = variants.len() - 1;
1309 for (i, (p, r)) in variants.iter().enumerate() {
1310 let sec = build(p, *r);
1311 if sec.total_rows <= max_rows || i == last {
1312 return (sec, i == 0);
1313 }
1314 }
1315 unreachable!("the last variant always returns")
1316 }
1317
1318 struct Composed {
1319 rows: Vec<Row>,
1320 report: ApprovalPaint,
1321 }
1322
1323 /// A decision: what the agent wants to do, where, and the choices. Paints a
1324 /// bordered overlay panel; hand it the area the card may use.
1325 #[derive(Clone, Debug)]
1326 pub struct ApprovalCard<'a> {
1327 pub subject: &'a ApprovalSubject<'a>,
1328 pub state: &'a ApprovalState,
1329 words: Cow<'a, ApprovalWords>,
1330 flag_non_ascii: bool,
1331 diff_preview: bool,
1332 }
1333
1334 impl<'a> ApprovalCard<'a> {
1335 #[must_use]
1336 pub fn new(subject: &'a ApprovalSubject<'a>, state: &'a ApprovalState) -> Self {
1337 Self {
1338 subject,
1339 state,
1340 words: Cow::Owned(ApprovalWords::default()),
1341 flag_non_ascii: true,
1342 diff_preview: false,
1343 }
1344 }
1345
1346 /// Words from the host, by reference.
1347 #[must_use]
1348 pub fn words(mut self, words: &'a ApprovalWords) -> Self {
1349 self.words = Cow::Borrowed(words);
1350 self
1351 }
1352
1353 /// Say when the subject holds non-ASCII text (a homoglyph can pass for a
1354 /// letter). On by default; a host whose people write in other scripts
1355 /// turns it off.
1356 #[must_use]
1357 pub fn flag_non_ascii(mut self, on: bool) -> Self {
1358 self.flag_non_ascii = on;
1359 self
1360 }
1361
1362 /// Color diff-shaped preview lines (`+`, `-`, `@@`) with semantic tones
1363 /// while keeping full [`visible_text`] escaping intact.
1364 #[must_use]
1365 pub fn diff_preview(mut self, on: bool) -> Self {
1366 self.diff_preview = on;
1367 self
1368 }
1369
1370 fn header(&self, theme: &Theme) -> String {
1371 let mark = glyphs::pick(State::NeedsYou.glyph(), theme.ascii());
1372 format!(
1373 "{mark} {}{}{}",
1374 self.words.needs_you,
1375 dot(theme.ascii()),
1376 self.words.kind(self.subject.kind)
1377 )
1378 }
1379
1380 fn rail(&self, theme: &Theme) -> KeyHints {
1381 let platform = Platform::current(theme.ascii());
1382 KeyHints::new(vec![
1383 KeyHint::new(
1384 keys::pair_label(KeyCode::Left, KeyCode::Right, platform),
1385 self.words.move_focus.clone(),
1386 ),
1387 KeyHint::new("Enter", self.words.choose_focused.clone()),
1388 KeyHint::new("Esc", self.words.cancel.clone()),
1389 ])
1390 }
1391
1392 /// The panel is only the frame: its own rail of hints would cost three
1393 /// rows even where the card is short of them, so the card draws the
1394 /// hints itself, last, and only where there is room.
1395 fn panel(&self, theme: &Theme) -> Panel<'static> {
1396 Panel::new(Depth::Overlay)
1397 .title(self.header(theme))
1398 .focused(true)
1399 }
1400
1401 fn choices_section(&self, width: usize, cap: usize, theme: &Theme, st: &Styles) -> Section {
1402 let platform = Platform::current(theme.ascii());
1403 let selected = theme.bg(Role::Selected);
1404 let items = self
1405 .state
1406 .choices()
1407 .iter()
1408 .enumerate()
1409 .map(|(i, choice)| {
1410 let focused = self.state.focus() == Some(i);
1411 let patch = |s: Style| if focused { s.patch(selected) } else { s };
1412 let mut units = trusted(
1413 glyphs::pick(glyphs::selection_marker(focused), theme.ascii()),
1414 patch(st.primary),
1415 );
1416 units.extend(trusted(" ", patch(st.plain)));
1417 if let Some(key) = choice.keys.first() {
1418 units.extend(trusted(&key.label(platform), patch(st.strong)));
1419 units.extend(trusted(" ", patch(st.plain)));
1420 }
1421 let label = if focused { st.strong } else { st.plain };
1422 units.extend(trusted(&choice.label, patch(label)));
1423 units
1424 })
1425 .collect();
1426 let sep = if theme.ascii() {
1427 trusted(" ", st.plain)
1428 } else {
1429 trusted(dot(false), st.border)
1430 };
1431 pack(items, &sep, width, cap)
1432 }
1433
1434 /// The "not shown" notice for `report`; see [`clip_notice`].
1435 fn notice(
1436 &self,
1437 report: &ApprovalPaint,
1438 width: usize,
1439 max_rows: usize,
1440 theme: &Theme,
1441 st: &Styles,
1442 ) -> (Section, bool) {
1443 let reveal = self
1444 .state
1445 .reveal_key()
1446 .map(|key| key.label(Platform::current(theme.ascii())));
1447 clip_notice(&self.words.clip, report, reveal, width, max_rows, theme, st)
1448 }
1449
1450 /// Lay the card's body out in `width` x `h`. Every part wraps; what does
1451 /// not fit is counted, and the choices come first.
1452 fn compose(&self, width: usize, h: usize, theme: &Theme) -> Composed {
1453 let st = Styles::new(theme);
1454 let ascii = theme.ascii();
1455 let words = &*self.words;
1456 let subject = self.subject;
1457 let cap = h.min(MAX_ROWS);
1458 let mut non_ascii = 0;
1459
1460 // Agent.
1461 let mut agent = Section::new(cap);
1462 if let Some(a) = &subject.agent {
1463 agent.line(width, None, |w| {
1464 w.words(&format!("{} ", words.requested_by), st.muted);
1465 non_ascii += w.subject(&a.name, ascii, &st.looks(st.strong));
1466 if a.sub_agent {
1467 w.words(&format!(" ({})", words.sub_agent), st.muted);
1468 }
1469 });
1470 }
1471
1472 // The subject, verbatim.
1473 let mut main = Section::new(cap);
1474 let first = if subject.kind == ApprovalKind::Command {
1475 "$ ".to_owned()
1476 } else {
1477 format!("{} ", glyphs::pick("›", ascii))
1478 };
1479 let gutter = Some((first.as_str(), st.primary, " ", st.plain));
1480 let fallback_path = subject
1481 .target
1482 .is_empty()
1483 .then(|| subject.path.as_deref().filter(|p| !p.is_empty()))
1484 .flatten();
1485 if let Some(path) = fallback_path {
1486 main.line(width, gutter, |w| {
1487 non_ascii += w.subject(path, ascii, &st.looks(st.strong));
1488 });
1489 } else if subject.target.is_empty() {
1490 main.line(width, gutter, |w| w.words(&words.clip.empty, st.muted));
1491 } else {
1492 main.line(width, gutter, |w| {
1493 non_ascii += w.subject(&subject.target, ascii, &st.looks(st.strong));
1494 });
1495 }
1496
1497 // Elevation and scope: a mark and words, never color alone.
1498 let mut facts = Section::new(cap);
1499 if subject.kind == ApprovalKind::Elevation {
1500 facts.line(width, None, |w| {
1501 w.words(&format!("{} ", glyphs::pick("⚠", ascii)), st.danger);
1502 w.words(&words.elevated, st.danger);
1503 });
1504 }
1505 match subject.scope {
1506 ApprovalScope::Outside => facts.line(width, None, |w| {
1507 w.words(&format!("{} ", glyphs::pick("⚠", ascii)), st.attention);
1508 w.words(&words.outside, st.attention);
1509 }),
1510 ApprovalScope::Inside => facts.line(width, None, |w| w.words(&words.inside, st.muted)),
1511 ApprovalScope::Unchecked => facts.line(width, None, |w| {
1512 w.words(
1513 &format!(
1514 "{} {}",
1515 glyphs::pick(glyphs::UNKNOWN, ascii),
1516 words.unchecked
1517 ),
1518 st.muted,
1519 );
1520 }),
1521 }
1522
1523 let mut cwd = Section::new(cap);
1524 if let Some(dir) = &subject.cwd {
1525 cwd.line(width, None, |w| {
1526 w.words(&format!("{} ", words.in_dir), st.muted);
1527 non_ascii += w.subject(dir, ascii, &st.looks(st.plain));
1528 });
1529 }
1530 if !subject.target.is_empty()
1531 && let Some(path) = subject.path.as_deref().filter(|p| !p.is_empty())
1532 {
1533 cwd.line(width, None, |w| {
1534 w.words(&format!("{} ", glyphs::pick("›", ascii)), st.muted);
1535 non_ascii += w.subject(path, ascii, &st.looks(st.plain));
1536 });
1537 }
1538
1539 let mut notes = Section::new(cap);
1540 for note in &subject.risk_notes {
1541 notes.line(width, None, |w| {
1542 w.words(&format!("{}: ", words.risk), st.attention);
1543 w.prose(note, ascii, &st.looks(st.plain));
1544 });
1545 }
1546
1547 let mut preview = Section::new(cap);
1548 if !subject.preview.is_empty() {
1549 preview.line(width, None, |w| w.words(&words.preview, st.muted));
1550 let rail = format!("{} ", glyphs::pick("│", ascii));
1551 for line in &subject.preview {
1552 let gutter = Some((rail.as_str(), st.border, rail.as_str(), st.border));
1553 let line_style = if self.diff_preview {
1554 if line.starts_with("@@") {
1555 st.muted
1556 } else if line.starts_with('+') && !line.starts_with("+++") {
1557 st.live
1558 } else if line.starts_with('-') && !line.starts_with("---") {
1559 st.diff_remove
1560 } else {
1561 st.plain
1562 }
1563 } else {
1564 st.plain
1565 };
1566 preview.line(width, gutter, |w| {
1567 w.prose(line, ascii, &st.looks(line_style));
1568 });
1569 }
1570 }
1571
1572 let mut flag = Section::new(cap);
1573 if self.flag_non_ascii && non_ascii > 0 {
1574 flag.line(width, None, |w| {
1575 w.words(&format!("{} ", glyphs::pick("⚠", ascii)), st.attention);
1576 w.words(&words.non_ascii.render(non_ascii), st.attention);
1577 });
1578 }
1579
1580 let choices = self.choices_section(width, cap, theme, &st);
1581
1582 // Display order. Priority: the first row of the subject, then where
1583 // and how (the facts), the rest of the subject, the agent, risk
1584 // notes, the non-ASCII note, the directory and the preview.
1585 let sections = [&agent, &main, &facts, &cwd, &notes, &preview, &flag];
1586 let steps: [(usize, usize); 8] = [
1587 (1, 1),
1588 (2, usize::MAX),
1589 (1, usize::MAX),
1590 (0, usize::MAX),
1591 (4, usize::MAX),
1592 (6, usize::MAX),
1593 (3, usize::MAX),
1594 (5, usize::MAX),
1595 ];
1596 let body_total: usize = sections.iter().map(|s| s.total_rows).sum();
1597 let mut choice_rows = choices.rows.len().min(h);
1598 if choice_rows == h && h > 0 {
1599 // No row would be left for the notice that must say the body was
1600 // cut: it takes the last choice row. A card that shows its
1601 // choices and hides what they are for would be a blind approval
1602 // with a button.
1603 choice_rows -= 1;
1604 }
1605 let after_choices = h - choice_rows;
1606
1607 let choices_hidden = choices.total_chars - choices_shown(&choices, choice_rows);
1608 // Hand out `after_choices - reserve` rows in priority order.
1609 let allocate = |reserve: usize| {
1610 let mut left = after_choices - reserve;
1611 let mut taken = [0usize; 7];
1612 for (i, upto) in steps {
1613 let more = (sections[i].total_rows.min(upto) - taken[i].min(upto)).min(left);
1614 taken[i] += more;
1615 left -= more;
1616 }
1617 let sum = |ids: &[usize]| {
1618 ids.iter().fold(ApprovalHidden::default(), |acc, &i| {
1619 acc.plus(sections[i].hidden(taken[i]))
1620 })
1621 };
1622 let report = ApprovalPaint {
1623 subject: sections[1].hidden(taken[1]),
1624 preview: sections[5].hidden(taken[5]),
1625 details: sum(&[0, 2, 3, 4, 6]),
1626 choices: choices_hidden,
1627 non_ascii,
1628 };
1629 (taken, left, report)
1630 };
1631
1632 // If the body cannot all fit, reserve the fewest rows that hold the
1633 // notice saying so: every row spent on the notice is one fewer for
1634 // the card's facts.
1635 let mut reserve = 0;
1636 if body_total > after_choices {
1637 reserve = 1.min(after_choices);
1638 while reserve < after_choices {
1639 let (_, _, report) = allocate(reserve);
1640 if self.notice(&report, width, reserve, theme, &st).1 {
1641 break;
1642 }
1643 reserve += 1;
1644 }
1645 }
1646 let (taken, mut left, report) = allocate(reserve);
1647
1648 let mut rows = Vec::new();
1649 for (i, sec) in sections.iter().enumerate() {
1650 rows.extend(sec.rows[..taken[i].min(sec.rows.len())].iter().cloned());
1651 }
1652 if report.clipped() {
1653 let (notice, _) = self.notice(&report, width, reserve, theme, &st);
1654 rows.extend(notice.rows.into_iter().take(reserve));
1655 } else if left > 0 {
1656 rows.push(Row {
1657 spans: Vec::new(),
1658 units: 0,
1659 });
1660 left -= 1;
1661 }
1662 rows.extend(choices.rows.iter().take(choice_rows).cloned());
1663 // The key hints come last, and only where there is room for them.
1664 let rail = self
1665 .rail(theme)
1666 .lines(u16::try_from(width).unwrap_or(u16::MAX), theme);
1667 if !report.clipped() && !rail.is_empty() && left > rail.len() {
1668 rows.push(Row {
1669 spans: Vec::new(),
1670 units: 0,
1671 });
1672 rows.extend(rail.into_iter().map(|line| Row {
1673 spans: line.spans,
1674 units: 0,
1675 }));
1676 }
1677 Composed { rows, report }
1678 }
1679
1680 /// Paint the card and say what it did not show.
1681 pub fn render(&self, area: Rect, buf: &mut Buffer, theme: &Theme) -> ApprovalPaint {
1682 let area = area.intersection(buf.area);
1683 let inner = self.panel(theme).draw(area, buf, theme);
1684 let inner = inner.intersection(area);
1685 let composed = self.compose(usize::from(inner.width), usize::from(inner.height), theme);
1686 paint_rows(&composed.rows, inner, buf);
1687 composed.report
1688 }
1689 }
1690
1691 fn choices_shown(choices: &Section, shown_rows: usize) -> usize {
1692 choices.rows[..shown_rows.min(choices.rows.len())]
1693 .iter()
1694 .map(|r| r.units)
1695 .sum()
1696 }
1697
1698 fn paint_rows(rows: &[Row], area: Rect, buf: &mut Buffer) {
1699 for (i, row) in rows.iter().enumerate().take(usize::from(area.height)) {
1700 let y = area.y + u16::try_from(i).unwrap_or(u16::MAX);
1701 buf.set_line(area.x, y, &Line::from(row.spans.clone()), area.width);
1702 }
1703 }
1704
1705 impl Paint for ApprovalCard<'_> {
1706 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
1707 self.render(area, buf, theme);
1708 }
1709
1710 /// Rows that show everything at `width`.
1711 fn height(&self, width: u16, theme: &Theme) -> u16 {
1712 let panel = self.panel(theme);
1713 let probe = |h: u16| {
1714 let area = Rect::new(0, 0, width, h);
1715 panel.draw(area, &mut Buffer::empty(area), theme)
1716 };
1717 let rows = self
1718 .compose(usize::from(probe(64).width), MAX_ROWS, theme)
1719 .rows
1720 .len();
1721 let wanted = u16::try_from(rows).unwrap_or(u16::MAX / 2);
1722 (wanted..=wanted.saturating_add(16))
1723 .find(|h| usize::from(probe(*h).height) >= rows)
1724 .unwrap_or_else(|| wanted.saturating_add(16))
1725 }
1726 }
1727
1728 // ---------------------------------------------------------------------------
1729 // Review verdicts
1730 // ---------------------------------------------------------------------------
1731
1732 /// What an automated reviewer concluded.
1733 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1734 pub enum ReviewKind {
1735 /// The reviewer let the action proceed.
1736 Allowed,
1737 /// The reviewer stopped the action.
1738 Denied,
1739 /// The reviewer set the action aside for the person.
1740 Held,
1741 /// The review failed or timed out. This is not a verdict about the
1742 /// action, and it never looks like one.
1743 Undecided,
1744 }
1745
1746 impl ReviewKind {
1747 pub const ALL: [ReviewKind; 4] = [
1748 ReviewKind::Allowed,
1749 ReviewKind::Denied,
1750 ReviewKind::Held,
1751 ReviewKind::Undecided,
1752 ];
1753
1754 /// The product state whose mark and hue this verdict wears. Four marks:
1755 /// `✓` `✕` `◆` `?`, which stay four different shapes in ASCII.
1756 #[must_use]
1757 pub const fn state(self) -> State {
1758 match self {
1759 ReviewKind::Allowed => State::Done,
1760 ReviewKind::Denied => State::Failed,
1761 ReviewKind::Held => State::NeedsYou,
1762 ReviewKind::Undecided => State::Unknown,
1763 }
1764 }
1765
1766 /// Whether the person has to do something about this verdict.
1767 #[must_use]
1768 pub const fn needs_a_next_step(self) -> bool {
1769 !matches!(self, ReviewKind::Allowed)
1770 }
1771 }
1772
1773 /// The words of a verdict. English by default.
1774 #[derive(Clone, Debug, PartialEq, Eq)]
1775 pub struct ReviewWords {
1776 pub allowed: Cow<'static, str>,
1777 pub denied: Cow<'static, str>,
1778 pub held: Cow<'static, str>,
1779 pub undecided: Cow<'static, str>,
1780 pub why: Cow<'static, str>,
1781 pub waiting_for: Cow<'static, str>,
1782 /// Under a held verdict.
1783 pub held_note: Cow<'static, str>,
1784 /// Under an undecided one: it is not a verdict.
1785 pub undecided_note: Cow<'static, str>,
1786 pub clip: ApprovalClipWords,
1787 }
1788
1789 impl Default for ReviewWords {
1790 fn default() -> Self {
1791 Self {
1792 allowed: "Allowed".into(),
1793 denied: "Denied".into(),
1794 held: "Held for you".into(),
1795 undecided: "Could not decide".into(),
1796 why: "Why".into(),
1797 waiting_for: "Waiting for".into(),
1798 held_note: "Your call.".into(),
1799 undecided_note: "No verdict. This is not a safety decision: your call.".into(),
1800 clip: ApprovalClipWords::default(),
1801 }
1802 }
1803 }
1804
1805 impl ReviewWords {
1806 fn word(&self, kind: ReviewKind) -> &str {
1807 match kind {
1808 ReviewKind::Allowed => &self.allowed,
1809 ReviewKind::Denied => &self.denied,
1810 ReviewKind::Held => &self.held,
1811 ReviewKind::Undecided => &self.undecided,
1812 }
1813 }
1814 }
1815
1816 /// A held, denied or undecided verdict that offers no next step.
1817 #[derive(Clone, Debug, PartialEq, Eq)]
1818 pub struct ReviewError;
1819
1820 impl std::fmt::Display for ReviewError {
1821 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1822 write!(
1823 f,
1824 "a denied, held or undecided review needs an enabled key or a waiting-for line"
1825 )
1826 }
1827 }
1828
1829 impl std::error::Error for ReviewError {}
1830
1831 /// An automated reviewer's verdict on one action, in the transcript.
1832 #[derive(Clone, Debug)]
1833 pub struct ReviewVerdict<'a> {
1834 pub kind: ReviewKind,
1835 pub reviewer: Cow<'a, str>,
1836 /// One line: why. Wrapped, never cut.
1837 pub reason: Cow<'a, str>,
1838 /// The action, verbatim, when the verdict should show it.
1839 pub subject: Option<Cow<'a, str>>,
1840 /// A plain word after the reviewer: "Deletes unseen files". No hue.
1841 pub category: Option<Cow<'a, str>>,
1842 /// What must happen first, as text with no key.
1843 pub waiting_for: Option<Cow<'a, str>>,
1844 /// Right-aligned in the quietest ink when it fits.
1845 pub id: Option<Cow<'a, str>>,
1846 /// What the person can do about it.
1847 pub hints: &'a KeyHints,
1848 words: Cow<'a, ReviewWords>,
1849 }
1850
1851 impl<'a> ReviewVerdict<'a> {
1852 /// A denied, held or undecided verdict must say what changes its outcome:
1853 /// an enabled key in `hints`, or a `waiting_for` line. Otherwise the
1854 /// person is told something stopped and given nothing to do about it.
1855 pub fn new(
1856 kind: ReviewKind,
1857 reviewer: impl Into<Cow<'a, str>>,
1858 reason: impl Into<Cow<'a, str>>,
1859 hints: &'a KeyHints,
1860 waiting_for: Option<Cow<'a, str>>,
1861 ) -> Result<Self, ReviewError> {
1862 let has_key = hints.items.iter().any(|h| h.enabled);
1863 let has_wait = waiting_for.as_deref().is_some_and(|w| !w.trim().is_empty());
1864 if kind.needs_a_next_step() && !has_key && !has_wait {
1865 return Err(ReviewError);
1866 }
1867 Ok(Self {
1868 kind,
1869 reviewer: reviewer.into(),
1870 reason: reason.into(),
1871 subject: None,
1872 category: None,
1873 waiting_for,
1874 id: None,
1875 hints,
1876 words: Cow::Owned(ReviewWords::default()),
1877 })
1878 }
1879
1880 #[must_use]
1881 pub fn subject(mut self, subject: impl Into<Cow<'a, str>>) -> Self {
1882 self.subject = Some(subject.into());
1883 self
1884 }
1885
1886 #[must_use]
1887 pub fn category(mut self, category: impl Into<Cow<'a, str>>) -> Self {
1888 self.category = Some(category.into());
1889 self
1890 }
1891
1892 #[must_use]
1893 pub fn id(mut self, id: impl Into<Cow<'a, str>>) -> Self {
1894 self.id = Some(id.into());
1895 self
1896 }
1897
1898 #[must_use]
1899 pub fn words(mut self, words: &'a ReviewWords) -> Self {
1900 self.words = Cow::Borrowed(words);
1901 self
1902 }
1903
1904 fn compose(&self, width: usize, h: usize, theme: &Theme) -> Composed {
1905 let st = Styles::new(theme);
1906 let ascii = theme.ascii();
1907 let words = &*self.words;
1908 let cap = h.min(MAX_ROWS);
1909 let state = self.kind.state();
1910 let hue = theme.fg(state.role());
1911
1912 let mut head = Section::new(cap);
1913 head.line(width, None, |w| {
1914 w.words(&format!("{} ", glyphs::pick(state.glyph(), ascii)), hue);
1915 w.words(words.word(self.kind), st.strong);
1916 w.words(dot(ascii), st.border);
1917 w.subject(&self.reviewer, ascii, &st.looks(st.muted));
1918 if let Some(category) = &self.category {
1919 w.words(dot(ascii), st.border);
1920 w.words(category, st.muted);
1921 }
1922 });
1923 if let (Some(id), 1, Some(row)) = (&self.id, head.total_rows, head.rows.first_mut()) {
1924 let used: usize = row.spans.iter().map(|s| text::width(&s.content)).sum();
1925 let id = text::display_safe(id);
1926 let id_w = text::width(&id);
1927 if used + 2 + id_w <= width {
1928 row.spans.push(Span::raw(" ".repeat(width - used - id_w)));
1929 row.spans.push(Span::styled(id.into_owned(), st.hint));
1930 }
1931 }
1932
1933 let mut subject = Section::new(cap);
1934 if let Some(src) = &self.subject {
1935 let gutter = Some(("$ ", st.primary, " ", st.plain));
1936 subject.line(width, gutter, |w| {
1937 w.subject(src, ascii, &st.looks(st.strong));
1938 });
1939 }
1940
1941 let mut reason = Section::new(cap);
1942 reason.line(width, None, |w| {
1943 w.words(&format!("{}: ", words.why), st.muted);
1944 w.prose(&self.reason, ascii, &st.looks(st.plain));
1945 });
1946
1947 let mut note = Section::new(cap);
1948 let note_text = match self.kind {
1949 ReviewKind::Held => Some(&words.held_note),
1950 ReviewKind::Undecided => Some(&words.undecided_note),
1951 ReviewKind::Allowed | ReviewKind::Denied => None,
1952 };
1953 if let Some(n) = note_text {
1954 note.line(width, None, |w| w.words(n, st.strong));
1955 }
1956 let mut waiting = Section::new(cap);
1957 if let Some(wait) = &self.waiting_for {
1958 waiting.line(width, None, |w| {
1959 w.words(&format!("{}: ", words.waiting_for), st.muted);
1960 w.prose(wait, ascii, &st.looks(st.plain));
1961 });
1962 }
1963
1964 // A key that would do nothing is not shown.
1965 let enabled = KeyHints::new(
1966 self.hints
1967 .items
1968 .iter()
1969 .filter(|h| h.enabled)
1970 .cloned()
1971 .collect(),
1972 );
1973 let hint_lines = enabled.lines(u16::try_from(width).unwrap_or(u16::MAX), theme);
1974 let mut hints = Section::new(cap);
1975 for line in hint_lines {
1976 hints.total_rows += 1;
1977 if hints.rows.len() < cap {
1978 hints.rows.push(Row {
1979 spans: line.spans,
1980 units: 0,
1981 });
1982 }
1983 }
1984
1985 // Display order: head, subject, reason, note, waiting, notice, hints.
1986 // Priority: the head, the hints, the action, then the reasons.
1987 let sections = [&head, &subject, &reason, &note, &waiting, &hints];
1988 let priority = [0, 5, 1, 2, 3, 4];
1989 let body_total: usize = sections.iter().map(|s| s.total_rows).sum();
1990 let allocate = |reserve: usize| {
1991 let mut left = h - reserve;
1992 let mut taken = [0usize; 6];
1993 for i in priority {
1994 taken[i] = sections[i].total_rows.min(left);
1995 left -= taken[i];
1996 }
1997 let report = ApprovalPaint {
1998 subject: subject.hidden(taken[1]),
1999 preview: ApprovalHidden::default(),
2000 details: head
2001 .hidden(taken[0])
2002 .plus(reason.hidden(taken[2]))
2003 .plus(note.hidden(taken[3]))
2004 .plus(waiting.hidden(taken[4])),
2005 choices: hints.total_rows.saturating_sub(taken[5]),
2006 non_ascii: 0,
2007 };
2008 (taken, report)
2009 };
2010 let mut reserve = 0;
2011 if body_total > h {
2012 reserve = 1.min(h);
2013 while reserve < h {
2014 let (_, report) = allocate(reserve);
2015 if clip_notice(&words.clip, &report, None, width, reserve, theme, &st).1 {
2016 break;
2017 }
2018 reserve += 1;
2019 }
2020 }
2021 let (taken, report) = allocate(reserve);
2022 let mut rows = Vec::new();
2023 for i in [0, 1, 2, 3, 4] {
2024 rows.extend(
2025 sections[i].rows[..taken[i].min(sections[i].rows.len())]
2026 .iter()
2027 .cloned(),
2028 );
2029 }
2030 if report.clipped() {
2031 let (notice, _) = clip_notice(&words.clip, &report, None, width, reserve, theme, &st);
2032 rows.extend(notice.rows.into_iter().take(reserve));
2033 }
2034 rows.extend(hints.rows[..taken[5].min(hints.rows.len())].iter().cloned());
2035 Composed { rows, report }
2036 }
2037
2038 /// Paint the verdict and say what it did not show.
2039 pub fn render(&self, area: Rect, buf: &mut Buffer, theme: &Theme) -> ApprovalPaint {
2040 let area = area.intersection(buf.area);
2041 let composed = self.compose(usize::from(area.width), usize::from(area.height), theme);
2042 paint_rows(&composed.rows, area, buf);
2043 composed.report
2044 }
2045 }
2046
2047 impl Paint for ReviewVerdict<'_> {
2048 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
2049 self.render(area, buf, theme);
2050 }
2051
2052 fn height(&self, width: u16, theme: &Theme) -> u16 {
2053 let rows = self.compose(usize::from(width), MAX_ROWS, theme).rows.len();
2054 u16::try_from(rows).unwrap_or(u16::MAX)
2055 }
2056 }
2057
2058 // ---------------------------------------------------------------------------
2059 // The aggregate
2060 // ---------------------------------------------------------------------------
2061
2062 /// The words of the aggregate row.
2063 #[derive(Clone, Debug, PartialEq, Eq)]
2064 pub struct ReviewAggregateWords {
2065 pub title: Cow<'static, str>,
2066 pub allowed: Cow<'static, str>,
2067 pub denied: Cow<'static, str>,
2068 pub held: Cow<'static, str>,
2069 pub undecided: Cow<'static, str>,
2070 pub reviewing: Cow<'static, str>,
2071 pub none_yet: Cow<'static, str>,
2072 }
2073
2074 impl Default for ReviewAggregateWords {
2075 fn default() -> Self {
2076 Self {
2077 title: "Auto-Review".into(),
2078 allowed: "allowed".into(),
2079 denied: "denied".into(),
2080 held: "held for you".into(),
2081 undecided: "could not decide".into(),
2082 reviewing: "reviewing".into(),
2083 none_yet: "nothing checked yet".into(),
2084 }
2085 }
2086 }
2087
2088 /// Several verdicts as one row with real counts:
2089 /// `Auto-Review · ✓ 42 allowed · ✕ 3 denied · ◆ 1 held for you · ? 1 could
2090 /// not decide`. A count of zero is left out; a row of zeros says nothing has
2091 /// been checked. Static: no spinner and no highlight.
2092 #[derive(Clone, Debug, Default, PartialEq, Eq)]
2093 pub struct ReviewAggregate {
2094 pub allowed: u32,
2095 pub denied: u32,
2096 pub held: u32,
2097 pub undecided: u32,
2098 /// Reviews running now, shown as `● reviewing 2`.
2099 pub reviewing: u32,
2100 pub words: ReviewAggregateWords,
2101 }
2102
2103 impl ReviewAggregate {
2104 #[must_use]
2105 pub fn new() -> Self {
2106 Self::default()
2107 }
2108
2109 /// Count verdicts.
2110 #[must_use]
2111 pub fn from_kinds(kinds: impl IntoIterator<Item = ReviewKind>) -> Self {
2112 let mut agg = Self::default();
2113 for kind in kinds {
2114 match kind {
2115 ReviewKind::Allowed => agg.allowed += 1,
2116 ReviewKind::Denied => agg.denied += 1,
2117 ReviewKind::Held => agg.held += 1,
2118 ReviewKind::Undecided => agg.undecided += 1,
2119 }
2120 }
2121 agg
2122 }
2123
2124 #[must_use]
2125 pub fn reviewing(mut self, n: u32) -> Self {
2126 self.reviewing = n;
2127 self
2128 }
2129
2130 fn section(&self, width: usize, cap: usize, theme: &Theme) -> Section {
2131 let st = Styles::new(theme);
2132 let ascii = theme.ascii();
2133 let words = &self.words;
2134 let mut items = vec![trusted(&words.title, st.strong)];
2135 let counted = [
2136 (ReviewKind::Allowed, self.allowed, &words.allowed),
2137 (ReviewKind::Denied, self.denied, &words.denied),
2138 (ReviewKind::Held, self.held, &words.held),
2139 (ReviewKind::Undecided, self.undecided, &words.undecided),
2140 ];
2141 let mut any = false;
2142 for (kind, n, word) in counted {
2143 if n == 0 {
2144 continue;
2145 }
2146 any = true;
2147 let state = kind.state();
2148 let mut unit = trusted(
2149 &format!("{} ", glyphs::pick(state.glyph(), ascii)),
2150 theme.fg(state.role()),
2151 );
2152 unit.extend(trusted(&format!("{n} "), st.strong));
2153 unit.extend(trusted(word, st.plain));
2154 items.push(unit);
2155 }
2156 if self.reviewing > 0 {
2157 any = true;
2158 let mut unit = trusted(
2159 &format!("{} ", glyphs::pick(State::Working.glyph(), ascii)),
2160 theme.fg(State::Working.role()),
2161 );
2162 unit.extend(trusted(&format!("{} ", words.reviewing), st.plain));
2163 unit.extend(trusted(&self.reviewing.to_string(), st.strong));
2164 items.push(unit);
2165 }
2166 if !any {
2167 items.push(trusted(&words.none_yet, st.muted));
2168 }
2169 let sep = if ascii {
2170 trusted(" ", st.plain)
2171 } else {
2172 trusted(dot(ascii), st.border)
2173 };
2174 pack(items, &sep, width, cap)
2175 }
2176
2177 /// Paint the row; returns how many items did not fit.
2178 pub fn render(&self, area: Rect, buf: &mut Buffer, theme: &Theme) -> usize {
2179 let area = area.intersection(buf.area);
2180 let sec = self.section(usize::from(area.width), usize::from(area.height), theme);
2181 let hidden = sec.total_chars - choices_shown(&sec, sec.rows.len());
2182 paint_rows(&sec.rows, area, buf);
2183 hidden
2184 }
2185 }
2186
2187 impl Paint for ReviewAggregate {
2188 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
2189 self.render(area, buf, theme);
2190 }
2191
2192 fn height(&self, width: u16, theme: &Theme) -> u16 {
2193 let sec = self.section(usize::from(width), MAX_ROWS, theme);
2194 u16::try_from(sec.total_rows).unwrap_or(u16::MAX)
2195 }
2196 }
2197
2198 // ---------------------------------------------------------------------------
2199 // Native bottom decision band over host-projected display facts
2200 // ---------------------------------------------------------------------------
2201
2202 /// A caller-owned option in canonical decision order. The band never handles
2203 /// its key or decides its effect. A withheld persistent action retains an empty
2204 /// rectangle at this index so pointer dispatch cannot change its meaning.
2205 #[derive(Clone, Debug)]
2206 pub struct DecisionBandAction {
2207 pub line: Line<'static>,
2208 pub persistent: bool,
2209 }
2210
2211 /// Validated rule coverage from the host. The band owns full/compact display
2212 /// fitting; it never reparses a command or constructs a permission rule.
2213 #[derive(Clone, Debug)]
2214 pub struct DecisionBandSave {
2215 pub summary: String,
2216 pub entries: Vec<String>,
2217 pub omitted: usize,
2218 pub label: String,
2219 pub separator: String,
2220 /// `{count}` is replaced with the number of additional rules.
2221 pub compact_more: String,
2222 pub full_more: String,
2223 pub label_style: Style,
2224 pub summary_style: Style,
2225 pub entries_style: Style,
2226 pub more_style: Style,
2227 }
2228
2229 impl DecisionBandSave {
2230 fn lines(&self, width: u16, compact: bool) -> Vec<Line<'static>> {
2231 let entries = self.entries.join("; ");
2232 if compact {
2233 let more = if self.omitted > 0 {
2234 self.compact_more
2235 .replace("{count}", &self.omitted.to_string())
2236 } else {
2237 String::new()
2238 };
2239 let budget = usize::from(width)
2240 .saturating_sub(
2241 2 + self.label.chars().count()
2242 + self.summary.chars().count()
2243 + self.separator.chars().count()
2244 + more.chars().count(),
2245 )
2246 .max(12);
2247 return vec![Line::from(vec![
2248 Span::raw(" "),
2249 Span::styled(self.label.clone(), self.label_style),
2250 Span::styled(self.summary.clone(), self.summary_style),
2251 Span::styled(
2252 format!(
2253 "{}{}{more}",
2254 self.separator,
2255 band_byte_clip(&entries, budget)
2256 ),
2257 self.entries_style,
2258 ),
2259 ])];
2260 }
2261 let mut lines = vec![
2262 Line::from(vec![
2263 Span::raw(" "),
2264 Span::styled(self.label.clone(), self.label_style),
2265 Span::styled(self.summary.clone(), self.summary_style),
2266 ]),
2267 Line::from(vec![
2268 Span::raw(" "),
2269 Span::styled(
2270 band_byte_clip(&entries, usize::from(width.saturating_sub(10)).max(20)),
2271 self.entries_style,
2272 ),
2273 ]),
2274 ];
2275 if self.omitted > 0 {
2276 lines.push(Line::from(vec![
2277 Span::raw(" "),
2278 Span::styled(
2279 self.full_more.replace("{count}", &self.omitted.to_string()),
2280 self.more_style,
2281 ),
2282 ]));
2283 }
2284 lines
2285 }
2286 }
2287
2288 fn band_byte_clip(value: &str, budget: usize) -> String {
2289 // Retain the native host's existing UTF-8-boundary preview contract.
2290 // This coverage is informational; full validated rules stay with the host.
2291 if value.len() <= budget {
2292 return value.to_owned();
2293 }
2294 let budget = budget.saturating_sub(3);
2295 let end = value
2296 .char_indices()
2297 .map(|(index, _)| index)
2298 .take_while(|index| *index <= budget)
2299 .last()
2300 .unwrap_or(0);
2301 format!("{}...", &value[..end])
2302 }
2303
2304 fn band_safe_span(span: &Span<'static>) -> Span<'static> {
2305 let mut safe = span.clone();
2306 if let Cow::Owned(value) = text::display_safe(&span.content) {
2307 safe.content = Cow::Owned(value);
2308 }
2309 safe
2310 }
2311
2312 fn band_safe_line(line: &Line<'static>) -> Line<'static> {
2313 let mut safe = line.clone();
2314 safe.spans = line.spans.iter().map(band_safe_span).collect();
2315 safe
2316 }
2317
2318 /// Exact Ratatui word-wrap measurement, shared by band layout and painting.
2319 #[must_use]
2320 pub fn decision_wrapped_rows(lines: &[Line<'_>], width: u16) -> u16 {
2321 use ratatui::widgets::{Paragraph, Wrap};
2322 let safe: Vec<_> = lines
2323 .iter()
2324 .map(|line| {
2325 let mut safe = line.clone();
2326 for span in &mut safe.spans {
2327 if let Cow::Owned(value) = text::display_safe(&span.content) {
2328 span.content = Cow::Owned(value);
2329 }
2330 }
2331 safe
2332 })
2333 .collect();
2334 let rows = if width == 0 {
2335 lines.len()
2336 } else {
2337 Paragraph::new(safe)
2338 .wrap(Wrap { trim: false })
2339 .line_count(width)
2340 };
2341 u16::try_from(rows).unwrap_or(u16::MAX)
2342 }
2343
2344 /// A native approval band over already-projected host display facts. Labels,
2345 /// styles, badges, risk/effect/owner data and decisions remain host authority.
2346 /// Every span and coverage string is run through [`text::display_safe`] before
2347 /// measurement and painting, preserving styles while removing bidi/controls.
2348 /// These are logical lines; final word-wrap, fit, save visibility, paint and
2349 /// pointer rectangles belong to the single plan below. No input handler or
2350 /// ApprovalState is constructed for this presentation.
2351 #[derive(Clone, Debug)]
2352 pub struct DecisionBand {
2353 pub body: Vec<Line<'static>>,
2354 pub saves: Vec<DecisionBandSave>,
2355 pub question: Line<'static>,
2356 pub actions: Vec<DecisionBandAction>,
2357 pub footer: Line<'static>,
2358 pub save_hint: Option<Span<'static>>,
2359 pub background: Style,
2360 pub rule: Span<'static>,
2361 pub truncation_hint: Span<'static>,
2362 pub collapsed: Option<Line<'static>>,
2363 }
2364
2365 /// The complete painted contract. Empty action boxes remain at their original
2366 /// indices. A host can enable persistent keys only while `save_shown` is true.
2367 #[derive(Clone, Debug)]
2368 pub struct DecisionBandPlan {
2369 pub region: Rect,
2370 pub body_rect: Rect,
2371 pub control_rect: Rect,
2372 pub save_rect: Rect,
2373 pub action_rects: Vec<Rect>,
2374 pub save_shown: bool,
2375 background: Style,
2376 rule: Span<'static>,
2377 hint: Span<'static>,
2378 head: Vec<Line<'static>>,
2379 save: Vec<Line<'static>>,
2380 controls: Vec<Line<'static>>,
2381 head_truncated: bool,
2382 collapsed: Option<Line<'static>>,
2383 }
2384
2385 impl DecisionBand {
2386 fn controls(&self, offer_save: bool) -> Vec<Line<'static>> {
2387 let mut controls = vec![self.question.clone()];
2388 controls.extend(
2389 self.actions
2390 .iter()
2391 .filter(|action| offer_save || !action.persistent)
2392 .map(|action| action.line.clone()),
2393 );
2394 let mut footer = self.footer.clone();
2395 if offer_save && let Some(hint) = &self.save_hint {
2396 footer.spans.push(hint.clone());
2397 }
2398 controls.push(footer);
2399 controls
2400 }
2401
2402 #[must_use]
2403 pub fn plan(&self, area: Rect) -> DecisionBandPlan {
2404 self.sanitized().plan_safe(area)
2405 }
2406
2407 fn sanitized(&self) -> Self {
2408 let mut safe = self.clone();
2409 safe.body = self.body.iter().map(band_safe_line).collect();
2410 safe.question = band_safe_line(&self.question);
2411 for action in &mut safe.actions {
2412 action.line = band_safe_line(&action.line);
2413 }
2414 safe.footer = band_safe_line(&self.footer);
2415 safe.save_hint = self.save_hint.as_ref().map(band_safe_span);
2416 safe.rule = band_safe_span(&self.rule);
2417 safe.truncation_hint = band_safe_span(&self.truncation_hint);
2418 safe.collapsed = self.collapsed.as_ref().map(band_safe_line);
2419 for save in &mut safe.saves {
2420 save.summary = text::display_safe(&save.summary).into_owned();
2421 for entry in &mut save.entries {
2422 *entry = text::display_safe(entry).into_owned();
2423 }
2424 save.label = text::display_safe(&save.label).into_owned();
2425 save.separator = text::display_safe(&save.separator).into_owned();
2426 save.compact_more = text::display_safe(&save.compact_more).into_owned();
2427 save.full_more = text::display_safe(&save.full_more).into_owned();
2428 }
2429 safe
2430 }
2431
2432 fn plan_safe(&self, area: Rect) -> DecisionBandPlan {
2433 let mut result = DecisionBandPlan {
2434 region: Rect::new(area.x, area.bottom(), 0, 0),
2435 body_rect: Rect::default(),
2436 control_rect: Rect::default(),
2437 save_rect: Rect::default(),
2438 action_rects: vec![Rect::default(); self.actions.len()],
2439 save_shown: false,
2440 background: self.background,
2441 rule: self.rule.clone(),
2442 hint: self.truncation_hint.clone(),
2443 head: Vec::new(),
2444 save: Vec::new(),
2445 controls: Vec::new(),
2446 head_truncated: false,
2447 collapsed: None,
2448 };
2449 if area.is_empty() {
2450 return result;
2451 }
2452 if let Some(line) = &self.collapsed {
2453 result.region = Rect::new(area.x, area.bottom().saturating_sub(1), area.width, 1);
2454 result.collapsed = Some(line.clone());
2455 return result;
2456 }
2457 let compact_save: Vec<_> = self
2458 .saves
2459 .iter()
2460 .flat_map(|save| save.lines(area.width, true))
2461 .collect();
2462 let save_reserve = decision_wrapped_rows(&compact_save, area.width);
2463 let controls_with_save = self.controls(true);
2464 let mut compact_body = self.body.clone();
2465 compact_body.extend(compact_save.iter().cloned());
2466 let compact_region = band_region(area, &compact_body, save_reserve, &controls_with_save);
2467 let compact_inner = compact_region.height.saturating_sub(1);
2468 let controls_rows =
2469 decision_wrapped_rows(&controls_with_save, area.width).min(compact_inner);
2470 let save_shown =
2471 !compact_save.is_empty() && save_reserve <= compact_inner.saturating_sub(controls_rows);
2472 let (body, save, controls, reserve) = if save_shown {
2473 let full_save: Vec<_> = self
2474 .saves
2475 .iter()
2476 .flat_map(|save| save.lines(area.width, false))
2477 .collect();
2478 let mut full_body = self.body.clone();
2479 full_body.extend(full_save.iter().cloned());
2480 let full_region = band_region(area, &full_body, save_reserve, &controls_with_save);
2481 let full_inner = full_region.height.saturating_sub(1);
2482 let full_controls =
2483 decision_wrapped_rows(&controls_with_save, area.width).min(full_inner);
2484 if decision_wrapped_rows(&full_body, area.width)
2485 <= full_inner.saturating_sub(full_controls)
2486 {
2487 (full_body, full_save, controls_with_save, save_reserve)
2488 } else {
2489 (compact_body, compact_save, controls_with_save, save_reserve)
2490 }
2491 } else {
2492 (self.body.clone(), Vec::new(), self.controls(false), 0)
2493 };
2494 result.region = band_region(area, &body, reserve, &controls);
2495 result.save_shown = save_shown;
2496 let inner = result.region.height.saturating_sub(1);
2497 let control_rows = decision_wrapped_rows(&controls, area.width).min(inner);
2498 let body_height = inner.saturating_sub(control_rows);
2499 result.body_rect = Rect::new(
2500 area.x,
2501 result.region.y.saturating_add(1),
2502 area.width,
2503 body_height,
2504 );
2505 result.control_rect =
2506 Rect::new(area.x, result.body_rect.bottom(), area.width, control_rows);
2507 let body_truncated = decision_wrapped_rows(&body, area.width) > body_height;
2508 let save_rows = if body_truncated {
2509 decision_wrapped_rows(&save, area.width).min(body_height)
2510 } else {
2511 decision_wrapped_rows(&save, area.width)
2512 };
2513 result.save_rect = Rect::new(
2514 area.x,
2515 if body_truncated {
2516 result.body_rect.bottom().saturating_sub(save_rows)
2517 } else {
2518 result
2519 .body_rect
2520 .y
2521 .saturating_add(decision_wrapped_rows(&self.body, area.width))
2522 },
2523 area.width,
2524 save_rows,
2525 );
2526 result.head_truncated = body_truncated;
2527 result.head = if body_truncated {
2528 self.body.clone()
2529 } else {
2530 body
2531 };
2532 result.save = if body_truncated { save } else { Vec::new() };
2533 let mut shown_index = 0;
2534 for (index, action) in self.actions.iter().enumerate() {
2535 if action.persistent && !save_shown {
2536 continue;
2537 }
2538 let first = 1 + shown_index;
2539 shown_index += 1;
2540 let top = decision_wrapped_rows(&controls[..first], area.width);
2541 let bottom = decision_wrapped_rows(&controls[..first + 1], area.width);
2542 let y = result.control_rect.y.saturating_add(top);
2543 let height = bottom
2544 .saturating_sub(top)
2545 .min(result.control_rect.bottom().saturating_sub(y));
2546 if height > 0 {
2547 result.action_rects[index] = Rect::new(area.x, y, area.width, height);
2548 }
2549 }
2550 result.controls = controls;
2551 result
2552 }
2553
2554 /// Paint and return the exact interactive contract for the visible buffer.
2555 pub fn render(&self, area: Rect, buf: &mut Buffer) -> DecisionBandPlan {
2556 let plan = self.plan(area.intersection(buf.area));
2557 plan.paint(buf);
2558 plan
2559 }
2560 }
2561
2562 impl DecisionBandPlan {
2563 fn paint(&self, buf: &mut Buffer) {
2564 use ratatui::widgets::{Block, Clear, Paragraph, Widget, Wrap};
2565 if self.region.is_empty() {
2566 return;
2567 }
2568 Clear.render(self.region, buf);
2569 if let Some(line) = &self.collapsed {
2570 Paragraph::new(line.clone()).render(self.region, buf);
2571 return;
2572 }
2573 Block::default()
2574 .style(self.background)
2575 .render(self.region, buf);
2576 let rule = self.rule.content.repeat(usize::from(self.region.width));
2577 buf.set_stringn(
2578 self.region.x,
2579 self.region.y,
2580 rule,
2581 usize::from(self.region.width),
2582 self.rule.style,
2583 );
2584 if self.head_truncated {
2585 let head_height = self.body_rect.height.saturating_sub(self.save_rect.height);
2586 if head_height > 0 {
2587 let shown = head_height.saturating_sub(1);
2588 if shown > 0 {
2589 Paragraph::new(self.head.clone())
2590 .wrap(Wrap { trim: false })
2591 .render(
2592 Rect {
2593 height: shown,
2594 ..self.body_rect
2595 },
2596 buf,
2597 );
2598 }
2599 buf.set_span(
2600 self.region.x,
2601 self.body_rect.y.saturating_add(shown),
2602 &self.hint,
2603 self.region.width,
2604 );
2605 }
2606 if self.save_rect.height > 0 {
2607 Paragraph::new(self.save.clone())
2608 .wrap(Wrap { trim: false })
2609 .render(self.save_rect, buf);
2610 }
2611 } else {
2612 Paragraph::new(self.head.clone())
2613 .wrap(Wrap { trim: false })
2614 .render(self.body_rect, buf);
2615 }
2616 Paragraph::new(self.controls.clone())
2617 .wrap(Wrap { trim: false })
2618 .render(self.control_rect, buf);
2619 }
2620 }
2621
2622 fn band_region(
2623 area: Rect,
2624 body: &[Line<'static>],
2625 save_rows: u16,
2626 controls: &[Line<'static>],
2627 ) -> Rect {
2628 if area.is_empty() {
2629 return Rect::new(area.x, area.bottom(), 0, 0);
2630 }
2631 let body_rows = decision_wrapped_rows(body, area.width);
2632 let control_rows = decision_wrapped_rows(controls, area.width);
2633 let desired = 1u16.saturating_add(body_rows).saturating_add(control_rows);
2634 let controls_floor = 1u16.saturating_add(control_rows).min(area.height);
2635 let head_rows = body_rows.saturating_sub(save_rows);
2636 let preview_rows = if area.height >= 16 {
2637 head_rows.min(4).saturating_add(save_rows)
2638 } else {
2639 save_rows
2640 };
2641 let preview_floor = controls_floor.saturating_add(preview_rows).min(area.height);
2642 let preferred_cap = area.height.div_ceil(2);
2643 let short_cap = area.height.saturating_mul(4).div_ceil(5);
2644 let save_floor = controls_floor.saturating_add(save_rows).min(area.height);
2645 let max_height = preferred_cap
2646 .max(preview_floor.min(short_cap.saturating_add(save_rows)))
2647 .max(save_floor)
2648 .min(area.height);
2649 let height = desired.clamp(controls_floor, max_height);
2650 Rect::new(
2651 area.x,
2652 area.y.saturating_add(area.height.saturating_sub(height)),
2653 area.width,
2654 height,
2655 )
2656 }
2657
2658 impl Paint for DecisionBand {
2659 fn paint(&self, area: Rect, buf: &mut Buffer, _theme: &Theme) {
2660 self.render(area, buf);
2661 }
2662 fn height(&self, width: u16, _theme: &Theme) -> u16 {
2663 self.plan(Rect::new(0, 0, width, u16::MAX)).region.height
2664 }
2665 }
2666
2666 lines RUST