Show TUI shortcut hints for the focused pane (#64024)

## Why

The sidebar can stay visible while the conversation has keyboard focus.
Showing sidebar shortcuts in that state makes keys such as `Esc` look
like they act on the sidebar even when the conversation receives them.

## What changed

Hide keyboard hints in unfocused panes and show the configured shortcut
for focusing the sidebar when it is available. Keep mouse controls
clickable, including the file path view's Back button when its keyboard
binding is disabled. An unmodified left click in the file path body
focuses the sidebar.

Use configured pager bindings for reading and search hints. Watch-only
agent transcripts use single-key pager bindings because they handle
pager keys directly.

## Testing

Add coverage for file path focus and mouse controls, hint placement and
click targets in narrow panes, and pager hints in watch-only transcripts.

GitOrigin-RevId: 3d9375d957789c9f71f6e45f919f815713536622
This commit is contained in:
Felipe Coury
2026-11-26 00:30:45 +00:00
committed by copyberry
parent 2055a99af4
commit dbb9b2e31e
17 changed files with 634 additions and 212 deletions
+1 -1
View File
@@ -260,7 +260,7 @@ impl App {
&& self.sidebar_chooser_available()
}
fn key_chord_contexts(&self, tui: &tui::Tui) -> crate::keymap::KeymapContextSet {
pub(super) fn key_chord_contexts(&self, tui: &tui::Tui) -> crate::keymap::KeymapContextSet {
let contexts = self.active_keymap_contexts();
if !self.conversation_focus_available(tui) {
return contexts;
+72 -35
View File
@@ -16,6 +16,7 @@ use crate::bottom_pane::CommandPopupPlacement;
use crate::bottom_pane::ComposerRenderOptions;
use crate::custom_terminal::Frame;
use crate::empty_state_animation::ComposerState;
use crate::footer_hint::HintFocus;
#[cfg(test)]
use crate::history_cell::HistoryRenderMode;
use crate::keymap::KeymapContext;
@@ -90,6 +91,7 @@ impl ConversationFrame {
}
pub(super) struct PreparedConversation {
hint_focus: HintFocus,
floating_shortcuts: bool,
area: Rect,
transcript_width: u16,
@@ -265,9 +267,8 @@ impl App {
}
let caller_inset = self.conversation_frame.inset;
let parent = self.sidebar_parent();
if !self.conversation_focus_available(tui)
&& let Some(pane) = self.sidebars.get_mut(&parent)
{
let conversation_available = self.conversation_focus_available(tui);
if !conversation_available && let Some(pane) = self.sidebars.get_mut(&parent) {
pane.close = None;
}
if let Some(pane) = self.sidebars.get_mut(&self.sidebar_parent())
@@ -347,6 +348,40 @@ impl App {
});
let mut sidebar_targets = Vec::new();
let sidebar_parent = self.sidebar_parent();
let center_focused = self.workspace_center_owns_input();
let panel = self
.conversation_frame
.panel_area()
.and_then(|_| self.panel_focus());
let blocked = self.pane_resize.is_some()
|| self.key_chord_matcher.is_pending()
|| self.sidebar().is_some_and(|pane| pane.close.is_some());
let conversation_available = conversation_available
&& !blocked
&& !center_focused
&& !self.chat_widget.quick_dial_menu_open();
let mut contexts = None;
let mut focus_hint = |action, label| {
let context = KeymapContext::Global;
let id = crate::keymap::KeymapActionId { context, action };
let binding = self.keymap.primary_hint(context, action).filter(|key| {
!matches!(key, crate::key_hint::ShortcutHint::Chord { .. })
|| contexts
.get_or_insert_with(|| self.key_chord_contexts(tui))
.contains_action(id)
});
binding.map_or(HintFocus::Inactive, |key| HintFocus::Focusable(key, label))
};
let hint_focus = match panel {
Some(PaneFocus::Sidebar) if conversation_available => HintFocus::Active,
Some(PaneFocus::Main) if conversation_available => {
focus_hint("focus_sidebar_content", "focus sidebar")
}
_ => HintFocus::Inactive,
};
if !conversation_available || hint_focus.is_active() {
prepared.hint_focus = HintFocus::Inactive;
}
let sidebar_image_protocol = self.preview_image_protocol(tui);
let sidebar_motion =
MotionMode::from_animations_enabled(self.local_settings.tui.animations);
@@ -433,12 +468,13 @@ impl App {
frames: &frames,
keymap: &self.keymap,
resize_hint,
hint_focus,
resize_preview: self
.divider_drag
.is_some_and(super::side_pane::DividerDrag::is_live_preview),
image_protocol: sidebar_image_protocol,
},
) && focused
) && hint_focus.is_active()
{
frame.cursor_position = Some(cursor);
}
@@ -472,14 +508,16 @@ impl App {
]))
}
CreationState::Failed { message, .. } => {
ratatui::text::Text::from(if resize_hint.is_some() {
message.clone()
} else {
crate::sidebar_chooser::creation_failure_text(
message,
&self.keymap,
)
})
let mut text = ratatui::text::Text::from(message.clone());
let hints = crate::sidebar_chooser::creation_failure_hints(
&self.keymap,
hint_focus,
body.width,
);
if hints.width() > 0 {
text.lines.push(hints);
}
text
}
};
ratatui::widgets::Paragraph::new(text)
@@ -499,16 +537,17 @@ impl App {
let row = crate::sidebar_chooser::body_row(*sidebar, sidebar.y);
crate::sidebar_chooser::resize_hint(hint, row.width)
} else {
let (hints, actions) = crate::sidebar_chooser::footer(
let hints = crate::sidebar_chooser::footer(
&self.keymap,
*sidebar,
pane.choice,
tabs,
new_chat,
hint_focus,
full_path.is_some(),
);
sidebar_targets.extend(
crate::sidebar_chooser::footer_targets(*sidebar, &hints, actions)
crate::sidebar_chooser::footer_targets(*sidebar, &hints)
.map(|(action, area)| (SidebarTarget::Footer(action), area)),
);
hints.line
@@ -738,6 +777,7 @@ impl App {
frames.schedule_frame();
}
PreparedConversation {
hint_focus: HintFocus::Active,
floating_shortcuts: false,
area,
transcript_width,
@@ -961,7 +1001,12 @@ impl App {
let area = prepared.area;
ratatui::widgets::Clear.render(area, frame.buffer);
let back = self.keymap.list.primary_hint(ListAction::Cancel);
let hint_focus = prepared.hint_focus;
let back = self
.keymap
.list
.primary_hint(ListAction::Cancel)
.filter(|_| hint_focus.is_active() && !self.transcript_view.has_active_interaction());
let heading = back.map_or_else(
|| "Watch only".to_owned(),
|hint| format!("{} back to agents · Watch only", hint.display_label()),
@@ -979,33 +1024,25 @@ impl App {
..area
};
let view = &mut self.transcript_view;
let footer = self
.pane_resize
.is_none()
let footer = hint_focus
.is_active()
.then(|| view.footer_with_navigation(body.width, prepared.motion, "end latest"))
.flatten();
let hints = crate::footer_hint::HintLine::new(
[
Some(crate::footer_hint::shortcut("↑/↓", "read")),
self.keymap
.pager
.find
.first()
.map(|key| crate::footer_hint::shortcut(&key.display_label(), "find")),
self.keymap
.primary_hint(KeymapContext::Global, "select_transcript")
.map(|hint| crate::footer_hint::shortcut(&hint.display_label(), "select")),
]
.into_iter()
.flatten(),
body.width,
);
let text = if self.pane_resize.is_some() {
crate::sidebar_chooser::resize_hint(side_pane::RESIZE_HINT, body.width).into()
} else if let Some(footer) = &footer {
footer.text.clone()
} else if !hint_focus.is_active()
&& let Some((query, _)) = view.search_footer(body.width)
{
query.into()
} else {
hints.line.into()
let hints = sidebar_document::footer::reading_hints(
&self.keymap,
sidebar_document::footer::PagerHints::SingleKeys,
/*link*/ None,
);
hint_focus.render_row(hints, body.width).line.into()
};
let footer_height = body.height.saturating_sub(1).min(text.height() as u16);
body.height -= footer_height;
+13
View File
@@ -304,6 +304,19 @@ impl App {
tui.frame_requester().schedule_frame();
if down {
self.sidebar_press = candidate;
if button == MouseButton::Left
&& mouse.modifiers.is_empty()
&& self.chooser_focus() == Some(PaneFocus::Main)
&& self.sidebar().is_some_and(|pane| pane.showing_file_path)
&& frame.sidebar_input == current
&& self.pane_resize.is_none()
&& frame.panel_area().is_some_and(|area| {
sidebar_chooser::file_path_areas(area)[0].contains(point)
})
{
self.sidebar_mut()
.show(SidebarContent::Chooser, PaneFocus::Sidebar);
}
return true;
}
let Some(press) = candidate.filter(|candidate| Some(*candidate) == pressed)
@@ -722,6 +722,35 @@ async fn opens_agent_transcript_beside_parent_and_returns_to_chooser() -> color_
);
assert!(!screen.contains("direct input is disabled"), "{screen}");
let keymap = toml::from_str(
r#"
[pager]
scroll_up = ["f12 u", "up"]
find = ["f12 f", "f3"]
"#,
)?;
app.keymap = crate::keymap::RuntimeKeymap::from_config(&keymap).expect("valid pager bindings");
app.chat_widget.apply_keymap_update(keymap, &app.keymap);
// A short viewport gives the displayed scroll key actual history to move through.
let screen = side_frame(&mut app, &mut tui, Size::new(/*width*/ 180, /*height*/ 8))?;
let footer = screen
.lines()
.last()
.unwrap()
.split_once('│')
.unwrap()
.1
.trim();
insta::assert_snapshot!(footer, @"↑/↓ read · f3 find · ⌃x [ select");
assert!(app.transcript_view.is_following());
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Up.into())))
.await?;
assert!(!app.transcript_view.is_following());
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::End.into())))
.await?;
assert!(app.transcript_view.is_following());
side_frame(&mut app, &mut tui, Size::new(/*width*/ 180, /*height*/ 20))?;
app.keymap.pager.jump_top = vec![crate::key_hint::plain(KeyCode::F(6))];
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::F(6).into())))
.await?;
+11 -10
View File
@@ -52,16 +52,17 @@ impl Confirmation {
Line::from(label).style(style).render(button, buf);
}
if let Some(footer) = body.rows().nth(offset + 2) {
footer_hint::HintLine::new(
[
footer_hint::shortcut("←/→", "choose"),
footer_hint::shortcut("Enter", "confirm"),
footer_hint::shortcut("Esc", "cancel"),
],
footer.width,
)
.line
.render(footer, buf);
footer_hint::HintFocus::Active
.render_row(
[
footer_hint::Hint::key("←/→", "choose"),
footer_hint::Hint::key("Enter", "confirm"),
footer_hint::Hint::key("Esc", "cancel"),
],
footer.width,
)
.line
.render(footer, buf);
}
buttons
}
+67 -37
View File
@@ -1,6 +1,6 @@
//! Read-only Markdown previews use the focused thread's workspace and app-server.
mod footer;
pub(super) mod footer;
pub(super) mod model_read;
mod open_error;
mod path_actions;
@@ -11,6 +11,8 @@ use super::sidebar::PaneFocus;
use super::sidebar::SidebarContent;
use super::*;
use crate::custom_terminal::Frame;
use crate::footer_hint::Hint;
use crate::footer_hint::HintFocus;
use crate::keymap::RuntimeKeymap;
use crate::markdown_render::FileLink;
use crate::markdown_render::SourceLocation;
@@ -102,6 +104,7 @@ pub(super) struct DocumentRenderOptions<'a> {
pub(super) keymap: &'a RuntimeKeymap,
pub(super) resize_preview: bool,
pub(super) resize_hint: Option<&'a str>,
pub(super) hint_focus: HintFocus,
pub(super) image_protocol: Option<ImageProtocol>,
}
@@ -214,6 +217,13 @@ impl Document {
self.path.basename().unwrap_or_default()
}
fn opens_live_on_enter(&self) -> bool {
self.awaits_open()
|| (self.is_model_snapshot()
&& self.link.is_none()
&& !self.owns_interaction_key(KeyCode::Enter.into()))
}
pub(super) fn awaits_open(&self) -> bool {
matches!(self.state, State::AwaitingOpen)
}
@@ -393,6 +403,7 @@ impl Document {
frames,
keymap,
resize_hint,
hint_focus,
resize_preview,
image_protocol,
} = options;
@@ -405,7 +416,8 @@ impl Document {
let line = if let Some(hint) = resize_hint {
crate::sidebar_chooser::resize_hint(hint, footer.width)
} else {
self.path_actions.revealed_footer(footer.width, frames)
self.path_actions
.revealed_footer(footer.width, frames, hint_focus)
};
line.render(footer, buf);
crate::sidebar_chooser::paint_file_path(
@@ -417,33 +429,32 @@ impl Document {
return None;
}
if self.is_model_snapshot() && body.height > 1 {
"Snapshot · Enter to open live"
.dim()
let open = (hint_focus.is_active() && self.opens_live_on_enter())
.then(|| Hint::key("enter", "open live"));
let banner = std::iter::once(Hint::Status("Snapshot".dim().into())).chain(open);
HintFocus::Active
.render_row(banner, body.width)
.line
.render(Rect { height: 1, ..body }, buf);
body.y += 1;
body.height -= 1;
}
let path_actions_available = self.path_actions_available() && body.height > 2;
if !matches!(self.state, State::Ready { .. }) {
let close = || {
Hint::key(
crate::key_hint::plain(KeyCode::Esc).display_label(),
"close",
)
};
let (base, max_rows) = match &self.state {
State::Image(_) => (
vec![
crate::footer_hint::shortcut(
&crate::key_hint::plain(KeyCode::Esc).display_label(),
"close",
),
crate::footer_hint::shortcut("←/→", "tabs"),
],
vec![close(), Hint::key("←/→", "tabs")],
body.height.saturating_sub(1).min(2),
),
State::Failed { error, .. } => {
let count = open_error::lines(&self.path, error, body.width).len();
let close = (count + 2 < usize::from(body.height)).then(|| {
crate::footer_hint::shortcut(
&crate::key_hint::plain(KeyCode::Esc).display_label(),
"close",
)
});
let close = (count + 2 < usize::from(body.height)).then(close);
(
close.into_iter().collect(),
body.height
@@ -466,11 +477,10 @@ impl Document {
usize::from(max_rows),
frames,
[true; 2],
hint_focus,
)
} else if base.is_empty() {
Vec::new()
} else {
vec![crate::footer_hint::HintLine::new(base, body.width).line]
hint_focus.render_lines(base, body.width, usize::from(max_rows.min(1)))
};
footer::paint(&mut body, lines, buf);
}
@@ -488,7 +498,8 @@ impl Document {
.into_iter()
.map(|line| Line::from(line.into_owned()))
.collect::<Vec<_>>();
lines.push("Focus this pane and press Enter to open.".dim().into());
let prompt = hint_focus.render_row([Hint::key("enter", "open")], body.width);
lines.push(prompt.line);
Paragraph::new(lines)
.wrap(ratatui::widgets::Wrap { trim: true })
.render(body, buf);
@@ -529,7 +540,10 @@ impl Document {
if view.advance_search(cells) {
frames.schedule_frame();
}
let footer = view.footer_with_navigation(body.width, motion, "Esc close");
let footer = hint_focus
.is_active()
.then(|| view.footer_with_navigation(body.width, motion, "Esc close"))
.flatten();
let text: ratatui::text::Text<'_> = if let Some(hint) = resize_hint {
crate::sidebar_chooser::resize_hint(hint, body.width).into()
} else if let Some(footer) = &footer
@@ -537,27 +551,46 @@ impl Document {
{
footer.text.clone()
} else {
let hints = footer::reader_hints(
let escape = if self.link.is_some() {
"clear link"
} else if target.is_some() {
"clear highlight"
} else {
"close"
};
let esc = crate::key_hint::plain(KeyCode::Esc).display_label();
let mut hints = vec![Hint::key(esc, escape)];
let available = footer::key_available(keymap);
if self.link.is_some() && available(KeyCode::Enter) {
hints.push(Hint::key("enter", "open link"));
}
let link = available(KeyCode::Tab).then(|| Hint::key("Tab", "link"));
hints.extend(footer::reading_hints(
keymap,
if target.is_some() {
"clear highlight"
} else {
"close"
},
);
footer::PagerHints::WithChords,
link,
));
let max_rows = usize::from(body.height.saturating_sub(1).min(2));
if path_actions_available {
self.path_actions
.footer_lines(
hints,
body.width,
usize::from(body.height.saturating_sub(1).min(2)),
max_rows,
frames,
footer::available_path_keys(keymap),
['c', 'p'].map(|ch| available(KeyCode::Char(ch))),
hint_focus,
)
.into()
} else {
crate::footer_hint::HintLine::new(hints, body.width)
.line
let query = (!hint_focus.is_active())
.then(|| view.search_footer(body.width).map(|(query, _)| query))
.flatten();
let rows = max_rows.saturating_sub(usize::from(query.is_some())).min(1);
query
.into_iter()
.chain(hint_focus.render_lines(hints, body.width, rows))
.collect::<Vec<_>>()
.into()
}
};
@@ -942,10 +975,7 @@ impl App {
}
if crate::key_hint::plain(KeyCode::Enter).is_press(*key)
&& let Some(parent) = parent
&& (doc.awaits_open()
|| (doc.is_model_snapshot()
&& doc.link.is_none()
&& !doc.owns_interaction_key(*key)))
&& doc.opens_live_on_enter()
{
doc.access = DocumentAccess::User;
if doc.awaits_open() {
+42 -25
View File
@@ -1,8 +1,9 @@
//! Builds preview shortcuts and reserves only the footer rows that are actually used.
use crate::footer_hint::shortcut;
use crate::footer_hint::Hint;
use crate::key_hint::KeyBinding;
use crate::key_hint::KeyBindingListExt;
use crate::key_hint::ShortcutHint;
use crate::keymap::KeymapContext;
use crate::keymap::RuntimeKeymap;
use crossterm::event::KeyCode;
@@ -12,35 +13,51 @@ use ratatui::text::Line;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
pub(super) fn reader_hints(keymap: &RuntimeKeymap, close_label: &str) -> Vec<Line<'static>> {
[
Some(shortcut(
&crate::key_hint::plain(KeyCode::Esc).display_label(),
close_label,
)),
Some(shortcut("↑/↓", "read")),
Some(shortcut(
&keymap
.pager
.find
.first()
.map_or_else(|| "F3".to_owned(), KeyBinding::display_label),
"find",
)),
Some(shortcut("Tab", "link")),
keymap
.primary_hint(KeymapContext::Global, "select_transcript")
.map(|hint| shortcut(&hint.display_label(), "select")),
/// Watch-only readers handle pager keys directly without dispatching pager chords.
pub(in crate::app) enum PagerHints {
SingleKeys,
WithChords,
}
pub(in crate::app) fn reading_hints(
keymap: &RuntimeKeymap,
pager_hints: PagerHints,
link: Option<Hint>,
) -> impl Iterator<Item = Hint> {
let pager = &keymap.pager;
let hint = |action, bindings: &[KeyBinding]| match pager_hints {
PagerHints::SingleKeys => {
crate::keymap::primary_binding(bindings).map(ShortcutHint::Single)
}
PagerHints::WithChords => pager.primary_hint(action, bindings),
};
let movement = [
hint("scroll_up", &pager.scroll_up),
hint("scroll_down", &pager.scroll_down),
]
.into_iter()
.flatten()
.map(crate::key_hint::ShortcutHint::display_label)
.collect::<Vec<_>>()
.join("/");
[
(!movement.is_empty()).then(|| Hint::key(movement, "read")),
hint("find", &pager.find)
.or_else(|| keymap.primary_hint(KeymapContext::Global, "find_transcript"))
.map(|hint| Hint::key(hint.display_label(), "find")),
link,
keymap
.primary_hint(KeymapContext::Global, "select_transcript")
.map(|hint| Hint::key(hint.display_label(), "select")),
]
.into_iter()
.flatten()
.collect()
}
pub(super) fn available_path_keys(keymap: &RuntimeKeymap) -> [bool; 2] {
pub(super) fn key_available(keymap: &RuntimeKeymap) -> impl Fn(KeyCode) -> bool + '_ {
let pager = &keymap.pager;
['c', 'p'].map(|ch| {
let key = KeyCode::Char(ch).into();
|code| {
let key = code.into();
![
&pager.jump_top,
&pager.jump_bottom,
@@ -56,7 +73,7 @@ pub(super) fn available_path_keys(keymap: &RuntimeKeymap) -> [bool; 2] {
]
.iter()
.any(|bindings| bindings.is_pressed(key))
})
}
}
pub(super) fn paint(body: &mut Rect, lines: Vec<Line<'_>>, buf: &mut Buffer) {
@@ -3,8 +3,8 @@
use crate::clipboard_copy::CopyFormat;
use crate::clipboard_copy::CopyStatus;
use crate::clipboard_copy::worker::CopyResult;
use crate::footer_hint::HintLine;
use crate::footer_hint::shortcut;
use crate::footer_hint::Hint;
use crate::footer_hint::HintFocus;
use crate::key_hint::plain;
use crate::keymap::ListAction;
use crate::sidebar_chooser;
@@ -118,26 +118,35 @@ impl PathActions {
}
}
pub(super) fn revealed_footer(&mut self, width: u16, frames: &FrameRequester) -> Line<'static> {
pub(super) fn revealed_footer(
&mut self,
width: u16,
frames: &FrameRequester,
focus: HintFocus,
) -> Line<'static> {
let esc = plain(KeyCode::Esc).display_label();
let hints = self.feedback_hint(frames).into_iter().chain([
shortcut(&format!("p/{esc}"), "hide path"),
shortcut("c", "copy path"),
]);
HintLine::new(hints, width).line
let hints = [
Hint::key(format!("p/{esc}"), "hide path"),
Hint::key("c", "copy path"),
];
let feedback = self.feedback_hint(frames).map(Hint::Status);
focus
.render_row(feedback.into_iter().chain(hints), width)
.line
}
pub(super) fn footer_lines(
&mut self,
base: Vec<Line<'static>>,
base: Vec<Hint>,
width: u16,
max_rows: usize,
frames: &FrameRequester,
available: [bool; 2],
focus: HintFocus,
) -> Vec<Line<'static>> {
// The first base hint is close or clear highlight. Navigation can overflow.
let mut base = base.into_iter();
let path_hints = [shortcut("c", "copy path"), shortcut("p", "show path")]
let path_hints = [Hint::key("c", "copy path"), Hint::key("p", "show path")]
.into_iter()
.zip(available)
.filter_map(|(hint, available)| available.then_some(hint));
@@ -145,12 +154,9 @@ impl PathActions {
.next()
.into_iter()
.chain(path_hints)
.chain(self.feedback_hint(frames))
.chain(self.feedback_hint(frames).map(Hint::Status))
.chain(base);
HintLine::wrapped(hints, width, max_rows)
.into_iter()
.map(|row| row.line)
.collect()
focus.render_lines(hints, width, max_rows)
}
fn feedback_hint(&mut self, frames: &FrameRequester) -> Option<Line<'static>> {
@@ -250,6 +250,7 @@ async fn document_preview_scenario() -> Result<()> {
app.keymap.pager.scroll_down = vec![KeyBinding::from_event(key)];
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))).await?;
let scrolled = side_frame(&mut app, &mut tui, size)?;
assert_eq!(scrolled.contains("Tab link"), key.code != KeyCode::Tab);
assert!(!scrolled.contains("# Guide"), "{scrolled}");
assert!(!scrolled.contains("Back to bottom"), "{scrolled}");
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Home.into())))
@@ -285,6 +286,16 @@ async fn document_preview_scenario() -> Result<()> {
.find_map(|line| line.find("Find: ").map(|start| line[start..].trim_end()))
.expect("document Find editor");
insta::assert_snapshot!(footer, @"Find: egg");
app.focus_workspace_composer(&mut tui);
assert_eq!(app.panel_focus(), Some(PaneFocus::Main));
let parked = side_frame(&mut app, &mut tui, size)?;
let sidebar = app.conversation_frame.panel_area().expect("document panel");
insta::assert_snapshot!(visible_sidebar_row(&tui, sidebar, sidebar.bottom() - 1), @"Find: egg");
assert!(!parked.contains("esc cancel"), "{parked}");
let pane = app.sidebar_mut();
pane.show(pane.visible_content().unwrap(), PaneFocus::Sidebar);
assert!(side_frame(&mut app, &mut tui, size)?.contains("Find: egg"));
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into())))
.await?;
let select = crossterm::event::KeyEvent::new(KeyCode::F(8), KeyModifiers::NONE);
@@ -299,6 +310,12 @@ async fn document_preview_scenario() -> Result<()> {
for key in [KeyCode::Char('v'), KeyCode::Right] {
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key.into()))).await?;
}
app.focus_workspace_composer(&mut tui);
let parked = side_frame(&mut app, &mut tui, size)?;
assert!(!parked.contains("q close"), "{parked}");
let pane = app.sidebar_mut();
pane.show(pane.visible_content().unwrap(), PaneFocus::Sidebar);
assert!(side_frame(&mut app, &mut tui, size)?.contains("q close"));
app.reconnect.offline = true;
let copy = crossterm::event::KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
assert!(matches!(
@@ -392,6 +409,13 @@ async fn document_preview_scenario() -> Result<()> {
.map(ratatui::buffer::Cell::symbol)
.collect::<String>();
insta::assert_snapshot!(highlighted, @"Next");
let line = visible_sidebar_row(&tui, sidebar, sidebar.bottom() - 1);
assert!(line.starts_with("esc clear link"), "{line}");
for key in [KeyCode::Esc, KeyCode::Tab] {
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key.into()))).await?;
assert_eq!(app.sidebar().unwrap().documents.len(), 1);
}
for key in [KeyCode::Home, KeyCode::Enter] {
assert!(
Box::pin(app.handle_document_input(&mut tui, &mut server, &TuiEvent::Key(key.into())))
@@ -5,4 +5,4 @@ expression: sidebar.trim_end()
---
Side chat × PLAN.md × Agent transcript × note.md × +
Open <workspace>/note.md?
Focus this pane and press Enter to open.
⌃x s focus sidebar
@@ -3,7 +3,7 @@ source: tui/src/app/sidebar_open_in_codex_tests.rs
expression: sidebar.trim_end()
---
PLAN.md × +
Snapshot · Enter to open live
Snapshot
Use the sidebar. ↑
@@ -12,5 +12,5 @@ expression: sidebar.trim_end()
esc clear highlight · c copy path
p show path · ↑/↓ read · f3 find …
⌃x s focus sidebar
+2
View File
@@ -101,6 +101,8 @@ mod session_lifecycle_requests;
mod side_chat_policy_tests;
#[path = "tests/sidebar_chooser_hover_tests.rs"]
mod sidebar_chooser_hover_tests;
#[path = "tests/sidebar_file_path_tests.rs"]
mod sidebar_file_path_tests;
mod startup;
#[path = "tests/startup_frame_tests.rs"]
mod startup_frame_tests;
+1 -1
View File
@@ -56,7 +56,7 @@ async fn chord_app() -> Result<(Box<App>, Tui, AppServerSession)> {
Ok((app, tui, app_server))
}
async fn press(
pub(super) async fn press(
app: &mut App,
tui: &mut Tui,
app_server: &mut AppServerSession,
@@ -0,0 +1,138 @@
#![cfg(test)]
use super::key_chords::press;
use super::*;
use crate::app::sidebar::PaneFocus;
use crate::app::sidebar::SidebarContent;
use crossterm::event::MouseEvent;
use pretty_assertions::assert_eq;
use unicode_width::UnicodeWidthStr;
async fn file_path_test_app() -> Result<(Box<App>, tui::Tui, AppServerSession)> {
let mut app = make_test_app().await;
let parent = ThreadId::new();
app.enqueue_primary_thread_session(
test_thread_session(parent, app.config.cwd.to_path_buf()),
vec![test_turn("parent-turn", TurnStatus::Completed, Vec::new())],
)
.await?;
app.transcript_cells
.push(Arc::new(crate::history_cell::AgentMarkdownCell::new(
"[Guide](./guide.md)".into(),
app.config.cwd.as_path(),
)));
enable_side_retention(&mut app)?;
app.local_settings.tui.animations = false;
let mut tui = crate::tui::test_support::make_test_tui()?;
tui.set_owned_screen(/*owned*/ true)?;
let mut server = start_config_write_test_app_server(&app).await?;
app.refresh_sidebar_files(&server, parent).await;
let pane = app.sidebar_mut();
pane.show(SidebarContent::Chooser, PaneFocus::Sidebar);
pane.choice = pane.chat_tabs().file_start();
let path = KeyCode::Char('p').into();
Box::pin(press(&mut app, &mut tui, &mut server, path)).await?;
assert!(app.sidebar().unwrap().showing_file_path);
Ok((app, tui, server))
}
#[tokio::test]
async fn sidebar_file_path_escape_requires_focus_but_mouse_back_does_not() -> Result<()> {
let (mut app, mut tui, mut server) = file_path_test_app().await?;
let size = Size::new(/*width*/ 140, /*height*/ 18);
let choice = app.sidebar().unwrap().choice;
let path = KeyCode::Char('p').into();
let esc = KeyCode::Esc.into();
app.focus_workspace_composer(&mut tui);
let frame = side_frame(&mut app, &mut tui, size)?;
fn footer(frame: &str) -> &str {
let row = frame.lines().last().unwrap();
row.rsplit_once('│').unwrap().1.trim()
}
insta::assert_snapshot!(footer(&frame), @"back · ⌃x s focus sidebar");
Box::pin(press(&mut app, &mut tui, &mut server, esc)).await?;
assert!(app.backtrack.primed);
assert_eq!(app.chooser_focus(), Some(PaneFocus::Main));
assert!(app.sidebar().unwrap().showing_file_path);
let click_back =
async |app: &mut App, tui: &mut tui::Tui, server: &mut AppServerSession| -> Result<()> {
let frame = side_frame(app, tui, size)?;
let (prefix, _) = frame.lines().last().unwrap().rsplit_once("back").unwrap();
let left = MouseButton::Left;
for kind in [MouseEventKind::Down(left), MouseEventKind::Up(left)] {
let event = mouse(kind, prefix.width() as u16, size.height - 1);
boxed_future!(app.handle_tui_event(tui, server, event)).await?;
}
assert!(!app.sidebar().unwrap().showing_file_path);
assert_eq!(app.chooser_focus(), Some(PaneFocus::Sidebar));
assert_eq!(app.sidebar().unwrap().choice, choice);
Ok(())
};
click_back(&mut app, &mut tui, &mut server).await?;
Box::pin(press(&mut app, &mut tui, &mut server, path)).await?;
let frame = side_frame(&mut app, &mut tui, size)?;
insta::assert_snapshot!(footer(&frame), @"esc back · ↓ scroll");
click_back(&mut app, &mut tui, &mut server).await?;
app.local_settings.tui.keymap = toml::from_str("[list]\ncancel = []")?;
enable_side_retention(&mut app)?;
Box::pin(press(&mut app, &mut tui, &mut server, path)).await?;
let frame = side_frame(&mut app, &mut tui, size)?;
assert_eq!(footer(&frame), "back · ↓ scroll");
click_back(&mut app, &mut tui, &mut server).await?;
server.shutdown().await?;
Ok(())
}
#[tokio::test]
async fn sidebar_file_path_body_click_focuses_without_bypassing_pending_chord() -> Result<()> {
let (mut app, mut tui, mut server) = file_path_test_app().await?;
app.chat_widget.insert_str("parent draft");
let choice = app.sidebar().unwrap().choice;
app.focus_workspace_composer(&mut tui);
let size = Size::new(/*width*/ 140, /*height*/ 18);
side_frame(&mut app, &mut tui, size)?;
let body =
crate::sidebar_chooser::file_path_areas(app.conversation_frame.panel_area().unwrap())[0];
let point = (body.right() - 1, body.bottom() - 1);
for (button, modifiers) in [
(MouseButton::Left, KeyModifiers::SHIFT),
(MouseButton::Left, KeyModifiers::CONTROL),
(MouseButton::Middle, KeyModifiers::NONE),
(MouseButton::Left, KeyModifiers::NONE),
] {
for kind in [MouseEventKind::Down(button), MouseEventKind::Up(button)] {
let event = TuiEvent::Mouse(MouseEvent {
kind,
column: point.0,
row: point.1,
modifiers,
});
boxed_future!(app.handle_tui_event(&mut tui, &mut server, event)).await?;
}
let focus = if button == MouseButton::Left && modifiers.is_empty() {
PaneFocus::Sidebar
} else {
PaneFocus::Main
};
assert_eq!(app.chooser_focus(), Some(focus));
assert_eq!(app.sidebar().unwrap().choice, choice);
assert!(app.sidebar().unwrap().showing_file_path);
assert_eq!(app.chat_widget.composer_text_with_pending(), "parent draft");
side_frame(&mut app, &mut tui, size)?;
}
let prefix = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL);
let esc = KeyCode::Esc.into();
Box::pin(press(&mut app, &mut tui, &mut server, prefix)).await?;
assert!(app.key_chord_matcher.is_pending());
Box::pin(press(&mut app, &mut tui, &mut server, esc)).await?;
assert!(!app.key_chord_matcher.is_pending());
assert!(app.sidebar().unwrap().showing_file_path);
Box::pin(press(&mut app, &mut tui, &mut server, esc)).await?;
assert!(!app.sidebar().unwrap().showing_file_path);
assert_eq!(app.chat_widget.composer_text_with_pending(), "parent draft");
server.shutdown().await?;
Ok(())
}
+124 -20
View File
@@ -1,9 +1,12 @@
//! Packs footer hints into rows without separating a shortcut from its label.
//! Shared tips style keyboard tokens separately from their labels; callers own clipping.
//! Resolve focus before measuring. Only visible buttons get mouse targets.
use crate::key_hint::ShortcutHint;
use crate::style::secondary_text_style;
use ratatui::style::Styled;
use ratatui::style::Stylize;
use ratatui::text::Line;
use std::borrow::Cow;
/// Show the configured scroll keys for directions with rows beyond the viewport.
pub(crate) fn scroll_keys(
@@ -28,23 +31,122 @@ pub(crate) fn shortcut(keys: &str, label: &str) -> Line<'static> {
Line::from(spans)
}
/// The same measured spans determine which hints fit and where each one can be clicked.
pub(crate) struct HintLine {
pub(crate) line: Line<'static>,
pub(crate) items: Vec<std::ops::Range<u16>>,
/// Omit unavailable actions entirely. An available button still works without a binding.
pub(crate) enum Hint<A = ()> {
Key(String, Cow<'static, str>),
Button {
key: Option<String>,
label: &'static str,
action: A,
before_focus: bool,
},
Status(Line<'static>),
}
impl HintLine {
/// Wrap complete shortcuts into at most `max_rows`, marking any remaining overflow.
pub(crate) fn wrapped(
hints: impl IntoIterator<Item = Line<'static>>,
impl Hint {
pub(crate) fn key(keys: impl Into<String>, label: impl Into<Cow<'static, str>>) -> Self {
Self::Key(keys.into(), label.into())
}
}
#[derive(Clone, Copy)]
pub(crate) enum HintFocus {
Active,
Inactive,
Focusable(ShortcutHint, &'static str),
}
impl HintFocus {
pub(crate) fn is_active(self) -> bool {
matches!(self, Self::Active)
}
pub(crate) fn render_row<A>(
self,
hints: impl IntoIterator<Item = Hint<A>>,
width: u16,
) -> HintLine<A> {
self.render_hints(hints, width, /*max_rows*/ 1)
.pop()
.unwrap_or_else(|| HintLine::new([], width))
}
pub(crate) fn render_lines(
self,
hints: impl IntoIterator<Item = Hint>,
width: u16,
max_rows: usize,
) -> Vec<Self> {
if max_rows == 0 {
) -> Vec<Line<'static>> {
self.render_hints(hints, width, max_rows)
.into_iter()
.map(|row| row.line)
.collect()
}
// Keep the active pane's order. In an inactive pane, put status and primary
// mouse controls ahead of the focus cue so they survive narrow widths.
fn render_hints<A>(
self,
hints: impl IntoIterator<Item = Hint<A>>,
width: u16,
max_rows: usize,
) -> Vec<HintLine<A>> {
let active = self.is_active();
let mut items = Vec::new();
let mut focus_index = 0;
for hint in hints {
let (line, action, priority) = match hint {
Hint::Key(..) if !active => continue,
Hint::Key(keys, label) => (shortcut(&keys, &label), None, false),
Hint::Status(line) => (line, None, true),
Hint::Button {
key,
label,
action,
before_focus,
} => {
let line = match key {
Some(key) if active => shortcut(&key, label),
_ => label.bold().into(),
};
(line, Some(action), before_focus)
}
};
if !active && priority {
items.insert(focus_index, (line, action));
focus_index += 1;
} else {
items.push((line, action));
}
}
if let Self::Focusable(key, label) = self {
items.insert(focus_index, (shortcut(&key.display_label(), label), None));
}
HintLine::wrapped(items, width, max_rows)
}
}
pub(crate) struct HintLine<A> {
pub(crate) line: Line<'static>,
pub(crate) targets: Vec<(std::ops::Range<u16>, A)>,
}
impl<A> HintLine<A> {
/// Wrap complete shortcuts into at most `max_rows`, marking any remaining overflow.
fn wrapped(hints: Vec<(Line<'static>, Option<A>)>, width: u16, max_rows: usize) -> Vec<Self> {
if max_rows == 0 || hints.is_empty() {
return Vec::new();
}
let mut rows = wrap_hint_rows(hints, width, /*separator_width*/ 3, Line::width).into_iter();
if max_rows == 1 {
return vec![Self::new(hints, width)];
}
let mut rows = wrap_hint_rows(
hints,
width,
/*separator_width*/ 3,
|(line, _)| line.width(),
)
.into_iter();
let mut lines = Vec::new();
while let Some(row) = rows.next() {
if lines.len() + 1 == max_rows {
@@ -56,30 +158,32 @@ impl HintLine {
lines
}
pub(crate) fn new(hints: impl IntoIterator<Item = Line<'static>>, width: u16) -> Self {
fn new(hints: impl IntoIterator<Item = (Line<'static>, Option<A>)>, width: u16) -> Self {
let mut hints = hints.into_iter().peekable();
let mut line = Line::default();
let mut items = Vec::new();
let mut targets = Vec::new();
let mut end = 0;
while let Some(hint) = hints.next() {
let start = end + if items.is_empty() { 0 } else { 3 };
while let Some((hint, action)) = hints.next() {
let start = end + if line.spans.is_empty() { 0 } else { 3 };
let next = start + hint.width();
let overflow_space = if hints.peek().is_some() { 2 } else { 0 };
if next + overflow_space > usize::from(width) {
if width > 0 {
let marker = if items.is_empty() { "…" } else { " …" };
let marker = if line.spans.is_empty() { "…" } else { " …" };
line.push_span(marker.set_style(secondary_text_style()));
}
break;
}
if !items.is_empty() {
if !line.spans.is_empty() {
line.push_span(" · ".set_style(secondary_text_style()));
}
line.extend(hint.spans);
items.push(start as u16..next as u16);
if let Some(action) = action {
targets.push((start as u16..next as u16, action));
}
end = next;
}
Self { line, items }
Self { line, targets }
}
}
+33
View File
@@ -37,3 +37,36 @@ fn retains_oversized_hints_and_an_empty_row() {
vec![Vec::<String>::new()]
);
}
#[test]
fn inactive_hints_keep_controls_and_measure_only_visible_items() {
use super::Hint;
use super::HintFocus;
let focus = HintFocus::Focusable(
crate::key_hint::plain(crossterm::event::KeyCode::Char('s')).into(),
"focus",
);
let hints = || {
[
Hint::Button {
key: Some("enter".into()),
label: "open",
action: 1,
before_focus: false,
},
Hint::Button {
key: None,
label: "返回",
action: 2,
before_focus: true,
},
Hint::Key("↓".into(), "move".into()),
]
};
let row = focus.render_row(hints(), /*width*/ 17);
assert_eq!(row.line.to_string(), "返回 · s focus …");
assert_eq!(row.targets, vec![(0..4, 2)]);
let rows = focus.render_hints(hints(), /*width*/ 14, /*max_rows*/ 2);
assert_eq!(rows[0].targets, vec![(0..4, 2)]);
assert_eq!(rows[1].targets, vec![(0..4, 1)]);
}
+52 -64
View File
@@ -1,7 +1,9 @@
//! The sidebar chooser belongs to its parent conversation and can remain open without taking input.
use crate::app_server_session::SideChat;
use crate::footer_hint;
use crate::footer_hint::Hint;
use crate::footer_hint::HintFocus;
use crate::footer_hint::HintLine;
use crate::keymap::KeymapContext;
use crate::keymap::ListAction;
use crate::keymap::RuntimeKeymap;
@@ -69,16 +71,15 @@ fn list_hint(keymap: &RuntimeKeymap, action: ListAction) -> Option<String> {
.map(super::key_hint::ShortcutHint::display_label)
}
pub(crate) fn creation_failure_text(message: &str, keymap: &RuntimeKeymap) -> String {
pub(crate) fn creation_failure_hints(
keymap: &RuntimeKeymap,
focus: HintFocus,
width: u16,
) -> Line<'static> {
let hints = [(ListAction::Accept, "retry"), (ListAction::Cancel, "back")]
.into_iter()
.filter_map(|(action, label)| Some(format!("{} {label}", list_hint(keymap, action)?)))
.collect::<Vec<_>>();
if hints.is_empty() {
message.to_owned()
} else {
format!("{message}\n{}", hints.join(" · "))
}
.filter_map(|(action, label)| Some(Hint::key(list_hint(keymap, action)?, label)));
focus.render_row(hints, width).line
}
pub(crate) fn footer(
@@ -87,21 +88,23 @@ pub(crate) fn footer(
choice: usize,
tabs: ChatTabs<'_>,
new_chat: NewChatState,
focus: HintFocus,
showing_path: bool,
) -> (footer_hint::HintLine, Vec<Option<ChooserAction>>) {
) -> HintLine<ChooserAction> {
let hint = |action| list_hint(keymap, action);
let width = body_row(area, area.y).width;
let button = |key, label, action: Option<ChooserAction>| {
action.map(|action| Hint::Button {
key,
label,
action,
before_focus: action == ChooserAction::Back,
})
};
if showing_path {
let (hints, actions): (Vec<_>, Vec<_>) = [
(hint(ListAction::Cancel), "back", Some(ChooserAction::Back)),
(hint(ListAction::MoveDown), "scroll", None),
]
.into_iter()
.filter_map(|(key, label, action)| Some((footer_hint::shortcut(&key?, label), action)))
.unzip();
return (
footer_hint::HintLine::new(hints, body_row(area, area.y).width),
actions,
);
let back = button(hint(ListAction::Cancel), "back", Some(ChooserAction::Back));
let scroll = hint(ListAction::MoveDown).map(|key| Hint::Key(key, "scroll".into()));
return focus.render_row(back.into_iter().chain(scroll), width);
}
let selected_file = tabs.file(choice);
let visible = choice_is_visible(area, tabs, choice);
@@ -118,17 +121,15 @@ pub(crate) fn footer(
let hide = keymap
.primary_hint(KeymapContext::Global, "hide_pane")
.map(super::key_hint::ShortcutHint::display_label);
let (hints, actions): (Vec<_>, Vec<_>) = [
(
hint(ListAction::Accept)
.filter(|_| {
visible
&& !tabs.agent_is_disabled(choice)
&& (new_chat == NewChatState::Available
|| selected_file.is_some()
|| tabs.agent(choice).is_some())
})
.filter(|_| selected_file.is_none() || tabs.file_preview_unavailable.is_none()),
let can_open = visible
&& !tabs.agent_is_disabled(choice)
&& (new_chat == NewChatState::Available
|| selected_file.is_some()
|| tabs.agent(choice).is_some())
&& (selected_file.is_none() || tabs.file_preview_unavailable.is_none());
let hints = [
button(
hint(ListAction::Accept),
if tabs.retry_row(choice)
|| tabs.opening.is_some_and(|o| {
Some(o.target.child) == tabs.choice(choice)
@@ -139,9 +140,9 @@ pub(crate) fn footer(
} else {
"open"
},
Some(ChooserAction::Open(choice)),
can_open.then_some(ChooserAction::Open(choice)),
),
(
button(
hint(ListAction::Cancel),
if tabs
.opening
@@ -153,23 +154,15 @@ pub(crate) fn footer(
},
Some(ChooserAction::Back),
),
(
selected_file
.filter(|_| visible && file_path_key_available(keymap))
.map(|_| "p".to_owned()),
button(
file_path_key_available(keymap).then(|| "p".to_owned()),
"path",
Some(ChooserAction::FilePath),
(visible && selected_file.is_some()).then_some(ChooserAction::FilePath),
),
((!movement.is_empty()).then_some(movement), "move", None),
(hide, "hide pane", Some(ChooserAction::Hide)),
]
.into_iter()
.filter_map(|(keys, label, action)| Some((footer_hint::shortcut(&keys?, label), action)))
.unzip();
(
footer_hint::HintLine::new(hints, body_row(area, area.y).width),
actions,
)
(!movement.is_empty()).then(|| Hint::Key(movement, "move".into())),
button(hide, "hide pane", Some(ChooserAction::Hide)),
];
focus.render_row(hints.into_iter().flatten(), width)
}
#[derive(Default)]
@@ -574,23 +567,18 @@ pub(crate) fn row_targets(
pub(crate) fn footer_targets(
area: Rect,
hints: &footer_hint::HintLine,
actions: Vec<Option<ChooserAction>>,
hints: &HintLine<ChooserAction>,
) -> impl Iterator<Item = (ChooserAction, Rect)> + '_ {
let row = body_row(area, area.bottom().saturating_sub(1));
hints
.items
.iter()
.zip(actions)
.filter_map(move |(range, action)| {
if area.height < 2 {
return None;
}
Some((
action?,
Rect::new(row.x + range.start, row.y, range.end - range.start, 1),
))
})
hints.targets.iter().filter_map(move |(range, action)| {
if area.height < 2 {
return None;
}
Some((
*action,
Rect::new(row.x + range.start, row.y, range.end - range.start, 1),
))
})
}
pub(crate) fn file_path_key_available(keymap: &RuntimeKeymap) -> bool {