Add a warning footer and dedicated warnings viewer to the TUI (#46751)

## Why

Keep diagnostics accessible without adding warning rows to the live conversation or changing the composer layout.

## What changed

- Show a deduplicated warning count in the passive footer, yielding to interactive hints.
- Open warning details with `F2`, `/warnings`, or a click on the warning notice. Support navigation, scrolling, and copying individual diagnostics while preserving the draft.
- Retain startup, runtime, MCP, and deprecation diagnostics in the full transcript. Group MCP details by server and preserve warnings during replay.
- Respect existing custom bindings and chord prefixes when enabling `F2`.
- Show an immediate explanation when `/pets` is unavailable.

## Testing

Add regression tests and snapshots for warning counts, draft preservation, viewer navigation and copying, narrow layouts, terminal scrollback, and keybinding conflicts.

GitOrigin-RevId: 2bc586430da60347cfbaa5bf128bc48f7f9dc777
This commit is contained in:
Eric Traut
2026-09-20 03:02:25 +00:00
committed by copyberry
parent 9ed1b74699
commit 6b0a1a8325
73 changed files with 1726 additions and 285 deletions
+22 -3
View File
@@ -267,6 +267,9 @@ mod transcript_export;
mod user_verification;
mod user_verification_errors;
mod user_verification_requests;
#[cfg(test)]
#[path = "app/warnings_tests.rs"]
mod warnings_tests;
mod working_directory;
use self::agent_navigation::AgentNavigationDirection;
@@ -866,6 +869,7 @@ impl App {
};
if self.reconnect.offline
&& !transcript_owns_input
&& !self.chat_widget.keymap_contexts().is_warnings()
&& let TuiEvent::Key(key) = &event
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
&& key.modifiers.contains(KeyModifiers::CONTROL)
@@ -890,6 +894,15 @@ impl App {
self.cancel_pending_key_chord();
}
if self.overlay.is_none()
&& self
.chat_widget
.handle_warning_event(&event, &self.transcript_cells)
{
self.cancel_primed_browsing_for_event(&event);
return Ok(AppRunControl::Continue);
}
let mut event = if let TuiEvent::Key(mut key_event) = event {
let escape = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
if self.should_recover_vim_insert_escape(key_event)
@@ -935,8 +948,12 @@ impl App {
}
}
if self.reconnect.offline
&& !self.chat_widget.keymap_contexts().is_warnings()
&& !matches!(&self.overlay, Some(Overlay::Transcript(_)))
&& let TuiEvent::Key(key) = &event
&& !(self.overlay.is_none()
&& self.chat_widget.no_modal_or_popup_active()
&& self.keymap.app.open_warnings.is_pressed(*key))
{
if self.reconnect.presentation == reconnect::ReconnectPresentation::Overview {
self.chat_widget.handle_disconnected_view_key(*key);
@@ -991,6 +1008,7 @@ impl App {
}
self.chat_widget.handle_paste(pasted);
if self.reconnect.offline
&& !self.chat_widget.keymap_contexts().is_warnings()
&& self.reconnect.presentation
== reconnect::ReconnectPresentation::Conversation
{
@@ -1014,7 +1032,7 @@ impl App {
return Ok(AppRunControl::Continue);
}
// Allow widgets to process any pending timers before rendering.
let had_active_view = self.chat_widget.has_active_view();
let had_active_modal = self.chat_widget.has_active_modal();
self.chat_widget.pre_draw_tick();
self.refresh_agents_overview_usage(app_server, tui.frame_requester());
let rendered_area = self.render_chat_widget_frame(tui, screen_size)?;
@@ -1024,8 +1042,8 @@ impl App {
{
self.request_owned_history(tui, app_server);
}
if !had_active_view
&& self.chat_widget.has_active_view()
if !had_active_modal
&& self.chat_widget.has_active_modal()
&& self.startup_protected_input_boundary
{
tui.discard_pending_input_before_interactive_screen()?;
@@ -1083,6 +1101,7 @@ impl App {
if tui.is_owned_screen() {
return self.render_owned_transcript(tui, screen_size);
}
self.chat_widget.sync_warnings(&self.transcript_cells);
let dashboard_visible = self
.chat_widget
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)
+6
View File
@@ -35,6 +35,8 @@ impl App {
&& !matches!(
&event,
AppEvent::OpenDaemonMenu
| AppEvent::OpenWarnings
| AppEvent::CopyWarning(_)
| AppEvent::ConfirmDaemonUpdate(_)
| AppEvent::RunDaemonUpdate(_)
| AppEvent::InsertHistoryCell(_)
@@ -309,6 +311,10 @@ impl App {
tracing::warn!(%thread_id, error = %err, "failed to load older transcript history");
}
}
AppEvent::OpenWarnings => self.chat_widget.open_warnings(&self.transcript_cells),
AppEvent::CopyWarning(text) => {
let _ = self.chat_widget.copy_transcript_selection(&text);
}
AppEvent::OpenTranscriptExportFilePrompt => {
self.chat_widget.show_transcript_export_file_prompt();
}
@@ -65,7 +65,7 @@ impl App {
grant_root: params.grant_root,
},
);
if self.startup_protected_input_boundary && !self.chat_widget.has_active_view() {
if self.startup_protected_input_boundary && !self.chat_widget.has_active_modal() {
self.startup_pending_protected_request = true;
}
}
+3 -2
View File
@@ -76,7 +76,8 @@ impl App {
lines: lines.clone(),
});
}
if deferred {
// Invisible diagnostics still update the badge without replacing the rendered tail.
if deferred || lines.is_empty() {
tui.frame_requester().schedule_frame();
return;
}
@@ -85,7 +86,7 @@ impl App {
self.last_rendered_history_tail = None;
} else {
self.insert_history_cell_lines(tui, cell.as_ref(), width);
self.last_rendered_history_tail = if self.overlay.is_none() && !lines.is_empty() {
self.last_rendered_history_tail = if self.overlay.is_none() {
Some(RenderedHistoryTail {
cell: Arc::downgrade(cell),
lines,
+15
View File
@@ -97,6 +97,17 @@ impl App {
}
let contexts = self.active_keymap_contexts();
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)
{
return Some(key_event);
}
if !was_pending
&& contexts.contains(crate::keymap::KeymapContext::Agents)
&& self
@@ -602,6 +613,10 @@ impl App {
app_server: &mut AppServerSession,
key_event: KeyEvent,
) -> bool {
if self.keymap.app.open_warnings.is_pressed(key_event) {
self.chat_widget.open_warnings(&self.transcript_cells);
return true;
}
let side_toggle_bindings = &self.keymap.app.toggle_side_conversation;
if side_toggle_bindings.is_pressed(key_event)
|| side_toggle_bindings.contains(&crate::key_hint::ctrl(KeyCode::Char('/')))
+5
View File
@@ -42,6 +42,7 @@ impl App {
tui: &mut tui::Tui,
screen_size: Size,
) -> Result<Rect> {
self.chat_widget.sync_warnings(&self.transcript_cells);
let motion = MotionMode::from_animations_enabled(self.local_settings.tui.animations);
let latest_navigation = if self.enter_returns_to_latest() {
"enter/esc latest"
@@ -419,6 +420,10 @@ mod tests;
#[path = "owned_transcript_input_tests.rs"]
mod input_tests;
#[cfg(test)]
#[path = "warning_notice_tests.rs"]
mod warning_notice_tests;
#[cfg(test)]
#[path = "owned_transcript_follow_tests.rs"]
mod follow_tests;
-13
View File
@@ -26,19 +26,6 @@ pub(super) fn snapshot_has_pending_interactive_request(snapshot: &ThreadEventSna
})
}
pub(super) fn event_is_notice(event: &ThreadBufferedEvent) -> bool {
matches!(
event,
ThreadBufferedEvent::Notification(notification)
if matches!(
notification.as_ref(),
ServerNotification::Warning(_)
| ServerNotification::GuardianWarning(_)
| ServerNotification::ConfigWarning(_)
)
)
}
/// A later turn resolves an earlier precaution; replay must preserve restored input.
pub(super) fn omit_resolved_misalignment_errors(
snapshot: &mut ThreadEventSnapshot,
+9 -5
View File
@@ -547,13 +547,17 @@ impl App {
self.last_rendered_history_tail = self
.native_history
.replayable_cells(&self.transcript_cells)
.last()
.map(|cell| super::history_ui::RenderedHistoryTail {
cell: Arc::downgrade(cell),
lines: cell.display_hyperlink_lines_for_mode(
.iter()
.rev()
.find_map(|cell| {
let lines = cell.display_hyperlink_lines_for_mode(
width,
self.chat_widget.history_render_mode(),
),
);
(!lines.is_empty()).then(|| super::history_ui::RenderedHistoryTail {
cell: Arc::downgrade(cell),
lines,
})
});
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut()
&& let Some(cell) = status_history.cell.upgrade()
@@ -0,0 +1,28 @@
---
source: tui/src/app/warnings_tests.rs
expression: "crate::chatwidget::tests::helpers::normalize_snapshot_paths(screen)"
---
Earlier transcript row 12
Earlier transcript row 13
Earlier transcript row 14
Earlier transcript row 15
Earlier transcript row 16
Earlier transcript row 17
Earlier transcript row 18
Earlier transcript row 19
Earlier transcript row 20
Earlier transcript row 21
Earlier transcript row 22
Warnings · 1 of 1 · Warning
Example warning
Full diagnostic with remediation.
esc back · ctrl+o copy · ←/→ warning · ↓ scroll
+7 -7
View File
@@ -114,7 +114,7 @@ impl App {
}
self.chat_widget.pre_draw_tick();
self.render_chat_widget_frame(tui, tui.terminal.last_known_screen_size)?;
if self.chat_widget.has_active_view() && self.startup_protected_input_boundary {
if self.chat_widget.has_active_modal() && self.startup_protected_input_boundary {
tui.discard_pending_input_before_interactive_screen()?;
self.startup_pending_protected_request = false;
}
@@ -1100,14 +1100,14 @@ See the Codex keymap documentation for supported actions and examples."
AppEvent::InsertHistoryCell(cell)
if cell.as_any().is::<history_cell::SessionInfoCell>()
);
let had_active_view = app.chat_widget.has_active_view();
let had_active_modal = app.chat_widget.has_active_modal();
match Box::pin(app.handle_event(tui, &mut app_server, event)).await {
Ok(AppRunControl::Continue) => {
if is_initial_session_header {
waiting_for_initial_session_header = false;
}
if !had_active_view
&& app.chat_widget.has_active_view()
if !had_active_modal
&& app.chat_widget.has_active_modal()
&& let Err(err) = app.render_startup_frame(tui, &app_event_rx)
{
break Err(err);
@@ -1244,12 +1244,12 @@ See the Codex keymap documentation for supported actions and examples."
app.primary_thread_id,
) {
waiting_for_initial_session_configured = false;
let had_active_view = app.chat_widget.has_active_view();
let had_active_modal = app.chat_widget.has_active_modal();
if let Err(err) = app.drain_active_thread_events(tui).await {
break Err(err);
}
if !had_active_view
&& app.chat_widget.has_active_view()
if !had_active_modal
&& app.chat_widget.has_active_modal()
&& let Err(err) = app.render_startup_frame(tui, &app_event_rx)
{
break Err(err);
+11 -19
View File
@@ -1,4 +1,4 @@
//! Coalesces startup diagnostics directly below the session splash.
//! Coalesce retained startup diagnostics without adding live transcript rows or forcing reflow.
use super::*;
use crate::history_cell::StartupWarningsCell;
@@ -28,6 +28,14 @@ impl App {
warnings
.mcp_servers
.extend(incoming.mcp_servers.iter().cloned());
for (server, messages) in &incoming.mcp_details {
let details = warnings.mcp_details.entry(server.clone()).or_default();
for message in messages {
if !details.contains(message) {
details.push(message.clone());
}
}
}
// The final MCP summary must retain the individual diagnostics' sign-in subset.
warnings
.sign_in_servers
@@ -35,18 +43,14 @@ impl App {
if warnings.messages.is_empty() {
return;
}
warnings.transcript_hint = crate::keymap::primary_binding(&self.keymap.app.open_transcript)
.map(|binding| binding.display_label());
let header = self
.transcript_cells
.iter()
.rposition(|cell| cell.as_any().is::<history_cell::SessionInfoCell>());
warnings.pending_header = header.is_none() && self.chat_widget.thread_id().is_none();
let ready_to_render = !warnings.pending_header;
let warnings: Arc<dyn HistoryCell> = Arc::new(warnings);
self.transcript_cells.insert(
header.map_or(/*default*/ 0, |index| index + 1),
warnings.clone(),
Arc::new(warnings),
);
self.native_history.retain(&self.transcript_cells);
if let Some(Overlay::Transcript(overlay)) = &mut self.overlay {
@@ -55,18 +59,6 @@ impl App {
if self.backtrack.overlay_preview_active {
self.apply_backtrack_selection_internal(self.backtrack.nth_user_message);
}
if ready_to_render {
if let Some(buffer) = self.initial_history_replay_buffer.as_mut() {
buffer.retained_lines.clear();
buffer.render_from_transcript_tail = true;
return;
}
self.schedule_immediate_resize_reflow(tui);
if let Err(error) =
self.maybe_run_resize_reflow(tui, tui.terminal.last_known_screen_size)
{
tracing::warn!(%error, "failed to refresh startup warnings");
}
}
tui.frame_requester().schedule_frame();
}
}
+10 -12
View File
@@ -3795,7 +3795,7 @@ async fn side_defers_parent_approval_overlay_until_parent_replay() -> Result<()>
}
#[tokio::test]
async fn replay_snapshot_with_pending_request_suppresses_replay_notices() {
async fn replay_snapshot_with_pending_request_retains_warnings_without_covering_approval() {
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
let thread_id =
ThreadId::from_string("00000000-0000-0000-0000-000000000011").expect("valid thread");
@@ -3829,14 +3829,19 @@ async fn replay_snapshot_with_pending_request_suppresses_replay_notices() {
assert_eq!(app.chat_widget.has_active_view(), true);
let mut replayed_history = String::new();
let mut warnings = Vec::new();
while let Ok(event) = app_event_rx.try_recv() {
if let AppEvent::InsertHistoryCell(cell) = event {
replayed_history.push_str(&lines_to_single_string(
&cell.transcript_lines(/*width*/ 80),
));
warnings.extend(
cell.warning_entries()
.into_iter()
.map(|entry| entry.details),
);
replayed_history.push_str(&lines_to_single_string(&cell.display_lines(/*width*/ 80)));
}
}
assert_eq!(warnings, vec![stale_warning]);
assert!(
replayed_history.is_empty(),
"expected pending approval replay to suppress session notices, got {replayed_history:?}"
@@ -5417,14 +5422,7 @@ async fn active_side_thread_renders_live_mcp_startup_notifications() {
app.insert_history_cell(&mut tui, cell);
}
}
let inline = app
.transcript_cells
.iter()
.flat_map(|cell| cell.display_lines(/*width*/ 120))
.map(|line| line.to_string())
.collect::<Vec<_>>()
.join("\n");
assert!(inline.contains("1 MCP startup issue"));
assert_eq!(history_cell::warning_count(&app.transcript_cells), 1);
let rendered = rendered_cells.join("\n");
assert!(app.chat_widget.side_conversation_active());
assert_eq!(rendered.matches("sentry is not logged in").count(), 1);
@@ -1,7 +0,0 @@
---
source: tui/src/app/tests/startup_warnings_tests.rs
expression: warnings.display_lines(100)
---
[
Line::from(Span::from("⚠ 3 MCP startup issues (2 need sign-in) · ctrl+t for details").yellow().dim()),
]
@@ -1,7 +0,0 @@
---
source: tui/src/app/tests/startup_warnings_tests.rs
expression: "app.transcript_cells[1].display_lines(100)"
---
[
Line::from(Span::from("⚠ 4 startup issues (3 MCP; 2 need sign-in) · ctrl+t for details").yellow().dim()),
]
+6 -3
View File
@@ -593,6 +593,8 @@ async fn startup_draft_delayed_approval_becomes_protected_on_redraw() -> Result<
let mut pending_startup_draft = Some(draft);
app.chat_widget
.restore_startup_draft_when_ready(&mut pending_startup_draft);
// The warning panel owns input but must not mask a later protected modal.
app.chat_widget.open_warnings(&[]);
let approval_request =
exec_approval_request(thread_id, "turn-1", "call-1", /*approval_id*/ None);
@@ -607,7 +609,8 @@ async fn startup_draft_delayed_approval_becomes_protected_on_redraw() -> Result<
.try_recv()
.expect("approval should be queued on the active thread");
app.handle_thread_event_now(approval_event);
assert!(!app.chat_widget.has_active_view());
assert!(app.chat_widget.has_active_view());
assert!(!app.chat_widget.has_active_modal());
assert!(app.startup_pending_protected_request);
app.handle_tui_event(
@@ -619,12 +622,12 @@ async fn startup_draft_delayed_approval_becomes_protected_on_redraw() -> Result<
assert!(app.startup_protected_input_boundary);
assert!(app.startup_pending_protected_request);
tokio::time::sleep(Duration::from_millis(/*millis*/ 75)).await;
tokio::time::sleep(Duration::from_millis(/*millis*/ 1100)).await;
let redraw_result = app
.handle_tui_event(&mut tui, &mut app_server, TuiEvent::Draw)
.await;
assert!(app.chat_widget.has_active_view());
assert!(app.chat_widget.has_active_modal());
assert!(!tui.terminal.viewport_area.is_empty());
while let Ok(event) = app_event_rx.try_recv() {
assert!(
@@ -110,16 +110,24 @@ async fn mcp_startup_summary_counts_servers_and_sign_in_subset() -> Result<()> {
drain_history(&mut app, &mut tui, &mut events);
assert_eq!(app.transcript_cells.len(), 2);
let warnings = &app.transcript_cells[1];
insta::assert_debug_snapshot!("mcp_startup_summary", warnings.display_lines(/*width*/ 100));
assert_eq!(history_cell::warning_count(&app.transcript_cells), 3);
assert_eq!(
history_cell::warning_entries(&app.transcript_cells)
.into_iter()
.map(|entry| (entry.source, entry.details.contains("Sign-in required.")))
.collect::<Vec<_>>(),
vec![
("MCP · alpha".into(), true),
("MCP · beta".into(), true),
("MCP · gamma".into(), false)
],
);
insta::assert_snapshot!(
"mcp_startup_details",
lines_to_single_string(&warnings.transcript_lines(/*width*/ 40))
);
insert_warnings(&mut app, &mut tui, &["Skill manifest is invalid."]);
insta::assert_debug_snapshot!(
"mixed_startup_summary",
app.transcript_cells[1].display_lines(/*width*/ 100)
);
assert_eq!(history_cell::warning_count(&app.transcript_cells), 4);
Ok(())
}
@@ -142,18 +150,13 @@ async fn startup_warnings_wait_for_splash_and_coalesce_with_full_details() -> Re
let transcript = app.transcript_cells[1].transcript_lines(/*width*/ 80);
insta::assert_snapshot!(format!("display:\n{}\n\ntranscript:\n{}", lines_to_single_string(&display), lines_to_single_string(&transcript)), @"
display:
⚠ 2 startup issues · ctrl+t for details
transcript:
⚠ Skill manifest is invalid.
⚠ MCP alpha failed to start.
");
app.keymap.app.open_transcript = vec![crate::key_hint::plain(crossterm::event::KeyCode::F(12))];
app.merge_startup_warnings(&mut tui, &StartupWarningsCell::default());
insta::assert_snapshot!(lines_to_single_string(&app.transcript_cells[1].display_lines(/*width*/ 80)), @"⚠ 2 startup issues · f12 for details");
app.keymap.app.open_transcript.clear();
app.merge_startup_warnings(&mut tui, &StartupWarningsCell::default());
insta::assert_snapshot!(lines_to_single_string(&app.transcript_cells[1].display_lines(/*width*/ 80)), @"⚠ 2 startup issues");
assert_eq!(history_cell::warning_count(&app.transcript_cells), 2);
Ok(())
}
@@ -199,7 +202,7 @@ async fn startup_skill_load_order_preserves_runtime_error_recurrence() -> Result
assert_eq!(app.transcript_cells.len(), 3);
let runtime = app.transcript_cells[1..]
.iter()
.flat_map(|cell| cell.display_lines(/*width*/ 120))
.flat_map(|cell| cell.transcript_lines(/*width*/ 120))
.collect::<Vec<_>>();
insta::allow_duplicates! {
insta::assert_snapshot!(lines_to_single_string(&runtime), @"
+10 -4
View File
@@ -125,6 +125,12 @@ async fn completed_thread_usage_updates_status_without_scrollback_reflow() -> Re
assert!(!app.transcript_reflow.has_pending_reflow());
assert!(pending_history_text(&tui).contains("/status"));
let status = Arc::clone(app.transcript_cells.last().expect("status card"));
app.insert_history_cell(
&mut tui,
Box::new(history_cell::new_warning_event("diagnostic".into())),
);
app.handle_event(
&mut tui,
&mut app_server,
@@ -137,10 +143,6 @@ async fn completed_thread_usage_updates_status_without_scrollback_reflow() -> Re
tui.pending_history_lines_for_test().is_empty(),
"a visible status tail should be replaced directly instead of appending a duplicate card"
);
let status = app
.transcript_cells
.last()
.expect("status card should remain in terminal history");
let rendered = lines_to_single_string(&status.display_lines(/*width*/ 90));
assert!(rendered.contains("50 credits"), "{rendered}");
app_server.shutdown().await?;
@@ -271,6 +273,10 @@ async fn account_change_discards_thread_usage_deferred_while_overlay_is_open() -
async fn terminal_reflow_rebases_pending_status_update_to_new_width() -> Result<()> {
let (mut app, mut app_server, mut tui, thread_id, request_id) =
app_with_pending_thread_usage().await?;
app.insert_history_cell(
&mut tui,
Box::new(history_cell::new_warning_event("diagnostic".into())),
);
app.insert_history_cell(
&mut tui,
Box::new(
@@ -45,6 +45,7 @@ async fn unavailable_thread_routes_local_and_recovery_commands() -> Result<()> {
"/agents",
"/subagents",
"/raw on",
"/warnings",
"/quit",
"/exit",
] {
@@ -64,6 +65,7 @@ async fn unavailable_thread_routes_local_and_recovery_commands() -> Result<()> {
| ("/agents", AppEvent::OpenAgentsOverview)
| ("/subagents", AppEvent::OpenAgentPicker)
| ("/raw on", AppEvent::RawOutputModeChanged { enabled: true })
| ("/warnings", AppEvent::OpenWarnings)
| ("/quit" | "/exit", AppEvent::Exit(_))
);
}
+6 -9
View File
@@ -397,7 +397,7 @@ impl App {
ThreadInteractiveRequest::Approval(request) => {
self.render_inactive_patch_preview(&request);
self.chat_widget.push_approval_request(request);
if self.startup_protected_input_boundary && !self.chat_widget.has_active_view() {
if self.startup_protected_input_boundary && !self.chat_widget.has_active_modal() {
self.startup_pending_protected_request = true;
}
}
@@ -1886,9 +1886,6 @@ impl App {
}
for (event, changes) in snapshot.events.into_iter().zip(request_changes) {
reasoning_replay.before_event(&event, &mut self.chat_widget);
if suppress_replay_notices && replay_filter::event_is_notice(&event) {
continue;
}
match (event, changes) {
(ThreadBufferedEvent::Request(request), Some(changes)) => {
self.handle_file_change_request(*request, changes)
@@ -2029,7 +2026,7 @@ impl App {
.handle_server_request(*request, /*replay_kind*/ None);
if may_open_protected_view
&& self.startup_protected_input_boundary
&& !self.chat_widget.has_active_view()
&& !self.chat_widget.has_active_modal()
{
self.startup_pending_protected_request = true;
}
@@ -2059,7 +2056,7 @@ impl App {
.handle_server_request(*request, Some(ReplayKind::ThreadSnapshot));
if may_open_protected_view
&& self.startup_protected_input_boundary
&& !self.chat_widget.has_active_view()
&& !self.chat_widget.has_active_modal()
{
self.startup_pending_protected_request = true;
}
@@ -2155,7 +2152,7 @@ impl App {
} else {
None
};
let had_active_view = self.chat_widget.has_active_view();
let had_active_modal = self.chat_widget.has_active_modal();
self.handle_thread_event_now_recovering_file_changes(event)
.await;
if let Some(user_message) = automatic_title_user_message
@@ -2169,8 +2166,8 @@ impl App {
super::thread_title::thread_title_prompt(&user_message),
);
}
if !had_active_view
&& self.chat_widget.has_active_view()
if !had_active_modal
&& self.chat_widget.has_active_modal()
&& self.startup_protected_input_boundary
{
self.chat_widget.pre_draw_tick();
@@ -0,0 +1,98 @@
//! Exercise warning delivery, detailed transcript toggling, and clearing through the owned UI.
use super::*;
use pretty_assertions::assert_eq;
fn screen(tui: &tui::Tui) -> String {
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
buffer
.content
.chunks(usize::from(buffer.area.width))
.map(|row| {
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim_end()
.to_owned()
})
.collect::<Vec<_>>()
.join("\n")
}
#[tokio::test]
async fn warning_notice_keeps_details_in_transcript_and_preserves_draft() -> Result<()> {
let mut app = crate::app::test_support::make_test_app().await;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_owned_screen(/*owned*/ true)?;
let size = Size::new(/*width*/ 80, /*height*/ 24);
app.chat_widget
.apply_external_edit("draft stays here".into());
let before = app.render_owned_transcript(&mut tui, size)?;
let cursor = tui.terminal.last_known_cursor_pos;
for message in [
"MCP example handshake failed",
"MCP startup incomplete (example)",
] {
app.insert_history_cell(
&mut tui,
Box::new(history_cell::StartupWarningsCell::mcp(
vec![message.into()],
["example".into()],
/*failure_reason*/ None,
)),
);
}
for _ in 0..2 {
app.insert_history_cell(
&mut tui,
Box::new(history_cell::new_warning_event(
"Sample runtime warning".into(),
)),
);
}
assert_eq!(app.render_owned_transcript(&mut tui, size)?, before);
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
let live = screen(&tui);
assert!(live.contains("⚠ 2 warnings"));
let shortcut = app
.keymap
.primary_hint(crate::keymap::KeymapContext::Global, "open_warnings")
.unwrap()
.display_label();
assert!(live.contains(&format!("{shortcut} to view")));
assert!(!live.contains("handshake failed"));
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
let position = buffer
.area
.positions()
.find(|position| buffer[*position].symbol() == "⚠")
.expect("warning badge");
assert!(app.chat_widget.handle_warning_event(
&TuiEvent::Mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: position.x,
row: position.y,
modifiers: KeyModifiers::NONE,
}),
&app.transcript_cells
));
app.chat_widget.handle_key_event(KeyCode::Esc.into());
app.open_transcript_overlay(&mut tui);
app.render_owned_transcript(&mut tui, size)?;
let detailed = screen(&tui);
assert!(detailed.contains("MCP example handshake failed"));
assert!(detailed.contains("Sample runtime warning"));
assert!(app.handle_owned_backtrack_event(
&mut tui,
&TuiEvent::Key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL))
)?);
app.render_owned_transcript(&mut tui, size)?;
assert_eq!(screen(&tui), live);
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
app.reset_transcript_state_after_clear();
app.render_owned_transcript(&mut tui, size)?;
assert!(!screen(&tui).contains("warnings"));
assert_eq!(history_cell::warning_count(&app.transcript_cells), 0);
tui.set_owned_screen(/*owned*/ false)?;
Ok(())
}
+232
View File
@@ -0,0 +1,232 @@
//! Exercise the warnings panel through the real app, including composer and scroll restoration.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn warnings_hide_and_restore_draft_and_freeze_until_reopened() -> Result<()> {
let mut app = crate::app::test_support::make_test_app().await;
let (widget, sender, mut events, _) =
crate::chatwidget::tests::make_chatwidget_manual_with_sender().await;
app.chat_widget = widget;
app.app_event_tx = sender;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_owned_screen(/*owned*/ true)?;
app.chat_widget.apply_external_edit("/m".into());
app.transcript_cells
.push(Arc::new(history_cell::PlainHistoryCell::new(
(0..50)
.map(|row| format!("Earlier transcript row {row}").into())
.collect(),
)));
app.insert_history_cell(
&mut tui,
Box::new(history_cell::new_warning_event(
"Example warning\nFull diagnostic with remediation.".into(),
)),
);
let size = Size::new(/*width*/ 80, /*height*/ 24);
app.render_owned_transcript(&mut tui, size)?;
app.transcript_view
.scroll(&app.transcript_cells, /*rows*/ -20);
app.render_owned_transcript(&mut tui, size)?;
let before = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal).clone();
let cursor = tui.terminal.last_known_cursor_pos;
app.chat_widget.open_warnings(&app.transcript_cells);
app.render_owned_transcript(&mut tui, size)?;
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
let screen = buffer
.content
.chunks(usize::from(size.width))
.map(|row| {
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(
"warnings_page",
crate::chatwidget::tests::helpers::normalize_snapshot_paths(screen),
);
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
app.reconnect.offline = true;
app.handle_tui_event(
&mut tui,
&mut app_server,
TuiEvent::Key(KeyCode::Char('E').into()),
)
.await?;
assert!(app.chat_widget.keymap_contexts().is_warnings());
assert_eq!(app.chat_widget.composer_text_with_pending(), "/m");
app.handle_tui_event(&mut tui, &mut app_server, TuiEvent::Paste("xample".into()))
.await?;
assert!(app.chat_widget.keymap_contexts().is_warnings());
app.chat_widget
.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
app.render_owned_transcript(&mut tui, size)?;
assert_eq!(
crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal),
&before
);
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
app.chat_widget.open_warnings(&app.transcript_cells);
app.insert_history_cell(
&mut tui,
Box::new(history_cell::new_warning_event("Later warning".into())),
);
app.render_owned_transcript(&mut tui, size)?;
let frozen = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal)
.content
.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>();
assert!(frozen.contains("1 of 1"));
app.chat_widget.handle_key_event(KeyCode::Esc.into());
assert_eq!(app.chat_widget.composer_text_with_pending(), "/m");
app.chat_widget.open_warnings(&app.transcript_cells);
app.chat_widget.handle_key_event(KeyCode::Right.into());
app.render_owned_transcript(&mut tui, size)?;
let reopened = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal)
.content
.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>();
assert!(reopened.contains("2 of 2"));
assert!(reopened.contains("Later warning"));
app.chat_widget.handle_key_event(KeyCode::Esc.into());
// An empty composer must not steal Escape for transcript backtracking.
app.chat_widget.apply_external_edit(String::new());
app.chat_widget.open_warnings(&app.transcript_cells);
let escape = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
assert!(!app.should_handle_backtrack_esc(escape));
app.chat_widget.handle_key_event(escape);
assert!(app.chat_widget.no_modal_or_popup_active());
app.handle_tui_event(
&mut tui,
&mut app_server,
TuiEvent::Key(KeyCode::F(2).into()),
)
.await?;
assert!(app.chat_widget.keymap_contexts().is_warnings());
app.chat_widget.handle_key_event(KeyCode::Esc.into());
app.chat_widget.apply_external_edit("/warnings".into());
app.handle_tui_event(
&mut tui,
&mut app_server,
TuiEvent::Key(KeyCode::Enter.into()),
)
.await?;
let event = std::iter::from_fn(|| events.try_recv().ok())
.find(|event| matches!(event, AppEvent::OpenWarnings))
.expect("offline /warnings dispatch");
app.handle_event(&mut tui, &mut app_server, event).await?;
assert!(app.chat_widget.keymap_contexts().is_warnings());
app.reconnect.offline = false;
app_server.shutdown().await?;
app.show_shutdown_feedback(&mut tui)?;
assert!(!app.chat_widget.keymap_contexts().is_warnings());
let screen = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal)
.content
.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>();
assert!(screen.contains("Shutting down"));
Ok(())
}
#[tokio::test]
async fn warnings_badge_and_pages_work_with_terminal_scrollback() -> Result<()> {
let mut app = crate::app::test_support::make_test_app().await;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_owned_screen(/*owned*/ false)?;
app.chat_widget.apply_external_edit("fallback draft".into());
app.insert_history_cell(
&mut tui,
Box::new(history_cell::new_warning_event(
"Fallback diagnostic".into(),
)),
);
let size = Size::new(/*width*/ 80, /*height*/ 24);
app.render_chat_widget_frame(&mut tui, size)?;
let before = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal).clone();
assert!(before.content.iter().any(|cell| cell.symbol() == "⚠"));
app.chat_widget.open_warnings(&app.transcript_cells);
app.render_chat_widget_frame(&mut tui, size)?;
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
let screen = buffer
.content
.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>();
for text in ["Warnings", "Fallback diagnostic"] {
assert!(screen.contains(text));
}
assert!(!screen.contains("fallback draft"));
app.chat_widget
.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
app.render_chat_widget_frame(&mut tui, size)?;
assert_eq!(
crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal),
&before
);
Ok(())
}
#[tokio::test]
async fn warnings_keep_remapped_copy_keys_out_of_composer_handlers() {
let (mut widget, _, mut rx, _) =
crate::chatwidget::tests::make_chatwidget_manual_with_sender().await;
let diagnostic = "Example warning\nFull diagnostic";
let cells: Vec<Arc<dyn HistoryCell>> =
vec![Arc::new(history_cell::new_warning_event(diagnostic.into()))];
for key in ['r', 'u'] {
let config: codex_config::types::TuiKeymap = serde_json::from_value(serde_json::json!({
"global": {"copy": format!("ctrl-{key}")},
"composer": {"history_search_previous": []},
"editor": {"kill_line_start": []}
}))
.expect("copy binding");
let runtime = crate::keymap::RuntimeKeymap::from_config(&config).expect("valid remap");
widget.apply_keymap_update(config, &runtime);
widget.open_warnings(&cells);
widget.handle_key_event(KeyEvent::new(KeyCode::Char(key), KeyModifiers::CONTROL));
let mut copied = Vec::new();
while let Ok(event) = rx.try_recv() {
if let AppEvent::CopyWarning(text) = event {
copied.push(text);
}
}
assert_eq!(copied, vec![diagnostic.to_string()]);
}
let mut app = crate::app::test_support::make_test_app().await;
let mut tui = crate::tui::test_support::make_test_tui().expect("test terminal");
let config = serde_json::from_value(serde_json::json!({
"global": {"copy": "ctrl-x c"},
"list": {"accept": "ctrl-x"}
}))
.expect("copy chord");
app.keymap = crate::keymap::RuntimeKeymap::from_config(&config).expect("valid chord");
widget.apply_keymap_update(config, &app.keymap);
widget.open_warnings(&cells);
app.chat_widget = widget;
assert!(
app.route_key_chord_event(
&mut tui,
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)
)
.is_none()
);
let key = app
.route_key_chord_event(&mut tui, KeyCode::Char('c').into())
.expect("copy action");
app.chat_widget.handle_key_event(key);
assert!(
std::iter::from_fn(|| rx.try_recv().ok())
.any(|event| matches!(event, AppEvent::CopyWarning(text) if text == diagnostic))
);
}
+4
View File
@@ -424,6 +424,10 @@ pub(crate) enum AppEvent {
/// Open the filename prompt for an on-demand Markdown transcript export.
OpenTranscriptExportFilePrompt,
/// Open retained warnings without changing the draft or transcript position.
OpenWarnings,
/// Copy a diagnostic and acknowledge in the footer, without appending history.
CopyWarning(String),
/// Export all current-thread history to the selected destination.
ExportTranscript {
+27 -5
View File
@@ -37,8 +37,7 @@
//! All completion suggestions render above the composer and preserve its footer.
//! Owned transcript frames overlay suggestions with blank rows above and below, without reserving
//! layout space. Those rows show scroll arrows when suggestions extend beyond the visible menu.
//! Transcript interactions hide suggestions while retaining their query and selection;
//! closing the interaction restores the same draft and completion state.
//! Warning and transcript views hide suggestions without losing the draft, query, or selection.
//! Measurement, painting, and cursor placement share that layout, including clipped views.
//! Unified mention tabs retain their position across filters; Left/Right also works at a bare `@`.
//!
@@ -140,7 +139,8 @@
//!
//! During reconnection, `handle_restricted_key` edits the draft directly without popup dispatch,
//! composer shortcuts, or submission; `?` becomes literal input. Enter and Tab leave the draft
//! intact until reconnection succeeds. When connected but the thread is unavailable, configured
//! intact until reconnection succeeds, except for the local `/warnings` command.
//! When connected but the thread is unavailable, configured
//! submit keys may dispatch explicitly allowed recovery and local commands; other drafts stay put.
//! Collapsed pastes expand into editable text so the full draft can be copied before quitting.
//!
@@ -374,6 +374,7 @@ mod sparkle;
mod status_surface;
mod vim_history;
mod vim_search;
mod warning_notice;
use self::attachment_state::AttachmentState;
use self::draft_state::ComposerMentionBinding;
@@ -498,6 +499,7 @@ fn parent_owned_command_is_allowed(command: SlashCommand, args: &str) -> bool {
| SlashCommand::Import
| SlashCommand::Hooks
| SlashCommand::Status
| SlashCommand::Warnings
| SlashCommand::Daemon
| SlashCommand::Usage
| SlashCommand::Ide
@@ -737,6 +739,9 @@ impl ChatComposer {
active_agent_label: None,
external_editor_key: default_keymap
.primary_hint(KeymapContext::Global, "open_external_editor"),
warning_notice_area: std::cell::Cell::default(),
show_warnings_key: default_keymap
.primary_hint(KeymapContext::Global, "open_warnings"),
show_transcript_key: default_keymap
.primary_hint(KeymapContext::Global, "open_transcript"),
find_transcript_key: default_keymap
@@ -1019,6 +1024,7 @@ impl ChatComposer {
self.draft.textarea.set_keymap_bindings(keymap);
self.footer.external_editor_key =
keymap.primary_hint(KeymapContext::Global, "open_external_editor");
self.footer.show_warnings_key = keymap.primary_hint(KeymapContext::Global, "open_warnings");
self.footer.show_transcript_key =
keymap.primary_hint(KeymapContext::Global, "open_transcript");
self.footer.find_transcript_key =
@@ -4643,9 +4649,11 @@ impl ChatComposer {
}
}
let transcript_hint_area = inset_footer_hint_area(footer_rect);
let warning_notice = self.warning_notice_layout(transcript_hint_area, options);
let warning_area = warning_notice.as_ref().map(|(area, _)| *area);
match options.footer {
Some(footer) => {
self.render_transcript_footer(transcript_hint_area, buf, footer);
self.render_transcript_footer(transcript_hint_area, buf, footer, warning_area);
}
None if self.shortcuts_above_composer(options) => {
let props = self.hint_footer_props(options);
@@ -4674,7 +4682,17 @@ impl ChatComposer {
| FooterMode::ShortcutOverlay
| FooterMode::EscHint => false,
};
let hint_rect = footer_rect;
let hint_rect = if let Some(warning_area) = warning_area {
Rect {
width: warning_area
.x
.saturating_sub(footer_rect.x)
.saturating_sub(/*rhs*/ 2),
..footer_rect
}
} else {
footer_rect
};
if let Some(input) = self.draft.textarea.vim_query() {
input.render(inset_footer_hint_area(hint_rect), buf);
} else if let Some(line) = self.history_search_footer_line() {
@@ -4890,6 +4908,10 @@ impl ChatComposer {
}
}
}
self.footer.warning_notice_area.set(warning_area);
if let Some((warning_area, line)) = warning_notice {
line.render(warning_area, buf);
}
let style = user_message_style();
Block::default().style(style).render(composer_rect, buf);
if !remote_images_rect.is_empty() {
@@ -14,6 +14,7 @@ fn parent_owned_thread_allows_bare_navigation_commands() {
("/btw", SlashCommand::Btw),
("/diff ", SlashCommand::Diff),
("/daemon", SlashCommand::Daemon),
("/warnings", SlashCommand::Warnings),
] {
let (mut composer, _rx) = new_test_composer();
composer.set_parent_owned_thread();
@@ -7,6 +7,7 @@
//! While the transcript owns input, the composer is dimmed and yields its cursor to the footer.
//! Hidden suggestions retain their query and selection until their input owner returns.
//! A pending quit contributes a derived release hint without changing stored footer state.
//! Warning notices use the passive hint row, including while typing, and yield to input controls.
//! Shortcut help occupies the space above the composer and keeps its close hint on the final row.
//! Passive transcript hints retain the shortcuts entry when it fits beside the complete hint.
@@ -60,6 +61,7 @@ pub(crate) enum CommandPopupPlacement {
/// A borrowed presentation shared by measurement, painting, and cursor placement.
#[derive(Clone, Copy, Default)]
pub(crate) struct ComposerRenderOptions<'a> {
pub(crate) warning_count: usize,
pub(crate) textarea_right_reserve: u16,
/// Keep configured status below the composer while hints occupy the final row.
pub(crate) separate_status_line: bool,
@@ -103,7 +105,7 @@ impl super::ChatComposer {
}
pub(super) fn footer_hint_height(&self, width: u16, options: ComposerRenderOptions<'_>) -> u16 {
if self.shortcuts_above_composer(options) {
if self.show_warning_notice(options) || self.shortcuts_above_composer(options) {
return 1;
}
options
@@ -120,9 +122,10 @@ impl super::ChatComposer {
pub(super) fn render_transcript_footer(
&self,
hint_area: Rect,
mut hint_area: Rect,
buf: &mut Buffer,
footer: &TranscriptFooter,
warning_area: Option<Rect>,
) {
let mut text = footer.text.clone();
if footer.cursor_column.is_none()
@@ -132,6 +135,12 @@ impl super::ChatComposer {
{
*line = flash.line.clone();
}
if let Some(warning_area) = warning_area {
hint_area.width = warning_area
.x
.saturating_sub(hint_area.x)
.saturating_sub(/*rhs*/ 2);
}
if !footer.is_interactive
&& !self.footer.flash_visible()
&& self.footer_mode() == FooterMode::ComposerEmpty
@@ -185,6 +194,8 @@ pub(super) struct FooterState {
pub(super) active_agent_label: Option<String>,
pub(super) external_editor_key: Option<ShortcutHint>,
pub(super) show_transcript_key: Option<ShortcutHint>,
pub(super) show_warnings_key: Option<ShortcutHint>,
pub(super) warning_notice_area: std::cell::Cell<Option<Rect>>,
pub(super) find_transcript_key: Option<ShortcutHint>,
pub(super) insert_newline_key: Option<ShortcutHint>,
pub(super) queue_key: Option<ShortcutHint>,
@@ -1,4 +1,5 @@
//! Restricted editing retains drafts; unavailable threads also allow recovery and local commands.
//! Restricted editing retains drafts and allows the local warnings viewer.
//! Unavailable threads also allow recovery and other local commands.
//! Paste Enter handling is shared with normal submission so buffered newlines survive both paths.
//! Recovery commands must occupy one line and be visible before the submit key expands pastes.
//! Offline draft edits also consume the Astra sparkle opportunity before rendering.
@@ -73,8 +74,7 @@ impl ChatComposer {
}
}
}
if mode == RestrictedInputMode::UnavailableThread
&& pending_pastes.is_empty()
if pending_pastes.is_empty()
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
&& self.submit_keys.is_pressed(key)
{
@@ -85,7 +85,8 @@ impl ChatComposer {
.or_else(|| input.inline_command(text).map(|command| command.command))
.filter(|_| text.trim().lines().count() == 1);
if matches!(command, Some(SlashCommandItem::Builtin(command))
if command.available_when_thread_unavailable())
if command == SlashCommand::Warnings
|| mode == RestrictedInputMode::UnavailableThread && command.available_when_thread_unavailable())
{
return self
.try_dispatch_bare_slash_command()
@@ -94,7 +95,7 @@ impl ChatComposer {
}
}
// Enter/Tab and configured submit bindings must never consume the draft offline.
// Other commands and prompts stay in the draft while offline.
// The basic editor reconciles attachments without invoking composer-level shortcuts.
if !matches!(key.code, KeyCode::Enter | KeyCode::Tab)
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
@@ -0,0 +1,27 @@
---
source: tui/src/bottom_pane/chat_composer/warning_notice_tests.rs
assertion_line: 105
expression: styled
---
Buffer {
area: Rect { x: 0, y: 0, width: 80, height: 5 },
content: [
" ",
"› keep this draft ",
" ",
" MODEL · ~/project ",
" ⚠ 3 warnings · f2 to view ",
],
styles: [
x: 0, y: 0, fg: Reset, bg: Rgb(44, 44, 44), underline: Reset, modifier: NONE,
x: 0, y: 1, fg: Reset, bg: Rgb(44, 44, 44), underline: Reset, modifier: BOLD,
x: 1, y: 1, fg: Reset, bg: Rgb(44, 44, 44), underline: Reset, modifier: NONE,
x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 54, y: 4, fg: Rgb(139, 139, 139), bg: Reset, underline: Reset, modifier: NONE,
x: 56, y: 4, fg: Rgb(196, 167, 103), bg: Reset, underline: Reset, modifier: NONE,
x: 66, y: 4, fg: Rgb(139, 139, 139), bg: Reset, underline: Reset, modifier: NONE,
x: 69, y: 4, fg: Rgb(222, 222, 222), bg: Reset, underline: Reset, modifier: BOLD,
x: 71, y: 4, fg: Rgb(139, 139, 139), bg: Reset, underline: Reset, modifier: NONE,
x: 79, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
]
}
@@ -0,0 +1,97 @@
//! Fit warning counts and the configured warnings shortcut into the existing passive hint row.
//! Interactive hints retain priority; warning delivery never changes composer geometry.
//! Only the count and warning label receive an amber accent; surrounding hints stay muted.
use super::*;
impl ChatComposer {
pub(crate) fn warning_notice_contains(&self, position: ratatui::layout::Position) -> bool {
self.footer
.warning_notice_area
.get()
.is_some_and(|area| area.contains(position))
}
pub(super) fn show_warning_notice(&self, options: ComposerRenderOptions<'_>) -> bool {
options.warning_count > 0
&& !options.footer.is_some_and(|footer| footer.is_interactive)
&& matches!(self.popups.active, ActivePopup::None)
&& super::super::footer::shows_passive_footer_line(&self.footer_props())
&& self.footer.hint_override.is_none()
&& !self.footer.flash_visible()
&& self.history_search.is_none()
&& self.draft.textarea.vim_query().is_none()
&& !self.quit_shortcut_hint_visible()
}
pub(super) fn warning_notice_layout(
&self,
hint_area: Rect,
options: ComposerRenderOptions<'_>,
) -> Option<(Rect, Line<'static>)> {
if !self.show_warning_notice(options) || hint_area.is_empty() {
return None;
}
// Leave space for ordinary hints, and one clear cell at the terminal's right edge.
let available = hint_area.width.saturating_sub(/*rhs*/ 1);
let mut budget = (available / 2).max(/*other*/ 14).min(available);
if let Some(footer) = options.footer {
// Navigation and loading hints must remain readable before spending spare columns
// on warnings. A warning may shrink to its count, or wait until that hint closes.
let hint_width = footer.text.width().min(usize::from(available)) as u16;
budget = budget.min(available.saturating_sub(hint_width.saturating_add(/*rhs*/ 2)));
}
if budget < Line::from(format!("⚠ {}", options.warning_count)).width() as u16 {
return None;
}
let line = self.warning_notice(options.warning_count, budget);
let width = line.width() as u16;
let area = Rect::new(
hint_area.right().saturating_sub(width + 1),
hint_area.bottom() - 1,
width,
/*height*/ 1,
);
Some((area, line))
}
pub(super) fn warning_notice(&self, count: usize, width: u16) -> Line<'static> {
let plural = if count == 1 { "" } else { "s" };
let accent = crate::style::warning_notice_style();
let secondary = crate::style::secondary_text_style();
let shortcut = self
.footer
.show_warnings_key
.map(ShortcutHint::display_label)
.unwrap_or_else(|| "/warnings".into());
let mut full = Line::from(vec![
"⚠ ".into(),
Span::styled(format!("{count} warning{plural}"), accent),
" · ".into(),
])
.style(secondary);
full.extend(key_hint::key_label_spans(&shortcut));
full.push_span(" to view");
if full.width() <= usize::from(width) {
return full;
}
let mut compact = Line::from(vec![
"⚠ ".into(),
Span::styled(count.to_string(), accent),
" · ".into(),
])
.style(secondary);
compact.extend(key_hint::key_label_spans(&shortcut));
if compact.width() <= usize::from(width) {
return compact;
}
truncate_line_with_ellipsis_if_overflow(
Line::from(vec!["⚠ ".into(), Span::styled(count.to_string(), accent)]).style(secondary),
usize::from(width),
)
}
}
#[cfg(test)]
#[path = "warning_notice_tests.rs"]
mod tests;
@@ -0,0 +1,165 @@
//! Warning notice layout, shortcut remapping, and input-priority coverage.
use super::*;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc::unbounded_channel;
fn composer() -> ChatComposer {
let (tx, _) = unbounded_channel();
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
AppEventSender::new(tx),
/*enhanced_keys_supported*/ false,
"Ask Codex".into(),
/*disable_paste_burst*/ true,
);
// Keep layout fixtures independent of platform-specific default shortcuts.
composer.footer.show_warnings_key = Some(crate::key_hint::plain(KeyCode::F(2)).into());
composer.set_status_line_enabled(/*enabled*/ true);
composer.set_status_line(Some(Line::from("MODEL · ~/project")));
composer
}
fn render(composer: &ChatComposer, width: u16, count: usize) -> Buffer {
let options = composer.resolve_render_options(ComposerRenderOptions {
separate_status_line: true,
warning_count: count,
command_popup_placement: CommandPopupPlacement::Overlay,
..Default::default()
});
let area = Rect::new(
/*x*/ 0,
/*y*/ 0,
width,
composer.desired_height_with_options(width, options),
);
let mut buffer = Buffer::empty(area);
composer.render_with_options(area, &mut buffer, /*mask_char*/ None, options);
buffer
}
fn text(buffer: &Buffer) -> String {
buffer
.content
.chunks(usize::from(buffer.area.width))
.map(|row| {
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim_end()
.to_owned()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn warning_notice_styles() {
let mut composer = composer();
composer.set_text_content("keep this draft".into(), Vec::new(), Vec::new());
let styled = crate::terminal_palette::with_test_default_colors(
crate::terminal_probe::DefaultColors {
fg: (222, 222, 222),
bg: (16, 16, 16),
},
|| render(&composer, /*width*/ 80, /*count*/ 3),
);
insta::assert_debug_snapshot!("warning_notice_styles", styled);
}
#[test]
fn light_warning_notice_clears_inherited_dimming() {
crate::terminal_palette::with_test_default_colors(
crate::terminal_probe::DefaultColors {
fg: (30, 30, 30),
bg: (255, 255, 255),
},
|| {
let composer = composer();
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 20, /*height*/ 1,
);
let mut buffer = Buffer::empty(area);
buffer.set_style(area, Style::default().dim());
composer
.warning_notice(/*count*/ 3, area.width)
.render(area, &mut buffer);
for cell in &buffer.content {
if !cell.symbol().trim().is_empty() {
assert!(!cell.modifier.contains(Modifier::DIM));
}
}
assert_eq!(buffer[(2, 0)].symbol(), "3");
assert_eq!(
buffer[(2, 0)].fg,
crate::style::warning_notice_style().fg.unwrap()
);
},
);
}
#[test]
fn warning_notice_respects_shortcuts_and_interactive_hints() {
let mut composer = composer();
composer.footer.show_warnings_key = Some(crate::key_hint::plain(KeyCode::F(12)).into());
assert!(text(&render(&composer, /*width*/ 64, /*count*/ 2)).contains("f12 to view"));
composer.footer.show_warnings_key = None;
assert!(text(&render(&composer, /*width*/ 64, /*count*/ 2)).contains("⚠ 2 · /warnings"));
let interactive = TranscriptFooter {
text: Line::from("Find: needle").into(),
cursor_column: Some(6),
is_interactive: true,
};
let options = composer.resolve_render_options(ComposerRenderOptions {
warning_count: 2,
footer: Some(&interactive),
..Default::default()
});
assert!(!composer.show_warning_notice(options));
let passive = ComposerRenderOptions {
warning_count: 2,
..Default::default()
};
composer.begin_history_search();
assert!(!composer.show_warning_notice(passive));
composer.history_search = None;
composer.set_footer_hint_override(Some(vec![("Ctrl+X".into(), "pending chord".into())]));
assert!(!composer.show_warning_notice(passive));
composer.set_footer_hint_override(/*items*/ None);
assert!(composer.show_warning_notice(passive));
composer.set_text_content("/".into(), Vec::new(), Vec::new());
composer.sync_popups();
assert!(!composer.show_warning_notice(passive));
}
#[test]
fn warnings_yield_to_queue_controls_and_complete_navigation_hints() {
let mut composer = composer();
composer.set_text_content("queued draft".into(), Vec::new(), Vec::new());
composer.set_task_running(/*running*/ true);
assert_eq!(
render(&composer, /*width*/ 32, /*count*/ 4),
render(&composer, /*width*/ 32, /*count*/ 0),
);
composer.set_task_running(/*running*/ false);
let footer = TranscriptFooter {
text: "esc latest".into(),
cursor_column: None,
is_interactive: false,
};
let options = composer.resolve_render_options(ComposerRenderOptions {
footer: Some(&footer),
warning_count: 4,
separate_status_line: true,
..Default::default()
});
for width in [12, 20] {
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, /*height*/ 1);
let notice = composer.warning_notice_layout(area, options);
assert_eq!(notice.is_some(), width > 12);
if let Some((warning, _)) = notice {
assert!(warning.x >= footer.text.width() as u16 + 2);
assert_eq!(warning.right(), area.right() - 1);
}
}
}
+101 -15
View File
@@ -84,6 +84,8 @@ mod status_surface_preview;
mod title_setup;
pub(crate) mod user_verification;
mod voice_strip;
mod warnings;
mod warnings_view;
pub(crate) use action_required_title::ACTION_REQUIRED_PREVIEW_PREFIX;
pub(crate) use action_required_title::build_action_required_title_text;
pub(crate) use actionable_banner::ActionableBanner;
@@ -273,6 +275,7 @@ 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>,
pub(crate) questions: Option<Box<AsyncQuestions>>,
delayed_approval_requests: VecDeque<DelayedApprovalRequest>,
last_composer_activity_at: Option<Instant>,
@@ -355,6 +358,7 @@ impl BottomPane {
Self {
composer,
view_stack: Vec::new(),
warnings_view: None,
questions: None,
delayed_approval_requests: VecDeque::new(),
last_composer_activity_at: None,
@@ -489,6 +493,9 @@ impl BottomPane {
/// overlays and selection views to continue using the previous bindings.
pub fn set_keymap_bindings(&mut self, keymap: &RuntimeKeymap) {
self.keymap = keymap.clone();
if let Some(view) = &mut self.warnings_view {
view.set_keymap(keymap);
}
self.composer.set_keymap_bindings(keymap);
if let Some(questions) = &mut self.questions {
questions.set_keymap(keymap);
@@ -710,7 +717,7 @@ impl BottomPane {
})
}
fn record_composer_activity_at(&mut self, now: Instant) {
pub(crate) fn record_composer_activity_at(&mut self, now: Instant) {
self.last_composer_activity_at = Some(now);
if self.has_pending_approval()
&& let Some(delay) = self.approval_prompt_delay_remaining(now)
@@ -755,6 +762,7 @@ impl BottomPane {
mode: RestrictedInputMode,
) -> InputResult {
self.view_stack.clear();
self.warnings_view = None;
self.delayed_approval_requests.clear();
self.composer
.set_input_enabled(/*enabled*/ true, /*placeholder*/ None);
@@ -776,6 +784,20 @@ impl BottomPane {
| KeyCode::Enter
| KeyCode::Tab
);
if self.warnings_active() {
if matches!(key_event.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
self.record_composer_activity_at(Instant::now());
}
if self
.warnings_view
.as_mut()
.is_some_and(|view| view.handle_key(key_event))
{
self.warnings_view = None;
}
self.request_redraw();
return InputResult::None;
}
if self.view_stack.is_empty()
&& let Some(questions) = self.questions.as_mut().filter(|q| q.expanded)
{
@@ -868,6 +890,11 @@ impl BottomPane {
/// Return the contexts whose ordinary handlers can consume the next key.
pub(crate) fn keymap_contexts(&self) -> KeymapContextSet {
if self.warnings_active()
&& let Some(view) = &self.warnings_view
{
return view.keymap_contexts();
}
if let Some(view) = self.view_stack.last() {
view.keymap_contexts()
} else if let Some(questions) = self.questions.as_ref().filter(|q| q.expanded) {
@@ -887,6 +914,11 @@ impl BottomPane {
/// was received, but it does not decide whether the process should exit; `ChatWidget` owns the
/// quit/interrupt state machine and uses the result to decide what happens next.
pub(crate) fn on_ctrl_c(&mut self) -> CancellationEvent {
if self.warnings_active() {
self.warnings_view = None;
self.request_redraw();
return CancellationEvent::Handled;
}
if self.view_stack.is_empty()
&& let Some(questions) = self.questions.as_mut().filter(|q| q.expanded)
{
@@ -919,6 +951,13 @@ impl BottomPane {
}
pub fn handle_paste(&mut self, pasted: String) {
if self.warnings_active() {
if !pasted.is_empty() {
self.record_composer_activity_at(Instant::now());
}
self.request_redraw();
return;
}
if self.view_stack.is_empty()
&& let Some(questions) = self.questions.as_mut().filter(|q| q.expanded)
{
@@ -1048,6 +1087,7 @@ impl BottomPane {
pub(crate) fn show_shutdown_in_progress(&mut self) {
self.view_stack.clear();
self.warnings_view = None;
self.composer.show_shutdown_in_progress();
self.request_redraw();
}
@@ -1109,6 +1149,9 @@ impl BottomPane {
}
pub(crate) fn set_footer_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
if let Some(view) = &mut self.warnings_view {
view.pending_hint = items.clone();
}
self.composer.set_footer_hint_override(items);
self.request_redraw();
}
@@ -1642,6 +1685,11 @@ impl BottomPane {
}
pub(crate) fn has_active_view(&self) -> bool {
self.warnings_view.is_some() || self.has_active_modal()
}
/// Warnings own input without replacing the composer with an interactive modal.
pub(crate) fn has_active_modal(&self) -> bool {
!self.view_stack.is_empty()
}
@@ -2024,6 +2072,11 @@ impl BottomPane {
&'a self,
mut options: ComposerRenderOptions<'a>,
) -> RenderableItem<'a> {
if self.warnings_active()
&& let Some(warnings) = &self.warnings_view
{
return RenderableItem::Borrowed(warnings);
}
if (self.is_task_running || !self.view_stack.is_empty())
&& let Some(banner) = &self.inline_banner
{
@@ -2128,6 +2181,7 @@ impl BottomPane {
let composer: RenderableItem<'_> = if let Some(questions) = question_editor {
RenderableItem::Borrowed(questions.as_ref())
} else if options.textarea_right_reserve == 0
&& options.warning_count == 0
&& options.footer.is_none()
&& !options.separate_status_line
&& options.command_popup_placement == CommandPopupPlacement::AboveComposer
@@ -2145,6 +2199,11 @@ impl BottomPane {
}
pub(crate) fn show_footer_flash(&mut self, line: Line<'static>, duration: Duration) {
if self.warnings_active()
&& let Some(view) = &mut self.warnings_view
{
view.flash = Some((line.clone(), Instant::now() + duration));
}
self.composer.show_footer_flash(line, duration);
self.request_redraw();
}
@@ -2655,24 +2714,51 @@ mod tests {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let tx = AppEventSender::new(tx_raw);
let features = Features::with_defaults();
let mut pane = test_pane(tx);
let now = Instant::now();
pane.last_composer_activity_at = Some(now);
for source in [
"composer",
"warning open",
"warning navigation",
"warning paste",
] {
let mut pane = test_pane(tx.clone());
match source {
"warning open" => pane.show_warnings(Vec::new()),
"warning navigation" => {
pane.show_warnings(Vec::new());
pane.last_composer_activity_at = None;
pane.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
}
"warning paste" => {
pane.show_warnings(Vec::new());
pane.last_composer_activity_at = None;
pane.handle_paste("query".into());
}
_ => pane.last_composer_activity_at = Some(Instant::now()),
}
let now = pane
.last_composer_activity_at
.expect("typing activity recorded");
pane.push_approval_request(exec_request(), &features);
pane.push_approval_request(exec_request(), &features);
assert!(pane.view_stack.is_empty());
assert_eq!(pane.delayed_approval_requests.len(), 1);
assert!(pane.view_stack.is_empty());
assert_eq!(pane.delayed_approval_requests.len(), 1);
if source == "warning navigation" {
pane.handle_key_event(KeyCode::Enter.into());
assert!(pane.warnings_active());
}
let now = pane.last_composer_activity_at.unwrap_or(now);
pane.pre_draw_tick_at(
now + APPROVAL_PROMPT_TYPING_IDLE_DELAY - Duration::from_millis(/*millis*/ 1),
);
assert!(pane.view_stack.is_empty());
assert_eq!(pane.delayed_approval_requests.len(), 1);
pane.pre_draw_tick_at(
now + APPROVAL_PROMPT_TYPING_IDLE_DELAY - Duration::from_millis(/*millis*/ 1),
);
assert!(pane.view_stack.is_empty());
assert_eq!(pane.delayed_approval_requests.len(), 1);
pane.pre_draw_tick_at(now + APPROVAL_PROMPT_TYPING_IDLE_DELAY);
assert_eq!(pane.view_stack.len(), 1);
assert!(pane.delayed_approval_requests.is_empty());
pane.pre_draw_tick_at(now + APPROVAL_PROMPT_TYPING_IDLE_DELAY);
assert_eq!(pane.view_stack.len(), 1);
assert!(pane.delayed_approval_requests.is_empty());
}
}
#[test]
@@ -333,6 +333,7 @@ mod tests {
SlashCommand::Mention,
SlashCommand::Status,
SlashCommand::Daemon,
SlashCommand::Warnings,
SlashCommand::Pwd,
SlashCommand::Usage,
]
@@ -33,6 +33,7 @@ expression: commands
/mention - mention a file
/status - show current session configuration and token usage
/daemon - Manage the local background server.
/warnings - view retained warnings and diagnostic details
/cd - change the current working directory
/pwd - show the current working directory
/title - configure which items appear in the terminal title
@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/warnings_view_tests.rs
expression: "draw(&view, 40, 9)"
---
Warnings · 1 of 2 · MCP · example
Long diagnostic 日 本 語
Details retained in full, including
remediation instructions.
Details retained in full, including
remediation instructions.
Details retained in full, including
esc back · ctrl+o copy · ←/→ warning
+29
View File
@@ -0,0 +1,29 @@
//! Warning-panel ownership and focus routing; the ordinary composer is never replaced.
use super::*;
use crate::history_cell::WarningEntry;
impl BottomPane {
pub(crate) fn show_warnings(&mut self, entries: Vec<WarningEntry>) {
self.warnings_view = Some(warnings_view::WarningsView::new(
entries,
self.keymap.clone(),
self.app_event_tx.clone(),
));
self.record_composer_activity_at(Instant::now());
self.request_redraw();
}
pub(crate) fn warnings_active(&self) -> bool {
self.warnings_view.is_some()
&& self.view_stack.is_empty()
&& !self
.questions
.as_ref()
.is_some_and(|questions| questions.expanded)
}
pub(crate) fn warning_notice_contains(&self, position: ratatui::layout::Position) -> bool {
self.no_modal_or_popup_active() && self.composer.warning_notice_contains(position)
}
}
@@ -0,0 +1,112 @@
//! A frozen set of warnings, shown one at a time without changing the retained draft.
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
use crate::history_cell::WarningEntry;
use crate::key_hint::KeyBindingListExt;
use crate::keymap::KeymapContext;
use crate::keymap::KeymapContextSet;
use crate::keymap::ListAction;
use crate::keymap::RuntimeKeymap;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use std::cell::Cell;
#[path = "warnings_view_render.rs"]
mod render;
pub(super) struct WarningsView {
entries: Vec<WarningEntry>,
current: usize,
offset: Cell<usize>,
page_size: Cell<usize>,
max_offset: Cell<usize>,
keymap: RuntimeKeymap,
tx: AppEventSender,
pub(super) pending_hint: Option<Vec<(String, String)>>,
pub(super) flash: Option<(ratatui::text::Line<'static>, std::time::Instant)>,
}
impl WarningsView {
pub(super) fn new(
entries: Vec<WarningEntry>,
keymap: RuntimeKeymap,
tx: AppEventSender,
) -> Self {
Self {
entries,
current: 0,
offset: Cell::new(/*value*/ 0),
page_size: Cell::new(/*value*/ 1),
max_offset: Cell::new(/*value*/ 0),
keymap,
tx,
pending_hint: None,
flash: None,
}
}
pub(super) fn set_keymap(&mut self, keymap: &RuntimeKeymap) {
self.keymap = keymap.clone();
}
pub(super) fn keymap_contexts(&self) -> KeymapContextSet {
KeymapContextSet::warnings()
}
/// Returns true when the user closes the viewer. No key is forwarded to the draft.
pub(super) fn handle_key(&mut self, event: KeyEvent) -> bool {
if event.kind == KeyEventKind::Release {
return false;
}
let action = self
.keymap
.list
.action_for(event)
.filter(|action| *action != ListAction::Accept);
if action.is_none() && self.keymap.app.open_warnings.is_pressed(event)
|| self.keymap.list.cancel.is_pressed(event)
{
return true;
}
if action.is_none() && self.keymap.app.copy.is_pressed(event) {
if let Some(entry) = self.entries.get(self.current) {
self.tx.send(AppEvent::CopyWarning(entry.details.clone()));
}
return false;
}
let offset = self.offset.get();
match action {
Some(ListAction::MoveLeft | ListAction::MoveRight) => {
let previous = self.current;
self.current = if action == Some(ListAction::MoveLeft) {
self.current.saturating_sub(/*rhs*/ 1)
} else {
(self.current + 1).min(self.entries.len().saturating_sub(/*rhs*/ 1))
};
if self.current != previous {
self.offset.set(/*val*/ 0);
}
}
Some(ListAction::MoveUp) => self.offset.set(offset.saturating_sub(/*rhs*/ 1)),
Some(ListAction::MoveDown) => self.offset.set((offset + 1).min(self.max_offset.get())),
Some(ListAction::PageUp) => {
self.offset.set(offset.saturating_sub(self.page_size.get()))
}
Some(ListAction::PageDown) => self.offset.set(
offset
.saturating_add(self.page_size.get())
.min(self.max_offset.get()),
),
Some(ListAction::JumpTop) => self.offset.set(/*val*/ 0),
Some(ListAction::JumpBottom) => self.offset.set(self.max_offset.get()),
Some(ListAction::Cancel) => return true,
Some(ListAction::Accept) | None => {}
}
false
}
}
#[cfg(test)]
#[path = "warnings_view_tests.rs"]
mod tests;
@@ -0,0 +1,105 @@
//! Show one complete diagnostic with bounded scrolling and the viewer's own footer.
use super::*;
use crate::bottom_pane::footer_hint_items_line;
use crate::render::renderable::Renderable;
use ratatui::buffer::Buffer;
use ratatui::layout::Constraint;
use ratatui::layout::Layout;
use ratatui::layout::Margin;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Widget;
impl Renderable for WarningsView {
fn desired_height(&self, _width: u16) -> u16 {
12
}
fn render(&self, area: Rect, buf: &mut Buffer) {
let area = area.inner(Margin::new(/*horizontal*/ 2, /*vertical*/ 0));
let [header, _, body, footer] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Min(0),
Constraint::Length(1),
])
.areas(area);
let entry = self.entries.get(self.current);
let title = match entry {
Some(entry) => format!(
"Warnings · {} of {} · {}",
self.current + 1,
self.entries.len(),
entry.source
),
None => "Warnings".to_string(),
};
Line::from(title.bold()).render(header, buf);
let details = entry.map_or("No warnings", |entry| entry.details.as_str());
let lines: Vec<_> = details
.lines()
.flat_map(|line| textwrap::wrap(line, usize::from(body.width.max(/*other*/ 1))))
.collect();
let page_size = usize::from(body.height.max(/*other*/ 1));
self.page_size.set(page_size);
self.max_offset.set(lines.len().saturating_sub(page_size));
let offset = self.offset.get().min(self.max_offset.get());
self.offset.set(offset);
for (row, line) in lines
.iter()
.skip(offset)
.take(usize::from(body.height))
.enumerate()
{
Line::from(line.as_ref()).render(
Rect::new(body.x, body.y + row as u16, body.width, /*height*/ 1),
buf,
);
}
let navigation = ["move_left", "move_right"]
.into_iter()
.filter_map(|action| self.keymap.primary_hint(KeymapContext::List, action))
.map(crate::key_hint::ShortcutHint::display_label)
.collect::<Vec<_>>()
.join("/");
let mut items = Vec::new();
for (hint, label) in [
(
self.keymap
.primary_hint(KeymapContext::List, "cancel")
.map(crate::key_hint::ShortcutHint::display_label),
"back",
),
(
self.keymap
.primary_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")
.map(crate::key_hint::ShortcutHint::display_label),
"scroll",
),
] {
if let Some(hint) = hint {
items.push((hint, label.to_string()));
if footer_hint_items_line(&items).width() > usize::from(footer.width) {
items.pop();
}
}
}
if let Some((line, expires_at)) = &self.flash
&& std::time::Instant::now() < *expires_at
{
line.clone().render(footer, buf);
} else {
footer_hint_items_line(self.pending_hint.as_ref().unwrap_or(&items))
.render(footer, buf);
}
}
}
@@ -0,0 +1,90 @@
//! Independent warning navigation, full-text copying, and bounded scrolling.
use super::*;
use crate::history_cell::WarningId;
use crate::render::renderable::Renderable;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use tokio::sync::mpsc::unbounded_channel;
fn entries() -> Vec<WarningEntry> {
vec![
WarningEntry {
id: WarningId::McpServer("example".into()),
source: "MCP · example".into(),
details: "MCP example could not connect\nSign in again using codex mcp login example"
.into(),
},
WarningEntry {
id: WarningId::Message("config".into()),
source: "Startup".into(),
details: "Unknown setting `old_option`\nRemove it from config.toml".into(),
},
]
}
fn key(view: &mut WarningsView, code: KeyCode) -> bool {
view.handle_key(KeyEvent::new(code, KeyModifiers::NONE))
}
fn draw(view: &WarningsView, width: u16, height: u16) -> String {
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let mut buffer = Buffer::empty(area);
view.render(area, &mut buffer);
buffer
.content
.chunks(usize::from(width))
.map(|row| {
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn warning_pages_copy_only_the_current_diagnostic() {
let (tx, mut rx) = unbounded_channel();
let mut view = WarningsView::new(
entries(),
RuntimeKeymap::from_config(&toml::from_str("[list]\nmove_right = 'x'").unwrap()).unwrap(),
AppEventSender::new(tx),
);
let (code, modifiers) = RuntimeKeymap::defaults().app.copy[0].parts();
for (navigation, index) in [(KeyCode::Char('x'), 1), (KeyCode::Left, 0)] {
key(&mut view, navigation);
let screen = draw(&view, /*width*/ 80, /*height*/ 12);
assert!(screen.contains(&format!("{} of 2", index + 1)));
assert!(screen.contains(entries()[index].details.lines().next().unwrap()));
view.handle_key(KeyEvent::new(code, modifiers));
assert!(
matches!(rx.try_recv(), Ok(AppEvent::CopyWarning(text)) if text == entries()[index].details)
);
}
assert!(key(&mut view, KeyCode::Esc));
}
#[test]
fn warning_pages_wrap_and_scroll_long_diagnostics() {
let (tx, _) = unbounded_channel();
let mut data = entries();
data[0].details = format!(
"Long diagnostic 日本語\n{}\nEND OF DIAGNOSTIC",
"Details retained in full, including remediation instructions.\n".repeat(/*n*/ 20)
);
let mut view = WarningsView::new(data, RuntimeKeymap::defaults(), AppEventSender::new(tx));
insta::assert_snapshot!("warnings_narrow", draw(&view, /*width*/ 40, /*height*/ 9));
key(&mut view, KeyCode::PageDown);
assert!(!draw(&view, /*width*/ 40, /*height*/ 9).contains("Long diagnostic"));
key(&mut view, KeyCode::End);
assert!(draw(&view, /*width*/ 40, /*height*/ 9).contains("END OF DIAGNOSTIC"));
key(&mut view, KeyCode::Right);
assert!(draw(&view, /*width*/ 40, /*height*/ 9).contains("Unknown setting"));
key(&mut view, KeyCode::Left);
assert!(draw(&view, /*width*/ 40, /*height*/ 9).contains("Long diagnostic"));
}
+4
View File
@@ -1811,6 +1811,10 @@ impl ChatWidget {
self.bottom_pane.has_active_view()
}
pub(crate) fn has_active_modal(&self) -> bool {
self.bottom_pane.has_active_modal()
}
pub(crate) fn show_esc_backtrack_hint(&mut self) {
self.bottom_pane.show_esc_backtrack_hint();
}
+3 -3
View File
@@ -30,8 +30,9 @@ impl ChatWidget {
..
} if modifiers.contains(KeyModifiers::CONTROL) && c.eq_ignore_ascii_case(&'c')
)
&& !key_hint::ctrl(KeyCode::Char('r')).is_press(key_event)
&& !key_hint::ctrl(KeyCode::Char('u')).is_press(key_event)
&& (self.bottom_pane.warnings_active()
|| (!key_hint::ctrl(KeyCode::Char('r')).is_press(key_event)
&& !key_hint::ctrl(KeyCode::Char('u')).is_press(key_event)))
{
let should_pause_active_goal = self
.bottom_pane
@@ -382,7 +383,6 @@ impl ChatWidget {
}
/// Report a transcript copy without adding history and return its outcome to the viewport.
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(crate) fn copy_transcript_selection(
&mut self,
text: &str,
+7 -13
View File
@@ -3,8 +3,8 @@
//! The app server reports MCP server startup as per-server status updates. This
//! module keeps the TUI's buffered startup round state coherent and translates
//! those updates into status headers, warnings, and queued-input release points.
//! Initial diagnostics coalesce beneath the splash; warnings after a turn starts
//! stay inline so failures during ongoing work remain visible.
//! Initial and runtime diagnostics remain in retained history and the warnings viewer;
//! compact history hides their full text behind the persistent warning notice.
use std::collections::BTreeSet;
@@ -293,17 +293,11 @@ impl ChatWidget {
servers: impl IntoIterator<Item = String>,
failure_reason: Option<McpServerStartupFailureReason>,
) {
if self.warning_display_state.startup_complete {
for message in messages {
self.on_warning(message);
}
} else {
self.add_to_history(crate::history_cell::StartupWarningsCell::mcp(
messages,
servers,
failure_reason,
));
}
self.add_to_history(crate::history_cell::StartupWarningsCell::mcp(
messages,
servers,
failure_reason,
));
}
/// Update startup state and retry installed-app discovery when its MCP server becomes ready.
+12
View File
@@ -176,6 +176,18 @@ impl ChatWidget {
};
self.add_warning_message(message.to_string());
// Warnings are collected outside the live transcript. A command the user
// just invoked also needs an immediate explanation above the composer.
self.bottom_pane.show_selection_view(SelectionViewParams {
title: Some("Pets unavailable".to_string()),
subtitle: Some(message.to_string()),
items: vec![SelectionItem {
name: "Close".to_string(),
dismiss_on_select: true,
..Default::default()
}],
..SelectionViewParams::picker()
});
true
}
+16 -1
View File
@@ -222,7 +222,22 @@ impl ChatWidget {
vec!["✓ ".green(), notification.message.into()].into(),
]);
}
ServerNotification::Warning(notification) => self.on_warning(notification.message),
ServerNotification::Warning(notification) => {
if self.warning_display_state.startup_complete {
self.on_warning(notification.message);
} else if self
.warning_display_state
.should_display(&notification.message)
{
// Unstable-feature and skill-budget notices arrive as ordinary warnings.
// Coalesce initialization diagnostics by lifecycle, not message wording.
// Both startup and runtime warnings retain details in the transcript.
self.add_to_history(history_cell::StartupWarningsCell::new(vec![
notification.message,
]));
self.request_redraw();
}
}
ServerNotification::GuardianWarning(notification) => {
if !notification
.message
+1
View File
@@ -223,6 +223,7 @@ impl ChatWidget {
};
self.bottom_pane
.as_renderable_with_options(crate::bottom_pane::ComposerRenderOptions {
warning_count: self.warning_display_state.count,
textarea_right_reserve: right_reserve,
separate_status_line: command_popup_placement
!= crate::bottom_pane::CommandPopupPlacement::AboveComposer,
@@ -501,6 +501,7 @@ impl ChatWidget {
self.add_hooks_output();
}
SlashCommand::Daemon => self.app_event_tx.send(AppEvent::OpenDaemonMenu),
SlashCommand::Warnings => self.app_event_tx.send(AppEvent::OpenWarnings),
SlashCommand::Status => {
if self.should_prefetch_rate_limits() {
let request_id = self.next_status_refresh_request_id;
@@ -1232,6 +1233,7 @@ impl ChatWidget {
}
}
SlashCommand::Feedback
| SlashCommand::Warnings
| SlashCommand::Export
| SlashCommand::New
| SlashCommand::Archive
@@ -0,0 +1,15 @@
---
source: tui/src/chatwidget/tests/slash_commands.rs
expression: "render_bottom_popup(&chat, width)"
---
Pets unavailable
Pets are disabled in tmux. Terminal
images don’t stay pane-local in tmux
and can corrupt scrollback or move
between panes. Run Codex outside
tmux to use pets.
› 1. Close
enter select · esc back
@@ -1,3 +1,4 @@
use super::helpers::drain_insert_history_transcript;
use super::*;
use codex_app_server_protocol::AuthRecoveryNotification;
use codex_protocol::error::CodexErr;
@@ -923,7 +924,7 @@ async fn live_app_server_warning_notification_renders_message() {
/*replay_kind*/ None,
);
let cells = drain_insert_history(&mut rx);
let cells = drain_insert_history_transcript(&mut rx);
assert_eq!(cells.len(), 1, "expected one warning history cell");
let rendered = lines_to_single_string(&cells[0]);
let normalized = rendered.split_whitespace().collect::<Vec<_>>().join(" ");
@@ -954,7 +955,7 @@ async fn live_app_server_warning_notification_renders_message() {
] {
chat.handle_server_notification(notification, /*replay_kind*/ None);
let [cell] = drain_insert_history(&mut rx)
let [cell] = drain_insert_history_transcript(&mut rx)
.try_into()
.expect("expected one authentication recovery history cell");
recovery_messages.push_str(&lines_to_single_string(&cell));
@@ -977,7 +978,7 @@ async fn live_app_server_guardian_warning_notification_renders_message() {
/*replay_kind*/ None,
);
let cells = drain_insert_history(&mut rx);
let cells = drain_insert_history_transcript(&mut rx);
assert_eq!(cells.len(), 1, "expected one warning history cell");
let rendered = lines_to_single_string(&cells[0]);
assert!(
@@ -1004,7 +1005,7 @@ async fn live_app_server_strict_review_required_notification_renders_message() {
/*replay_kind*/ None,
);
let cells = drain_insert_history(&mut rx);
let cells = drain_insert_history_transcript(&mut rx);
assert_eq!(cells.len(), 1, "expected one warning history cell");
assert_chatwidget_snapshot!("strict_review_required", lines_to_single_string(&cells[0]));
chat.on_exec_command_output_delta("cmd-1", "streamed output\n");
@@ -1020,7 +1021,7 @@ async fn live_app_server_strict_review_required_notification_renders_message() {
}
#[tokio::test]
async fn config_warning_during_turn_remains_inline() {
async fn config_warning_during_turn_retains_transcript_details() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
handle_turn_started(&mut chat, "turn-1");
chat.handle_server_notification(
@@ -1032,7 +1033,7 @@ async fn config_warning_during_turn_remains_inline() {
}),
/*replay_kind*/ None,
);
let cells = drain_insert_history(&mut rx);
let cells = drain_insert_history_transcript(&mut rx);
insta::assert_snapshot!(
"runtime_config_warning",
cells
@@ -1665,7 +1666,7 @@ async fn live_app_server_rate_limit_error_renders_upstream_message() {
}
#[tokio::test]
async fn live_app_server_server_overloaded_error_renders_warning() {
async fn live_app_server_server_overloaded_error_renders_error() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.handle_server_notification(
@@ -1703,7 +1704,7 @@ async fn live_app_server_server_overloaded_error_renders_warning() {
let cells = drain_insert_history(&mut rx);
assert_eq!(cells.len(), 1);
assert_eq!(lines_to_single_string(&cells[0]), "⚠ server overloaded\n");
assert_eq!(lines_to_single_string(&cells[0]), "■ server overloaded\n");
assert!(!chat.bottom_pane.is_task_running());
}
@@ -1047,7 +1047,7 @@ async fn blocked_image_restore_preserves_mention_bindings() {
);
assert_eq!(chat.bottom_pane.take_mention_bindings(), mention_bindings);
let cells = drain_insert_history(&mut rx);
let cells = drain_insert_history_transcript(&mut rx);
let warning = cells
.last()
.map(|lines| lines_to_single_string(lines))
@@ -1,3 +1,4 @@
use super::helpers::drain_insert_history_transcript;
use super::*;
use pretty_assertions::assert_eq;
@@ -307,7 +308,7 @@ async fn guardian_denied_exec_renders_warning_and_denied_request() {
let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal");
term.set_viewport_area(viewport);
for lines in drain_insert_history(&mut rx) {
for lines in drain_insert_history_transcript(&mut rx) {
crate::insert_history::insert_history_lines(&mut term, lines)
.expect("Failed to insert history lines in test");
}
@@ -523,7 +524,7 @@ async fn guardian_timed_out_exec_renders_warning_and_timed_out_request() {
let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal");
term.set_viewport_area(viewport);
for lines in drain_insert_history(&mut rx) {
for lines in drain_insert_history_transcript(&mut rx) {
crate::insert_history::insert_history_lines(&mut term, lines)
.expect("Failed to insert history lines in test");
}
@@ -1,3 +1,4 @@
use super::helpers::drain_insert_history_transcript;
use super::*;
use crate::app_event::HistoryLookupResponse;
use codex_app_server_protocol::ImageReference;
@@ -114,7 +115,7 @@ async fn replayed_failed_turns_preserve_overload_warnings_between_retries() {
ReplayKind::ResumeInitialMessages,
);
let rendered = drain_insert_history(&mut rx)
let rendered = drain_insert_history_transcript(&mut rx)
.into_iter()
.map(|lines| lines_to_single_string(&lines))
.collect::<String>();
@@ -164,16 +164,16 @@ async fn mcp_startup_updates_preserve_streaming_status_suppression() {
}
#[tokio::test]
async fn mcp_startup_summary_distinguishes_initial_resume_from_task_switch() {
async fn mcp_startup_warning_identity_survives_resume_and_task_switch() {
use AppServerTurnStatus::Completed;
use AppServerTurnStatus::InProgress;
use ReplayKind::ResumeInitialMessages;
use ReplayKind::ThreadSnapshot;
for (replay_kind, status, compact) in [
(ResumeInitialMessages, Completed, true),
(ResumeInitialMessages, InProgress, false),
(ThreadSnapshot, Completed, false),
for (replay_kind, status) in [
(ResumeInitialMessages, Completed),
(ResumeInitialMessages, InProgress),
(ThreadSnapshot, Completed),
] {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
chat.replay_thread_turns(
@@ -194,7 +194,7 @@ async fn mcp_startup_summary_distinguishes_initial_resume_from_task_switch() {
compact_cells.push(cell.as_any().is::<history_cell::StartupWarningsCell>());
}
}
assert_eq!(compact_cells, vec![compact; 2]);
assert_eq!(compact_cells, vec![true; 2]);
}
}
@@ -610,7 +610,7 @@ async fn mcp_startup_failure_restores_running_status_header() {
"MCP client for `alpha` failed to start: handshake failed",
);
notify_mcp_status(&mut chat, "beta", McpServerStartupState::Ready);
let warnings = super::helpers::drain_insert_history(&mut rx);
let warnings = drain_insert_history(&mut rx);
insta::assert_snapshot!(
"runtime_mcp_warning",
warnings
@@ -3813,7 +3813,7 @@ async fn select_ultra_with_multi_agent_thread_limit(max_threads: usize) -> (bool
selected_ultra = true;
}
AppEvent::InsertHistoryCell(cell) => {
warnings.push(lines_to_single_string(&cell.display_lines(/*width*/ 80)));
warnings.push(lines_to_single_string(&cell.transcript_lines(/*width*/ 80)));
}
_ => {}
}
@@ -1,3 +1,4 @@
use super::helpers::drain_insert_history_transcript;
use super::*;
use codex_app_server_protocol::ImageReference;
use pretty_assertions::assert_eq;
@@ -292,7 +293,7 @@ async fn esc_with_review_queued_steers_shows_warning_and_does_not_interrupt() {
chat.thread_id = Some(ThreadId::new());
handle_turn_started(&mut chat, "turn-1");
handle_entered_review_mode(&mut chat, "feature branch");
let _ = drain_insert_history(&mut rx);
let _ = drain_insert_history_transcript(&mut rx);
chat.input_queue
.pending_steers
.push_back(pending_steer("review follow-up"));
@@ -304,7 +305,7 @@ async fn esc_with_review_queued_steers_shows_warning_and_does_not_interrupt() {
assert_eq!(chat.input_queue.pending_steers.len(), 1);
assert_no_submit_op(&mut op_rx);
let cells = drain_insert_history(&mut rx);
let cells = drain_insert_history_transcript(&mut rx);
let last = lines_to_single_string(cells.last().expect("review warning"));
assert_chatwidget_snapshot!("review_submission_warning_snapshot", last);
}
@@ -1,3 +1,4 @@
use super::helpers::drain_insert_history_transcript;
use super::*;
use crate::bottom_pane::slash_commands::ServiceTierCommand;
use pretty_assertions::assert_eq;
@@ -2977,14 +2978,20 @@ async fn slash_pet_hide_disables_pets_even_on_unsupported_terminal() {
#[tokio::test]
#[serial]
async fn slash_pets_on_unsupported_terminal_warns_without_picker() {
async fn slash_pets_in_tmux_shows_notice_and_preserves_draft() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
force_tmux_pet_image_unsupported(&mut chat);
chat.bottom_pane
.set_composer_text("Keep this draft".to_string(), Vec::new(), Vec::new());
chat.dispatch_command(SlashCommand::Pets);
assert!(!chat.bottom_pane.has_active_view());
let cells = drain_insert_history(&mut rx);
assert!(chat.bottom_pane.has_active_view());
assert_chatwidget_snapshot!(
"slash_pets_unavailable_tmux_40",
render_bottom_popup(&chat, /*width*/ 40),
);
let cells = drain_insert_history_transcript(&mut rx);
let rendered = cells
.iter()
.map(|lines| lines_to_single_string(lines))
@@ -2992,11 +2999,15 @@ async fn slash_pets_on_unsupported_terminal_warns_without_picker() {
.join("\n");
assert!(rendered.contains("Pets are disabled in tmux."));
assert!(rendered.contains("outside tmux"));
chat.handle_key_event(KeyEvent::from(KeyCode::Esc));
assert!(!chat.bottom_pane.has_active_view());
assert_eq!(chat.bottom_pane.composer_text(), "Keep this draft");
}
#[tokio::test]
#[serial]
async fn slash_pets_with_arg_on_unsupported_terminal_warns_without_selection() {
async fn slash_pets_with_arg_on_unsupported_terminal_shows_notice_without_selection() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
force_tmux_pet_image_unsupported(&mut chat);
@@ -3004,7 +3015,9 @@ async fn slash_pets_with_arg_on_unsupported_terminal_warns_without_selection() {
.set_composer_text("/pets chefito".to_string(), Vec::new(), Vec::new());
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
let cells = drain_insert_history(&mut rx);
assert!(chat.bottom_pane.has_active_view());
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("Pets are disabled in tmux."));
let cells = drain_insert_history_transcript(&mut rx);
let rendered = cells
.iter()
.map(|lines| lines_to_single_string(lines))
@@ -3013,6 +3026,11 @@ async fn slash_pets_with_arg_on_unsupported_terminal_warns_without_selection() {
assert!(rendered.contains("Pets are disabled in tmux."));
assert_matches!(rx.try_recv(), Err(TryRecvError::Empty));
assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty));
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert!(!chat.bottom_pane.has_active_view());
assert_matches!(rx.try_recv(), Err(TryRecvError::Empty));
assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty));
}
#[tokio::test]
@@ -3023,8 +3041,12 @@ async fn slash_pets_on_unsupported_terminal_shows_terminal_warning() {
chat.dispatch_command(SlashCommand::Pets);
assert!(!chat.bottom_pane.has_active_view());
let cells = drain_insert_history(&mut rx);
assert!(chat.bottom_pane.has_active_view());
assert!(
render_bottom_popup(&chat, /*width*/ 80)
.contains("Pets aren’t available in this terminal.")
);
let cells = drain_insert_history_transcript(&mut rx);
let rendered = cells
.iter()
.map(|lines| lines_to_single_string(lines))
@@ -3042,8 +3064,9 @@ async fn slash_pets_on_old_iterm2_shows_upgrade_warning() {
chat.dispatch_command(SlashCommand::Pets);
assert!(!chat.bottom_pane.has_active_view());
let cells = drain_insert_history(&mut rx);
assert!(chat.bottom_pane.has_active_view());
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("Pets require iTerm2 3.6 or newer."));
let cells = drain_insert_history_transcript(&mut rx);
let rendered = cells
.iter()
.map(|lines| lines_to_single_string(lines))
@@ -3643,6 +3666,9 @@ async fn transcript_copy_feedback_stays_in_the_footer_without_history_or_interru
"transcript_copy_unconfirmed_narrow",
render_bottom_popup(&chat, /*width*/ 40)
);
chat.open_warnings(&[Arc::new(history_cell::new_warning_event(
"selected café".into(),
))]);
let result = chat.copy_transcript_selection_with("selected café", |_text| {
Err("clipboard unavailable".to_string())
});
@@ -6,10 +6,10 @@ expression: rendered
› The workspace also looks super confusing with its separator.
⚠ Selected model is at capacity. Please try a different model.
■ Selected model is at capacity. Please try a different model.
› The workspace also looks super confusing with its separator.
⚠ Selected model is at capacity. Please try a different model.
■ Selected model is at capacity. Please try a different model.
@@ -1,7 +1,17 @@
---
source: tui/src/chatwidget/tests/slash_commands.rs
assertion_line: 3677
expression: "render_bottom_popup(&chat, 80)"
---
› Ask Codex to do anything
Warnings · 1 of 1 · Warning
selected café
Copy failed: clipboard unavailable
@@ -1,3 +1,4 @@
use super::helpers::drain_insert_history_transcript;
use super::*;
use crate::bottom_pane::goal_status_indicator_line;
use crate::chatwidget::ThreadUsageOutcome;
@@ -146,7 +147,7 @@ async fn app_server_model_verification_renders_warning() {
vec![AppServerModelVerification::TrustedAccessForCyber],
);
let cells = drain_insert_history(&mut rx);
let cells = drain_insert_history_transcript(&mut rx);
assert_eq!(cells.len(), 1);
let rendered = lines_to_single_string(&cells[0]);
assert!(rendered.contains("multiple flags for possible cybersecurity risk"));
@@ -609,13 +610,13 @@ async fn rate_limit_usage_warnings_early_threshold_is_scoped_and_deduplicated()
usage.plan_type = plan_type;
usage.primary.as_mut().unwrap().window_duration_mins = window_minutes;
chat.on_rate_limit_snapshot(Some(usage.clone()));
assert!(drain_insert_history(&mut rx).is_empty());
assert!(drain_insert_history_transcript(&mut rx).is_empty());
// Rolling updates retain the plan learned from the account usage response.
usage.plan_type = None;
usage.primary.as_mut().unwrap().used_percent = 50;
chat.on_rolling_rate_limit_snapshot(usage.clone());
let warnings = drain_insert_history(&mut rx);
let warnings = drain_insert_history_transcript(&mut rx);
assert_eq!(!warnings.is_empty(), should_warn_early);
if should_warn_early {
insta::allow_duplicates! {
@@ -627,13 +628,13 @@ async fn rate_limit_usage_warnings_early_threshold_is_scoped_and_deduplicated()
}
chat.on_rolling_rate_limit_snapshot(usage.clone());
assert!(drain_insert_history(&mut rx).is_empty());
assert!(drain_insert_history_transcript(&mut rx).is_empty());
for used_percent in [75, 90, 95] {
usage.primary.as_mut().unwrap().used_percent = used_percent;
chat.on_rolling_rate_limit_snapshot(usage.clone());
assert_eq!(drain_insert_history(&mut rx).len(), 1);
assert_eq!(drain_insert_history_transcript(&mut rx).len(), 1);
chat.on_rolling_rate_limit_snapshot(usage.clone());
assert!(drain_insert_history(&mut rx).is_empty());
assert!(drain_insert_history_transcript(&mut rx).is_empty());
}
}
}
+1 -1
View File
@@ -363,7 +363,7 @@ impl ChatWidget {
message
};
self.add_to_history(history_cell::new_warning_event(message));
self.add_to_history(history_cell::new_error_event(message));
self.request_redraw();
self.maybe_send_next_queued_input();
}
+46
View File
@@ -1,4 +1,9 @@
//! Deduplicate incoming diagnostics and project them into the warning footer and viewer.
use crate::history_cell::HistoryCell;
use crate::tui::TuiEvent;
use std::collections::HashSet;
use std::sync::Arc;
const FALLBACK_MODEL_METADATA_WARNING_PREFIX: &str = "Model metadata for `";
const FALLBACK_MODEL_METADATA_WARNING_SUFFIX: &str =
@@ -6,6 +11,7 @@ const FALLBACK_MODEL_METADATA_WARNING_SUFFIX: &str =
#[derive(Default)]
pub(super) struct WarningDisplayState {
pub(super) count: usize,
/// Completed resume history does not end startup; active work does.
pub(super) startup_complete: bool,
/// Initialization config warnings may also arrive as ordinary thread warnings.
@@ -26,3 +32,43 @@ fn fallback_model_metadata_warning_slug(message: &str) -> Option<&str> {
.strip_prefix(FALLBACK_MODEL_METADATA_WARNING_PREFIX)?
.strip_suffix(FALLBACK_MODEL_METADATA_WARNING_SUFFIX)
}
impl super::ChatWidget {
pub(crate) fn open_warnings(&mut self, cells: &[Arc<dyn HistoryCell>]) {
self.bottom_pane
.show_warnings(crate::history_cell::warning_entries(cells));
}
pub(crate) fn sync_warnings(&mut self, cells: &[Arc<dyn HistoryCell>]) {
self.warning_display_state.count = crate::history_cell::warning_count(cells);
}
pub(crate) fn handle_warning_event(
&mut self,
event: &TuiEvent,
cells: &[Arc<dyn HistoryCell>],
) -> bool {
if let TuiEvent::Key(key) = event
&& self.bottom_pane.warnings_active()
&& matches!(
key.kind,
crossterm::event::KeyEventKind::Press | crossterm::event::KeyEventKind::Repeat
)
{
// Chord routing may consume this key before it reaches the warning panel.
self.bottom_pane
.record_composer_activity_at(std::time::Instant::now());
}
if let TuiEvent::Mouse(mouse) = event
&& mouse.kind
== crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left)
&& self
.bottom_pane
.warning_notice_contains(ratatui::layout::Position::new(mouse.column, mouse.row))
{
self.open_warnings(cells);
return true;
}
false
}
}
-10
View File
@@ -145,15 +145,7 @@ pub(crate) use warnings::WarningEntry;
pub(crate) use warnings::WarningHistoryCell;
pub(crate) use warnings::WarningId;
pub(crate) use warnings::WarningKey;
#[allow(
unused_imports,
reason = "Used by later layers of the TUI refresh stack."
)]
pub(crate) use warnings::warning_count;
#[allow(
unused_imports,
reason = "Used by later layers of the TUI refresh stack."
)]
pub(crate) use warnings::warning_entries;
#[cfg(test)]
@@ -212,13 +204,11 @@ pub(crate) trait HistoryCell: std::fmt::Debug + Send + Sync + Any {
}
/// Diagnostics exposed by the warnings picker, retaining their source and full text.
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
fn warning_entries(&self) -> Vec<WarningEntry> {
Vec::new()
}
/// Stable diagnostic identities, independent of rendered wrapping and duplicate delivery.
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
fn warning_keys(&self) -> Vec<WarningKey<'_>> {
Vec::new()
}
+3 -3
View File
@@ -269,11 +269,11 @@ impl HistoryCell for DeprecationNoticeCell {
}
fn live_raw_lines(&self) -> Vec<Line<'static>> {
self.raw_lines()
Vec::new()
}
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
self.transcript_lines(width)
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
Vec::new()
}
fn warning_keys(&self) -> Vec<WarningKey<'_>> {
@@ -1,8 +1,9 @@
//! Compact startup diagnostics with full details retained in the transcript.
//! Startup diagnostics retained in the transcript and counted in the warning footer.
//! Affected sources are unique; sign-in servers are a subset of MCP servers.
use super::*;
use codex_app_server_protocol::McpServerStartupFailureReason;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
#[derive(Clone, Debug, Default)]
@@ -10,9 +11,10 @@ pub(crate) struct StartupWarningsCell {
pub(crate) messages: Vec<String>,
pub(crate) other_sources: BTreeSet<String>,
pub(crate) mcp_servers: BTreeSet<String>,
pub(crate) mcp_details: BTreeMap<String, Vec<String>>,
pub(crate) sign_in_servers: BTreeSet<String>,
/// Whether diagnostics arrived before a session was attached.
pub(crate) pending_header: bool,
pub(crate) transcript_hint: Option<String>,
}
impl StartupWarningsCell {
@@ -35,6 +37,10 @@ impl StartupWarningsCell {
None => BTreeSet::new(),
};
Self {
mcp_details: mcp_servers
.iter()
.map(|server| (server.clone(), messages.clone()))
.collect(),
messages,
mcp_servers,
sign_in_servers,
@@ -44,37 +50,49 @@ impl StartupWarningsCell {
}
impl HistoryCell for StartupWarningsCell {
#[allow(clippy::disallowed_methods)]
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
if self.pending_header || self.messages.is_empty() || width == 0 {
return Vec::new();
}
let mcp_count = self.mcp_servers.len();
let count = mcp_count + self.other_sources.len();
let sign_in_count = self.sign_in_servers.len();
let plural = if count == 1 { "" } else { "s" };
let source = if mcp_count == count { "MCP " } else { "" };
let mut summary = format!("⚠ {count} {source}startup issue{plural}");
let mut breakdown = Vec::new();
if mcp_count > 0 && mcp_count < count {
breakdown.push(format!("{mcp_count} MCP"));
}
if sign_in_count > 0 {
let verb = if sign_in_count == 1 { "needs" } else { "need" };
breakdown.push(format!("{sign_in_count} {verb} sign-in"));
}
if !breakdown.is_empty() {
summary.push_str(&format!(" ({})", breakdown.join("; ")));
}
if let Some(hint) = &self.transcript_hint {
summary.push_str(&format!(" · {hint} for details"));
}
vec![
crate::line_truncation::truncate_line_with_ellipsis_if_overflow(
Line::from(summary.yellow().dim()),
width as usize,
),
]
fn warning_entries(&self) -> Vec<WarningEntry> {
self.other_sources
.iter()
.map(|message| WarningEntry {
id: WarningId::Message(message.clone()),
source: "Startup".into(),
details: message.clone(),
})
.chain(self.mcp_servers.iter().map(|server| WarningEntry {
id: WarningId::McpServer(server.clone()),
source: format!("MCP · {server}"),
details: {
let mut details = self.mcp_details.get(server).map_or_else(
|| format!("MCP startup incomplete: {server}"),
|messages| messages.join("\n\n"),
);
if self.sign_in_servers.contains(server) {
details.push_str("\n\nSign-in required.");
}
details
},
}))
.collect()
}
fn live_raw_lines(&self) -> Vec<Line<'static>> {
Vec::new()
}
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
Vec::new()
}
fn warning_keys(&self) -> Vec<WarningKey<'_>> {
self.other_sources
.iter()
.map(|message| WarningKey::Message(message))
.chain(
self.mcp_servers
.iter()
.map(|server| WarningKey::McpServer(server)),
)
.collect()
}
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
+2 -2
View File
@@ -2950,8 +2950,8 @@ fn deprecation_notice_renders_summary_with_details() {
Some("Use flag `bar` instead.".to_string()),
);
let lines = cell.transcript_lines(/*width*/ 80);
assert_eq!(cell.display_lines(/*width*/ 80), lines);
assert_eq!(cell.live_raw_lines(), cell.raw_lines());
assert!(cell.display_lines(/*width*/ 80).is_empty());
assert!(cell.live_raw_lines().is_empty());
let rendered = render_lines(&lines);
assert_eq!(
rendered,
+13 -12
View File
@@ -1,12 +1,12 @@
//! Render inline warnings and retain diagnostic identities for the later warning footer.
//! Retain warning details for the transcript while exposing stable identities to the footer.
//! Message identities deduplicate replay; MCP identities count affected servers, not summary rows.
use super::*;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::sync::Arc;
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(crate) enum WarningId {
Message(String),
McpServer(String),
@@ -14,23 +14,24 @@ pub(crate) enum WarningId {
/// A retained diagnostic. Identity is independent of wrapping and duplicate delivery.
#[derive(Clone, Debug, Eq, PartialEq)]
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(crate) struct WarningEntry {
pub(crate) id: WarningId,
pub(crate) source: String,
pub(crate) details: String,
}
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(crate) fn warning_entries(cells: &[Arc<dyn HistoryCell>]) -> Vec<WarningEntry> {
let mut entries: Vec<WarningEntry> = Vec::new();
let mut indices = BTreeMap::new();
for entry in cells.iter().flat_map(|cell| cell.warning_entries()) {
if let Some(existing) = entries.iter_mut().find(|existing| existing.id == entry.id) {
if let Some(&index) = indices.get(&entry.id) {
let existing: &mut WarningEntry = &mut entries[index];
if !existing.details.contains(&entry.details) {
existing.details.push_str("\n\n");
existing.details.push_str(&entry.details);
}
} else {
indices.insert(entry.id.clone(), entries.len());
entries.push(entry);
}
}
@@ -38,7 +39,6 @@ pub(crate) fn warning_entries(cells: &[Arc<dyn HistoryCell>]) -> Vec<WarningEntr
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(crate) enum WarningKey<'a> {
Message(&'a str),
McpServer(&'a str),
@@ -46,20 +46,18 @@ pub(crate) enum WarningKey<'a> {
#[derive(Debug)]
pub(crate) struct WarningHistoryCell {
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(super) key: String,
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(super) diagnostic: String,
pub(super) details: PrefixedWrappedHistoryCell,
}
impl HistoryCell for WarningHistoryCell {
fn live_raw_lines(&self) -> Vec<Line<'static>> {
self.details.raw_lines()
Vec::new()
}
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
self.details.display_lines(width)
fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
Vec::new()
}
fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
@@ -83,7 +81,6 @@ impl HistoryCell for WarningHistoryCell {
}
}
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(crate) fn warning_count(cells: &[Arc<dyn HistoryCell>]) -> usize {
cells
.iter()
@@ -91,3 +88,7 @@ pub(crate) fn warning_count(cells: &[Arc<dyn HistoryCell>]) -> usize {
.collect::<BTreeSet<_>>()
.len()
}
#[cfg(test)]
#[path = "warnings_tests.rs"]
mod tests;
@@ -0,0 +1,60 @@
//! Warning identities survive replay and preserve complete transcript details.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn warning_count_deduplicates_messages_mcp_summaries_and_composites() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![
Arc::new(new_warning_event("Repeated warning".into())),
Arc::new(StartupWarningsCell::new(vec!["Repeated warning".into()])),
Arc::new(StartupWarningsCell::mcp(
vec!["MCP alpha failed".into()],
["alpha".into()],
/*failure_reason*/ None,
)),
Arc::new(StartupWarningsCell::mcp(
vec!["MCP startup incomplete".into()],
["alpha".into()],
/*failure_reason*/ None,
)),
Arc::new(CompositeHistoryCell::new(vec![Box::new(
new_warning_event("Another warning".into()),
)])),
];
assert_eq!(warning_count(&cells), 3);
assert_eq!(
warning_entries(&cells),
vec![
WarningEntry {
id: WarningId::Message("Repeated warning".into()),
source: "Warning".into(),
details: "Repeated warning".into()
},
WarningEntry {
id: WarningId::McpServer("alpha".into()),
source: "MCP · alpha".into(),
details: "MCP alpha failed\n\nMCP startup incomplete".into()
},
WarningEntry {
id: WarningId::Message("Another warning".into()),
source: "Warning".into(),
details: "Another warning".into()
},
]
);
let replay = [cells.clone(), cells.clone()].concat();
assert_eq!(warning_count(&replay), 3);
assert_eq!(warning_entries(&replay), warning_entries(&cells));
assert_eq!(warning_count(&[]), 0);
assert!(
cells
.iter()
.all(|cell| cell.compact_hyperlink_lines(/*width*/ 40).is_empty())
);
assert!(cells.iter().all(|cell| {
cell.display_lines_for_mode(/*width*/ 40, HistoryRenderMode::Raw)
.is_empty()
}));
assert!(cells.iter().all(|cell| !cell.raw_lines().is_empty()));
}
+20
View File
@@ -99,6 +99,8 @@ pub(crate) struct AppKeymap {
pub(crate) find_transcript: Vec<KeyBinding>,
/// Focus activity groups in the owned transcript to inspect their details.
pub(crate) focus_activity: Vec<KeyBinding>,
/// Open retained warnings without replacing the composer.
pub(crate) open_warnings: Vec<KeyBinding>,
/// Open external editor for the current draft.
pub(crate) open_external_editor: Vec<KeyBinding>,
/// Copy the last agent response to the clipboard.
@@ -661,6 +663,19 @@ impl RuntimeKeymap {
})
})
.collect();
// New defaults must not invalidate an existing custom binding or chord prefix.
let open_warnings_defaults: Vec<_> = defaults
.app
.open_warnings
.iter()
.copied()
.filter(|binding| {
!configured_context_binding_is_used(keymap, *binding)
&& !chords.bindings.iter().any(|chord| {
chord.chord.prefix.normalized_parts() == binding.normalized_parts()
})
})
.collect();
let app = AppKeymap {
open_agents: resolve_bindings(
@@ -683,6 +698,7 @@ impl RuntimeKeymap {
&focus_activity_defaults,
"tui.keymap.global.focus_activity",
)?,
open_warnings: open_warnings_defaults,
open_external_editor: resolve_bindings(
keymap.global.open_external_editor.as_ref(),
&defaults.app.open_external_editor,
@@ -1625,6 +1641,7 @@ impl RuntimeKeymap {
open_transcript: default_bindings![ctrl(KeyCode::Char('t'))],
find_transcript: default_bindings![plain(KeyCode::F(3))],
focus_activity: default_bindings![plain(KeyCode::F(4))],
open_warnings: default_bindings![plain(KeyCode::F(2))],
open_external_editor: default_bindings![ctrl(KeyCode::Char('g'))],
copy: default_bindings![ctrl(KeyCode::Char('o'))],
clear_terminal: default_bindings![ctrl(KeyCode::Char('l'))],
@@ -1984,6 +2001,7 @@ impl RuntimeKeymap {
("open_transcript", self.app.open_transcript.as_slice()),
("find_transcript", self.app.find_transcript.as_slice()),
("focus_activity", self.app.focus_activity.as_slice()),
("open_warnings", self.app.open_warnings.as_slice()),
(
"open_external_editor",
self.app.open_external_editor.as_slice(),
@@ -2089,6 +2107,7 @@ impl RuntimeKeymap {
("open_transcript", self.app.open_transcript.as_slice()),
("find_transcript", self.app.find_transcript.as_slice()),
("focus_activity", self.app.focus_activity.as_slice()),
("open_warnings", self.app.open_warnings.as_slice()),
(
"open_external_editor",
self.app.open_external_editor.as_slice(),
@@ -2147,6 +2166,7 @@ impl RuntimeKeymap {
("open_transcript", self.app.open_transcript.as_slice()),
("find_transcript", self.app.find_transcript.as_slice()),
("focus_activity", self.app.focus_activity.as_slice()),
("open_warnings", self.app.open_warnings.as_slice()),
(
"open_external_editor",
self.app.open_external_editor.as_slice(),
+12 -2
View File
@@ -134,8 +134,17 @@ macro_rules! runtime_group_mut {
};
}
macro_rules! configured_binding_slot {
($keymap:ident, $group:ident, $action:ident, runtime_only) => {
None
};
($keymap:ident, $group:ident, $action:ident) => {
Some(&$keymap.$group.$action)
};
}
macro_rules! define_runtime_action_bindings {
($($context:literal => $context_id:ident, $group:ident, $config_group:ident [$($action:ident),+ $(,)?]),+ $(,)?) => {
($($context:literal => $context_id:ident, $group:ident, $config_group:ident [$($action:ident $(=> $runtime_only:ident)?),+ $(,)?]),+ $(,)?) => {
/// Resolve a config context/action pair to its runtime identity.
pub(crate) fn keymap_action_id(
context: &str,
@@ -172,7 +181,7 @@ macro_rules! define_runtime_action_bindings {
$(
$(
($context, stringify!($action)) => {
Some(&keymap.$config_group.$action)
configured_binding_slot!(keymap, $config_group, $action $(, $runtime_only)?)
}
)+
)+
@@ -264,6 +273,7 @@ define_runtime_action_bindings! {
open_transcript,
find_transcript,
focus_activity,
open_warnings => runtime_only,
open_external_editor,
copy,
clear_terminal,
+51 -15
View File
@@ -43,6 +43,7 @@ pub(crate) struct KeymapContextSet(u32);
const ACTIVITY_FOCUS: u32 = 1 << 13;
const TRANSCRIPT_CLOSE: u32 = 1 << 15;
const WARNINGS_FOCUS: u32 = 1 << 16;
const TRANSCRIPT_BROWSING: u32 = 1 << 14;
@@ -72,6 +73,15 @@ impl KeymapContextSet {
)
}
/// Warning pages admit navigation plus their own toggle and copy.
pub(crate) const fn warnings() -> Self {
Self(context_bit(KeymapContext::List) | context_bit(KeymapContext::Global) | WARNINGS_FOCUS)
}
pub(crate) const fn is_warnings(self) -> bool {
self.0 & WARNINGS_FOCUS != 0
}
/// Whether this input path can dispatch the action, including focus-specific exclusions.
pub(crate) fn contains_action(self, action: KeymapActionId) -> bool {
self.contains(action.context)
@@ -84,6 +94,12 @@ impl KeymapContextSet {
&& (self.0 & TRANSCRIPT_BROWSING == 0
|| action.context != KeymapContext::Global
|| action.action == "open_transcript")
&& (!self.is_warnings()
|| action.context != KeymapContext::List
|| action.action != "accept")
&& (!self.is_warnings()
|| action.context != KeymapContext::Global
|| matches!(action.action, "open_warnings" | "copy"))
}
pub(crate) const fn with(self, context: KeymapContext) -> Self {
@@ -212,6 +228,30 @@ or a two-stroke chord such as `ctrl-x ctrl-t`.",
Ok(keymap_chords)
}
fn binding_for_completion(
&self,
prefix: KeyBinding,
event: KeyEvent,
contexts: KeymapContextSet,
) -> Option<&RuntimeChordBinding> {
self.bindings
.iter()
.filter(|binding| {
contexts.contains_action(binding.action)
&& binding.chord.prefix == prefix
&& chord_stroke_matches(binding.chord.completion, event)
})
.min_by_key(|binding| {
(
!(contexts.0 & TRANSCRIPT_CLOSE != 0
&& binding.action.context == KeymapContext::Pager
&& binding.action.action == "close_transcript"),
contexts.is_warnings() && binding.action.context != KeymapContext::List,
contexts.is_warnings() && binding.action.context == KeymapContext::Global,
)
})
}
pub(crate) fn configured_specs(&self, action: KeymapActionId) -> Option<&[String]> {
self.configured_specs
.iter()
@@ -294,14 +334,21 @@ impl KeyChordMatcher {
.bindings
.iter()
.filter(|binding| {
binding.chord.prefix == pending.prefix
&& pending.contexts.contains_action(binding.action)
let (code, modifiers) = binding.chord.completion.parts();
keymap
.binding_for_completion(
pending.prefix,
KeyEvent::new(code, modifiers),
pending.contexts,
)
.is_some_and(|active| std::ptr::eq(active, *binding))
})
.take(/*n*/ 6)
{
let label = match binding.action.action {
"focus_activity" => "activity",
"find_transcript" => "find",
"open_warnings" => "warnings",
action => action,
};
items.push((
@@ -371,19 +418,8 @@ impl KeyChordMatcher {
if crate::key_hint::plain(KeyCode::Esc).is_press(key_event) {
return KeyChordMatch::Cancelled;
}
if let Some(binding) = keymap
.bindings
.iter()
.filter(|binding| {
contexts.contains_action(binding.action)
&& binding.chord.prefix == pending.prefix
&& chord_stroke_matches(binding.chord.completion, key_event)
})
.min_by_key(|binding| {
!(contexts.0 & TRANSCRIPT_CLOSE != 0
&& binding.action.context == KeymapContext::Pager
&& binding.action.action == "close_transcript")
})
if let Some(binding) =
keymap.binding_for_completion(pending.prefix, key_event, contexts)
{
let Some(dispatch_event) = dispatch_event(binding.action) else {
return KeyChordMatch::Ignored;
+29
View File
@@ -595,3 +595,32 @@ fn pending_hint_skips_whole_oversized_configured_completions() {
]
);
}
#[test]
fn warning_context_keeps_local_chords_ahead_of_copy_and_hides_unreachable_hints() {
let config = serde_json::from_value(serde_json::json!({
"global":{"copy":"ctrl-x c", "open_agents":"ctrl-x a"},
"list":{"jump_bottom":"ctrl-x c"}
}))
.unwrap();
let runtime = RuntimeKeymap::from_config(&config).unwrap();
let mut matcher = KeyChordMatcher::default();
let contexts = KeymapContextSet::warnings();
let prefix = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL);
matcher.advance(prefix, &runtime.chords, contexts);
assert_eq!(
matcher.pending_hint_items(&runtime.chords, /*width*/ 80),
Some(vec![
("ctrl+x".into(), "then".into()),
("c".into(), "jump bottom".into()),
("esc".into(), "cancel".into()),
])
);
let KeyChordMatch::Completed(event) =
matcher.advance(KeyCode::Char('c').into(), &runtime.chords, contexts)
else {
panic!("list action")
};
assert!(runtime.list.jump_bottom.is_pressed(event));
assert!(!runtime.app.copy.is_pressed(event));
}
+10 -15
View File
@@ -115,6 +115,11 @@ fn explicit_activity_remapping_and_unbinding_replace_all_defaults() {
vec![key_hint::plain(KeyCode::F(12))],
Some("f12"),
),
(
json!("page-up"),
vec![key_hint::plain(KeyCode::PageUp)],
Some("pgup"),
),
(json!([]), Vec::new(), None),
(json!("ctrl-x t"), Vec::new(), Some("ctrl+x t")),
] {
@@ -132,23 +137,13 @@ fn explicit_activity_remapping_and_unbinding_replace_all_defaults() {
}
#[test]
fn explicit_activity_bindings_cannot_shadow_list_navigation() {
for (focus, movement) in [
("f12", "f12"),
("f12 t", "f12"),
("f12", "f12 t"),
("f12 t", "f12 t"),
] {
fn warnings_defaults_preserve_custom_keys_and_chord_prefixes() {
for binding in ["f2", "f2 f12"] {
let keymap: TuiKeymap = serde_json::from_value(json!({
"global": {"focus_activity": focus},
"list": {"move_up": movement},
"editor": {"move_left": binding}
}))
.unwrap();
let error = RuntimeKeymap::from_config(&keymap)
.expect_err("activity focus shares list navigation while inspecting groups");
assert!(
error.contains("focus_activity") && error.contains("move_up"),
"{error}"
);
let runtime = RuntimeKeymap::from_config(&keymap).expect("existing binding remains valid");
assert!(runtime.app.open_warnings.is_empty());
}
}
+2
View File
@@ -87,6 +87,8 @@ pub(super) const KEYMAP_ACTIONS: &[KeymapActionDescriptor] = &[
action("global", "Global", "open_agents", "Open the shared agent-session overview."),
action("global", "Global", "open_transcript", "Open the transcript overlay."),
action("global", "Global", "find_transcript", "Find text in the full transcript."),
// Keep the new warnings action out of shared-config writes until older strict readers
// accept it. Its built-in shortcuts remain available.
action("global", "Global", "focus_activity", "Focus transcript activity groups to expand or collapse their details."),
action("global", "Global", "open_external_editor", "Open the current draft in an external editor."),
action("global", "Global", "copy", "Copy the last agent response to the clipboard."),
+5
View File
@@ -51,6 +51,7 @@ pub enum SlashCommand {
Mention,
Status,
Daemon,
Warnings,
Cd,
#[strum(to_string = "pwd", serialize = "cwd")]
Pwd,
@@ -111,6 +112,7 @@ impl SlashCommand {
SlashCommand::Import => "import setup, this project, and recent chats from Claude Code",
SlashCommand::Hooks => "view and manage lifecycle hooks",
SlashCommand::Daemon => "Manage the local background server.",
SlashCommand::Warnings => "view retained warnings and diagnostic details",
SlashCommand::Status => "show current session configuration and token usage",
SlashCommand::Cd => "change the current working directory",
SlashCommand::Pwd => "show the current working directory",
@@ -197,6 +199,7 @@ impl SlashCommand {
| SlashCommand::Mention
| SlashCommand::Status
| SlashCommand::Daemon
| SlashCommand::Warnings
| SlashCommand::Pwd
| SlashCommand::Usage
| SlashCommand::Ide
@@ -221,6 +224,7 @@ impl SlashCommand {
| SlashCommand::Quit
| SlashCommand::Exit
| SlashCommand::Status
| SlashCommand::Warnings
| SlashCommand::DebugConfig
| SlashCommand::Pwd
| SlashCommand::Rollout
@@ -266,6 +270,7 @@ impl SlashCommand {
| SlashCommand::Hooks
| SlashCommand::Status
| SlashCommand::Daemon
| SlashCommand::Warnings
| SlashCommand::Pwd
| SlashCommand::Usage
| SlashCommand::DebugConfig
-2
View File
@@ -186,12 +186,10 @@ fn user_message_accent_color_for(
}
/// Muted amber keeps the passive warning count visible without looking like an error.
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(crate) fn warning_notice_style() -> Style {
warning_notice_style_for(default_bg(), effective_stdout_color_level())
}
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
fn warning_notice_style_for(background: Option<(u8, u8, u8)>, level: StdoutColorLevel) -> Style {
let preferred = if background.is_some_and(is_light) {
(139, 98, 20)
@@ -66,7 +66,7 @@ async fn incompatible_daemon_falls_back_for_default_and_explicit_features() -> R
};
let mut terminal = PtyCodex::start(&cwd, home, &args)?;
terminal.wait_for_startup()?;
terminal.wait_for_screen("startup issue")?;
terminal.wait_for_screen("warning")?;
terminal.write_input(b"\x14")?;
let (snapshot, warning_end) = match scenario {
"default" => (