Add a keep-and-next action to the warnings viewer (#48206)

## Why

Closing the warnings viewer dismisses warnings whose pages were displayed. Allow users to keep a warning available for later review while moving through the remaining warnings.

## What changed

- Press `k` to keep the current warning and advance, closing the viewer after the last warning.
- Preserve kept warnings when applying queued dismissal updates, so a later keep decision takes precedence for the same warning details.
- Reserve `k` in the viewer, update footer hints, and suppress key repeats so holding it does not skip warnings or modify the restored draft.

## Testing

Add coverage for keeping warnings, leaving unvisited warnings undismissed, conflicting key bindings, repeated key events, draft preservation, and queued dismissal updates. Update warning footer snapshots.

GitOrigin-RevId: da267b9142ddda78086418192970db2aec370d3a
This commit is contained in:
Felipe Coury
2026-09-25 20:26:45 +00:00
committed by copyberry
parent 7703f8b354
commit 4193f1acfb
12 changed files with 146 additions and 39 deletions
+6 -1
View File
@@ -348,12 +348,17 @@ impl App {
}
}
AppEvent::OpenWarnings => self.chat_widget.open_warnings(&self.transcript_cells),
AppEvent::UpdateWarnings { transcript, dismissed } => {
AppEvent::UpdateWarnings { transcript, dismissed, kept } => {
if !Arc::ptr_eq(&transcript, &self.chat_widget.warning_display_state.transcript) {
return Ok(AppRunControl::Continue);
}
let state = &mut self.chat_widget.warning_display_state.dismissed;
state.extend(dismissed.into_iter().map(|entry| (entry.id, entry.details)));
for entry in kept {
if state.get(&entry.id) == Some(&entry.details) {
state.remove(&entry.id);
}
}
self.chat_widget.warning_display_state.synced_cells = None;
tui.frame_requester().schedule_frame();
}
+7 -6
View File
@@ -99,12 +99,13 @@ impl App {
let was_pending = self.key_chord_matcher.is_pending();
if !was_pending
&& contexts.is_warnings()
&& !crate::key_hint::is_plain_text_key_event(key_event)
&& self
.keymap
.list
.action_for(key_event)
.is_some_and(|action| action != crate::keymap::ListAction::Accept)
&& (crate::key_hint::plain(KeyCode::Char('k')).is_press(key_event)
|| (!crate::key_hint::is_plain_text_key_event(key_event)
&& self
.keymap
.list
.action_for(key_event)
.is_some_and(|action| action != crate::keymap::ListAction::Accept)))
{
return Some(key_event);
}
@@ -25,4 +25,4 @@ Earlier transcript row 22
esc dismiss & close · ctrl+o copy · ←/→ warning · ↓ scroll
k keep & next · esc dismiss & close · ctrl+o copy · ←/→ warning · ↓ scroll
+24 -7
View File
@@ -67,10 +67,15 @@ async fn warnings_hide_and_restore_draft_and_freeze_until_reopened() -> Result<(
app.handle_tui_event(
&mut tui,
&mut app_server,
TuiEvent::Key(KeyCode::Esc.into()),
TuiEvent::Key(KeyCode::Char('k').into()),
)
.await?;
assert!(!app.chat_widget.keymap_contexts().is_warnings());
let repeat =
KeyEvent::new_with_kind(KeyCode::Char('k'), KeyModifiers::NONE, KeyEventKind::Repeat);
app.handle_tui_event(&mut tui, &mut app_server, TuiEvent::Key(repeat))
.await?;
assert_eq!(app.chat_widget.composer_text_with_pending(), "/m");
app.render_owned_transcript(&mut tui, size)?;
assert_eq!(
crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal),
@@ -90,11 +95,11 @@ async fn warnings_hide_and_restore_draft_and_freeze_until_reopened() -> Result<(
.map(ratatui::buffer::Cell::symbol)
.collect::<String>();
assert!(frozen.contains("1 of 1"));
// The first close's queued update may arrive while the frozen viewer is reopened.
let first_dismissal = std::iter::from_fn(|| events.try_recv().ok())
.find(|event| matches!(event, AppEvent::UpdateWarnings { dismissed, .. } if !dismissed.is_empty()))
.expect("the first close queued a dismissal");
app.handle_event(&mut tui, &mut app_server, first_dismissal)
// The first keep's queued update may arrive while the frozen viewer is reopened.
let first_keep = std::iter::from_fn(|| events.try_recv().ok())
.find(|event| matches!(event, AppEvent::UpdateWarnings { kept, .. } if !kept.is_empty()))
.expect("the first keep queued a decision");
app.handle_event(&mut tui, &mut app_server, first_keep)
.await?;
app.chat_widget.handle_key_event(KeyCode::Esc.into());
assert_eq!(app.chat_widget.composer_text_with_pending(), "/m");
@@ -216,7 +221,7 @@ async fn warnings_badge_and_pages_work_with_terminal_scrollback() -> Result<()>
assert!(screen.contains(text));
}
assert!(!screen.contains("fallback draft"));
app.chat_widget.handle_key_event(KeyCode::Esc.into());
app.chat_widget.handle_key_event(KeyCode::Char('k').into());
app.render_chat_widget_frame(&mut tui, size)?;
assert_eq!(
crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal),
@@ -274,6 +279,18 @@ async fn warnings_changed_details_reappear_and_clear_resets_dismissal() -> Resul
app.insert_history_cell(&mut tui, Box::new(original.clone()));
app.chat_widget.open_warnings(&app.transcript_cells);
assert_eq!(render_bottom_popup(&app.chat_widget, /*width*/ 80), before);
// Terminal input can win the race with queued app events in embedded mode.
// Reopen before applying the prior dismissal; keep must be the final decision.
app.chat_widget.handle_key_event(KeyCode::Esc.into());
app.chat_widget.open_warnings(&app.transcript_cells);
app.chat_widget.handle_key_event(KeyCode::Char('k').into());
while let Ok(event) = events.try_recv() {
if matches!(event, AppEvent::UpdateWarnings { .. }) {
app.handle_event(&mut tui, &mut app_server, event).await?;
}
}
app.chat_widget.open_warnings(&app.transcript_cells);
assert_eq!(render_bottom_popup(&app.chat_widget, /*width*/ 80), before);
// Clear before the queued dismissal arrives, then deliver the same warning again.
app.chat_widget.handle_key_event(KeyCode::Esc.into());
app.reset_app_ui_state_after_clear();
+2 -1
View File
@@ -448,10 +448,11 @@ pub(crate) enum AppEvent {
OpenWarnings,
/// Copy a diagnostic and acknowledge in the footer, without appending history.
CopyWarning(String),
/// Dismiss the visited diagnostics for this transcript, using the frozen warning details.
/// Apply the user's decisions for the frozen warning details, in viewer-close order.
UpdateWarnings {
transcript: Arc<()>,
dismissed: Vec<crate::history_cell::WarningEntry>,
kept: Vec<crate::history_cell::WarningEntry>,
},
/// Export all current-thread history to the selected destination.
+5
View File
@@ -282,6 +282,8 @@ pub(crate) struct BottomPane {
/// Stack of views displayed instead of the composer (e.g. popups/modals).
view_stack: Vec<Box<dyn BottomPaneView>>,
warnings_view: Option<warnings_view::WarningsView>,
/// A keep press can close the viewer; its remaining repeats must not edit the draft.
pub(crate) suppress_warning_keep_repeat: bool,
pub(crate) questions: Option<Box<AsyncQuestions>>,
delayed_approval_requests: VecDeque<DelayedApprovalRequest>,
last_composer_activity_at: Option<Instant>,
@@ -368,6 +370,7 @@ impl BottomPane {
composer,
view_stack: Vec::new(),
warnings_view: None,
suppress_warning_keep_repeat: false,
questions: None,
delayed_approval_requests: VecDeque::new(),
last_composer_activity_at: None,
@@ -820,6 +823,8 @@ impl BottomPane {
.is_some_and(|view| view.handle_key(key_event))
&& let Some(view) = self.warnings_view.take()
{
self.suppress_warning_keep_repeat =
key_hint::plain(KeyCode::Char('k')).is_press(key_event);
view.close();
}
self.request_redraw();
@@ -10,4 +10,4 @@ expression: "draw(&view, 40, 9)"
Details retained in full, including
remediation instructions.
Details retained in full, including
esc dismiss & close · ctrl+o copy
k keep & next · esc dismiss & close
+32 -13
View File
@@ -1,17 +1,20 @@
//! A frozen set of warnings, shown one at a time without changing the retained draft.
//! On intentional close, dismiss only warnings whose pages were actually drawn.
//! On intentional close, dismiss only warnings actually drawn, unless the user kept them.
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
use crate::history_cell::WarningEntry;
use crate::key_hint;
use crate::key_hint::KeyBindingListExt;
use crate::keymap::KeymapContext;
use crate::keymap::KeymapContextSet;
use crate::keymap::ListAction;
use crate::keymap::RuntimeKeymap;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use std::cell::Cell;
use std::collections::BTreeSet;
use std::sync::Arc;
#[path = "warnings_view_render.rs"]
@@ -22,6 +25,7 @@ pub(super) struct WarningsView {
transcript: Arc<()>,
current: usize,
visited: Vec<Cell<bool>>,
kept: BTreeSet<usize>,
offset: Cell<usize>,
page_size: Cell<usize>,
max_offset: Cell<usize>,
@@ -43,6 +47,7 @@ impl WarningsView {
entries,
transcript,
current: 0,
kept: BTreeSet::new(),
offset: Cell::new(/*value*/ 0),
page_size: Cell::new(/*value*/ 1),
max_offset: Cell::new(/*value*/ 0),
@@ -62,16 +67,20 @@ impl WarningsView {
}
pub(super) fn close(self) {
let dismissed: Vec<_> = self
.entries
.into_iter()
.zip(self.visited)
.filter_map(|(entry, visited)| visited.get().then_some(entry))
.collect();
if !dismissed.is_empty() {
let mut dismissed = Vec::new();
let mut kept = Vec::new();
for (index, (entry, visited)) in self.entries.into_iter().zip(self.visited).enumerate() {
if self.kept.contains(&index) {
kept.push(entry);
} else if visited.get() {
dismissed.push(entry);
}
}
if !dismissed.is_empty() || !kept.is_empty() {
self.tx.send(AppEvent::UpdateWarnings {
transcript: self.transcript,
dismissed,
kept,
});
}
}
@@ -81,11 +90,21 @@ impl WarningsView {
if event.kind == KeyEventKind::Release {
return false;
}
let action = self
.keymap
.list
.action_for(event)
.filter(|action| *action != ListAction::Accept);
let action = if key_hint::plain(KeyCode::Char('k')).is_press(event) {
if event.kind != KeyEventKind::Press {
return false;
}
self.kept.insert(self.current);
if self.current + 1 >= self.entries.len() {
return true;
}
Some(ListAction::MoveRight)
} else {
self.keymap
.list
.action_for(event)
.filter(|action| *action != ListAction::Accept)
};
if action.is_none() && self.keymap.app.open_warnings.is_pressed(event) {
return true;
}
@@ -64,30 +64,43 @@ impl Renderable for WarningsView {
buf,
);
}
// Plain k belongs to this viewer, including when configured as a chord prefix.
let hint = |context, action| {
self.keymap.primary_hint(context, action).filter(|hint| {
let binding = match hint {
crate::key_hint::ShortcutHint::Single(binding)
| crate::key_hint::ShortcutHint::Chord {
prefix: binding, ..
} => binding,
};
*binding != key_hint::plain(KeyCode::Char('k'))
})
};
let navigation = ["move_left", "move_right"]
.into_iter()
.filter_map(|action| self.keymap.primary_hint(KeymapContext::List, action))
.filter_map(|action| hint(KeymapContext::List, action))
.map(crate::key_hint::ShortcutHint::display_label)
.collect::<Vec<_>>()
.join("/");
let mut items = Vec::new();
for (hint, label) in [
(Some("k".to_string()), "keep & next"),
(
self.keymap
.primary_hint(KeymapContext::List, "cancel")
.map(crate::key_hint::ShortcutHint::display_label),
Some(
hint(KeymapContext::List, "cancel")
.unwrap_or_else(|| key_hint::ctrl(KeyCode::Char('c')).into())
.display_label(),
),
"dismiss & close",
),
(
self.keymap
.primary_hint(KeymapContext::Global, "copy")
hint(KeymapContext::Global, "copy")
.map(crate::key_hint::ShortcutHint::display_label),
"copy",
),
((!navigation.is_empty()).then_some(navigation), "warning"),
(
self.keymap
.primary_hint(KeymapContext::List, "move_down")
hint(KeymapContext::List, "move_down")
.map(crate::key_hint::ShortcutHint::display_label),
"scroll",
),
@@ -133,3 +133,39 @@ fn warnings_dismiss_only_drawn_pages_after_navigation_skips_a_frame() {
]
);
}
#[test]
fn warnings_keep_current_and_next_without_dismissing_unvisited_pages() {
let (tx, mut rx) = unbounded_channel();
let mut data = entries();
data.push(WarningEntry {
id: WarningId::Message("later".into()),
source: "Startup".into(),
details: "Not yet viewed".into(),
});
let expected = vec![data[1].clone()];
// Keep owns k in this viewer even when a list action is remapped to it.
let keymap = RuntimeKeymap::from_config(
&toml::from_str("[list]\nmove_up = 'up'\ncancel = 'k'").unwrap(),
)
.unwrap();
let mut view = WarningsView::new(data, Arc::default(), keymap, AppEventSender::new(tx));
assert!(!key(&mut view, KeyCode::Char('k')));
let screen = draw(&view, /*width*/ 80, /*height*/ 12);
assert!(screen.contains("2 of 3"));
assert!(screen.contains("ctrl+c dismiss & close"));
let repeat =
KeyEvent::new_with_kind(KeyCode::Char('k'), KeyModifiers::NONE, KeyEventKind::Repeat);
assert!(!view.handle_key(repeat));
assert!(draw(&view, /*width*/ 80, /*height*/ 12).contains("2 of 3"));
key(&mut view, KeyCode::Left);
assert!(key(&mut view, KeyCode::F(2)));
view.close();
let Ok(AppEvent::UpdateWarnings {
dismissed, kept, ..
}) = rx.try_recv()
else {
panic!("expected warning decisions");
};
assert_eq!((dismissed, kept), (expected, vec![entries()[0].clone()]));
}
@@ -13,4 +13,4 @@ expression: "super::helpers::render_bottom_popup(&chat, 80)"
esc dismiss & close · ctrl+o copy · ←/→ warning · ↓ scroll
k keep & next · esc dismiss & close · ctrl+o copy · ←/→ warning · ↓ scroll
+10
View File
@@ -83,6 +83,16 @@ impl super::ChatWidget {
event: &TuiEvent,
cells: &[Arc<dyn HistoryCell>],
) -> bool {
if let TuiEvent::Key(key) = event
&& self.bottom_pane.suppress_warning_keep_repeat
{
if key.kind == crossterm::event::KeyEventKind::Repeat
&& crate::key_hint::plain(crossterm::event::KeyCode::Char('k')).is_press(*key)
{
return true;
}
self.bottom_pane.suppress_warning_keep_repeat = false;
}
if let TuiEvent::Key(key) = event
&& self.bottom_pane.warnings_active()
&& matches!(