| 1 | //! Approval option selection and modal state. |
| 2 | //! |
| 3 | //! This module owns approval-card interaction and event emission. Risk policy, |
| 4 | //! persistent rules, preview formatting, and sandbox elevation remain separate |
| 5 | //! authority boundaries. |
| 6 | //! |
| 7 | //! Enter allows the highlighted action by default, so an Enter that approves |
| 8 | //! is admitted only after the card has been the top prompt for |
| 9 | //! `ENTER_ARMING_DELAY` (the view stack re-arms it each time the card becomes |
| 10 | //! the top view again) and `ENTER_QUIET_GAP` after the previous Enter or |
| 11 | //! character key on this card. A refused Enter says so in a status notice. |
| 12 | //! Known limits: a key-repeat delay longer than the arming delay, a repeat |
| 13 | //! slower than the quiet gap, and the letter shortcuts (`y`, `a`, `1`) are |
| 14 | //! not covered by this guard. Unit tests answer a card the instant it is |
| 15 | //! built, so the guard starts off under `cfg(test)` and a test turns it on. |
| 16 | |
| 17 | use std::cell::{Cell, RefCell}; |
| 18 | use std::time::{Duration, Instant}; |
| 19 | |
| 20 | use codewhale_config::ToolAskRule; |
| 21 | use crossterm::event::{ |
| 22 | KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, |
| 23 | }; |
| 24 | use ratatui::layout::Rect; |
| 25 | |
| 26 | use crate::tui::views::{ModalKind, ModalView, ViewAction, ViewEvent}; |
| 27 | use crate::tui::widgets::{ApprovalWidget, Renderable}; |
| 28 | use codewhale_execpolicy::canonical_action::canonical_action_alias; |
| 29 | use codewhale_localization::{Locale, MessageId, tr}; |
| 30 | use codewhale_runtime::config::ApprovalDefaultSelection; |
| 31 | |
| 32 | use super::previews::exact_edit_file_preview_lines; |
| 33 | use super::{ApprovalRequest, ReviewDecision}; |
| 34 | #[cfg(test)] |
| 35 | use codewhale_engine::core::authority::RiskLevel; |
| 36 | |
| 37 | pub(crate) const ENTER_ARMING_DELAY: Duration = Duration::from_millis(750); |
| 38 | pub(crate) const ENTER_QUIET_GAP: Duration = Duration::from_millis(200); |
| 39 | |
| 40 | /// Indices into the option list shared by both variants. |
| 41 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 42 | pub enum ApprovalOption { |
| 43 | ApproveOnce, |
| 44 | ApproveAlways, |
| 45 | AllowExactRepo, |
| 46 | Deny, |
| 47 | Abort, |
| 48 | OpenPermissions, |
| 49 | } |
| 50 | |
| 51 | impl ApprovalOption { |
| 52 | const ORDER: [ApprovalOption; 3] = [ |
| 53 | ApprovalOption::ApproveOnce, |
| 54 | ApprovalOption::ApproveAlways, |
| 55 | ApprovalOption::Deny, |
| 56 | ]; |
| 57 | const ORDER_WITH_PERSISTENT_ALLOW: [ApprovalOption; 3] = [ |
| 58 | ApprovalOption::ApproveOnce, |
| 59 | ApprovalOption::AllowExactRepo, |
| 60 | ApprovalOption::Deny, |
| 61 | ]; |
| 62 | |
| 63 | /// Workflow elevated-plan card (#4126): Approve / Edit plan / Cancel. |
| 64 | const WORKFLOW_ORDER: [ApprovalOption; 3] = [ |
| 65 | ApprovalOption::ApproveOnce, |
| 66 | ApprovalOption::Deny, |
| 67 | ApprovalOption::Abort, |
| 68 | ]; |
| 69 | |
| 70 | fn order_for(request: &ApprovalRequest) -> &'static [ApprovalOption] { |
| 71 | if request.tool_name == "workflow" { |
| 72 | &Self::WORKFLOW_ORDER |
| 73 | } else if request.owner.is_none() && request.can_save_allow_rule() { |
| 74 | &Self::ORDER_WITH_PERSISTENT_ALLOW |
| 75 | } else { |
| 76 | &Self::ORDER |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | pub(crate) fn from_index_for(request: &ApprovalRequest, idx: usize) -> ApprovalOption { |
| 81 | Self::order_for(request) |
| 82 | .get(idx) |
| 83 | .copied() |
| 84 | .unwrap_or(Self::Abort) |
| 85 | } |
| 86 | |
| 87 | fn index_for(self, request: &ApprovalRequest) -> usize { |
| 88 | Self::order_for(request) |
| 89 | .iter() |
| 90 | .position(|o| *o == self) |
| 91 | .unwrap_or(Self::order_for(request).len().saturating_sub(1)) |
| 92 | } |
| 93 | |
| 94 | fn decision(self) -> Option<ReviewDecision> { |
| 95 | Some(match self { |
| 96 | ApprovalOption::ApproveOnce => ReviewDecision::Approved, |
| 97 | ApprovalOption::ApproveAlways => ReviewDecision::ApprovedForSession, |
| 98 | ApprovalOption::AllowExactRepo => ReviewDecision::Approved, |
| 99 | // Workflow maps Deny → "Edit plan" (model revises plan). |
| 100 | ApprovalOption::Deny => ReviewDecision::Denied, |
| 101 | ApprovalOption::Abort => ReviewDecision::Abort, |
| 102 | ApprovalOption::OpenPermissions => return None, |
| 103 | }) |
| 104 | } |
| 105 | |
| 106 | fn grants(self) -> bool { |
| 107 | matches!( |
| 108 | self.decision(), |
| 109 | Some(ReviewDecision::Approved | ReviewDecision::ApprovedForSession) |
| 110 | ) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | /// Approval overlay state managed by the modal view stack |
| 115 | #[derive(Debug, Clone)] |
| 116 | pub struct ApprovalView { |
| 117 | request: ApprovalRequest, |
| 118 | pub(super) selected: usize, |
| 119 | pub(crate) scope_selected: ApprovalOption, |
| 120 | pub(super) row_hitboxes: RefCell<Vec<Rect>>, |
| 121 | pub(super) scopes_toggle_hitbox: RefCell<Option<Rect>>, |
| 122 | pub(super) details_toggle_hitbox: RefCell<Option<Rect>>, |
| 123 | pub(super) scope_menu_hitboxes: RefCell<Vec<(ApprovalOption, Rect)>>, |
| 124 | /// Whether the last paint showed the persistent-rule save preview. The |
| 125 | /// save offer (`[2 / p]`) only works while it is on screen, so a |
| 126 | /// person never saves a rule without seeing what it covers. Starts |
| 127 | /// false: nothing is offered before the card has been painted. |
| 128 | save_preview_shown: Cell<bool>, |
| 129 | details_shown: Cell<bool>, |
| 130 | locale: Locale, |
| 131 | pub(super) timeout: Option<Duration>, |
| 132 | pub(super) requested_at: Instant, |
| 133 | pub(crate) scopes_open: bool, |
| 134 | pub(crate) details_expanded: bool, |
| 135 | pub(super) answerable_since: Option<Instant>, |
| 136 | pub(super) last_enter_at: Option<Instant>, |
| 137 | pub(super) last_char_key_at: Option<Instant>, |
| 138 | pub(super) enter_guard: bool, |
| 139 | } |
| 140 | |
| 141 | impl ApprovalView { |
| 142 | #[cfg(test)] |
| 143 | pub fn new(request: ApprovalRequest) -> Self { |
| 144 | Self::new_for_locale(request, Locale::En) |
| 145 | } |
| 146 | |
| 147 | #[cfg(test)] |
| 148 | pub fn new_for_locale(request: ApprovalRequest, locale: Locale) -> Self { |
| 149 | Self::new_with_default_selection(request, locale, ApprovalDefaultSelection::default()) |
| 150 | } |
| 151 | |
| 152 | /// `default_selection` is `[approval] default_selection` (#5293). The |
| 153 | /// default highlights "allow once", so Enter allows the one action shown; |
| 154 | /// `deny` is a user opting into Enter refusing it. |
| 155 | pub fn new_with_default_selection( |
| 156 | request: ApprovalRequest, |
| 157 | locale: Locale, |
| 158 | default_selection: ApprovalDefaultSelection, |
| 159 | ) -> Self { |
| 160 | // Resolve the semantic option because its numeric index differs for |
| 161 | // persistent-allow and workflow approval cards. |
| 162 | let selected = match default_selection { |
| 163 | ApprovalDefaultSelection::Deny => ApprovalOption::Deny, |
| 164 | ApprovalDefaultSelection::AllowOnce => ApprovalOption::ApproveOnce, |
| 165 | } |
| 166 | .index_for(&request); |
| 167 | Self { |
| 168 | request, |
| 169 | selected, |
| 170 | scope_selected: ApprovalOption::ApproveOnce, |
| 171 | row_hitboxes: RefCell::new(Vec::new()), |
| 172 | scopes_toggle_hitbox: RefCell::new(None), |
| 173 | details_toggle_hitbox: RefCell::new(None), |
| 174 | scope_menu_hitboxes: RefCell::new(Vec::new()), |
| 175 | save_preview_shown: Cell::new(false), |
| 176 | details_shown: Cell::new(false), |
| 177 | locale, |
| 178 | timeout: None, |
| 179 | requested_at: Instant::now(), |
| 180 | scopes_open: false, |
| 181 | details_expanded: false, |
| 182 | answerable_since: None, |
| 183 | last_enter_at: None, |
| 184 | last_char_key_at: None, |
| 185 | enter_guard: !cfg!(test), |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | /// Bound how long this card may wait (#6101). `Some(timeout)` resolves |
| 190 | /// the card to **deny** once the duration elapses (fail-closed); `None` |
| 191 | /// waits indefinitely. A zero duration is treated as `None` so the |
| 192 | /// config convention (`0` = wait forever) holds at this layer too. |
| 193 | #[must_use] |
| 194 | pub fn with_timeout(mut self, timeout: Option<Duration>) -> Self { |
| 195 | self.timeout = timeout.filter(|timeout| !timeout.is_zero()); |
| 196 | self |
| 197 | } |
| 198 | |
| 199 | pub(super) fn select_prev(&mut self) { |
| 200 | self.step_selection(-1); |
| 201 | } |
| 202 | |
| 203 | pub(super) fn select_next(&mut self) { |
| 204 | self.step_selection(1); |
| 205 | } |
| 206 | |
| 207 | fn scope_options(&self) -> Vec<ApprovalOption> { |
| 208 | if self.is_workflow_plan_approval() { |
| 209 | return ApprovalOption::WORKFLOW_ORDER.to_vec(); |
| 210 | } |
| 211 | let mut options = vec![ApprovalOption::ApproveOnce, ApprovalOption::ApproveAlways]; |
| 212 | if self.request.owner.is_none() && self.request.can_save_allow_rule() { |
| 213 | options.push(ApprovalOption::AllowExactRepo); |
| 214 | } |
| 215 | if self.offers_permission_settings() { |
| 216 | options.push(ApprovalOption::OpenPermissions); |
| 217 | } |
| 218 | options |
| 219 | } |
| 220 | |
| 221 | pub(crate) fn offers_permission_settings(&self) -> bool { |
| 222 | self.request.owner.is_none() && !self.is_workflow_plan_approval() |
| 223 | } |
| 224 | |
| 225 | fn toggle_scopes(&mut self) { |
| 226 | self.scopes_open = !self.scopes_open; |
| 227 | if self.scopes_open { |
| 228 | self.details_expanded = false; |
| 229 | self.scope_selected = ApprovalOption::ApproveOnce; |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | fn toggle_details(&mut self) { |
| 234 | self.details_expanded = !self.details_expanded; |
| 235 | if self.details_expanded { |
| 236 | self.scopes_open = false; |
| 237 | self.details_shown.set(true); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | /// Move the selection, skipping options the card is not offering. |
| 242 | fn step_selection(&mut self, delta: isize) { |
| 243 | if self.scopes_open { |
| 244 | let options = self.scope_options(); |
| 245 | let current = options |
| 246 | .iter() |
| 247 | .position(|opt| *opt == self.scope_selected) |
| 248 | .unwrap_or(0); |
| 249 | let mut next = current; |
| 250 | for _ in 0..options.len() { |
| 251 | next = codewhale_tui_kit::list_nav::wrap_index(next, options.len(), delta); |
| 252 | if self.offers(options[next]) { |
| 253 | self.scope_selected = options[next]; |
| 254 | break; |
| 255 | } |
| 256 | } |
| 257 | return; |
| 258 | } |
| 259 | if !self.is_workflow_plan_approval() { |
| 260 | let next = if self.current_option() == ApprovalOption::ApproveOnce { |
| 261 | ApprovalOption::Deny |
| 262 | } else { |
| 263 | ApprovalOption::ApproveOnce |
| 264 | }; |
| 265 | self.selected = next.index_for(&self.request); |
| 266 | return; |
| 267 | } |
| 268 | let order = ApprovalOption::order_for(&self.request); |
| 269 | let mut selected = self.selected; |
| 270 | for _ in 0..order.len() { |
| 271 | selected = codewhale_tui_kit::list_nav::wrap_index(selected, order.len(), delta); |
| 272 | if self.offers(order[selected]) { |
| 273 | break; |
| 274 | } |
| 275 | } |
| 276 | self.selected = selected; |
| 277 | } |
| 278 | |
| 279 | /// Whether the card currently offers `option`. Persistent rules require |
| 280 | /// their painted preview; hidden session grants require opening details. |
| 281 | pub(crate) fn offers(&self, option: ApprovalOption) -> bool { |
| 282 | match option { |
| 283 | ApprovalOption::OpenPermissions => { |
| 284 | self.scopes_open |
| 285 | && self |
| 286 | .scope_menu_hitboxes |
| 287 | .borrow() |
| 288 | .iter() |
| 289 | .any(|(option, _)| *option == ApprovalOption::OpenPermissions) |
| 290 | } |
| 291 | ApprovalOption::AllowExactRepo => self.save_preview_shown.get(), |
| 292 | ApprovalOption::ApproveAlways => { |
| 293 | ApprovalOption::order_for(&self.request).contains(&option) |
| 294 | || self.details_shown.get() |
| 295 | || self.scopes_open |
| 296 | } |
| 297 | _ => true, |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /// Record whether the paint that just ran showed the save preview. |
| 302 | pub(crate) fn set_save_preview_shown(&self, shown: bool) { |
| 303 | self.save_preview_shown.set(shown); |
| 304 | } |
| 305 | |
| 306 | pub(super) fn current_option(&self) -> ApprovalOption { |
| 307 | if self.scopes_open { |
| 308 | self.scope_selected |
| 309 | } else { |
| 310 | ApprovalOption::from_index_for(&self.request, self.selected) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | /// The agent that owns this card, when it is a child's request. |
| 315 | #[cfg(test)] |
| 316 | #[must_use] |
| 317 | pub fn owner(&self) -> Option<&super::ApprovalOwner> { |
| 318 | self.request.owner.as_ref() |
| 319 | } |
| 320 | |
| 321 | /// Whether this approval is the elevated Workflow plan card (#4126). |
| 322 | #[must_use] |
| 323 | pub fn is_workflow_plan_approval(&self) -> bool { |
| 324 | self.request.tool_name == "workflow" |
| 325 | } |
| 326 | |
| 327 | /// Test-only accessor for the selected option's decision. |
| 328 | #[cfg(test)] |
| 329 | pub(super) fn current_decision(&self) -> ReviewDecision { |
| 330 | self.current_option().decision().expect("approval decision") |
| 331 | } |
| 332 | |
| 333 | /// Selected option for the renderer (used by the widget tests too). |
| 334 | pub fn selected(&self) -> usize { |
| 335 | self.selected |
| 336 | } |
| 337 | |
| 338 | pub(crate) fn set_mouse_hitboxes(&self, hitboxes: Vec<Rect>) { |
| 339 | *self.row_hitboxes.borrow_mut() = hitboxes; |
| 340 | } |
| 341 | |
| 342 | pub(crate) fn set_scopes_toggle_hitbox(&self, hitbox: Option<Rect>) { |
| 343 | *self.scopes_toggle_hitbox.borrow_mut() = hitbox; |
| 344 | } |
| 345 | |
| 346 | pub(crate) fn set_details_toggle_hitbox(&self, hitbox: Option<Rect>) { |
| 347 | *self.details_toggle_hitbox.borrow_mut() = hitbox; |
| 348 | } |
| 349 | |
| 350 | pub(crate) fn set_scope_menu_hitboxes(&self, hitboxes: Vec<(ApprovalOption, Rect)>) { |
| 351 | *self.scope_menu_hitboxes.borrow_mut() = hitboxes; |
| 352 | } |
| 353 | |
| 354 | /// Risk level for the renderer's accent picking. |
| 355 | #[cfg(test)] |
| 356 | pub fn risk(&self) -> RiskLevel { |
| 357 | self.request.risk |
| 358 | } |
| 359 | |
| 360 | pub(crate) fn locale(&self) -> Locale { |
| 361 | self.locale |
| 362 | } |
| 363 | |
| 364 | pub(super) fn enter_may_commit(&mut self, option: ApprovalOption, now: Instant) -> bool { |
| 365 | if !self.enter_guard { |
| 366 | return true; |
| 367 | } |
| 368 | let answerable_since = *self.answerable_since.get_or_insert(now); |
| 369 | let previous_enter = self.last_enter_at.replace(now); |
| 370 | if !option.grants() { |
| 371 | return true; |
| 372 | } |
| 373 | now.saturating_duration_since(answerable_since) >= ENTER_ARMING_DELAY |
| 374 | && previous_enter.is_none_or(|at| now.saturating_duration_since(at) >= ENTER_QUIET_GAP) |
| 375 | && self |
| 376 | .last_char_key_at |
| 377 | .is_none_or(|at| now.saturating_duration_since(at) >= ENTER_QUIET_GAP) |
| 378 | } |
| 379 | |
| 380 | /// Commit the given option and close the approval modal. |
| 381 | fn commit_option(&mut self, option: ApprovalOption) -> ViewAction { |
| 382 | if !self.offers(option) { |
| 383 | // Fail closed: a rule whose coverage is not on screen is never |
| 384 | // saved, and nothing else is decided in its place. |
| 385 | return ViewAction::None; |
| 386 | } |
| 387 | let Some(decision) = option.decision() else { |
| 388 | return ViewAction::Emit(ViewEvent::OpenPermissionSettings); |
| 389 | }; |
| 390 | self.selected = option.index_for(&self.request); |
| 391 | if option == ApprovalOption::AllowExactRepo && self.request.can_save_allow_rule() { |
| 392 | self.emit_decision_with_rules( |
| 393 | decision, |
| 394 | false, |
| 395 | self.request.persistent_allow_rules.clone(), |
| 396 | ) |
| 397 | } else { |
| 398 | self.emit_decision(decision, false) |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | fn emit_decision(&self, decision: ReviewDecision, timed_out: bool) -> ViewAction { |
| 403 | self.emit_decision_with_rules(decision, timed_out, Vec::new()) |
| 404 | } |
| 405 | |
| 406 | fn emit_decision_with_rules( |
| 407 | &self, |
| 408 | decision: ReviewDecision, |
| 409 | timed_out: bool, |
| 410 | persistent_rules: Vec<ToolAskRule>, |
| 411 | ) -> ViewAction { |
| 412 | ViewAction::EmitAndClose(ViewEvent::ApprovalDecision { |
| 413 | tool_id: self.request.id.clone(), |
| 414 | tool_name: self.request.tool_name.clone(), |
| 415 | decision, |
| 416 | timed_out, |
| 417 | approval_key: self.request.approval_key.clone(), |
| 418 | approval_grouping_key: self.request.approval_grouping_key.clone(), |
| 419 | persistent_rules, |
| 420 | subject: Some(self.request.receipt_subject()), |
| 421 | }) |
| 422 | } |
| 423 | |
| 424 | fn emit_params_pager(&self) -> ViewAction { |
| 425 | // The compact prompt keeps the about/impact dossier out of the |
| 426 | // default band; the pager is where that context now lives. |
| 427 | let locale = self.locale(); |
| 428 | let about_label = tr(locale, MessageId::ApprovalLabelAbout); |
| 429 | let impact_label = tr(locale, MessageId::ApprovalLabelImpact); |
| 430 | let mut content = String::new(); |
| 431 | content.push_str(&about_label); |
| 432 | content.push_str(&self.request.description_for_locale(locale)); |
| 433 | content.push('\n'); |
| 434 | for impact in self.request.impacts_for_locale(locale) { |
| 435 | content.push_str(&impact_label); |
| 436 | content.push_str(&impact); |
| 437 | content.push('\n'); |
| 438 | } |
| 439 | content.push('\n'); |
| 440 | if canonical_action_alias(&self.request.tool_name, &self.request.params) == "edit_file" |
| 441 | && let Some(preview_lines) = exact_edit_file_preview_lines(&self.request.params, locale) |
| 442 | { |
| 443 | content.push_str(&tr(locale, MessageId::ApprovalLabelPreview)); |
| 444 | content.push_str(":\n"); |
| 445 | for line in preview_lines { |
| 446 | content.push_str(&line); |
| 447 | content.push('\n'); |
| 448 | } |
| 449 | content.push('\n'); |
| 450 | } |
| 451 | if !self.is_workflow_plan_approval() { |
| 452 | content.push_str(&format!( |
| 453 | "[a] {}\n", |
| 454 | tr(locale, MessageId::ApprovalOptionApproveAlways) |
| 455 | )); |
| 456 | } |
| 457 | if let Some(preview) = self.request.ask_rule_save_preview() { |
| 458 | content.push_str(&format!( |
| 459 | "[s] {}\n {} {} · {}{}\n", |
| 460 | tr(locale, MessageId::ApprovalSaveAskRuleHint) |
| 461 | .trim_start_matches(|c: char| c.is_whitespace() || c == '·') |
| 462 | .trim_start_matches("s ") |
| 463 | .trim(), |
| 464 | tr(locale, MessageId::ApprovalFieldSave).trim_end(), |
| 465 | preview.summary(locale), |
| 466 | preview.entries.join(" · "), |
| 467 | if preview.omitted > 0 { |
| 468 | format!( |
| 469 | " +{}", |
| 470 | tr(locale, MessageId::ApprovalSaveMore) |
| 471 | .replace("{count}", &preview.omitted.to_string()) |
| 472 | ) |
| 473 | } else { |
| 474 | String::new() |
| 475 | } |
| 476 | )); |
| 477 | } |
| 478 | if self.request.owner.is_none() { |
| 479 | content.push_str(&format!( |
| 480 | "[Esc] {}\n", |
| 481 | tr(locale, MessageId::ApprovalOptionAbortTurn) |
| 482 | )); |
| 483 | } |
| 484 | content.push('\n'); |
| 485 | content.push_str( |
| 486 | &serde_json::to_string_pretty(&self.request.params) |
| 487 | .unwrap_or_else(|_| self.request.params.to_string()), |
| 488 | ); |
| 489 | self.details_shown.set(true); |
| 490 | ViewAction::Emit(ViewEvent::OpenTextPager { |
| 491 | title: tr(locale, MessageId::ApprovalToolParamsTitle) |
| 492 | .replace("{tool}", &self.request.tool_name), |
| 493 | content, |
| 494 | }) |
| 495 | } |
| 496 | |
| 497 | fn is_timed_out(&self) -> bool { |
| 498 | match self.timeout { |
| 499 | Some(timeout) => self.requested_at.elapsed() >= timeout, |
| 500 | None => false, |
| 501 | } |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | impl ModalView for ApprovalView { |
| 506 | fn kind(&self) -> ModalKind { |
| 507 | ModalKind::Approval |
| 508 | } |
| 509 | |
| 510 | fn approval_request_id(&self) -> Option<&str> { |
| 511 | Some(&self.request.id) |
| 512 | } |
| 513 | |
| 514 | fn as_any_mut(&mut self) -> &mut dyn std::any::Any { |
| 515 | self |
| 516 | } |
| 517 | |
| 518 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 519 | if key.kind != KeyEventKind::Press { |
| 520 | return ViewAction::None; |
| 521 | } |
| 522 | if self.offers_permission_settings() |
| 523 | && crate::tui::shell_key_routing::is_permission_cycle_shortcut(&key) |
| 524 | { |
| 525 | return ViewAction::Emit(ViewEvent::OpenPermissionSettings); |
| 526 | } |
| 527 | // Details and permissions routes never answer the approval. |
| 528 | if crate::tui::shell_key_routing::is_tool_details_shortcut(&key) { |
| 529 | return self.emit_params_pager(); |
| 530 | } |
| 531 | if !key.modifiers.difference(KeyModifiers::SHIFT).is_empty() { |
| 532 | return ViewAction::None; |
| 533 | } |
| 534 | let now = Instant::now(); |
| 535 | if key.code == KeyCode::Enter { |
| 536 | let option = self.current_option(); |
| 537 | if !self.enter_may_commit(option, now) { |
| 538 | return ViewAction::Emit(ViewEvent::StatusToast { |
| 539 | message: tr(self.locale, MessageId::ApprovalEnterIgnored).into_owned(), |
| 540 | level: crate::tui::app::StatusToastLevel::Info, |
| 541 | }); |
| 542 | } |
| 543 | return self.commit_option(option); |
| 544 | } |
| 545 | self.answerable_since.get_or_insert(now); |
| 546 | if matches!(key.code, KeyCode::Char(_)) { |
| 547 | self.last_char_key_at = Some(now); |
| 548 | } |
| 549 | match key.code { |
| 550 | KeyCode::Tab | KeyCode::Char('d') | KeyCode::Char('D') => { |
| 551 | self.toggle_details(); |
| 552 | ViewAction::None |
| 553 | } |
| 554 | KeyCode::Char('m') | KeyCode::Char('M') => { |
| 555 | self.toggle_scopes(); |
| 556 | ViewAction::None |
| 557 | } |
| 558 | KeyCode::Up | KeyCode::Left | KeyCode::Char('k') => { |
| 559 | self.select_prev(); |
| 560 | ViewAction::None |
| 561 | } |
| 562 | KeyCode::Down | KeyCode::Right | KeyCode::Char('j') => { |
| 563 | self.select_next(); |
| 564 | ViewAction::None |
| 565 | } |
| 566 | // Direct shortcuts; '1' / '2' map to the first two options |
| 567 | // so a numeric pad still works for approve flows. |
| 568 | KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Char('1') => { |
| 569 | self.commit_option(ApprovalOption::ApproveOnce) |
| 570 | } |
| 571 | KeyCode::Char('2') if self.scopes_open && !self.is_workflow_plan_approval() => { |
| 572 | self.commit_option(ApprovalOption::ApproveAlways) |
| 573 | } |
| 574 | KeyCode::Char('3') if self.scopes_open && !self.is_workflow_plan_approval() => { |
| 575 | self.commit_option(ApprovalOption::AllowExactRepo) |
| 576 | } |
| 577 | KeyCode::Char('p') | KeyCode::Char('P') |
| 578 | if !self.is_workflow_plan_approval() |
| 579 | && ApprovalOption::order_for(&self.request) |
| 580 | .contains(&ApprovalOption::AllowExactRepo) => |
| 581 | { |
| 582 | self.commit_option(ApprovalOption::AllowExactRepo) |
| 583 | } |
| 584 | KeyCode::Char('a') | KeyCode::Char('A') if !self.is_workflow_plan_approval() => { |
| 585 | self.commit_option(ApprovalOption::ApproveAlways) |
| 586 | } |
| 587 | // Workflow plan card (#4126): [2/e] Edit plan, [3/n/d] Cancel. |
| 588 | KeyCode::Char('e') | KeyCode::Char('E') | KeyCode::Char('2') |
| 589 | if self.is_workflow_plan_approval() => |
| 590 | { |
| 591 | self.commit_option(ApprovalOption::Deny) |
| 592 | } |
| 593 | KeyCode::Char('s') | KeyCode::Char('S') |
| 594 | if self.request.can_save_ask_rule() && self.details_shown.get() => |
| 595 | { |
| 596 | self.emit_decision_with_rules( |
| 597 | ReviewDecision::Approved, |
| 598 | false, |
| 599 | self.request.persistent_ask_rules.clone(), |
| 600 | ) |
| 601 | } |
| 602 | KeyCode::Char('n') | KeyCode::Char('N') => { |
| 603 | if self.is_workflow_plan_approval() { |
| 604 | self.commit_option(ApprovalOption::Abort) |
| 605 | } else { |
| 606 | self.commit_option(ApprovalOption::Deny) |
| 607 | } |
| 608 | } |
| 609 | KeyCode::Char('3') if self.is_workflow_plan_approval() => { |
| 610 | self.commit_option(ApprovalOption::Abort) |
| 611 | } |
| 612 | KeyCode::Esc if self.scopes_open => { |
| 613 | self.scopes_open = false; |
| 614 | ViewAction::None |
| 615 | } |
| 616 | // A child's card hides on Esc: the request stays pending (footer |
| 617 | // row, `/agents`) and the parent's turn is never cancelled. |
| 618 | KeyCode::Esc if self.request.owner.is_some() => ViewAction::Close, |
| 619 | KeyCode::Esc => self.emit_decision(ReviewDecision::Abort, false), |
| 620 | KeyCode::Char('g') | KeyCode::Char('G') => match self.request.owner.as_ref() { |
| 621 | Some(owner) => ViewAction::Emit(ViewEvent::OpenAgentTranscript { |
| 622 | agent_id: owner.agent_id.clone(), |
| 623 | }), |
| 624 | None => ViewAction::None, |
| 625 | }, |
| 626 | _ => ViewAction::None, |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction { |
| 631 | match mouse.kind { |
| 632 | MouseEventKind::ScrollUp => { |
| 633 | self.select_prev(); |
| 634 | ViewAction::None |
| 635 | } |
| 636 | MouseEventKind::ScrollDown => { |
| 637 | self.select_next(); |
| 638 | ViewAction::None |
| 639 | } |
| 640 | MouseEventKind::Down(MouseButton::Left) => { |
| 641 | let pos = ratatui::layout::Position::new(mouse.column, mouse.row); |
| 642 | if self |
| 643 | .scopes_toggle_hitbox |
| 644 | .borrow() |
| 645 | .is_some_and(|rect| rect.contains(pos)) |
| 646 | { |
| 647 | self.toggle_scopes(); |
| 648 | return ViewAction::None; |
| 649 | } |
| 650 | if self |
| 651 | .details_toggle_hitbox |
| 652 | .borrow() |
| 653 | .is_some_and(|rect| rect.contains(pos)) |
| 654 | { |
| 655 | self.toggle_details(); |
| 656 | return ViewAction::None; |
| 657 | } |
| 658 | if self.scopes_open { |
| 659 | let clicked_scope = self |
| 660 | .scope_menu_hitboxes |
| 661 | .borrow() |
| 662 | .iter() |
| 663 | .find_map(|(option, rect)| rect.contains(pos).then_some(*option)); |
| 664 | if let Some(option) = clicked_scope { |
| 665 | return self.commit_option(option); |
| 666 | } |
| 667 | } |
| 668 | let clicked = self |
| 669 | .row_hitboxes |
| 670 | .borrow() |
| 671 | .iter() |
| 672 | .position(|rect| rect.contains(pos)); |
| 673 | if let Some(index) = clicked { |
| 674 | return self |
| 675 | .commit_option(ApprovalOption::from_index_for(&self.request, index)); |
| 676 | } |
| 677 | ViewAction::None |
| 678 | } |
| 679 | _ => ViewAction::None, |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | fn render(&self, area: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) { |
| 684 | let approval_widget = ApprovalWidget::new(&self.request, self); |
| 685 | approval_widget.render(area, buf); |
| 686 | } |
| 687 | |
| 688 | fn occupied_region(&self, area: ratatui::layout::Rect) -> ratatui::layout::Rect { |
| 689 | // The approval is an inline, bottom-anchored prompt: it only occupies |
| 690 | // a band at the bottom of the frame so the backdrop dims that band and |
| 691 | // the transcript above stays visible. Must match what `render` paints. |
| 692 | ApprovalWidget::new(&self.request, self).inline_region(area) |
| 693 | } |
| 694 | |
| 695 | fn docked_height(&self, width: u16) -> u16 { |
| 696 | ApprovalWidget::new(&self.request, self).docked_height(width) |
| 697 | } |
| 698 | |
| 699 | fn on_became_top(&mut self, at: Instant) { |
| 700 | self.answerable_since = Some(at); |
| 701 | self.last_enter_at = None; |
| 702 | self.last_char_key_at = None; |
| 703 | } |
| 704 | |
| 705 | fn tick(&mut self) -> ViewAction { |
| 706 | self.answerable_since.get_or_insert_with(Instant::now); |
| 707 | if self.is_timed_out() { |
| 708 | return self.emit_decision(ReviewDecision::Denied, true); |
| 709 | } |
| 710 | ViewAction::None |
| 711 | } |
| 712 | } |
| 713 |