Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,12 @@
# TUI bottom pane (state machines)
When changing the paste-burst or chat-composer state machines in this folder, keep the docs in sync:
- Update the relevant module docs (`chat_composer.rs` and/or `paste_burst.rs`) so they remain a
readable, top-down explanation of the current behavior.
- Keep implementations/docstrings aligned unless a divergence is intentional and documented.
Practical check:
- After edits, sanity-check that docs mention only APIs/behavior that exist in code (especially the
Enter/newline paths and `disable_paste_burst` semantics).

View File

@@ -0,0 +1,25 @@
use super::TerminalTitleItem;
pub(crate) const ACTION_REQUIRED_PREVIEW_PREFIX: &str = "[ ! ] Action Required";
pub(crate) fn build_action_required_title_text<I, F>(
prefix: &str,
items: I,
excluded_items: &[TerminalTitleItem],
mut value_for: F,
) -> String
where
I: IntoIterator<Item = TerminalTitleItem>,
F: FnMut(TerminalTitleItem) -> Option<String>,
{
let mut parts = vec![prefix.to_string()];
for item in items {
if item == TerminalTitleItem::Spinner || excluded_items.contains(&item) {
continue;
}
if let Some(value) = value_for(item) {
parts.push(value);
}
}
parts.join(" | ")
}

View File

@@ -0,0 +1,278 @@
//! Shared title, description, and CTA content for banners in the TUI bottom pane.
//!
//! Workspace notices and backend banners share the existing selection list for CTA dispatch.
//! The inline wrapper owns presentation and dismissal while preserving normal composer input.
use super::BottomPane;
use super::BottomPaneView;
use super::SelectionItem;
use super::SelectionViewParams;
use super::list_selection_view::ListSelectionView;
use crate::render::Insets;
use crate::render::RectExt;
use crate::render::renderable::Renderable;
use crate::terminal_palette::best_color;
use crate::terminal_palette::default_fg;
use crate::wrapping::word_wrap_line_with_source;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Color;
use ratatui::style::Style;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Widget;
use std::cell::Cell;
#[derive(Default)]
pub(crate) struct ActionableBanner {
pub(crate) title: String,
pub(crate) description: String,
pub(crate) actions: Vec<SelectionItem>,
pub(crate) initial_selected_idx: Option<usize>,
pub(crate) dismissal: BannerDismissal,
pub(crate) view_id: Option<&'static str>,
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum BannerDismissal {
#[default]
Dismissible,
Persistent,
}
pub(super) struct InlineBanner {
content: InlineBannerContent,
dismissal: BannerDismissal,
shown: Cell<bool>,
// Current visibility is separate from whether this banner has ever been shown.
pub(super) visible: Cell<bool>,
dismissed: bool,
visible_action_count: Cell<usize>,
}
enum InlineBannerContent {
Actions(Box<ListSelectionView>),
Information {
header: Box<dyn Renderable>,
hint: Line<'static>,
},
}
impl Renderable for InlineBanner {
fn render(&self, area: Rect, buf: &mut Buffer) {
self.visible_action_count.set(0);
self.visible.set(!self.dismissed && !area.is_empty());
if !self.visible.get() {
return;
}
self.shown.set(true);
match &self.content {
InlineBannerContent::Actions(view) => {
view.render(area, buf);
self.visible_action_count.set(view.rendered_item_count());
}
InlineBannerContent::Information { header, hint } => {
let content = area.inset(Insets::tlbr(
/*top*/ 1, /*left*/ 2, /*bottom*/ 1, /*right*/ 2,
));
header.render(content, buf);
let y = content
.y
.saturating_add(header.desired_height(content.width) + 1);
if y < area.bottom() {
Renderable::render(
hint,
Rect::new(content.x, y, content.width, /*height*/ 1),
buf,
);
}
}
}
}
fn desired_height(&self, width: u16) -> u16 {
if self.dismissed {
return 0;
}
match &self.content {
InlineBannerContent::Actions(view) => view.desired_height(width),
InlineBannerContent::Information { header, hint } => {
header.desired_height(width.saturating_sub(4))
+ if hint.width() == 0 { 2 } else { 4 }
}
}
}
}
/// Multiline banner copy uses the same word wrapping for measurement and rendering.
struct BannerContent(Vec<Line<'static>>);
impl BannerContent {
fn wrapped_lines(&self, width: u16) -> Vec<crate::terminal_hyperlinks::HyperlinkLine> {
let mut lines = crate::terminal_hyperlinks::annotate_web_urls(self.0.clone())
.into_iter()
.flat_map(|source| {
let wrapped = word_wrap_line_with_source(&source.line, usize::from(width));
crate::terminal_hyperlinks::remap_source_wrapped_line(&source, wrapped)
})
.collect::<Vec<_>>();
if lines.len() > 8 {
lines.truncate(7);
lines.push(crate::terminal_hyperlinks::HyperlinkLine::new(
"…".dim().into(),
));
}
lines
}
}
impl Renderable for BannerContent {
fn render(&self, area: Rect, buf: &mut Buffer) {
let lines = self.wrapped_lines(area.width);
// Explicit foreground avoids a terminal's separate bold color washing out the title.
let foreground = default_fg().map(best_color).unwrap_or(Color::Reset);
Widget::render(
crate::terminal_hyperlinks::HyperlinkParagraph::new(
&lines,
Style::default().fg(foreground),
),
area,
buf,
);
}
fn desired_height(&self, width: u16) -> u16 {
self.wrapped_lines(width).len() as u16
}
}
impl From<ActionableBanner> for SelectionViewParams {
fn from(banner: ActionableBanner) -> Self {
let lines = banner
.title
.lines()
.map(|line| Line::from(line.to_owned().bold()))
.chain(
banner
.description
.lines()
.map(|line| Line::from(line.to_owned())),
)
.collect();
Self {
view_id: banner.view_id,
header: Box::new(BannerContent(lines)),
items: banner.actions,
initial_selected_idx: banner.initial_selected_idx,
..Self::picker()
}
}
}
impl BottomPane {
/// Display a banner above the composer without interrupting active dialogs or losing a draft.
pub(crate) fn set_inline_banner(&mut self, banner: Option<ActionableBanner>) {
self.inline_banner = banner.map(|banner| {
let dismissal = banner.dismissal;
let has_actions = !banner.actions.is_empty();
let mut params: SelectionViewParams = banner.into();
params.header_gap = 0;
params.allow_cancel = dismissal == BannerDismissal::Dismissible;
for item in &mut params.items {
item.dismiss_on_select = false;
}
let hint = match (dismissal, has_actions) {
(BannerDismissal::Persistent, true) => "Press a number to choose",
(BannerDismissal::Persistent, false) => "",
(BannerDismissal::Dismissible, true) => {
"Press a number to choose · esc to dismiss · type to continue"
}
(BannerDismissal::Dismissible, false) => "esc to dismiss · type to continue",
};
let hint: Line<'static> = hint.dim().into();
params.footer_hint = Some(hint.clone());
InlineBanner {
content: if has_actions {
InlineBannerContent::Actions(Box::new(ListSelectionView::new(
params,
self.app_event_tx.clone(),
self.keymap.list.clone(),
)))
} else {
InlineBannerContent::Information {
header: params.header,
hint,
}
},
dismissal,
shown: Cell::new(false),
visible: Cell::new(false),
dismissed: false,
visible_action_count: Cell::new(0),
}
});
self.request_redraw();
}
/// Observation for the owning controller; model hiding is not a dismissal.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn inline_banner_lifecycle(&self) -> (bool, bool) {
self.inline_banner
.as_ref()
.map_or((false, false), |banner| {
(banner.shown.get(), banner.dismissed)
})
}
pub(super) fn inline_banner_accepts_dismissal(&self) -> bool {
self.inline_banner.as_ref().is_some_and(|banner| {
banner.visible.get()
&& !banner.dismissed
&& banner.dismissal == BannerDismissal::Dismissible
})
}
pub(super) fn handle_inline_banner_key(&mut self, key: KeyEvent) -> bool {
// Draft input, completion menus, and paste bursts retain all of their normal keys.
if !self.composer_is_empty()
|| (key.code == KeyCode::Esc && self.composer.shortcut_overlay_visible())
|| self.composer.popup_active()
|| self.composer.is_in_paste_burst()
|| self.composer_should_handle_vim_insert_escape(key)
|| self.is_task_running
|| key.kind != KeyEventKind::Press
|| key.modifiers != KeyModifiers::NONE
{
return false;
}
let Some(banner) = self.inline_banner.as_mut() else {
return false;
};
if !banner.visible.get() || banner.dismissed {
return false;
}
match key.code {
KeyCode::Esc if banner.dismissal == BannerDismissal::Persistent => return false,
KeyCode::Esc => {
banner.dismissed = true;
}
KeyCode::Char(digit @ '1'..='9') => {
if digit as usize - '1' as usize >= banner.visible_action_count.get() {
return false;
}
let InlineBannerContent::Actions(view) = &mut banner.content else {
return false;
};
view.handle_key_event(key);
let _ = view.take_last_selected_index();
}
_ => return false,
}
self.request_redraw();
true
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,73 @@
//! Render file-change approval descriptions and cross-platform destinations.
use super::approval_overlay::ApplyPatchApprovalRequest;
use crate::diff_model::FileChange;
use crate::render::renderable::Renderable;
use crate::terminal_hyperlinks::HyperlinkText;
use akode_utils_path_uri::LegacyAppPathString;
use ratatui::style::Stylize;
use ratatui::text::Line;
pub(super) fn build_header(request: &ApplyPatchApprovalRequest) -> Box<dyn Renderable> {
let mut header = Vec::new();
if let Some(thread_label) = &request.thread_label {
header.push(Line::from(vec![
"Thread: ".into(),
thread_label.clone().bold(),
]));
}
if !header.is_empty() {
header.push(Line::from(""));
}
let description = request
.reason
.as_deref()
.filter(|reason| !reason.is_empty())
.unwrap_or("Apply proposed file edits");
header.push(Line::from_iter([
"Description: ".into(),
description.to_string().italic(),
]));
let mut destinations: Vec<_> = request
.changes
.iter()
.flat_map(|(path, change)| {
let move_destination = match change {
FileChange::Update {
move_path: Some(move_path),
..
} => Some(move_path),
FileChange::Add { .. }
| FileChange::Delete { .. }
| FileChange::Update {
move_path: None, ..
} => None,
};
std::iter::once(path).chain(move_destination)
})
.map(|path| {
LegacyAppPathString::from_path(path)
.to_inferred_path_uri()
.map(|path| path.inferred_native_path_string())
.unwrap_or_else(|| request.cwd.join(path).display().to_string())
})
.collect();
destinations.sort();
destinations.dedup();
if destinations.is_empty() {
header.push(Line::from(vec![
"Destination: ".into(),
"unavailable".bold(),
]));
}
for destination in destinations {
header.push(Line::from_iter([
"Destination: ".into(),
destination.bold(),
]));
}
Box::new(HyperlinkText::new(header))
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,101 @@
//! Clipped approval headers expose the configured route to their complete payload.
use super::*;
use crate::keymap::RuntimeKeymap;
use pretty_assertions::assert_eq;
#[test]
fn clipped_exec_approval_opens_the_complete_command() {
let command = format!(
"{}printf destructive_suffix",
"printf benign\n".repeat(/*n*/ 20)
);
let reason = format!(
"{}reason_suffix",
"A reason requiring review.\n".repeat(/*n*/ 20)
);
let mut snapshots = Vec::new();
for binding in [Some(key_hint::ctrl(KeyCode::Char('g'))), None] {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let mut keymap = RuntimeKeymap::defaults();
keymap.approval.open_fullscreen = binding.into_iter().collect();
let mut view = ApprovalOverlay::new(
ApprovalRequest::Exec(ExecApprovalRequest {
kind: Default::default(),
thread_id: ThreadId::new(),
thread_label: None,
id: "clipped-approval".into(),
environment_id: Some("local".into()),
command: vec!["sh".into(), "-c".into(), command.clone()],
reason: Some(reason.clone()),
available_decisions: vec![
CommandExecutionApprovalDecision::Accept,
CommandExecutionApprovalDecision::Cancel,
],
network_approval_context: None,
additional_permissions: None,
}),
AppEventSender::new(tx),
Features::with_defaults(),
keymap.approval,
keymap.list,
);
for (width, height) in [(80, 14), (40, 10), (40, 8), (40, 7)] {
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let mut buffer = Buffer::empty(area);
view.render(area, &mut buffer);
let rows: Vec<String> = (0..height)
.map(|y| {
(0..width)
.map(|x| buffer[(x, y)].symbol())
.collect::<String>()
.trim_end()
.to_owned()
})
.collect();
let elision = rows.iter().find(|row| row.contains("[…")).unwrap();
assert_eq!(elision.contains("⌃g view all"), binding.is_some());
assert!(rows.last().unwrap().contains("cancel"));
assert!(!rows.iter().any(|row| row.contains("destructive_suffix")));
assert!(!rows.iter().any(|row| row.contains("reason_suffix")));
assert!(rows.iter().any(|row| row.contains("Yes, proceed")));
snapshots.push(format!(
"bound={} {width}x{height}\n{}",
binding.is_some(),
rows.join("\n")
));
}
let area = Rect::new(
/*x*/ 0,
/*y*/ 0,
/*width*/ 80,
view.desired_height(/*width*/ 80),
);
let mut buffer = Buffer::empty(area);
view.render(area, &mut buffer);
let complete = buffer
.content
.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>();
assert!(complete.contains("destructive_suffix"));
assert!(complete.contains("reason_suffix"));
assert!(!complete.contains("[…"));
if binding.is_some() {
view.handle_key_event(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::CONTROL));
let AppEvent::FullScreenApprovalRequest(ApprovalRequest::Exec(request)) =
rx.try_recv().unwrap()
else {
panic!("fullscreen should open the original approval");
};
assert_eq!(
request.command,
vec!["sh".to_owned(), "-c".to_owned(), command.clone()]
);
assert_eq!(request.reason, Some(reason.clone()));
assert!(!view.is_complete());
assert!(rx.try_recv().is_err());
}
}
insta::assert_snapshot!(snapshots.join("\n\n"));
}

View File

@@ -0,0 +1,97 @@
---
source: tui/src/bottom_pane/approval_overlay/clipping_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
bound=true 80x14
Would you like to run the following command?
Environment: local
Reason: A reason requiring review.A reason requiring review.A reason
requiring review.A reason requiring review.A reason requiring review.A
reason requiring review.A reason requiring review.A reason requiring
review.A reason requiring review.A reason requiring review.A reason
requiring review.A reason requiring review.A reason requiring review.A
[… 34 lines] ⌃g view all
› 1. Yes, proceed (y)
2. No, and tell Codex what to do differently (esc)
Press enter to confirm or esc to cancel
bound=true 40x10
Would you like to run the following
command?
[… 43 lines] ⌃g view all
› 1. Yes, proceed (y)
2. No, and tell Codex what to do
differently (esc)
Press enter to confirm or esc to
cancel
bound=true 40x8
Would you like to run the following
[… 43 lines] ⌃g view all
› 1. Yes, proceed (y)
2. No, and tell Codex what to do
differently (esc)
Press enter to confirm or esc to
cancel
bound=true 40x7
[… 43 lines] ⌃g view all
› 1. Yes, proceed (y)
2. No, and tell Codex what to do
differently (esc)
Press enter to confirm or esc to
cancel
bound=false 80x14
Would you like to run the following command?
Environment: local
Reason: A reason requiring review.A reason requiring review.A reason
requiring review.A reason requiring review.A reason requiring review.A
reason requiring review.A reason requiring review.A reason requiring
review.A reason requiring review.A reason requiring review.A reason
requiring review.A reason requiring review.A reason requiring review.A
[… 34 lines]
› 1. Yes, proceed (y)
2. No, and tell Codex what to do differently (esc)
Press enter to confirm or esc to cancel
bound=false 40x10
Would you like to run the following
command?
[… 43 lines]
› 1. Yes, proceed (y)
2. No, and tell Codex what to do
differently (esc)
Press enter to confirm or esc to
cancel
bound=false 40x8
Would you like to run the following
[… 43 lines]
› 1. Yes, proceed (y)
2. No, and tell Codex what to do
differently (esc)
Press enter to confirm or esc to
cancel
bound=false 40x7
[… 43 lines]
› 1. Yes, proceed (y)
2. No, and tell Codex what to do
differently (esc)
Press enter to confirm or esc to
cancel

View File

@@ -0,0 +1,316 @@
//! Route question actions through the shared composer, preserving drafts until delivery accepts them.
//! Inline Other reserves Up/Down for choices; j/k retain their Vim behavior.
use super::*;
use ratatui::layout::Rect;
impl AsyncQuestions {
pub(crate) fn handles_key_as_editing(&self, key: KeyEvent) -> bool {
self.focus_is_notes() && self.composer.handles_key_as_editing(key)
}
pub(super) fn other_selected(&self) -> bool {
self.has_options() && self.selected_option_index() == Some(self.options().len())
}
pub(super) fn other_label(&self) -> String {
self.current_answer()
.filter(|_| !self.other_selected())
.map(|answer| answer.draft.text.trim())
.filter(|text| !text.is_empty())
.map(|text| &text[..text.floor_char_boundary(512)])
.map(|text| crate::text_formatting::truncate_text(text, /*max_graphemes*/ 128))
.unwrap_or_else(|| self.other_placeholder().to_string())
}
pub(super) fn focus_other(&mut self) {
self.select_option(self.options().len());
}
pub(super) fn select_option(&mut self, index: usize) {
self.save_current_draft();
self.state.pending[self.state.current_idx]
.options_state
.selected_idx = Some(index);
self.sync_composer_placeholder();
}
pub(super) fn edit(&mut self, key: KeyEvent) {
if key.kind == KeyEventKind::Repeat && self.keymap.composer.queue.is_pressed(key) {
return;
}
if self.keymap.composer.submit.is_pressed(key) && !self.composer.is_in_paste_burst() {
self.composer.flush_pending_input();
}
let before = self.composer.snapshot_draft();
let (result, _) = self.composer.handle_key_event(key);
let queued = matches!(result, InputResult::Queued { .. });
if matches!(
result,
InputResult::Submitted { .. } | InputResult::Queued { .. }
) {
self.composer.restore_draft(before);
self.go_next_or_submit();
if queued && let Some(QuestionSubmission::Submit(text)) = self.submission.take() {
self.submission = Some(QuestionSubmission::Queue(text));
}
}
}
pub(super) fn other_prefix_width(&self, width: u16) -> u16 {
let full = format!("› {}. ", self.options_len()).width() as u16;
if full + 2 <= width {
full
} else {
width.saturating_sub(2).min(2)
}
}
pub(super) fn other_input_area(&self, options_area: Rect) -> Rect {
let prefix_width = self.other_prefix_width(options_area.width);
let width = options_area.width.saturating_sub(prefix_width);
let height = self
.composer
.inline_input_height(width)
.clamp(1, 8)
.min(options_area.height);
Rect::new(
options_area.x.saturating_add(prefix_width),
options_area.bottom().saturating_sub(height),
width,
height,
)
}
pub(super) fn render_inline_options(&self, area: Rect, buf: &mut ratatui::buffer::Buffer) {
use ratatui::text::Line;
use ratatui::widgets::Widget;
let input = self.other_input_area(area);
let named_area = Rect::new(area.x, area.y, area.width, input.y.saturating_sub(area.y));
let mut rows = self.option_rows(named_area.width);
rows.pop();
let mut state = ScrollState::default();
while state.scroll_top + 1 < rows.len()
&& measure_rows_height(&rows, &state, rows.len(), named_area.width) > named_area.height
{
state.scroll_top += 1;
}
if measure_rows_height(&rows, &state, rows.len(), named_area.width) <= named_area.height {
self.visible_options
.set((state.scroll_top, rows.len() - state.scroll_top));
}
crate::bottom_pane::request_user_input::render::render_rows_bottom_aligned(
named_area,
buf,
&rows,
&state,
rows.len(),
"",
);
let margin = Rect::new(
area.x,
input.y,
input.x.saturating_sub(area.x),
input.height.min(1),
);
let prefix = format!("› {}. ", self.options_len());
Line::from(if usize::from(margin.width) < prefix.width() {
"› ".to_string()
} else {
prefix
})
.style(crate::style::accent_style())
.render(margin, buf);
self.composer.render_inline_input(input, buf);
}
pub(crate) fn set_keymap(&mut self, keymap: &RuntimeKeymap) {
self.keymap = keymap.clone();
self.composer.set_keymap_bindings(keymap);
}
pub(crate) fn set_vim_enabled(&mut self, enabled: bool) {
self.composer.set_vim_enabled(enabled);
}
}
impl BottomPaneView for AsyncQuestions {
fn keymap_contexts(&self) -> crate::keymap::KeymapContextSet {
if self.focus_is_notes() {
self.composer.keymap_contexts().with(KeymapContext::Chat)
} else {
crate::keymap::KeymapContextSet::new(KeymapContext::List).with(KeymapContext::Chat)
}
}
fn prefer_esc_to_handle_key_event(&self) -> bool {
true
}
fn will_interrupt_turn_on_key_event(&self, key: KeyEvent) -> bool {
!self.handles_key_as_editing(key) && self.keymap.chat.interrupt_turn.is_pressed(key)
}
fn handle_key_event(&mut self, key: KeyEvent) {
if key.kind == KeyEventKind::Repeat && self.other_selector == Some(key.code) {
return;
}
self.other_selector = None;
if key.kind == KeyEventKind::Release || self.is_complete() {
return;
}
self.snooze_auto_resolution();
if self.handles_key_as_editing(key) {
self.edit(key);
return;
}
if self.keymap.chat.interrupt_turn.is_pressed(key) {
self.app_event_tx.interrupt();
return;
}
if key.kind == KeyEventKind::Press && self.keymap.chat.skip_question.is_pressed(key) {
if self.delivery_enabled {
self.accept_answer();
}
return;
}
if self.keymap.chat.edit_queued_message.is_pressed(key) {
self.navigate(/*forward*/ true);
return;
}
if self.keymap.chat.prompt_stack_back.is_pressed(key) {
self.navigate(/*forward*/ false);
return;
}
if self.focus_is_notes() && self.keymap.composer.submit.is_pressed(key) {
if key.kind != KeyEventKind::Press {
return;
}
let empty = self.composer.current_text_with_pending().trim().is_empty();
if empty && !self.composer.is_in_paste_burst() {
if !self.other_selected() {
self.go_next_or_submit();
}
} else {
self.edit(key);
}
return;
}
if self.has_options() {
// Default j/k start Other; explicit printable list remaps keep their meaning.
let printable = matches!(key.code, KeyCode::Char(_))
&& !crate::key_hint::has_ctrl_or_alt(key.modifiers);
let remapped = self.keymap.list.action_for(key).is_some_and(|action| {
self.keymap.list.bindings_for(action)
!= RuntimeKeymap::defaults().list.bindings_for(action)
});
if (!printable || remapped)
&& (!self.focus_is_notes() || matches!(key.code, KeyCode::Up | KeyCode::Down))
{
let count = self.options_len();
let visible = self.visible_options.get().1.max(1);
let mut state = self.state.pending[self.state.current_idx].options_state;
match self.keymap.list.action_for(key) {
Some(ListAction::MoveUp) => state.move_up_wrap(count),
Some(ListAction::MoveDown) => state.move_down_wrap(count),
Some(ListAction::PageUp) => state.page_up_clamped(count, visible),
Some(ListAction::PageDown) => state.page_down_clamped(count, visible),
Some(ListAction::JumpTop) => state.jump_top(count, visible),
Some(ListAction::JumpBottom) => state.jump_bottom(count, visible),
Some(ListAction::Cancel) => {
self.set_expanded(/*expanded*/ false);
return;
}
Some(ListAction::MoveLeft | ListAction::MoveRight) => return,
Some(ListAction::Accept) | None => {}
}
if !matches!(
self.keymap.list.action_for(key),
Some(ListAction::Accept) | None
) {
self.select_option(state.selected_idx.unwrap_or(0));
self.state.pending[self.state.current_idx].options_state = state;
return;
}
}
}
if self.focus_is_notes() {
self.edit(key);
return;
}
if self.keymap.list.action_for(key) == Some(ListAction::Accept) {
if key.kind != KeyEventKind::Press {
return;
}
self.go_next_or_submit();
} else if let KeyCode::Char(ch) = key.code
&& !crate::key_hint::has_ctrl_or_alt(key.modifiers)
{
if let Some(index) = self.option_index_for_digit(ch) {
if key.kind != KeyEventKind::Press {
return;
}
self.select_option(index);
if self.other_selected() {
self.other_selector = Some(key.code);
} else {
self.go_next_or_submit();
}
} else {
self.focus_other();
self.composer.resume_text_entry();
self.edit(key);
}
}
}
fn terminal_title_requires_action(&self) -> bool {
!self.is_complete()
}
fn is_complete(&self) -> bool {
self.unanswered_count() == 0
}
fn on_ctrl_c(&mut self) -> CancellationEvent {
if self.composer.cancel_vim_search() || self.composer.cancel_history_search() {
return CancellationEvent::Handled;
}
if self.focus_is_notes() && self.composer.clear_for_ctrl_c().is_some() {
self.save_current_draft();
self.sync_composer_placeholder();
} else {
return CancellationEvent::NotHandled;
}
CancellationEvent::Handled
}
fn handle_paste(&mut self, text: String) -> bool {
if self.is_complete() || text.is_empty() {
return false;
}
self.snooze_auto_resolution();
if !self.focus_is_notes() {
self.focus_other();
}
self.composer.flush_pending_input();
self.composer.handle_paste(text)
}
fn flush_paste_burst_if_due(&mut self) -> bool {
self.composer.flush_paste_burst_if_due()
}
fn is_in_paste_burst(&self) -> bool {
self.composer.is_in_paste_burst()
}
fn next_frame_delay(&self) -> Option<Duration> {
self.timer_remaining(Instant::now())
.map(|remaining| {
if remaining > Duration::from_secs(20) {
remaining - Duration::from_secs(20)
} else {
remaining.min(Duration::from_secs(1))
}
})
.into_iter()
.chain(self.composer.footer_flash_delay())
.min()
}
}

View File

@@ -0,0 +1,122 @@
//! Allocate question, options, input, and footer rows without intermediate layout plans.
//! Tight layouts reserve freeform editing space; named choices require the complete prompt.
use ratatui::layout::Rect;
use crate::terminal_hyperlinks::HyperlinkLine;
use super::AsyncQuestions;
use super::DESIRED_SPACERS_BETWEEN_SECTIONS;
pub(super) struct LayoutSections {
pub(super) progress_area: Rect,
pub(super) question_area: Rect,
pub(super) question_lines: Vec<HyperlinkLine>,
pub(super) options_area: Rect,
/// Layout already measured the wrapped choices, so the footer can use this flag
/// without parsing and wrapping their Markdown again.
pub(super) show_option_tip: bool,
pub(super) notes_area: Rect,
pub(super) footer_lines: u16,
pub(super) spacer_after_input: u16,
}
impl AsyncQuestions {
pub(super) fn layout_sections(&self, area: Rect) -> LayoutSections {
let has_options = self.has_options();
let full_options_height = self.options_required_height(area.width);
let mut question_lines = self.wrapped_question_lines(area.width);
let mut footer_pref = self.footer_lines(area.width, /*option_tip*/ None).len() as u16;
if has_options
&& question_lines.len()
+ usize::from(full_options_height)
+ usize::from(footer_pref)
+ usize::from(self.unanswered_count() > 1)
+ usize::from(DESIRED_SPACERS_BETWEEN_SECTIONS)
> usize::from(area.height)
{
footer_pref = self.footer_lines(area.width, Some(self.option_tip())).len() as u16;
}
let progress_pref = u16::from(self.unanswered_count() > 1);
let min_notes = u16::from(!has_options).min(area.height);
let available = area.height.saturating_sub(min_notes);
let question_height = question_lines.len().min(usize::from(
available.saturating_sub(u16::from(self.other_selected())),
)) as u16;
question_lines.truncate(usize::from(question_height));
let mut remaining = available.saturating_sub(question_height);
let mut options_height = 0;
let mut spacer_before_question = 0;
let spacer_after_question;
let mut spacer_after_options = 0;
let mut spacer_after_input = 0;
let progress_height;
let footer_lines;
let notes_height;
if has_options {
let min_options_height = remaining.min(1);
// Reserve hints and spacers while retaining a row for the selected option.
let reserved = footer_pref + progress_pref + DESIRED_SPACERS_BETWEEN_SECTIONS;
options_height =
full_options_height.min(remaining.saturating_sub(reserved).max(min_options_height));
remaining -= options_height;
progress_height = progress_pref.min(remaining);
remaining -= progress_height;
spacer_after_options = u16::from(remaining > footer_pref);
remaining -= spacer_after_options;
footer_lines = footer_pref.min(remaining);
remaining -= footer_lines;
spacer_after_question = u16::from(remaining > 0);
remaining -= spacer_after_question;
options_height += remaining.min(full_options_height.saturating_sub(options_height));
notes_height = 0;
} else {
// Freeform answers take their preferred input height before hints and progress.
let preferred_notes = self
.composer
.inline_input_height(area.width)
.clamp(1, 8)
.saturating_sub(min_notes)
.min(remaining);
remaining -= preferred_notes;
footer_lines = footer_pref.min(remaining);
remaining -= footer_lines;
progress_height = progress_pref.min(remaining);
remaining -= progress_height;
spacer_after_input = u16::from(remaining > 0);
remaining -= spacer_after_input;
// Drop padding before input or prompt content in a constrained viewport.
spacer_before_question = u16::from(remaining >= 2 && self.unanswered_count() > 1);
spacer_after_question = u16::from(remaining >= 1);
notes_height = min_notes + preferred_notes + remaining
- spacer_before_question
- spacer_after_question;
}
let mut y = area.y;
let mut take_rows = |height| {
let rows = Rect::new(area.x, y, area.width, height);
y = y.saturating_add(height);
rows
};
let progress_area = take_rows(progress_height);
take_rows(spacer_before_question);
let question_area = take_rows(question_height);
take_rows(spacer_after_question);
let options_area = take_rows(options_height);
take_rows(spacer_after_options);
let notes_area = take_rows(notes_height);
LayoutSections {
progress_area,
question_area,
question_lines,
options_area,
show_option_tip: options_height > 0 && options_height < full_options_height,
notes_area,
footer_lines,
spacer_after_input,
}
}
}

View File

@@ -0,0 +1,269 @@
//! Inline editing for asynchronous questions. Legacy request_user_input keeps its own overlay.
//! Local submissions and committed desktop replies remove questions; arrival never steals focus.
//! Live turn completion recovers unsent typed drafts before removing pending questions.
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::CancellationEvent;
use crate::bottom_pane::ChatComposer;
use crate::bottom_pane::ChatComposerConfig;
use crate::bottom_pane::InputResult;
use crate::bottom_pane::bottom_pane_view::BottomPaneView;
use crate::bottom_pane::chat_composer::ComposerDraft;
use crate::bottom_pane::scroll_state::ScrollState;
use crate::bottom_pane::selection_popup_common::GenericDisplayRow;
use crate::bottom_pane::selection_popup_common::measure_rows_height;
use crate::key_hint::KeyBindingListExt;
use crate::keymap::KeymapContext;
use crate::keymap::ListAction;
use crate::keymap::RuntimeKeymap;
use crate::markdown::render_markdown_for_viewport;
use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::prefix_hyperlink_lines;
use akode_protocol::items::AsyncUserInputQuestion;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use std::collections::HashSet;
use std::time::Duration;
use std::time::Instant;
use unicode_width::UnicodeWidthStr;
mod input;
mod layout;
mod render;
mod state;
const OTHER_OPTION_LABEL: &str = "Other";
pub(super) const TIP_SEPARATOR: &str = " ";
pub(super) const DESIRED_SPACERS_BETWEEN_SECTIONS: u16 = 2;
#[derive(Debug, Clone, PartialEq)]
struct PendingQuestion {
message_id: String,
question_id: String,
question: AsyncUserInputQuestion,
options_state: ScrollState,
draft: ComposerDraft,
expires_at: Option<Instant>,
}
/// Locally retained async questions; replayed message IDs cannot resurrect handled answers.
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct QuestionState {
pending: Vec<PendingQuestion>,
current_idx: usize,
expanded: bool,
seen_ids: HashSet<String>,
answered_ids: HashSet<String>,
}
pub(crate) enum QuestionSubmission {
Submit(String),
Queue(String),
}
pub(crate) struct AsyncQuestions {
app_event_tx: AppEventSender,
state: QuestionState,
pub(crate) expanded: bool,
pub(crate) has_queued_messages: bool,
pub(crate) delivery_enabled: bool,
pub(crate) submission: Option<QuestionSubmission>,
visible_options: std::cell::Cell<(usize, usize)>,
keymap: RuntimeKeymap,
// Ignore autorepeat from the number key that opened Other.
other_selector: Option<KeyCode>,
pub(super) composer: ChatComposer,
}
impl AsyncQuestions {
pub(crate) fn new(
app_event_tx: AppEventSender,
has_input_focus: bool,
enhanced_keys_supported: bool,
disable_paste_burst: bool,
keymap: RuntimeKeymap,
) -> Self {
let mut composer = ChatComposer::new_with_config(
has_input_focus,
app_event_tx.clone(),
enhanced_keys_supported,
"Type your answer".into(),
disable_paste_burst,
ChatComposerConfig {
reset_vim_on_submission: false,
..ChatComposerConfig::plain_text()
},
);
composer.set_keymap_bindings(&keymap);
composer.set_footer_hint_override(Some(Vec::new()));
Self {
app_event_tx,
state: QuestionState::default(),
expanded: false,
has_queued_messages: false,
delivery_enabled: true,
submission: None,
visible_options: std::cell::Cell::new((0, 0)),
keymap,
other_selector: None,
composer,
}
}
fn current_question(&self) -> Option<&AsyncUserInputQuestion> {
self.current_answer().map(|answer| &answer.question)
}
fn current_answer_mut(&mut self) -> Option<&mut PendingQuestion> {
self.state.pending.get_mut(self.state.current_idx)
}
fn current_answer(&self) -> Option<&PendingQuestion> {
self.state.pending.get(self.state.current_idx)
}
pub(super) fn progress_prefix_text(&self) -> String {
let current = self.state.current_idx + 1;
let total = self.unanswered_count();
format!("{current} of {total}")
}
fn options(&self) -> &[String] {
self.current_question()
.and_then(|q| q.options.as_deref())
.unwrap_or_default()
}
fn has_options(&self) -> bool {
!self.options().is_empty()
}
fn options_len(&self) -> usize {
self.options().len() + usize::from(self.has_options())
}
fn option_index_for_digit(&self, ch: char) -> Option<usize> {
let idx = ch.to_digit(10)?.checked_sub(1)? as usize;
(idx < self.options_len()).then_some(idx)
}
fn selected_option_index(&self) -> Option<usize> {
self.current_answer()
.and_then(|answer| answer.options_state.selected_idx)
}
pub(super) fn wrapped_question_lines(&self, width: u16) -> Vec<HyperlinkLine> {
self.current_question()
.map(|question| render_markdown_for_viewport(&question.title, width))
.unwrap_or_default()
}
fn focus_is_notes(&self) -> bool {
!self.has_options() || self.other_selected()
}
pub(super) fn option_rows(&self, width: u16) -> Vec<GenericDisplayRow> {
if !self.has_options() {
return Vec::new();
};
let other = self.other_label();
self.options()
.iter()
.chain(std::iter::once(&other))
.enumerate()
.map(|(index, label)| {
let prefix = if self.selected_option_index() == Some(index) {
'›'
} else {
' '
};
let number = index + 1;
let prefix = format!("{prefix} {number}. ");
let indent = prefix.width();
let is_choice = index < self.options().len();
let mut row = GenericDisplayRow {
name: format!("{prefix}{label}"),
wrap_indent: Some(indent),
selection_style: is_choice.then(super::picker_style::selection_style),
..Default::default()
};
if is_choice && usize::from(width) > indent {
let lines = render_markdown_for_viewport(label, width - indent as u16);
row.wrapped_name =
prefix_hyperlink_lines(lines, prefix.into(), " ".repeat(indent).into());
}
row
})
.collect()
}
pub(super) fn options_required_height(&self, width: u16) -> u16 {
if !self.has_options() {
return 0;
}
let rows = self.option_rows(width);
if self.other_selected() {
let prefix = self.other_prefix_width(width);
measure_rows_height(
&rows[..rows.len() - 1],
&ScrollState::default(),
rows.len(),
width,
) + self
.composer
.inline_input_height(width.saturating_sub(prefix).max(1))
.clamp(1, 8)
} else {
measure_rows_height(&rows, &ScrollState::default(), rows.len(), width)
}
}
fn save_current_draft(&mut self) {
self.composer.flush_pending_input();
if self.focus_is_notes() {
let draft = self.composer.snapshot_draft();
if let Some(answer) = self.current_answer_mut() {
answer.draft = draft;
}
}
}
fn restore_current_draft(&mut self) {
self.sync_composer_placeholder();
let draft = self
.current_answer()
.map(|answer| answer.draft.clone())
.unwrap_or_default();
self.composer.restore_inline_draft(draft);
}
fn other_placeholder(&self) -> &'static str {
if self
.options()
.iter()
.any(|label| label.eq_ignore_ascii_case("Other"))
{
"Other (write an answer)"
} else {
OTHER_OPTION_LABEL
}
}
fn sync_composer_placeholder(&mut self) {
let text = if self.other_selected() {
self.other_placeholder()
} else {
"Type your answer"
};
self.composer.set_placeholder_text(text.to_string());
}
pub(crate) fn unanswered_count(&self) -> usize {
self.state.pending.len()
}
}
#[cfg(test)]
#[path = "state_tests.rs"]
mod tests;

View File

@@ -0,0 +1,238 @@
//! Lay out question text, choices, inline editing, and key hints within the available rows.
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::text::Span;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use crate::bottom_pane::selection_popup_common::menu_surface_inset;
use crate::bottom_pane::selection_popup_common::menu_surface_padding_height;
use crate::bottom_pane::selection_popup_common::render_menu_surface;
use crate::render::renderable::Renderable;
use crate::terminal_hyperlinks::HyperlinkParagraph;
use super::AsyncQuestions;
use super::TIP_SEPARATOR;
use crate::bottom_pane::request_user_input::render::render_rows_bottom_aligned;
use crate::bottom_pane::request_user_input::render::truncate_line_word_boundary_with_ellipsis;
use crate::keymap::KeymapContext;
impl Renderable for AsyncQuestions {
fn cursor_style(&self, area: Rect) -> crossterm::cursor::SetCursorStyle {
self.composer.cursor_style(area)
}
fn desired_height(&self, width: u16) -> u16 {
let width = menu_surface_inset(Rect::new(/*x*/ 0, /*y*/ 0, width, u16::MAX)).width;
let extra_height = self.options_required_height(width)
+ if !self.has_options() {
self.composer.inline_input_height(width).clamp(1, 8)
} else {
0
}
+ 2
+ u16::from(!self.has_options() && self.unanswered_count() > 1)
+ self.footer_lines(width, /*option_tip*/ None).len() as u16
+ u16::from(self.unanswered_count() > 1)
+ menu_surface_padding_height();
u16::try_from(self.wrapped_question_lines(width).len() + usize::from(extra_height))
.unwrap_or(u16::MAX)
}
fn render(&self, area: Rect, buf: &mut Buffer) {
self.visible_options.set((0, 0));
ratatui::widgets::Clear.render(area, buf);
let content_area = render_menu_surface(area, buf);
if content_area.is_empty() {
return;
}
let sections = self.layout_sections(content_area);
Paragraph::new(self.progress_prefix_text().dim()).render(sections.progress_area, buf);
HyperlinkParagraph::new(
&sections.question_lines,
crate::style::accent_style().not_bold(),
)
.render(sections.question_area, buf);
if self.other_selected() {
self.render_inline_options(sections.options_area, buf);
} else if self.has_options() && sections.options_area.height > 0 {
let option_rows = self.option_rows(sections.options_area.width);
let mut options_state = self.state.pending[self.state.current_idx].options_state;
let selected = options_state.selected_idx.unwrap_or(0);
let heights: Vec<_> = option_rows
.iter()
.map(|row| {
super::measure_rows_height(
std::slice::from_ref(row),
&super::ScrollState::default(),
/*max_results*/ 1,
sections.options_area.width,
)
})
.collect();
let available = sections.options_area.height;
if heights.iter().sum::<u16>() <= available {
options_state.scroll_top = 0;
}
let mut first = options_state.scroll_top.min(selected);
while first < selected && heights[first..=selected].iter().sum::<u16>() > available {
first += 1;
}
let mut used = 0;
let visible = heights[first..]
.iter()
.take_while(|&&height| {
used += height;
used <= available
})
.count();
options_state.scroll_top = first;
self.visible_options.set((first, visible));
render_rows_bottom_aligned(
sections.options_area,
buf,
&option_rows,
&options_state,
option_rows.len().max(1),
"No options",
);
}
if !self.has_options() {
self.composer.render_inline_input(sections.notes_area, buf);
}
let footer_area = Rect::new(
content_area.x,
sections.notes_area.bottom() + sections.spacer_after_input,
content_area.width,
sections.footer_lines,
);
let input_bottom = if self.other_selected() {
sections.options_area.bottom()
} else {
sections.notes_area.bottom()
};
if self.focus_is_notes()
&& footer_area.y > input_bottom
&& let Some(mode) = self.composer.vim_mode_indicator_span()
{
Line::from(mode).right_aligned().render(
Rect::new(
content_area.x,
footer_area.y - 1,
content_area.width,
/*height*/ 1,
),
buf,
);
}
let option_tip = sections.show_option_tip.then(|| self.option_tip());
let lines = self
.footer_lines(footer_area.width, option_tip)
.into_iter()
.map(|line| truncate_line_word_boundary_with_ellipsis(line, footer_area.width as usize))
.collect::<Vec<_>>();
Paragraph::new(lines).render(footer_area, buf);
}
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
if !self.focus_is_notes() {
return None;
}
let content_area = menu_surface_inset(area);
if content_area.width == 0 || content_area.height == 0 {
return None;
}
let sections = self.layout_sections(content_area);
let input_area = if self.other_selected() {
self.other_input_area(sections.options_area)
} else {
sections.notes_area
};
if input_area.width == 0 || input_area.height == 0 {
return None;
}
self.composer.inline_cursor_pos(input_area)
}
}
impl AsyncQuestions {
pub(super) fn footer_lines(
&self,
width: u16,
option_tip: Option<Span<'static>>,
) -> Vec<Line<'static>> {
if !self.focus_is_notes()
&& let Some(flash) = self.composer.inline_flash()
{
return vec![flash];
}
let mut tips = Vec::new();
let chat_hint = |action| self.keymap.primary_hint(KeymapContext::Chat, action);
let (context, action) = if self.focus_is_notes() {
(KeymapContext::Composer, "submit")
} else {
(KeymapContext::List, "accept")
};
// Existing cross-context keymaps keep chat priority in questions.
if let Some(key) = self.keymap.primary_hint(context, action)
&& (self.focus_is_notes()
|| !matches!(key, crate::key_hint::ShortcutHint::Single(binding)
if self.keymap.chat.interrupt_turn.contains(&binding)
|| self.keymap.chat.edit_queued_message.contains(&binding)))
{
tips.push(crate::footer_hint::shortcut(&key.display_label(), "submit"));
}
if let Some(key) = chat_hint("skip_question") {
tips.push(crate::footer_hint::shortcut(&key.display_label(), "skip"));
}
tips.extend(option_tip.map(Line::from));
if let Some(key) = chat_hint("prompt_stack_back") {
let label = if self.state.current_idx > 0 {
"prev question"
} else {
"main prompt"
};
tips.push(crate::footer_hint::shortcut(&key.display_label(), label));
}
let next = if self.state.current_idx + 1 < self.state.pending.len() {
Some("next question")
} else if self.has_queued_messages {
Some("queued messages")
} else {
None
};
if let Some(label) = next
&& let Some(key) = chat_hint("edit_queued_message")
{
tips.push(crate::footer_hint::shortcut(&key.display_label(), label));
}
let mut lines = Vec::new();
let mut line = Line::default();
for tip in tips {
if !line.spans.is_empty() {
if line.width() + TIP_SEPARATOR.len() + tip.width() > usize::from(width) {
lines.push(std::mem::take(&mut line));
} else {
line.spans.push(TIP_SEPARATOR.into());
}
}
line.spans.extend(tip.spans);
}
lines.push(line);
lines
}
pub(super) fn option_tip(&self) -> Span<'static> {
format!(
"option {}/{}",
self.selected_option_index().unwrap_or(0) + 1,
self.options_len()
)
.dim()
}
}

View File

@@ -0,0 +1,11 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: text
---
A lengthy prompt. A lengthy prompt.
A lengthy prompt. A lengthy prompt.
A lengthy prompt. A lengthy prompt.
A lengthy prompt. A lengthy prompt.
A lengthy prompt. A lengthy prompt.
visible answer

View File

@@ -0,0 +1,19 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&buffer)
---
Second
1. A suggested answer that is long enough to
wrap across multiple rows
› 2. long draft
long draft
long draft
long draft
long draft
long draft
long draft
enter submit ⌃] skip ⇧→ main prompt

View File

@@ -0,0 +1,11 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: "buffer_text(&render_editor(&editor, 50, 8))"
---
Second
› 2. A suggested answer that is long enough to
wrap across multiple rows
Expand terminal to read the entire option

View File

@@ -0,0 +1,7 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
assertion_line: 483
expression: buffer_text(&clipped)
---
Long question Long question Long question Long

View File

@@ -0,0 +1,15 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&buffer)
---
2 of 2
Second
11. Option 11
12. Option 12
› 13. earlier answer
reverse-i-search: e enter accept · esc
enter submit ⌃] skip option 13/13
⇧→ prev question

View File

@@ -0,0 +1,19 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
assertion_line: 220
expression: "rendered[0]"
---
1 of 2
Run this command:
printf '診 断 '
Then review the diagnostics
(https://example.com/diagnostics?view=full)?
Type your answer
enter submit ⌃] skip ⇧→ main prompt
⇧← next question

View File

@@ -0,0 +1,12 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&buffer)
---
2 of 2
Second
› 1. Other
2. Other (write an answer)
enter submit ⌃] skip ⇧→ prev question

View File

@@ -0,0 +1,11 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&buffer)
---
2 of
Secon
d
› x
ente…
⌃]…

View File

@@ -0,0 +1,23 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: "format!(\"Full height:\\n{}\\n\\nClipped:\\n{}\", buffer_text(&buffer),\nbuffer_text(&clipped),)"
---
Full height:
Second
› 1. abcdefgh
ijklmno
2. pqrstuvw
xyzabcd
3. Other
enter submit
⌃] skip
⇧→ main prompt
Clipped:
Second
› 1. abcdefgh

View File

@@ -0,0 +1,6 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&buffer)
---
2. pqrstuvw
› 3. Other

View File

@@ -0,0 +1,15 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&buffer)
---
2 of 2
Second
› 1. Option 1 is long enough to wrap across
rows
2. Option 2 is long enough to wrap across
rows
f9 submit ⌃] skip option 1/13
⇧→ prev question

View File

@@ -0,0 +1,14 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&buffer)
---
Second
› 1. A suggested answer that is
long enough to wrap across
multiple rows
2. Other
enter submit ⌃] skip
⇧→ main prompt

View File

@@ -0,0 +1,16 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&buffer)
---
Second
1. A suggested answer that is
long enough to wrap across
multiple rows
› 2. An alternative answer that
wraps across several option
rows
enter submit ⌃] skip
⇧→ main prompt

View File

@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
expression: buffer_text(&clipped)
---
Second
› 2. A suggested answer that is
long enough to wrap across
multiple rows
enter submit ⌃] skip
option 2/3 ⇧→ main prompt

View File

@@ -0,0 +1,16 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
assertion_line: 171
expression: "crate::terminal_hyperlinks::strip_osc8(&buffer_text(&buffer))"
---
2 of 2
Review this change
(https://github.com/openai/codex/
pull/12345?diff=split)?
› 1. Named
2. Other
enter submit ⌃] skip
⇧→ prev question

View File

@@ -0,0 +1,14 @@
---
source: tui/src/bottom_pane/async_questions/state_tests.rs
assertion_line: 253
expression: buffer_text(&buffer)
---
Long question Long question Long question Long
question Long question Long question Long
question Long question Long question Long
question Long question Long question Long
question Long question Long question Long
question Long question Long question Long
question Long question Long question Long
› 2. Other

View File

@@ -0,0 +1,283 @@
//! Pending async questions retain drafts until handled locally, answered by another client, or a live turn ends.
//! Message IDs survive removal so replay cannot reopen an answered or skipped question.
use super::*;
use crate::history_cell::sanitize_user_text;
use akode_context_fragments::AnsweredQuestion;
use akode_context_fragments::ContextualUserFragment;
use akode_utils_string::take_bytes_at_char_boundary;
// Match the model-authored title budget used by AnsweredQuestion.
const MAX_RECOVERED_QUESTION_TITLE_BYTES: usize = 512;
impl AsyncQuestions {
pub(crate) fn append(&mut self, message_id: &str, questions: &[AsyncUserInputQuestion]) {
if questions.is_empty() || !self.state.seen_ids.insert(message_id.to_string()) {
return;
}
let was_empty = self.state.pending.is_empty();
let expires_at = (!self.expanded).then(|| Instant::now() + Duration::from_secs(30));
for (index, question) in questions.iter().enumerate() {
// Match the desktop's JSON.stringify([tool name, item id, question index]).
let question_id =
serde_json::json!(["request_user_input_async", message_id, index]).to_string();
if self.state.answered_ids.contains(&question_id)
|| self.state.answered_ids.contains(message_id)
{
continue;
}
// Bound work before cloning or wrapping model-authored suggestions.
let question = AsyncUserInputQuestion {
title: question.title.clone(),
options: question.options.as_ref().map(|options| {
options
.iter()
.take(32)
.filter(|label| label.len() <= 512)
.cloned()
.collect()
}),
};
let has_options = question
.options
.as_ref()
.is_some_and(|options| !options.is_empty());
let mut options_state = ScrollState::new();
options_state.selected_idx = has_options.then_some(0);
self.state.pending.push(PendingQuestion {
message_id: message_id.into(),
question_id,
question,
options_state,
draft: ComposerDraft::default(),
expires_at,
});
}
if was_empty {
self.state.current_idx = 0;
self.restore_current_draft();
}
}
pub(crate) fn set_expanded(&mut self, expanded: bool) {
self.save_current_draft();
self.expanded = expanded && !self.state.pending.is_empty();
if self.expanded {
self.snooze_auto_resolution();
}
}
pub(crate) fn navigate(&mut self, forward: bool) -> bool {
let next = if forward {
self.state.current_idx.checked_add(1)
} else {
self.state.current_idx.checked_sub(1)
};
let Some(next) = next.filter(|&index| index < self.state.pending.len()) else {
return false;
};
self.save_current_draft();
self.visible_options.set((0, 0));
self.state.current_idx = next;
self.restore_current_draft();
true
}
pub(super) fn snooze_auto_resolution(&mut self) {
for question in &mut self.state.pending {
question.expires_at = None;
}
}
pub(super) fn timer_remaining(&self, now: Instant) -> Option<Duration> {
self.state
.pending
.iter()
.filter_map(|question| question.expires_at?.checked_duration_since(now))
.filter(|remaining| !remaining.is_zero())
.min()
}
pub(crate) fn countdown(&self, now: Instant) -> Option<String> {
self.timer_remaining(now)
.filter(|remaining| *remaining <= Duration::from_secs(20))
.map(|remaining| format!("{}s", remaining.as_secs_f64().ceil() as u64))
}
pub(super) fn go_next_or_submit(&mut self) {
self.save_current_draft();
if !self.delivery_enabled {
return;
}
let Some(answer) = self.current_answer() else {
return;
};
let selected = answer
.options_state
.selected_idx
.and_then(|index| answer.question.options.as_ref()?.get(index))
.map(String::as_str)
.unwrap_or_default();
// Only a fully displayed model-authored option may become user authorization.
let (first, count) = self.visible_options.get();
let index = self.selected_option_index().unwrap_or(0);
if !self.focus_is_notes() && !(first..first + count).contains(&index) {
self.composer.show_footer_flash(
"Expand terminal to read the entire option".into(),
Duration::from_secs(5),
);
return;
}
let text = if self.focus_is_notes() {
answer.draft.text_with_pending()
} else {
selected.to_string()
};
let text = text.trim();
if text.is_empty() {
return;
}
let reply = AnsweredQuestion::new(&answer.question_id, &answer.question.title, text)
.render()
.into_text()
.unwrap_or_default();
if reply.chars().count() > akode_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS {
self.composer.show_footer_flash(
"Answer too long; shorten it before sending".into(),
Duration::from_secs(5),
);
} else {
self.submission = Some(QuestionSubmission::Submit(reply));
}
}
/// Return whether resolving these answers changed the expanded question's input target.
pub(crate) fn resolve_answers(&mut self, question_ids: &[String]) -> bool {
// History can arrive before live questions or before restoring local drafts.
self.state.answered_ids.extend(question_ids.iter().cloned());
// Older desktop replies identify the whole source message instead of one question.
let answered = |question: &PendingQuestion| {
question_ids.contains(&question.question_id)
|| question_ids.contains(&question.message_id)
};
if !self.state.pending.iter().any(answered) {
return false;
}
let current_answered = self.current_answer().is_some_and(answered);
let displayed_answer_changed = self.expanded && current_answered;
if current_answered {
self.composer.flush_pending_input();
}
let current_idx = self
.state
.pending
.iter()
.take(self.state.current_idx)
.filter(|question| !answered(question))
.count();
self.state.pending.retain(|question| !answered(question));
self.state.current_idx = if current_idx < self.state.pending.len() {
current_idx
} else {
0
};
self.expanded &= !self.state.pending.is_empty();
self.visible_options.set((0, 0));
if current_answered {
self.restore_current_draft();
self.composer.reset_vim_mode();
}
displayed_answer_changed
}
pub(crate) fn accept_answer(&mut self) {
if self.state.pending.is_empty() {
return;
}
self.composer.flush_pending_input();
self.visible_options.set((0, 0));
self.state.pending.remove(self.state.current_idx);
if self.state.current_idx >= self.state.pending.len() {
self.state.current_idx = 0;
}
self.expanded &= !self.state.pending.is_empty();
self.restore_current_draft();
self.composer.reset_vim_mode();
}
pub(crate) fn clear_pending(&mut self) {
// Keep seen_ids so replay cannot restore questions from the previous prompt.
self.state.pending.clear();
self.state.current_idx = 0;
self.expanded = false;
self.submission = None;
self.visible_options.set((0, 0));
self.restore_current_draft();
self.composer.reset_vim_mode();
}
/// Recover unsent typed answers with their quoted questions before clearing pending questions.
pub(crate) fn take_pending_drafts(&mut self) -> Vec<String> {
self.save_current_draft();
let drafts = self
.state
.pending
.iter()
.filter_map(PendingQuestion::recovered_draft)
.collect();
self.clear_pending();
drafts
}
pub(crate) fn capture(&mut self) -> QuestionState {
self.composer.cancel_history_search();
self.save_current_draft();
self.state.expanded = self.expanded;
self.state.clone()
}
pub(crate) fn restore(&mut self, saved: QuestionState) {
self.visible_options.set((0, 0));
let incoming = std::mem::replace(&mut self.state, saved);
let mut answered_ids = incoming.answered_ids;
answered_ids.extend(self.state.answered_ids.iter().cloned());
self.state.pending.extend(
incoming
.pending
.into_iter()
.filter(|question| !self.state.seen_ids.contains(&question.message_id)),
);
self.state.seen_ids.extend(incoming.seen_ids);
self.expanded = self.state.expanded && !self.state.pending.is_empty();
if self.expanded {
self.snooze_auto_resolution();
}
self.restore_current_draft();
self.resolve_answers(&answered_ids.into_iter().collect::<Vec<_>>());
}
}
impl PendingQuestion {
fn recovered_draft(&self) -> Option<String> {
let answer = self.draft.text_with_pending();
let answer = answer.trim();
if answer.is_empty() {
return None;
}
let title = &self.question.title;
let prefix = take_bytes_at_char_boundary(title, MAX_RECOVERED_QUESTION_TITLE_BYTES);
let sanitized = sanitize_user_text(prefix.into());
let mut quoted = textwrap::indent(&sanitized, "> ");
if quoted.ends_with('\n') {
quoted.pop();
}
if quoted.is_empty() {
quoted.push_str("> ");
}
if prefix.len() < title.len() {
quoted.push('…');
}
Some(format!("{quoted}\n\n{answer}"))
}
}

View File

@@ -0,0 +1,658 @@
//! Exercise question drafts, selection, and the constrained terminal viewport.
use super::*;
use crate::render::renderable::Renderable;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
fn editor() -> AsyncQuestions {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let mut editor = AsyncQuestions::new(
AppEventSender::new(tx),
/*has_input_focus*/ true,
/*enhanced_keys_supported*/ true,
/*disable_paste_burst*/ true,
RuntimeKeymap::defaults(),
);
editor.append(
"message",
&[
question("First", /*options*/ None),
question("Second", Some(vec!["Named".into()])),
],
);
editor
}
#[test]
fn taking_pending_drafts_preserves_order_expands_pastes_and_skips_blank_drafts() {
let mut editor = editor();
editor.state.pending[0].question.title = "First\n\n".into();
editor.set_expanded(/*expanded*/ true);
let large_answer = "typed answer ".repeat(/*n*/ 200);
editor.handle_paste(large_answer.clone());
editor.navigate(/*forward*/ true);
editor.handle_key_event(KeyEvent::from(KeyCode::Char('2')));
editor.handle_paste(" other answer ".into());
editor.append("blank", &[question("Blank?", /*options*/ None)]);
assert_eq!(
editor.take_pending_drafts(),
vec![
format!("> First\n>\n\n{}", large_answer.trim()),
"> Second\n\nother answer".to_string()
]
);
assert_eq!((editor.unanswered_count(), editor.expanded), (0, false));
assert!(editor.submission.is_none());
}
#[test]
fn taking_pending_drafts_bounds_question_titles_without_truncating_answers() {
for (character, retained_count) in [("a", 512), ("界", 170), ("\x07", 0)] {
let mut editor = editor();
editor.state.pending[0].question.title =
character.repeat(akode_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS + 1);
let answer = "typed answer ".repeat(/*n*/ 200);
editor.handle_paste(answer.clone());
assert_eq!(
editor.take_pending_drafts(),
vec![format!(
"> {}…\n\n{}",
character.repeat(retained_count),
answer.trim(),
)]
);
}
}
#[test]
fn replay_preserves_drafts_and_does_not_reopen_handled_questions() {
let mut original = editor();
original.set_expanded(/*expanded*/ true);
original.accept_answer();
original.handle_key_event(KeyEvent::from(KeyCode::Char('2')));
let saved = original.capture();
for replay_first in [false, true] {
let mut restored = editor();
if !replay_first {
restored.state = QuestionState::default();
}
restored.restore(saved.clone());
restored.append("message", &[question("First", /*options*/ None)]);
assert_eq!(restored.capture(), saved);
restored.accept_answer();
restored.append("message", &[question("First", /*options*/ None)]);
assert_eq!(restored.unanswered_count(), 0);
}
}
#[test]
fn arrival_preserves_vim_undo_and_navigation_flushes_buffered_input() {
let mut editor = editor();
editor.set_expanded(/*expanded*/ true);
editor.set_vim_enabled(/*enabled*/ true);
editor.handle_key_event(KeyEvent::from(KeyCode::Char('i')));
editor.handle_paste("draft".into());
editor.handle_key_event(KeyEvent::from(KeyCode::Esc));
editor.append("new", &[question("New", /*options*/ None)]);
editor.handle_key_event(KeyEvent::from(KeyCode::Char('u')));
assert_eq!(editor.composer.current_text(), "");
editor.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
assert_eq!(editor.composer.current_text(), "draft");
editor.set_vim_enabled(/*enabled*/ false);
editor.composer.set_disable_paste_burst(/*disabled*/ false);
editor.composer.move_cursor_to_end();
for ch in "buffered".chars() {
editor.handle_key_event(KeyEvent::from(KeyCode::Char(ch)));
}
assert!(editor.composer.is_in_paste_burst());
editor.navigate(/*forward*/ true);
editor.navigate(/*forward*/ false);
assert_eq!(editor.composer.current_text_with_pending(), "draftbuffered");
for ch in "skipped".chars() {
editor.handle_key_event(KeyEvent::from(KeyCode::Char(ch)));
}
assert!(editor.composer.is_in_paste_burst());
editor.handle_key_event(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::CONTROL));
editor.composer.flush_pending_input();
assert_eq!(
(
editor.current_question().unwrap().title.as_str(),
editor.composer.current_text()
),
("Second", String::new())
);
}
#[test]
fn long_prompt_keeps_the_active_input_visible() {
let mut editor = editor();
editor.state.pending[0].question.title = "A lengthy prompt. ".repeat(30);
editor.handle_paste("visible answer".into());
let buffer = render_editor(&editor, /*width*/ 40, /*height*/ 8);
let text = buffer_text(&buffer);
assert!(text.contains("visible answer"));
insta::assert_snapshot!("long_prompt_active_input", text);
}
#[test]
fn wrapped_question_url_keeps_its_complete_destination() {
let url = "https://github.com/openai/codex/pull/12345?diff=split";
let mut editor = editor();
editor.navigate(/*forward*/ true);
editor.state.pending[1].question.title = format!("Review this change ({url})?");
let width = 40;
let full_height = editor.desired_height(width);
for height in [full_height, 4] {
let buffer = render_editor(&editor, width, height);
let linked_text = buffer
.content
.iter()
.filter_map(|cell| {
let symbol = cell.symbol();
symbol.contains("\x1b]8;;").then(|| {
let text = crate::terminal_hyperlinks::strip_osc8(symbol);
assert_eq!(
symbol,
crate::terminal_hyperlinks::osc8_hyperlink(url, &text)
);
text
})
})
.collect::<String>();
if height == full_height {
assert_eq!(linked_text, url);
insta::assert_snapshot!(
"question_wrapped_url",
crate::terminal_hyperlinks::strip_osc8(&buffer_text(&buffer))
);
} else {
assert!(!linked_text.is_empty());
assert!(url.starts_with(&linked_text));
assert_ne!(linked_text, url);
}
}
}
#[test]
fn markdown_question_preserves_formatting_and_link_destinations() {
let url = "https://example.com/diagnostics?view=full";
let title = format!(
"Run **this command**:\n\n```sh\nprintf '診断'\n```\nThen review the [diagnostics]({url})?\n"
);
let mut rendered = Vec::new();
for line_ending in ["\n", "\r\n"] {
let mut editor = editor();
editor.state.pending[0].question.title = title.replace('\n', line_ending);
for width in [20, 60] {
let height = editor.desired_height(width);
let buffer = render_editor(&editor, width, height);
let linked_text = buffer
.content
.iter()
.filter_map(|cell| {
let symbol = cell.symbol();
symbol.contains("\x1b]8;;").then(|| {
let text = crate::terminal_hyperlinks::strip_osc8(symbol);
assert_eq!(
symbol,
crate::terminal_hyperlinks::osc8_hyperlink(url, &text)
);
text
})
})
.collect::<String>();
assert!(linked_text.contains("diagnostics"));
let text = crate::terminal_hyperlinks::strip_osc8(&buffer_text(&buffer));
if width == 60 {
let bold_text = buffer
.content
.iter()
.filter(|cell| cell.modifier.contains(Modifier::BOLD))
.map(ratatui::buffer::Cell::symbol)
.collect::<String>();
assert!(bold_text.contains("this command"));
assert!(!bold_text.contains("Run "));
rendered.push(text);
}
}
}
assert_eq!(rendered[0], rendered[1]);
insta::assert_snapshot!("question_multiline", rendered[0]);
}
#[test]
fn selected_other_renders_as_a_dim_placeholder() {
let mut editor = editor();
editor.navigate(/*forward*/ true);
editor.handle_key_event(KeyEvent::from(KeyCode::Char('2')));
let mut repeat = KeyEvent::from(KeyCode::Char('2'));
repeat.kind = KeyEventKind::Repeat;
editor.handle_key_event(repeat);
assert!(editor.composer.is_empty());
editor.handle_paste("saved".into());
editor.handle_key_event(KeyEvent::from(KeyCode::Up));
editor.handle_key_event(KeyEvent::from(KeyCode::Char('2')));
editor.handle_key_event(repeat);
assert_eq!(editor.composer.current_text(), "saved");
editor.handle_key_event(KeyEvent::from(KeyCode::Char('2')));
editor.handle_key_event(repeat);
assert_eq!(editor.composer.current_text(), "saved22");
editor.on_ctrl_c();
editor.state.pending[1].question.title = "Long question ".repeat(40);
let buffer = render_editor(&editor, /*width*/ 50, /*height*/ 10);
let area = buffer.area;
assert!(editor.cursor_pos(area).is_some());
let input = editor.other_input_area(
editor
.layout_sections(crate::bottom_pane::selection_popup_common::menu_surface_inset(area))
.options_area,
);
for offset in 0..5 {
assert_eq!(buffer[(input.x + offset, input.y)].modifier, Modifier::DIM);
}
insta::assert_snapshot!("selected_other_placeholder", buffer_text(&buffer));
editor.state.pending[1].question.title = "Second".into();
render_editor(&editor, /*width*/ 50, /*height*/ 10);
editor.set_vim_enabled(/*enabled*/ true);
editor.handle_key_event(KeyEvent::from(KeyCode::Char('i')));
editor.handle_paste("draft".into());
editor.handle_key_event(KeyEvent::from(KeyCode::Esc));
editor.handle_key_event(KeyEvent::from(KeyCode::Up));
assert_eq!(editor.selected_option_index(), Some(0));
editor.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert!(editor.submission.take().is_some());
editor.handle_key_event(KeyEvent::from(KeyCode::Char('x')));
editor.handle_key_event(KeyEvent::from(KeyCode::Esc));
for _ in 0..2 {
editor.handle_key_event(KeyEvent::from(KeyCode::Char('u')));
}
assert_eq!(editor.composer.current_text(), "");
}
fn buffer_text(buffer: &ratatui::buffer::Buffer) -> String {
(buffer.area.y..buffer.area.bottom())
.map(|y| {
(buffer.area.x..buffer.area.right())
.map(|x| buffer[(x, y)].symbol())
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn question_choice_remaps_paging_and_inline_feedback() {
use akode_config::types::KeybindingSpec;
use akode_config::types::KeybindingsSpec;
use akode_config::types::TuiKeymap;
let mut editor = editor();
editor.navigate(/*forward*/ true);
editor.state.pending[1].question.options = Some(
(1..=12)
.map(|i| format!("Option {i} is long enough to wrap across rows"))
.collect(),
);
let mut config = TuiKeymap::default();
config.list.move_down = Some(KeybindingsSpec::One(KeybindingSpec("x".into())));
config.list.accept = Some(KeybindingsSpec::One(KeybindingSpec("f9".into())));
config.list.jump_top = Some(KeybindingsSpec::One(KeybindingSpec("7".into())));
editor.set_keymap(&RuntimeKeymap::from_config(&config).unwrap());
editor.handle_key_event(KeyEvent::from(KeyCode::Down));
assert_eq!(editor.selected_option_index(), Some(0));
editor.handle_key_event(KeyEvent::from(KeyCode::Char('x')));
assert_eq!(editor.selected_option_index(), Some(1));
let mut buffer = render_editor(&editor, /*width*/ 50, /*height*/ 12);
let area = buffer.area;
let visible = editor.visible_options.get().1;
assert_eq!(visible, 2);
editor.handle_key_event(KeyEvent::from(KeyCode::PageDown));
assert_eq!(editor.selected_option_index(), Some(1 + visible));
editor.handle_key_event(KeyEvent::from(KeyCode::Char('7')));
assert_eq!(editor.selected_option_index(), Some(0));
editor.handle_key_event(KeyEvent::from(KeyCode::Char('7')));
assert_eq!(editor.selected_option_index(), Some(0));
editor.render(area, &mut buffer);
insta::assert_snapshot!("question_remapped_choice_footer", buffer_text(&buffer));
}
#[test]
fn question_inline_history_search() {
let mut editor = editor();
editor.navigate(/*forward*/ true);
editor.state.pending[1].question.options =
Some((1..=12).map(|i| format!("Option {i}")).collect());
editor.select_option(/*index*/ 12);
editor
.composer
.record_replayed_user_message_history(crate::bottom_pane::HistoryEntry::new(
"earlier answer".into(),
));
editor.handle_paste("original answer".into());
let saved = editor.capture();
editor.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
editor.handle_key_event(KeyEvent::from(KeyCode::Char('e')));
let buffer = render_editor(&editor, /*width*/ 50, /*height*/ 12);
assert!(
buffer
.content
.iter()
.any(|cell| cell.modifier.contains(Modifier::REVERSED))
);
insta::assert_snapshot!("question_inline_history_search", buffer_text(&buffer));
assert_eq!(editor.capture(), saved);
}
#[test]
fn question_other_remains_visible_at_nine_columns_and_distinguishes_named_other() {
let mut editor = editor();
editor.navigate(/*forward*/ true);
editor.state.pending[1].question.options = Some(vec!["Other".into()]);
editor.handle_paste("other".into());
editor.on_ctrl_c();
editor.handle_key_event(KeyEvent::from(KeyCode::Up));
let buffer = render_editor(&editor, /*width*/ 50, /*height*/ 12);
insta::assert_snapshot!("question_named_other", buffer_text(&buffer));
editor.select_option(/*index*/ 1);
editor.handle_paste("x".into());
let buffer = render_editor(&editor, /*width*/ 9, /*height*/ 8);
let narrow = buffer.area;
assert!(editor.cursor_pos(narrow).is_some());
assert!(buffer.content.iter().any(|cell| cell.symbol() == "x"));
insta::assert_snapshot!("question_narrow_other", buffer_text(&buffer));
}
#[test]
fn question_options_reserve_wrapped_height_at_the_width_boundary() {
let mut editor = editor();
editor.state.pending.remove(/*index*/ 0);
editor.state.pending[0].question.options =
Some(vec!["abcdefgh *ijklmno*".into(), "pqrstuvw xyzabcd".into()]);
editor.restore_current_draft();
// The five-column option prefix makes each named choice exactly 21 columns.
assert_eq!(
(
editor.options_required_height(/*width*/ 20),
editor.options_required_height(/*width*/ 21),
),
(5, 3)
);
let width = 24;
let buffer = render_editor(&editor, width, editor.desired_height(width));
assert_eq!(editor.visible_options.get(), (0, 3));
// Two padding rows and the question leave only one line of the selected two-line option.
let clipped = render_editor(&editor, width, /*height*/ 4);
assert_eq!(editor.visible_options.get(), (0, 0));
editor.go_next_or_submit();
assert!(editor.submission.is_none());
insta::assert_snapshot!(
"question_options_width_boundary",
format!(
"Full height:\n{}\n\nClipped:\n{}",
buffer_text(&buffer),
buffer_text(&clipped),
)
);
}
#[test]
fn question_other_excludes_clipped_options_at_the_width_boundary() {
let mut editor = editor();
editor.state.pending.remove(/*index*/ 0);
editor.state.pending[0].question.options =
Some(vec!["abcdefgh ijklmno".into(), "pqrstuvw xyzabcd".into()]);
editor.select_option(/*index*/ 2);
// Other keeps one input row, leaving too little room for a complete named choice.
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 20, /*height*/ 2,
);
let mut buffer = Buffer::empty(area);
editor.render_inline_options(area, &mut buffer);
assert_eq!(editor.visible_options.get(), (0, 0));
insta::assert_snapshot!(
"question_other_clipped_width_boundary",
buffer_text(&buffer)
);
}
#[test]
fn question_wrapped_options_and_other_share_the_text_indent() {
let mut editor = editor();
editor.state.pending.remove(0);
editor.state.pending[0].question.options = Some(vec![
"A suggested answer that is long enough to wrap across multiple rows".into(),
]);
editor.restore_current_draft();
let buffer = render_editor(&editor, /*width*/ 36, /*height*/ 16);
insta::assert_snapshot!("question_wrapped_named_option", buffer_text(&buffer));
let options = editor.state.pending[0].question.options.as_mut().unwrap();
options.insert(
0,
"Another suggested answer that wraps over several rows before the selected option".into(),
);
editor.select_option(/*index*/ 1);
let clipped = render_editor(&editor, /*width*/ 36, /*height*/ 10);
insta::assert_snapshot!("question_wrapped_selected_option", buffer_text(&clipped));
render_editor(&editor, /*width*/ 0, /*height*/ 0);
editor.go_next_or_submit();
assert!(editor.submission.is_none());
render_editor(&editor, /*width*/ 36, /*height*/ 6);
editor.go_next_or_submit();
assert!(editor.submission.is_none());
insta::assert_snapshot!(
"question_clipped_choice_rejected",
buffer_text(&render_editor(
&editor, /*width*/ 50, /*height*/ 8
))
);
render_editor(&editor, /*width*/ 80, /*height*/ 20);
editor.go_next_or_submit();
assert!(editor.submission.take().is_some());
editor.append(
"many",
&[question("Bounded", Some(vec!["x".repeat(41); 1000]))],
);
editor.navigate(/*forward*/ true);
assert_eq!(editor.options().len(), 32);
render_editor(&editor, /*width*/ 50, /*height*/ 10);
let height = editor.desired_height(/*width*/ 50);
assert_eq!(editor.visible_options.get().1, 2);
editor.handle_key_event(KeyEvent::from(KeyCode::End));
assert_eq!(editor.desired_height(/*width*/ 50), height);
assert_eq!(
editor.current_answer().unwrap().options_state,
ScrollState {
selected_idx: Some(editor.options_len() - 1),
scroll_top: editor.options_len() - editor.visible_options.get().1,
}
);
editor.handle_key_event(KeyEvent::from(KeyCode::Up));
render_editor(&editor, /*width*/ 80, /*height*/ 80);
assert_eq!(editor.visible_options.get(), (0, editor.options_len()));
editor.state.pending[editor.state.current_idx]
.question
.title = "Long question ".repeat(3 * 65_536);
assert_eq!(editor.desired_height(/*width*/ 50), u16::MAX);
let clipped = render_editor(&editor, /*width*/ 50, /*height*/ 3);
editor.go_next_or_submit();
assert!(editor.submission.is_none());
insta::assert_snapshot!("question_clipped_prompt", buffer_text(&clipped));
editor.state.pending.last_mut().unwrap().question.title = "Question".into();
for action in ["move_left", "move_right", "cancel"] {
let config = toml::from_str(&format!("[list]\n{action} = '1'")).unwrap();
editor.set_keymap(&RuntimeKeymap::from_config(&config).unwrap());
editor.set_expanded(/*expanded*/ true);
render_editor(&editor, /*width*/ 80, /*height*/ 80);
for modifiers in [KeyModifiers::CONTROL, KeyModifiers::ALT] {
editor.handle_key_event(KeyEvent::new(KeyCode::Char('1'), modifiers));
assert!(editor.submission.is_none());
}
editor.handle_key_event(KeyEvent::from(KeyCode::Char('1')));
assert_eq!(editor.expanded, action != "cancel");
assert!(editor.submission.is_none());
}
}
#[test]
fn question_wrapped_other_shares_the_text_indent() {
let mut editor = editor();
editor.state.pending.remove(0);
editor.state.pending[0].question.options = Some(vec![
"A suggested answer that is long enough to wrap across multiple rows".into(),
]);
editor.select_option(/*index*/ 1);
editor.handle_paste("An alternative answer that wraps across several option rows".into());
let buffer = render_editor(&editor, /*width*/ 36, /*height*/ 16);
insta::assert_snapshot!("question_wrapped_other", buffer_text(&buffer));
editor.composer.clear_for_ctrl_c();
editor.handle_paste(" \n ".into());
editor.select_option(/*index*/ 0);
assert_eq!(editor.other_label(), "Other");
editor.select_option(/*index*/ 1);
editor
.composer
.set_text_content("long draft\n".repeat(1000), Vec::new(), Vec::new());
editor.composer.move_cursor_to_end();
let buffer = render_editor(&editor, /*width*/ 50, /*height*/ 18);
assert_eq!(editor.cursor_pos(buffer.area), Some((7, 12)));
insta::assert_snapshot!("question_capped_other", buffer_text(&buffer));
editor.select_option(/*index*/ 0);
assert!(editor.other_label().len() <= 128);
editor.state.pending[0].draft.text = format!("a{}", "\u{301}".repeat(10_000));
assert!(editor.other_label().len() <= 512);
}
fn question(title: &str, options: Option<Vec<String>>) -> AsyncUserInputQuestion {
AsyncUserInputQuestion {
title: title.into(),
options,
}
}
fn render_editor(editor: &AsyncQuestions, width: u16, height: u16) -> Buffer {
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let mut buffer = Buffer::empty(area);
editor.render(area, &mut buffer);
buffer
}
#[test]
fn existing_cross_context_keymaps_load_without_misleading_submit_hints() {
for action in ["interrupt_turn", "edit_queued_message"] {
let config =
toml::from_str(&format!("[chat]\n{action} = 'f12'\n[list]\naccept = 'f12'")).unwrap();
let keymap = RuntimeKeymap::from_config(&config).unwrap();
let mut editor = editor();
editor.navigate(/*forward*/ true);
editor.set_keymap(&keymap);
insta::allow_duplicates! { insta::assert_snapshot!(editor.footer_lines(/*width*/ 100, /*option_tip*/ None)[0].to_string(), @"⌃] skip ⇧→ prev question"); }
editor.handle_key_event(KeyEvent::from(KeyCode::F(12)));
assert!(editor.submission.is_none());
}
}
#[test]
fn question_navigation_resets_history_recall() {
let mut editor = editor();
for text in ["older", "newer"] {
editor.composer.record_replayed_user_message_history(
crate::bottom_pane::HistoryEntry::new(text.into()),
);
}
editor.handle_key_event(KeyCode::Up.into());
assert_eq!(editor.composer.current_text(), "newer");
editor.navigate(/*forward*/ true);
editor.navigate(/*forward*/ false);
editor.handle_key_event(KeyCode::Up.into());
assert_eq!(editor.composer.current_text(), "newer");
}
#[test]
fn named_choices_share_selection_while_other_keeps_its_inline_cursor() {
crate::terminal_palette::with_test_default_colors(
crate::terminal_probe::DefaultColors {
fg: (30, 30, 30),
bg: (255, 255, 255),
},
|| {
let mut editor = editor();
editor.navigate(/*forward*/ true);
editor.state.pending[1].question.options =
Some(vec!["*Named* [guide](https://example.com)".into()]);
let linked_g = crate::terminal_hyperlinks::osc8_hyperlink("https://example.com", "g");
for width in [40, 80] {
editor.select_option(/*index*/ 0);
let buffer = render_editor(&editor, width, /*height*/ 16);
assert!(buffer.content.iter().any(|cell| cell.symbol() == linked_g));
let cell = buffer
.content
.iter()
.find(|cell| cell.symbol() == "N")
.unwrap();
assert_eq!(cell.bg, crate::bottom_pane::selection_style().bg.unwrap());
assert!(cell.modifier.contains(Modifier::ITALIC));
editor.select_option(/*index*/ 1);
let buffer = render_editor(&editor, width, /*height*/ 16);
let cursor = editor.cursor_pos(buffer.area).unwrap();
assert_eq!(buffer[cursor].symbol(), "O");
assert_ne!(
buffer[cursor].bg,
crate::bottom_pane::selection_style().bg.unwrap()
);
}
},
);
}
#[test]
fn answered_questions_do_not_reopen_when_history_precedes_local_drafts() {
let mut original = editor();
let saved = original.capture();
original.resolve_answers(&["unknown".into()]);
assert_eq!(original.state.pending, saved.pending);
let mut restored = editor();
restored.state = QuestionState::default();
restored.resolve_answers(&[r#"["request_user_input_async","message",0]"#.into()]);
restored.append(
"message",
&[
question("First", /*options*/ None),
question("Second", /*options*/ None),
],
);
assert_eq!(restored.unanswered_count(), 1);
restored.restore(saved);
assert_eq!(restored.state.pending, original.state.pending[1..]);
// Legacy desktop replies refer to the entire source message.
restored.resolve_answers(&["message".into()]);
assert_eq!(restored.unanswered_count(), 0);
assert!(restored.composer.is_empty());
}
#[test]
fn oversized_question_ids_keep_questions_answerable_without_echoing_the_id() {
let mut editor = editor();
editor.clear_pending();
editor.append(&"x".repeat(1024), &[question("Question", /*options*/ None)]);
assert_eq!(editor.unanswered_count(), 1);
editor.set_expanded(/*expanded*/ true);
editor.handle_paste("Answer".into());
render_editor(&editor, /*width*/ 80, /*height*/ 20);
editor.go_next_or_submit();
let Some(QuestionSubmission::Submit(reply)) = editor.submission else {
panic!("submitted answer");
};
assert_eq!(reply, "> Question\n\nAnswer");
}

View File

@@ -0,0 +1,249 @@
use crate::app::app_server_requests::ResolvedAppServerRequest;
use crate::bottom_pane::ApprovalRequest;
use crate::bottom_pane::McpServerElicitationFormRequest;
use crate::key_hint::KeyBinding;
use crate::keymap::KeymapContextSet;
use crate::render::renderable::Renderable;
use crate::terminal_program_status::ProgramStatusKind;
use akode_app_server_protocol::ToolRequestUserInputParams;
use crossterm::event::KeyEvent;
use std::time::Instant;
use super::CancellationEvent;
/// Reason an active bottom-pane view finished.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ViewCompletion {
Accepted,
Cancelled,
}
/// How a view is placed over the preceding view in the bottom-pane stack.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum ViewPresentation {
#[default]
Inline,
Centered,
}
/// Trait implemented by every view that can be shown in the bottom pane.
pub(crate) trait BottomPaneView: Renderable {
/// Centered views preserve the preceding view as their backdrop.
fn presentation(&self) -> ViewPresentation {
ViewPresentation::Inline
}
/// Refresh an open configuration panel, including one below a child editor.
/// Returns whether this view contains a configuration panel.
fn update_config_panel(&mut self, _update: &crate::config_panel::ConfigPanelUpdate) -> bool {
false
}
/// Acknowledge that a queued configuration editor has opened.
fn config_editor_opened(&mut self) {}
/// Mark a queued editor activation inactive after a non-key interaction.
fn interrupt_config_editor_transition(&mut self) {}
/// Handle a key event while the view is active. A redraw is always
/// scheduled after this call.
fn handle_key_event(&mut self, _key_event: KeyEvent) {}
/// Handle a configured action while preserving the physical key that triggered it.
fn handle_key_event_with_activation_key(
&mut self,
key_event: KeyEvent,
_activation_key: Option<KeyBinding>,
) {
self.handle_key_event(key_event);
}
/// Observe a press or repeat while another view is on top without handling it as input.
fn observe_key_event_while_covered(
&mut self,
_key_event: KeyEvent,
_activation_key: KeyBinding,
) {
}
/// Observe key releases that the bottom pane otherwise filters before view dispatch.
fn handle_key_release(&mut self, _key_event: KeyEvent) {}
/// Return the keymap contexts whose handlers are active in this view.
fn keymap_contexts(&self) -> KeymapContextSet {
KeymapContextSet::default()
}
/// Whether this local-only view can continue handling input while disconnected.
fn accepts_input_when_disconnected(&self) -> bool {
false
}
/// Return `true` if the view has finished and should be removed.
fn is_complete(&self) -> bool {
false
}
/// Return the completion reason once the view has finished.
fn completion(&self) -> Option<ViewCompletion> {
None
}
/// Return true when this view should be removed after a child view is accepted.
fn dismiss_after_child_accept(&self) -> bool {
false
}
/// Clear any pending child-flow cleanup marker after a child view is cancelled.
fn clear_dismiss_after_child_accept(&mut self) {}
/// Stable identifier for views that need external refreshes while open.
fn view_id(&self) -> Option<&'static str> {
None
}
/// Actual item index for list-based views that want to preserve selection
/// across external refreshes.
fn selected_index(&self) -> Option<usize> {
None
}
/// Current toggle values for list items that preserve local choices across refreshes.
fn selection_toggle_states(&self) -> Vec<Option<super::SelectionToggleState>> {
Vec::new()
}
/// Mark one previously emitted toggle action as complete.
fn complete_selection_toggle(&mut self, _index: usize) {}
/// Current query for searchable list views that preserve filtering across refreshes.
fn search_query(&self) -> Option<&str> {
None
}
/// Apply a matching background suggestion when this view supports text prefills.
fn apply_text_suggestion(
&mut self,
_request_id: uuid::Uuid,
_suggestion: Option<&str>,
) -> bool {
false
}
/// Active tab id for tabbed list-based views.
#[allow(dead_code)]
fn active_tab_id(&self) -> Option<&str> {
None
}
/// Handle Ctrl-C while this view is active.
fn on_ctrl_c(&mut self) -> CancellationEvent {
CancellationEvent::NotHandled
}
/// Return true if Esc should be routed through `handle_key_event` instead
/// of the `on_ctrl_c` cancellation path.
fn prefer_esc_to_handle_key_event(&self) -> bool {
false
}
/// Return true when this key event will interrupt the active agent turn.
fn will_interrupt_turn_on_key_event(&self, _key_event: KeyEvent) -> bool {
false
}
/// Optional paste handler. Return true if the view modified its state and
/// needs a redraw.
fn handle_paste(&mut self, _pasted: String) -> bool {
false
}
/// Flush any pending paste-burst state. Return true if state changed.
///
/// This lets a modal that reuses `ChatComposer` participate in the same
/// time-based paste burst flushing as the primary composer.
fn flush_paste_burst_if_due(&mut self) -> bool {
false
}
/// Whether the view is currently holding paste-burst transient state.
///
/// When `true`, the bottom pane will schedule a short delayed redraw to
/// give the burst time window a chance to flush.
fn is_in_paste_burst(&self) -> bool {
false
}
/// Process time-based state immediately before rendering.
///
/// Return true when state changed and the bottom pane should redraw or
/// complete the active view.
fn pre_draw_tick(&mut self, _now: Instant) -> bool {
false
}
/// The patch whose inline review should end when this prompt is answered.
fn current_patch_approval(&self) -> Option<&super::ApplyPatchApprovalRequest> {
None
}
/// Try to handle approval request; return the original value if not
/// consumed.
fn try_consume_approval_request(
&mut self,
request: ApprovalRequest,
) -> Option<ApprovalRequest> {
Some(request)
}
/// Try to handle request_user_input; return the original value if not
/// consumed.
fn try_consume_user_input_request(
&mut self,
request: ToolRequestUserInputParams,
) -> Option<ToolRequestUserInputParams> {
Some(request)
}
/// Try to handle a supported MCP server elicitation form request; return the original value if
/// not consumed.
fn try_consume_mcp_server_elicitation_request(
&mut self,
request: McpServerElicitationFormRequest,
) -> Option<McpServerElicitationFormRequest> {
Some(request)
}
/// Return true when this view already presents the matching app-server request.
fn matches_app_server_request(&self, _request: &ResolvedAppServerRequest) -> bool {
false
}
/// Dismiss a request that was resolved by another client.
///
/// Returns `true` when the view changed state.
fn dismiss_app_server_request(&mut self, _request: &ResolvedAppServerRequest) -> bool {
false
}
/// Whether this view means the session is blocked waiting for the user.
///
/// Views that return `true` surface an "Action Required" terminal title
/// instead of the normal working spinner so terminal tabs clearly show that
/// Codex needs user input.
fn terminal_title_requires_action(&self) -> bool {
false
}
/// Classify interactive requests that prevent the agent from continuing.
///
/// Ordinary settings and navigation views do not block a running agent.
fn program_status_blocked_kind(&self) -> Option<ProgramStatusKind> {
None
}
/// Return the next time-based redraw this view needs while it is active.
fn next_frame_delay(&self) -> Option<std::time::Duration> {
None
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
//! Availability of the empty-prompt agents shortcut and its footer hint.
//!
//! Draft contents, transient input surfaces, and explicit editor remaps take precedence.
use super::*;
impl ChatComposer {
pub(crate) fn agents_navigation_key_available(&self) -> bool {
let move_left = if self.draft.textarea.is_vim_normal_mode() {
&self.vim_normal_keymap.move_left
} else {
&self.editor_keymap.move_left
};
move_left.is_pressed(KeyCode::Left.into())
}
pub(super) fn agents_navigation_available(&self) -> bool {
self.command_center_enabled
&& self.agents_navigation_key_available()
&& self.has_focus
&& self.draft.input_enabled
&& self.slash_commands_enabled()
&& self.is_empty()
&& !self.is_in_paste_burst()
&& !self.popup_active()
&& !self.draft.textarea.is_vim_operator_pending()
}
pub(super) fn handle_agents_navigation(&mut self, key: KeyEvent) -> bool {
if key.kind == KeyEventKind::Press
&& key_hint::plain(KeyCode::Left).is_press(key)
&& self.agents_navigation_available()
{
self.app_event_tx.send(AppEvent::OpenAgentsOverview);
return true;
}
false
}
}

View File

@@ -0,0 +1,159 @@
use super::tests::new_test_composer;
use super::tests::snapshot_composer_state_with_width;
use super::tests::type_chars_humanlike;
use super::*;
use assert_matches::assert_matches;
use pretty_assertions::assert_eq;
#[test]
fn parent_owned_thread_allows_local_commands() {
for (command, expected) in [
("/agents", SlashCommand::Agents),
("/subagents", SlashCommand::MultiAgents),
("/side", SlashCommand::Side),
("/btw", SlashCommand::Btw),
("/diff ", SlashCommand::Diff),
("/daemon", SlashCommand::Daemon),
("/warnings", SlashCommand::Warnings),
] {
let (mut composer, _rx) = new_test_composer();
composer.set_parent_owned_thread();
composer.set_text_content(command.to_string(), Vec::new(), Vec::new());
assert_eq!(
composer.handle_submission(/*should_queue*/ false).0,
InputResult::Command(expected)
);
}
for (command, args) in [
(SlashCommand::Title, "model"),
(SlashCommand::Statusline, "model --no-colors"),
] {
let (mut composer, _rx) = new_test_composer();
composer.set_parent_owned_thread();
let name = command.command();
composer.set_text_content(format!("/{name} {args}"), Vec::new(), Vec::new());
assert_eq!(
composer.handle_key_event(KeyCode::Enter.into()).0,
InputResult::CommandWithArgs(command, args.into(), Vec::new())
);
}
}
#[test]
fn parent_owned_thread_allows_safe_command_selected_from_prefix() {
let (mut composer, _rx) = new_test_composer();
composer.set_parent_owned_thread();
type_chars_humanlike(&mut composer, &['/', 'a', 'g']);
let result = composer
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
.0;
assert_eq!(result, InputResult::Command(SlashCommand::Agents));
}
#[test]
fn left_navigates_only_from_an_empty_prompt() {
let (mut composer, mut events) = new_test_composer();
composer.command_center_enabled = true;
composer.insert_str("ab");
composer.handle_key_event(KeyCode::Left.into());
composer.insert_str("!");
assert_eq!(composer.current_text(), "a!b");
assert!(events.try_recv().is_err());
composer.clear_for_ctrl_c();
for kind in [KeyEventKind::Repeat, KeyEventKind::Release] {
composer.handle_key_event(KeyEvent::new_with_kind(
KeyCode::Left,
KeyModifiers::NONE,
kind,
));
}
assert!(events.try_recv().is_err());
composer.handle_key_event(KeyCode::Left.into());
assert_matches!(events.try_recv(), Ok(AppEvent::OpenAgentsOverview));
}
#[test]
fn left_respects_attachments_pastes_and_other_input_surfaces() {
let setups: [fn(&mut ChatComposer); 4] = [
|composer| composer.config = ChatComposerConfig::plain_text(),
|composer| composer.set_remote_image_urls(vec!["https://example.com/image.png".into()]),
|composer| {
composer.handle_key_event(KeyCode::Char('x').into());
},
|composer| {
composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
},
];
for setup in setups {
let (mut composer, mut events) = new_test_composer();
composer.command_center_enabled = true;
setup(&mut composer);
composer.handle_key_event(KeyCode::Left.into());
assert!(
!std::iter::from_fn(|| events.try_recv().ok())
.any(|event| matches!(event, AppEvent::OpenAgentsOverview))
);
}
}
#[test]
fn agents_navigation_hint_snapshots() {
for name in [
"agents_navigation_enabled",
"agents_navigation_help",
"agents_navigation_status",
] {
snapshot_composer_state_with_width(
name,
/*width*/ 80,
/*enhanced_keys_supported*/ false,
|composer| {
composer.command_center_enabled = true;
match name {
"agents_navigation_help" => {
composer.handle_key_event(KeyCode::Char('?').into());
}
"agents_navigation_status" => {
composer.set_status_line_enabled(/*enabled*/ true);
composer.set_status_line(Some(Line::from("model · project").into()));
}
_ => {}
}
},
);
}
}
#[test]
fn left_respects_editor_and_vim_history_remaps() {
use akode_config::types::KeybindingSpec;
use akode_config::types::KeybindingsSpec;
use akode_config::types::TuiKeymap;
for vim in [false, true] {
let (mut composer, mut events) = new_test_composer();
composer.command_center_enabled = true;
composer.insert_str("previous");
composer.handle_key_event(KeyCode::Enter.into());
let mut config = TuiKeymap::default();
if vim {
config.vim_normal.move_left = Some(KeybindingsSpec::One(KeybindingSpec("h".into())));
config.vim_normal.move_up = Some(KeybindingsSpec::One(KeybindingSpec("left".into())));
} else {
config.editor.move_left = Some(KeybindingsSpec::One(KeybindingSpec("ctrl-b".into())));
config.editor.move_up = Some(KeybindingsSpec::One(KeybindingSpec("left".into())));
}
composer.set_keymap_bindings(&RuntimeKeymap::from_config(&config).unwrap());
composer.set_vim_enabled(vim);
assert!(composer.footer_props().key_hints.agents.is_none());
composer.handle_key_event(KeyCode::Left.into());
assert_eq!(composer.current_text(), "previous");
assert!(events.try_recv().is_err());
}
}

View File

@@ -0,0 +1,224 @@
//! Attachment bookkeeping for the chat composer, including local image placeholders,
//! remote-image rows, and keyboard selection over those rows.
use std::collections::HashSet;
use std::path::PathBuf;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use ratatui::style::Stylize;
use ratatui::text::Line;
use super::InputResult;
use crate::bottom_pane::LocalImageAttachment;
use crate::bottom_pane::textarea::TextArea;
use akode_protocol::models::local_image_label_text;
use akode_protocol::user_input::TextElement;
#[derive(Debug, Default)]
pub(super) struct AttachmentState {
pub(super) local_images: Vec<LocalImageAttachment>,
pub(super) remote_image_urls: Vec<String>,
pub(super) selected_remote_image_index: Option<usize>,
}
impl AttachmentState {
pub(super) fn is_empty(&self) -> bool {
self.local_images.is_empty() && self.remote_image_urls.is_empty()
}
pub(super) fn local_image_paths(&self) -> Vec<PathBuf> {
self.local_images
.iter()
.map(|image| image.path.clone())
.collect()
}
pub(super) fn set_remote_image_urls(&mut self, urls: Vec<String>, textarea: &mut TextArea) {
self.remote_image_urls = urls;
self.selected_remote_image_index = None;
self.relabel_local_images(textarea);
}
pub(super) fn remote_image_urls(&self) -> Vec<String> {
self.remote_image_urls.clone()
}
pub(super) fn take_remote_image_urls(&mut self, textarea: &mut TextArea) -> Vec<String> {
let urls = std::mem::take(&mut self.remote_image_urls);
self.selected_remote_image_index = None;
self.relabel_local_images(textarea);
urls
}
pub(super) fn clear_remote_image_urls(&mut self) {
self.remote_image_urls.clear();
self.selected_remote_image_index = None;
}
pub(super) fn reset_local_images(
&mut self,
local_image_paths: Vec<PathBuf>,
textarea: &mut TextArea,
) {
self.local_images.clear();
self.local_images.extend(
local_image_paths
.into_iter()
.enumerate()
.map(|(index, path)| LocalImageAttachment {
placeholder: local_image_label_text(self.remote_image_urls.len() + index + 1),
path,
}),
);
self.selected_remote_image_index = None;
self.relabel_local_images(textarea);
}
pub(super) fn attach_image(&mut self, textarea: &mut TextArea, path: PathBuf) {
let image_number = self.remote_image_urls.len() + self.local_images.len() + 1;
let placeholder = local_image_label_text(image_number);
textarea.insert_element(&placeholder);
self.local_images
.push(LocalImageAttachment { placeholder, path });
}
pub(super) fn prune_local_images_for_submission(
&mut self,
text: &str,
text_elements: &[TextElement],
) {
if self.local_images.is_empty() {
return;
}
let image_placeholders: HashSet<&str> = text_elements
.iter()
.filter_map(|element| element.placeholder(text))
.collect();
self.local_images
.retain(|image| image_placeholders.contains(image.placeholder.as_str()));
}
#[cfg(test)]
pub(super) fn take_recent_submission_images(&mut self) -> Vec<PathBuf> {
std::mem::take(&mut self.local_images)
.into_iter()
.map(|image| image.path)
.collect()
}
pub(super) fn remote_image_lines(&self) -> Vec<Line<'static>> {
self.remote_image_urls
.iter()
.enumerate()
.map(|(index, _)| {
let label = local_image_label_text(index + 1);
if self.selected_remote_image_index == Some(index) {
label.cyan().reversed().into()
} else {
label.cyan().into()
}
})
.collect()
}
pub(super) fn clear_remote_image_selection(&mut self) {
self.selected_remote_image_index = None;
}
pub(super) fn handle_remote_image_selection_key(
&mut self,
key_event: &KeyEvent,
textarea: &mut TextArea,
) -> Option<(InputResult, bool)> {
if self.remote_image_urls.is_empty()
|| key_event.modifiers != KeyModifiers::NONE
|| key_event.kind != KeyEventKind::Press
{
return None;
}
match key_event.code {
KeyCode::Up => {
if let Some(selected) = self.selected_remote_image_index {
self.selected_remote_image_index = Some(selected.saturating_sub(1));
Some((InputResult::None, true))
} else if textarea.cursor() == 0 {
self.selected_remote_image_index = Some(self.remote_image_urls.len() - 1);
Some((InputResult::None, true))
} else {
None
}
}
KeyCode::Down => {
if let Some(selected) = self.selected_remote_image_index {
if selected + 1 < self.remote_image_urls.len() {
self.selected_remote_image_index = Some(selected + 1);
} else {
self.clear_remote_image_selection();
}
Some((InputResult::None, true))
} else {
None
}
}
KeyCode::Delete | KeyCode::Backspace => {
if let Some(selected) = self.selected_remote_image_index {
self.remove_selected_remote_image(selected, textarea);
Some((InputResult::None, true))
} else {
None
}
}
_ => None,
}
}
pub(super) fn remove_deleted_local_placeholders(
&mut self,
removed_payloads: &[String],
textarea: &mut TextArea,
) -> bool {
let previous_len = self.local_images.len();
self.local_images.retain(|image| {
!removed_payloads
.iter()
.any(|payload| payload == &image.placeholder)
});
let removed_any = self.local_images.len() != previous_len;
if removed_any {
self.relabel_local_images(textarea);
}
removed_any
}
pub(super) fn relabel_local_images(&mut self, textarea: &mut TextArea) {
for (index, image) in self.local_images.iter_mut().enumerate() {
let expected = local_image_label_text(self.remote_image_urls.len() + index + 1);
if image.placeholder == expected {
continue;
}
let current = std::mem::replace(&mut image.placeholder, expected.clone());
let _renamed = textarea.replace_element_payload(&current, &expected);
}
}
fn remove_selected_remote_image(&mut self, selected_index: usize, textarea: &mut TextArea) {
if selected_index >= self.remote_image_urls.len() {
self.clear_remote_image_selection();
return;
}
self.remote_image_urls.remove(selected_index);
self.selected_remote_image_index = if self.remote_image_urls.is_empty() {
None
} else {
Some(selected_index.min(self.remote_image_urls.len() - 1))
};
self.relabel_local_images(textarea);
}
}

View File

@@ -0,0 +1,146 @@
use super::super::tests::new_test_composer;
use super::super::tests::snapshot_composer_state_with_width;
use super::super::*;
use crossterm::event::MouseEvent;
use crossterm::event::MouseEventKind;
use pretty_assertions::assert_eq;
#[test]
fn blockquote_paste_continues_current_line_prefix() {
for (draft, pasted, expected) in [
("> ", "first\nsecond", "> first\n> second\n\n"),
("> ", "first\n", "> first\n\n"),
("intro\n> ", "α\r\n\r\nβ\r", "intro\n> α\n> \n> β\n\n"),
(
"> existing ",
"first\nsecond",
"> existing first\n> second\n\n",
),
("text > ", "first\nsecond", "text > first\nsecond"),
(">", "first\nsecond", ">first\nsecond"),
(
"> quote\nplain ",
"first\nsecond",
"> quote\nplain first\nsecond",
),
("> ", "single", "> single"),
("!> ", "out\npwd", "!> out\npwd"),
// A space before the bang keeps the draft in normal text mode.
(" !echo hi\n> ", "out\npwd", " !echo hi\n> out\n> pwd\n\n"),
] {
let (mut composer, _rx) = new_test_composer();
composer.insert_str(draft);
composer.handle_paste(pasted.to_string());
assert_eq!(composer.current_text(), expected);
}
}
#[test]
fn blockquote_paste_uses_cursor_line_and_preserves_suffix() {
let (mut composer, _rx) = new_test_composer();
composer.insert_str("intro\n> suffix\nend");
composer.draft.textarea.set_cursor("intro\n> ".len());
composer.handle_paste("first\nsecond".to_string());
assert_eq!(
composer.draft.textarea.text(),
"intro\n> first\n> second\n\nsuffix\nend"
);
composer.insert_str("next ");
assert_eq!(
composer.current_text(),
"intro\n> first\n> second\n\nnext suffix\nend"
);
}
#[test]
fn blockquote_paste_large_expands_quoted_text_on_submit() {
let (mut composer, _rx) = new_test_composer();
composer.insert_str("> ");
let first = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD);
composer.handle_paste(format!("{first}\nsecond"));
let quoted = format!("{first}\n> second");
let placeholder = format!("[Pasted Content {} chars]", quoted.chars().count());
assert_eq!(
composer.draft.textarea.text(),
format!("> {placeholder}\n\n")
);
assert_eq!(
composer.draft.pending_pastes,
vec![(placeholder, quoted.clone())]
);
composer.insert_str("Next block");
let (result, _) = composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
let InputResult::Submitted { text, .. } = result else {
panic!("expected Submitted");
};
assert_eq!(text, format!("> {quoted}\n\nNext block"));
}
#[test]
fn blockquote_paste_rendered() {
snapshot_composer_state_with_width(
"blockquote_paste",
/*width*/ 60,
/*enhanced_keys_supported*/ false,
|composer| {
composer.insert_str("Please explain:\n> ");
composer.handle_paste("first line\n\nlast line\n".to_string());
composer.insert_str("Next block");
},
);
}
#[test]
fn blockquote_paste_replacing_selected_prefix_stays_literal() {
let (mut composer, _rx) = new_test_composer();
composer.insert_str("> selected");
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 10,
);
composer.render(area, &mut Buffer::empty(area));
let (x, y) = composer.cursor_pos(area).unwrap();
for (kind, column) in [
(
MouseEventKind::Down(crossterm::event::MouseButton::Left),
x - 10,
),
(MouseEventKind::Drag(crossterm::event::MouseButton::Left), x),
] {
let event = MouseEvent {
kind,
column,
row: y,
modifiers: KeyModifiers::NONE,
};
assert!(composer.prepare_mouse(event));
composer.render(area, &mut Buffer::empty(area));
assert!(composer.handle_mouse(event));
}
composer.handle_paste("first\nsecond".to_string());
assert_eq!(composer.current_text(), "first\nsecond");
}
#[test]
fn blockquote_paste_embedded_answer_starts_next_block() {
let (mut composer, _rx) = new_test_composer();
composer.config = ChatComposerConfig::plain_text();
composer.insert_str("> ");
composer.handle_paste("first\nsecond".to_string());
composer.insert_str("Next block");
assert_eq!(composer.current_text(), "> first\n> second\n\nNext block");
}
#[test]
fn blockquote_paste_embedded_answer_rendered() {
snapshot_composer_state_with_width(
"blockquote_paste_embedded_answer",
/*width*/ 60,
/*enhanced_keys_supported*/ false,
|composer| {
composer.config = ChatComposerConfig::plain_text();
composer.insert_str("> ");
composer.handle_paste("first line\n\nlast line".to_string());
composer.insert_str("Next block");
},
);
}

View File

@@ -0,0 +1,358 @@
//! Cursor-neighborhood resolution for sigil-prefixed composer completions.
use super::ends_plaintext_at_dollar_mention;
use super::ends_plaintext_at_mention;
use super::is_mention_name_char;
use crate::bottom_pane::textarea::TextArea;
use crate::mention_codec::is_common_env_var;
use std::ops::Range;
/// Narrows one whitespace-delimited candidate to the editable segment around `anchor`.
///
/// Atomic elements form hard boundaries. If the anchor is inside an element, the raw candidate is
/// retained only when it is needed to identify that the candidate is already bound.
fn prefixed_candidate_range(
textarea: &TextArea,
range: Range<usize>,
anchor: usize,
prefix: char,
allow_empty: bool,
) -> Option<(Range<usize>, String)> {
let text = textarea.text();
let prefix_len = prefix.len_utf8();
let raw_prefixed = text
.get(range.clone())
.filter(|token| token.starts_with(prefix))
.map(|token| (range.clone(), token[prefix_len..].to_string()));
let mut segment_start = range.start;
let mut segment_end = range.end;
let mut has_element_boundary = false;
let anchor = anchor.clamp(range.start, range.end);
for element in textarea.text_element_ranges_overlapping(range) {
has_element_boundary = true;
if element.end <= anchor {
segment_start = element.end;
continue;
}
if anchor <= element.start {
segment_end = element.start;
} else {
segment_start = anchor;
segment_end = anchor;
}
break;
}
if !has_element_boundary {
return raw_prefixed;
}
let segmented_prefixed = text
.get(segment_start..segment_end)
.and_then(|token| token.strip_prefix(prefix))
.filter(|query| allow_empty || !query.is_empty())
.map(|query| (segment_start..segment_end, query.to_string()));
if segmented_prefixed.is_some()
|| raw_prefixed.as_ref().is_none_or(|(range, query)| {
prefixed_token_range_is_editable(textarea, prefix, range, query)
})
{
segmented_prefixed
} else {
raw_prefixed
}
}
/// Extracts a token prefixed with `prefix` under the cursor, if any.
///
/// The returned string does not include the prefix. Resolution considers the tokens on both sides
/// of same-line separator whitespace and preserves their ranges for cross-sigil arbitration. It
/// stops editable candidates at atomic text elements, and line breaks never provide affinity.
pub(super) fn current_prefixed_token_range(
textarea: &TextArea,
prefix: char,
allow_empty: bool,
) -> Option<(Range<usize>, String)> {
current_prefixed_token_range_with_dollar_predicate(
textarea,
prefix,
allow_empty,
dollar_query_is_completable,
)
}
/// Extracts a prefixed token while using the provided dollar-query predicate for separator
/// arbitration.
pub(super) fn current_prefixed_token_range_with_dollar_predicate(
textarea: &TextArea,
prefix: char,
allow_empty: bool,
dollar_query_is_completable: impl Fn(&str) -> bool,
) -> Option<(Range<usize>, String)> {
let cursor_offset = textarea.cursor();
let text = textarea.text();
// Adjust the provided byte offset to the nearest valid char boundary at or before it.
let mut safe_cursor = cursor_offset.min(text.len());
if safe_cursor < text.len() && !text.is_char_boundary(safe_cursor) {
safe_cursor = text
.char_indices()
.map(|(i, _)| i)
.take_while(|&i| i <= cursor_offset)
.last()
.unwrap_or(0);
}
let before_cursor = &text[..safe_cursor];
let after_cursor = &text[safe_cursor..];
let is_horizontal_whitespace = |c: char| {
c.is_whitespace()
&& !matches!(
c,
'\n' | '\r' | '\u{000B}' | '\u{000C}' | '\u{0085}' | '\u{2028}' | '\u{2029}'
)
};
let at_whitespace = after_cursor.chars().next().is_some_and(char::is_whitespace);
let after_horizontal_whitespace = before_cursor
.chars()
.next_back()
.is_some_and(is_horizontal_whitespace);
let cursor_starts_token = after_horizontal_whitespace && !at_whitespace;
let next_non_separator = after_cursor.chars().find(|c| !is_horizontal_whitespace(*c));
let separator_precedes_token = next_non_separator.is_some_and(|c| !c.is_whitespace());
let separator_precedes_completion = next_non_separator.is_some_and(|c| matches!(c, '$' | '@'));
let at_separator = (at_whitespace || after_horizontal_whitespace) && separator_precedes_token;
let end_left = if at_separator {
before_cursor
.trim_end_matches(is_horizontal_whitespace)
.len()
} else {
let end_left_rel = after_cursor
.char_indices()
.find(|(_, c)| c.is_whitespace())
.map(|(idx, _)| idx)
.unwrap_or(after_cursor.len());
safe_cursor + end_left_rel
};
let start_left = text[..end_left]
.char_indices()
.rfind(|(_, c)| c.is_whitespace())
.map(|(idx, c)| idx + c.len_utf8())
.unwrap_or(0);
let ws_len_right: usize = after_cursor
.chars()
.take_while(|c| is_horizontal_whitespace(*c))
.map(char::len_utf8)
.sum();
let start_right = safe_cursor + ws_len_right;
let end_right_rel = text[start_right..]
.char_indices()
.find(|(_, c)| c.is_whitespace())
.map(|(idx, _)| idx)
.unwrap_or(text.len() - start_right);
let end_right = start_right + end_right_rel;
let token_right = if start_right < end_right {
Some(&text[start_right..end_right])
} else {
None
};
let left_prefixed = prefixed_candidate_range(
textarea,
start_left..end_left,
safe_cursor,
prefix,
allow_empty,
);
let right_prefixed = prefixed_candidate_range(
textarea,
start_right..end_right,
start_right,
prefix,
allow_empty,
);
if cursor_starts_token {
let right_is_bound = token_right
.and_then(|token| {
let prefix = token.chars().next()?;
matches!(prefix, '$' | '@').then_some((prefix, &token[prefix.len_utf8()..]))
})
.is_some_and(|(prefix, query)| {
!prefixed_token_range_is_editable(
textarea,
prefix,
&(start_right..end_right),
query,
)
});
return if right_is_bound {
left_prefixed
} else {
right_prefixed
};
}
if allow_empty && after_cursor.starts_with(prefix) {
let left_fragment = &text[start_left..safe_cursor];
if let Some(left_token) = left_fragment.strip_prefix(prefix)
&& left_token
.as_bytes()
.iter()
.all(|byte| is_mention_name_char(*byte))
{
let left_range = start_left..safe_cursor;
let left_is_editable =
prefixed_token_range_is_editable(textarea, prefix, &left_range, left_token);
if left_token.is_empty() || prefix == '$' && left_is_editable {
return Some((left_range, left_token.to_string()));
}
if !left_is_editable {
return left_prefixed.or(right_prefixed);
}
}
}
if at_separator {
if after_horizontal_whitespace && !separator_precedes_completion {
return right_prefixed;
}
if prefix == '$'
&& left_prefixed
.as_ref()
.is_some_and(|(_, query)| !dollar_query_is_completable(query))
&& right_prefixed
.as_ref()
.is_some_and(|(_, query)| dollar_query_is_completable(query))
{
return right_prefixed;
}
if prefix == '@'
&& right_prefixed.as_ref().is_some_and(|(range, query)| {
prefixed_token_range_is_editable(textarea, prefix, range, query)
})
{
return right_prefixed;
}
if left_prefixed.as_ref().is_some_and(|(range, token)| {
!prefixed_token_range_is_editable(textarea, prefix, range, token)
}) {
return right_prefixed.or(left_prefixed);
}
if left_prefixed
.as_ref()
.is_some_and(|(_, token)| token.is_empty())
&& !allow_empty
{
return right_prefixed;
}
return left_prefixed.or(right_prefixed);
}
if after_cursor.starts_with(prefix) {
let prefix_starts_token = before_cursor
.chars()
.next_back()
.is_none_or(char::is_whitespace);
return if prefix_starts_token {
right_prefixed.or(left_prefixed)
} else {
left_prefixed
};
}
left_prefixed.or(right_prefixed)
}
/// Returns whether a token candidate's sigil and mention name are editable plaintext.
///
/// A candidate is bound when either its entire range is atomic or its mention-name prefix is
/// atomic and the remaining text begins with a terminator for that sigil.
pub(super) fn prefixed_token_range_is_editable(
textarea: &TextArea,
prefix: char,
range: &Range<usize>,
token: &str,
) -> bool {
if textarea.element_id_for_exact_range(range.clone()).is_some() {
return false;
}
let name_len = token
.as_bytes()
.iter()
.take_while(|byte| is_mention_name_char(**byte))
.count();
let mention_end = range.start + prefix.len_utf8() + name_len;
let ends_bound_mention = if prefix == '@' {
ends_plaintext_at_mention(textarea.text().as_bytes(), mention_end)
} else {
ends_plaintext_at_dollar_mention(textarea.text().as_bytes(), mention_end)
};
!(name_len > 0
&& mention_end < range.end
&& ends_bound_mention
&& textarea
.element_id_for_exact_range(range.start..mention_end)
.is_some())
}
/// Rejects shell-like dollar syntax while preserving lowercase and plugin-qualified skill queries.
///
/// Uppercase common environment-variable spellings and tokens beginning with a positional or
/// special shell parameter are excluded. The check uses the complete colon-qualified name so a
/// skill such as `home` or `home:search` is not mistaken for `$HOME`.
pub(super) fn dollar_query_is_completable(query: &str) -> bool {
matches!(dollar_query_kind(query), DollarQueryKind::Completable)
}
/// Classifies text after `$` for arbitration between shell syntax and mention completion.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum DollarQueryKind {
Completable,
ShellVariable,
DefiniteShellParameter,
/// A digit-leading query containing a non-digit, or a `-` query with a suffix.
AmbiguousShellParameter,
Invalid,
}
/// Conservatively classifies a dollar query before the mention catalog is consulted.
///
/// Numeric-only and exact special-parameter forms remain definite shell syntax. A digit-leading
/// query containing a non-digit, or a `-` query with a suffix, is ambiguous because loaded
/// mentions may legally use those spellings.
pub(super) fn dollar_query_kind(query: &str) -> DollarQueryKind {
let name_end = query
.as_bytes()
.iter()
.take_while(|byte| is_mention_name_char(**byte) || **byte == b':')
.count();
let name = &query[..name_end];
let is_shell_var =
name.bytes().all(|byte| !byte.is_ascii_lowercase()) && is_common_env_var(name);
let is_shell_parameter = name
.as_bytes()
.first()
.is_some_and(|byte| *byte == b'-' || byte.is_ascii_digit());
let is_numeric_parameter = !name.is_empty() && name.bytes().all(|byte| byte.is_ascii_digit());
if query.is_empty() {
DollarQueryKind::Completable
} else if name_end == 0 {
DollarQueryKind::Invalid
} else if is_shell_var {
DollarQueryKind::ShellVariable
} else if is_numeric_parameter || matches!(name, "-" | "_") {
DollarQueryKind::DefiniteShellParameter
} else if is_shell_parameter {
DollarQueryKind::AmbiguousShellParameter
} else {
DollarQueryKind::Completable
}
}
#[cfg(test)]
#[path = "completion_target_tests.rs"]
mod tests;

View File

@@ -0,0 +1,219 @@
use super::*;
use crate::bottom_pane::textarea::TextArea;
use pretty_assertions::assert_eq;
#[test]
fn current_prefixed_token_affinity_does_not_cross_line_break() {
for (text, prefix, allow_empty) in [
("@file\n continue", '@', false),
("continue \n@file", '@', false),
("$skill\n continue", '$', true),
("continue \n$skill", '$', true),
] {
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.set_cursor(text.find(" ").expect("indentation present") + 1);
assert_eq!(
current_prefixed_token_range(&textarea, prefix, allow_empty),
None
);
}
}
#[test]
fn current_prefixed_token_affinity_does_not_cross_separator_before_plain_text() {
for (text, prefix, allow_empty) in [("@old word", '@', false), ("$old word", '$', true)] {
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.set_cursor(text.find(" ").expect("separator present") + 1);
assert_eq!(
current_prefixed_token_range(&textarea, prefix, allow_empty),
None
);
}
}
#[test]
fn current_prefixed_token_prefers_right_after_adjacent_target() {
let bound = "@bound";
let left = "@bound@old";
let text = "@bound@old @new";
let right_start = left.len() + 2;
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.add_element_range(0..bound.len());
textarea.set_cursor(left.len());
assert_eq!(
current_prefixed_token_range(&textarea, '@', /*allow_empty*/ false),
Some((right_start..text.len(), "new".to_string()))
);
}
#[test]
fn current_prefixed_token_prefers_right_at_token_start() {
let text = "$old $new";
let right_start = "$old ".len();
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.set_cursor(right_start);
assert_eq!(
current_prefixed_token_range(&textarea, '$', /*allow_empty*/ true),
Some((right_start..text.len(), "new".to_string()))
);
}
#[test]
fn current_prefixed_token_falls_back_from_bound_at_token_on_right() {
let text = "@left @bound";
let bound_start = text.find("@bound").expect("bound mention");
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.add_element_range(bound_start..text.len());
textarea.set_cursor("@left ".len());
assert_eq!(
current_prefixed_token_range(&textarea, '@', /*allow_empty*/ true),
Some((0.."@left".len(), "left".to_string()))
);
}
#[test]
fn current_prefixed_token_falls_back_from_bound_dollar_suffix_on_right() {
for suffix in ["/path", ".config"] {
let text = format!("$left $bound{suffix}");
let bound_start = text.find("$bound").expect("bound skill mention");
let bound_end = bound_start + "$bound".len();
let mut textarea = TextArea::new();
textarea.insert_str(&text);
textarea.add_element_range(bound_start..bound_end);
textarea.set_cursor("$left ".len());
assert_eq!(
current_prefixed_token_range(&textarea, '$', /*allow_empty*/ true),
Some((0.."$left".len(), "left".to_string()))
);
}
}
#[test]
fn current_prefixed_token_targets_later_segment_between_bound_elements() {
let text = "$bound1$one$bound2$two$bound3";
let bound2_start = text.find("$bound2").expect("second bound mention");
let two_start = text.find("$two").expect("later plaintext target");
let bound3_start = text.find("$bound3").expect("third bound mention");
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.add_element_range(0.."$bound1".len());
textarea.add_element_range(bound2_start..two_start);
textarea.add_element_range(bound3_start..text.len());
textarea.set_cursor(two_start + "$t".len());
assert_eq!(
current_prefixed_token_range(&textarea, '$', /*allow_empty*/ true),
Some((two_start..bound3_start, "two".to_string()))
);
}
#[test]
fn current_prefixed_token_bounds_right_candidate_before_bound_element() {
let text = "continue @other@bound";
let other_start = text.find("@other").expect("editable mention");
let bound_start = text.find("@bound").expect("bound mention");
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.add_element_range(bound_start..text.len());
textarea.set_cursor(other_start);
assert_eq!(
current_prefixed_token_range(&textarea, '@', /*allow_empty*/ false),
Some((other_start..bound_start, "other".to_string()))
);
}
#[test]
fn current_prefixed_token_stops_before_overlapping_element() {
let editable = "$other";
let placeholder = "[Pasted Content 1001 chars]";
let text = format!("{editable}{placeholder}");
let mut textarea = TextArea::new();
textarea.insert_str(&text);
textarea.add_element_range(editable.len()..text.len());
textarea.set_cursor(editable.len());
assert_eq!(
current_prefixed_token_range(&textarea, '$', /*allow_empty*/ true),
Some((0..editable.len(), "other".to_string()))
);
}
#[test]
fn current_prefixed_token_stops_at_trailing_space_before_line_break() {
let text = "$figma \nnext";
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.set_cursor("$figma ".len());
assert_eq!(
current_prefixed_token_range(&textarea, '$', /*allow_empty*/ true),
None
);
}
#[test]
fn current_prefixed_token_keeps_nested_dollar_prefix_in_same_token() {
let text = "$HOME/$USER";
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.set_cursor(text.find("$USER").expect("nested prefix present"));
assert_eq!(
current_prefixed_token_range(&textarea, '$', /*allow_empty*/ true),
Some((0..text.len(), "HOME/$USER".to_string()))
);
}
#[test]
fn typed_qualified_suffix_preserves_bound_plain_mention() {
// Qualified skill bindings and history persistence are intentionally deferred. Typing a
// suffix after a bound plain mention must not reinterpret it as an editable qualified one.
let bound = "$google-calendar";
let text = "$google-calendar:availability";
let mut textarea = TextArea::new();
textarea.insert_str(text);
textarea.add_element_range(0..bound.len());
textarea.set_cursor(text.len());
let (range, token) = current_prefixed_token_range(&textarea, '$', /*allow_empty*/ true)
.expect("dollar token should be present");
assert_eq!((range.clone(), token.as_str()), (0..text.len(), &text[1..]));
assert!(!prefixed_token_range_is_editable(
&textarea, '$', &range, &token,
));
}
#[test]
fn dollar_query_classifies_shell_and_skill_syntax() {
assert!(!dollar_query_is_completable("{AKODE_HOME}/config.toml"));
assert!(!dollar_query_is_completable("(pwd)"));
assert!(dollar_query_is_completable("home:search"));
assert!(dollar_query_is_completable("home"));
assert!(!dollar_query_is_completable("HOME"));
for query in ["0", "1", "12", "-", "_"] {
assert!(!dollar_query_is_completable(query));
assert_eq!(
dollar_query_kind(query),
DollarQueryKind::DefiniteShellParameter
);
}
for query in ["1_suffix", "1foo", "-x"] {
assert!(!dollar_query_is_completable(query));
assert_eq!(
dollar_query_kind(query),
DollarQueryKind::AmbiguousShellParameter
);
}
}

View File

@@ -0,0 +1,265 @@
//! Shared composer geometry keeps rendering, measurement, and the cursor aligned.
use super::*;
use crate::bottom_pane::voice_strip::VoiceStrip;
use crate::bottom_pane::voice_strip::VoiceStripState;
use crate::render::renderable::Renderable;
use crate::tui::FrameRequester;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
impl ChatComposer {
pub(crate) fn set_voice_strip(
&mut self,
state: Option<VoiceStripState>,
frame_requester: FrameRequester,
) {
match (self.voice_strip.as_mut(), state) {
(Some(strip), Some(state)) => strip.update(state),
(_, Some(state)) => self.voice_strip = Some(VoiceStrip::new(state, frame_requester)),
(_, None) => self.voice_strip = None,
}
}
pub(super) fn render_voice_strip(&self, composer_rect: Rect, buf: &mut Buffer) {
if let Some(strip) = &self.voice_strip
&& composer_rect.height >= strip.desired_height(composer_rect.width) + 4
{
let voice_rect = Rect {
y: composer_rect.y.saturating_add(/*rhs*/ 1),
height: strip.desired_height(composer_rect.width),
..composer_rect
};
strip.render(voice_rect, buf);
}
}
}
impl ChatComposer {
pub(super) fn layout_with_options(
&self,
area: Rect,
options: ComposerRenderOptions<'_>,
) -> ComposerLayout {
let mut footer_hint_height = self.footer_hint_height(area.width, options);
let mut status_height = self.status_surface_height(area.width, options);
let shared = footer_hint_height > 1 && self.shows_shared_status(options);
if shared || status_height > 1 {
// Extra status rows yield to the draft, voice strip and other composer surfaces.
let desired =
self.height_with_rows(area.width, options, footer_hint_height, status_height);
let rows = if shared {
&mut footer_hint_height
} else {
&mut status_height
};
*rows = rows
.saturating_sub(desired.saturating_sub(area.height))
.max(1);
}
let status_height = status_height.min(
area.height
.saturating_sub(footer_hint_height.saturating_add(/*rhs*/ 3)),
);
let status = Rect {
y: area
.bottom()
.saturating_sub(footer_hint_height)
.saturating_sub(status_height)
.max(area.y),
height: status_height,
..area
};
let area = Rect {
height: area.height - status_height,
..area
};
let popup_height = if self.popups.active.is_above_composer()
&& options.command_popup_placement != CommandPopupPlacement::AboveComposer
{
footer_hint_height
} else {
self.popups
.active
.required_height(area.width, footer_hint_height)
};
let voice_rows = self
.voice_strip
.as_ref()
.map_or(0, |strip| strip.desired_height(area.width) + 1);
let shortcuts_above = self.shortcuts_above_composer(options);
let (composer_rect, popup_rect, mut footer_rect) = if shortcuts_above {
let [shortcuts, composer, footer] = Layout::vertical([
Constraint::Max(footer_height(&self.hint_footer_props(options), area.width)),
Constraint::Min(3 + voice_rows),
Constraint::Length(footer_hint_height),
])
.areas(area);
(composer, shortcuts, footer)
} else if self.popups.active.is_above_composer() {
// Preserve the draft first, then its footer, and use remaining space for suggestions.
let [mut composer, mut popup, footer] = Layout::vertical([
Constraint::Min(3 + voice_rows),
Constraint::Max(popup_height.saturating_sub(footer_hint_height)),
Constraint::Length(footer_hint_height),
])
.areas(area);
popup.y = area.y;
composer.y = popup.bottom();
(composer, popup, footer)
} else {
let [composer, popup] = Layout::vertical([
Constraint::Min(3 + voice_rows),
Constraint::Max(popup_height),
])
.areas(area);
(composer, popup, popup)
};
footer_rect.y = footer_rect.y.saturating_add(status.height);
// Keep the draft visible when clipped.
let voice_rows = voice_rows * u16::from(composer_rect.height >= voice_rows + 3);
let mut textarea_rect = composer_rect.inset(Insets::tlbr(
/*top*/ 1 + voice_rows,
LIVE_PREFIX_COLS,
/*bottom*/ 1,
/*right*/ 1u16.saturating_add(options.textarea_right_reserve),
));
let remote_images_height = self
.attachments
.remote_image_lines()
.len()
.try_into()
.unwrap_or(u16::MAX)
.min(textarea_rect.height.saturating_sub(2));
let remote_images_separator = u16::from(remote_images_height > 0);
let consumed = remote_images_height.saturating_add(remote_images_separator);
let remote_images_rect = Rect {
x: textarea_rect.x,
y: textarea_rect.y,
width: textarea_rect.width,
height: remote_images_height,
};
let mut thumbnails = Rect {
y: textarea_rect.y.saturating_add(consumed),
height: self.thumbnail_height(textarea_rect.width, options),
..textarea_rect
};
let available = textarea_rect.height.saturating_sub(consumed);
if thumbnails.height > 0
&& available.saturating_sub(thumbnails.height)
< self
.draft
.textarea
.desired_height(textarea_rect.width)
.max(1)
{
thumbnails.height = 0;
}
textarea_rect.y = thumbnails.bottom();
textarea_rect.height = available - thumbnails.height;
ComposerLayout {
thumbnails,
status,
composer: composer_rect,
remote_images: remote_images_rect,
textarea: textarea_rect,
popup: popup_rect,
footer: footer_rect,
}
}
fn thumbnail_height(&self, width: u16, options: ComposerRenderOptions<'_>) -> u16 {
options.image_previews.map_or(0, |previews| {
previews.height(width, self.attachments.local_images.len())
})
}
pub(crate) fn cursor_pos_with_options(
&self,
area: Rect,
options: ComposerRenderOptions<'_>,
) -> Option<(u16, u16)> {
let layout = self.layout_with_options(area, options);
if let Some(footer) = options.footer.filter(|footer| footer.is_interactive) {
let area = inset_footer_hint_area(layout.footer);
return footer
.cursor_column
.filter(|column| *column < area.width && area.height > 0)
.map(|column| (area.x + column, area.y));
}
if !self.draft.input_enabled || self.attachments.selected_remote_image_index.is_some() {
return None;
}
if let Some(pos) = self
.vim_search_cursor_pos(layout.footer)
.or_else(|| self.history_search_cursor_pos(layout.footer))
{
return Some(pos);
}
let state = *self.draft.textarea_state.borrow();
self.draft
.textarea
.cursor_pos_with_state(layout.textarea, state)
}
pub(crate) fn desired_height_with_options(
&self,
width: u16,
options: ComposerRenderOptions<'_>,
) -> u16 {
self.height_with_rows(
width,
options,
self.footer_hint_height(width, options),
self.status_surface_height(width, options),
)
}
fn height_with_rows(
&self,
width: u16,
options: ComposerRenderOptions<'_>,
footer_hint_height: u16,
status_height: u16,
) -> u16 {
const COLS_WITH_MARGIN: u16 = LIVE_PREFIX_COLS + 1;
let inner_width =
width.saturating_sub(COLS_WITH_MARGIN.saturating_add(options.textarea_right_reserve));
let remote_images_height: u16 = self
.attachments
.remote_image_lines()
.len()
.try_into()
.unwrap_or(u16::MAX);
let remote_images_separator = u16::from(remote_images_height > 0);
[
self.draft.textarea.desired_height(inner_width),
remote_images_height,
self.thumbnail_height(inner_width, options),
remote_images_separator,
status_height,
if self.shortcuts_above_composer(options) {
footer_height(&self.hint_footer_props(options), width)
} else {
0
},
2,
self.voice_strip.as_ref().map_or(/*default*/ 0, |strip| {
strip.desired_height(width).saturating_add(1)
}),
if self.popups.active.is_above_composer()
&& options.command_popup_placement != CommandPopupPlacement::AboveComposer
{
footer_hint_height
} else {
self.popups
.active
.required_height(width, footer_hint_height)
},
]
.into_iter()
.fold(0, u16::saturating_add)
}
}

View File

@@ -0,0 +1,60 @@
//! Editable composer draft state kept separate from composer control flow.
use std::cell::RefCell;
use std::collections::HashMap;
use crate::bottom_pane::MentionBinding;
use crate::bottom_pane::paste_burst::PasteBurst;
use crate::bottom_pane::textarea::TextArea;
use crate::bottom_pane::textarea::TextAreaState;
pub(super) struct DraftState {
pub(super) textarea: TextArea,
pub(super) textarea_state: RefCell<TextAreaState>,
pub(super) is_bash_mode: bool,
pub(super) pending_pastes: Vec<(String, String)>,
pub(super) input_enabled: bool,
pub(super) input_disabled_placeholder: Option<String>,
pub(super) paste_burst: PasteBurst,
pub(super) disable_paste_burst: bool,
/// Byte offset of the space added by the last skill completion, until the next key is resolved.
pub(super) skill_completion_space: Option<usize>,
pub(super) mention_bindings: HashMap<u64, ComposerMentionBinding>,
pub(super) recent_submission_mention_bindings: Vec<MentionBinding>,
}
impl DraftState {
pub(super) fn new() -> Self {
Self {
textarea: TextArea::new(),
textarea_state: RefCell::new(TextAreaState::default()),
is_bash_mode: false,
pending_pastes: Vec::new(),
input_enabled: true,
input_disabled_placeholder: None,
paste_burst: PasteBurst::default(),
disable_paste_burst: false,
skill_completion_space: None,
mention_bindings: HashMap::new(),
recent_submission_mention_bindings: Vec::new(),
}
}
pub(super) fn skill_completion_space_for_char(&self, ch: char) -> Option<usize> {
self.skill_completion_space.filter(|&space| {
",.;:!?)]}。,、!?》".contains(ch)
&& self.textarea.allows_paste_burst()
&& !self.textarea.is_vim_replace_mode()
&& self.textarea.cursor() == space + 1
&& self.textarea.mouse_selection_range().is_none()
&& self.textarea.text().get(space..space + 1) == Some(" ")
})
}
}
#[derive(Clone, Debug)]
pub(super) struct ComposerMentionBinding {
pub(super) sigil: char,
pub(super) mention: String,
pub(super) path: String,
}

View File

@@ -0,0 +1,79 @@
//! Embedded composers preserve literal drafts and show validation feedback in place.
use super::tests::new_test_composer;
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn plain_text_composer_keeps_command_prefixes_literal() {
let (mut composer, _rx) = new_test_composer();
composer.config = ChatComposerConfig::plain_text();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_footer_hint_override(Some(Vec::new()));
for (prefix, modifiers) in [
('!', KeyModifiers::NONE),
('/', KeyModifiers::NONE),
('?', KeyModifiers::NONE),
('?', KeyModifiers::SHIFT),
] {
composer.handle_key_event(KeyEvent::new(KeyCode::Char(prefix), modifiers));
composer.handle_paste("keep this literal".into());
assert_eq!(
composer.handle_key_event(KeyCode::Tab.into()).0,
InputResult::Submitted {
text: format!("{prefix}keep this literal"),
text_elements: Vec::new(),
}
);
}
}
#[test]
fn buffered_typing_survives_vim_changes_and_cancellation() {
let (mut composer, _rx) = new_test_composer();
composer.handle_key_event(KeyCode::Char('x').into());
composer.set_vim_enabled(/*enabled*/ true);
assert_eq!(composer.current_text(), "x");
composer.set_vim_enabled(/*enabled*/ false);
composer.handle_key_event(KeyCode::Char('y').into());
assert_eq!(composer.clear_for_ctrl_c(), Some("xy".into()));
assert!(!composer.is_in_paste_burst());
composer.handle_key_event(KeyCode::Up.into());
assert_eq!(composer.current_text(), "xy");
}
#[test]
fn paste_enter_retains_a_one_character_first_line() {
let (mut composer, _rx) = new_test_composer();
composer.handle_key_event(KeyCode::Char('x').into());
assert!(composer.handle_paste_enter(Instant::now()));
assert_eq!(composer.clear_for_ctrl_c(), Some("x\n".into()));
}
#[test]
fn embedded_composer_shows_validation_error_without_losing_draft() {
let (mut composer, mut rx) = new_test_composer();
composer.config = ChatComposerConfig::plain_text();
composer.set_footer_hint_override(Some(vec![("enter".into(), "submit".into())]));
composer.set_context_window_pending(/*pending*/ true);
let text = "x".repeat(MAX_USER_INPUT_TEXT_CHARS + 1);
composer.handle_paste(text.clone());
assert_eq!(
composer.handle_key_event(KeyCode::Enter.into()).0,
InputResult::None
);
assert_eq!(composer.current_text_with_pending(), text);
assert!(matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_))));
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 5,
);
let mut buffer = Buffer::empty(area);
composer.render(area, &mut buffer);
let footer = (0..area.width)
.map(|x| buffer[(x, area.bottom() - 1)].symbol())
.collect::<String>();
insta::assert_snapshot!(footer.trim_end(), @" Message too long; limit 1048576 characters");
assert!(composer.footer_flash_delay().is_some());
composer.footer.flash.as_mut().unwrap().expires_at = Instant::now() - Duration::from_secs(1);
assert_eq!(composer.footer_flash_delay(), None);
}

View File

@@ -0,0 +1,412 @@
//! Footer and status-row presentation state for the chat composer.
//! Owners schedule flash expiry redraws; replacing a draft clears its flash.
//! One resolved layout supplies the status, input, popup, and hint rectangles to each consumer.
//! Slash-command and unified mention suggestions preserve passive footer content while keeping input.
//! Interactive transcript footers keep focus over nonempty composer hints. Their owner projects
//! actual pending chord hints; unrelated hints resume when the transcript interaction closes.
//! 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.
//! Only the two base composer modes opt into fresh-thread decoration; queries and help do not.
//! 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.
use std::time::Instant;
use super::super::footer::footer_height;
use super::super::footer::reset_mode_after_activity;
use super::ActivePopup;
use super::warning_notice;
use crate::bottom_pane::footer::FooterKeyHints;
use crate::bottom_pane::footer::FooterProps;
use crate::bottom_pane::footer_content::FooterContent;
use crate::key_hint;
use crossterm::event::KeyCode;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Styled;
use ratatui::text::Line;
use ratatui::text::Text;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use crate::bottom_pane::footer::CollaborationModeIndicator;
use crate::bottom_pane::footer::FooterMode;
use crate::bottom_pane::footer::GoalStatusIndicator;
use crate::key_hint::KeyBinding;
use crate::key_hint::ShortcutHint;
use crate::style::secondary_text_style;
use std::time::Duration;
/// Resolved rectangles shared by painting and cursor placement, without retained layout state.
pub(super) struct ComposerLayout {
pub(super) status: Rect,
pub(super) composer: Rect,
pub(super) remote_images: Rect,
pub(super) thumbnails: Rect,
pub(super) textarea: Rect,
pub(super) popup: Rect,
pub(super) footer: Rect,
}
/// Per-frame transcript content; the composer remains the only footer layout owner.
pub(crate) struct TranscriptFooter {
pub(crate) text: Text<'static>,
pub(crate) cursor_column: Option<u16>,
pub(crate) is_interactive: bool,
}
/// Whether composer suggestions reserve space, cover transcript rows, or stay hidden.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum CommandPopupPlacement {
#[default]
AboveComposer,
Overlay,
/// Retain suggestions while another surface owns input above the draft.
Hidden,
}
/// A borrowed presentation shared by measurement, painting, and cursor placement.
#[derive(Clone, Copy, Default)]
pub(crate) struct ComposerRenderOptions<'a> {
/// Fullscreen limits the composer independently of activity and modal views.
pub(crate) max_height: Option<u16>,
pub(crate) image_previews: Option<&'a crate::transcript_image::composer::ComposerImages>,
pub(crate) rendered_selection:
Option<&'a std::cell::RefCell<crate::rendered_selection::RenderedSelection>>,
/// Reserve a shared hint row independently of whether it currently contains a notice.
pub(crate) composer_gap: Option<&'a crate::bottom_pane::ComposerGap>,
pub(crate) working_tip: Option<&'a crate::turn_tip::TurnTip>,
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,
/// Topmost frame row available for suggestions overlaying the transcript.
pub(crate) overlay_top: u16,
/// The workspace paints the open Presets menu over the completed frame.
pub(crate) floating_shortcuts: bool,
pub(crate) unfocused: bool,
pub(crate) command_popup_placement: CommandPopupPlacement,
pub(crate) footer: Option<&'a TranscriptFooter>,
}
impl super::ChatComposer {
pub(super) fn footer_props(&self) -> FooterProps {
let mode = self.footer_mode();
let is_wsl = {
#[cfg(target_os = "linux")]
{
mode == FooterMode::ShortcutOverlay && crate::clipboard_paste::is_probably_wsl()
}
#[cfg(not(target_os = "linux"))]
{
false
}
};
FooterProps {
mode,
esc_backtrack_hint: self.footer.esc_backtrack_hint,
is_task_running: self.is_task_running,
queue_submissions: self.queue_submissions,
quit_shortcut_key: self.footer.quit_shortcut_key,
collaboration_modes_enabled: self.collaboration_modes_enabled,
is_wsl,
status_line_value: self.footer.status_line_value.clone(),
status_line_enabled: self.footer.status_line_enabled,
key_hints: FooterKeyHints {
agents: self
.agents_navigation_available()
.then_some(key_hint::plain(KeyCode::Left).into()),
toggle_shortcuts: self.footer.toggle_shortcuts_key,
queue: self.footer.queue_key,
insert_newline: self.footer.insert_newline_key,
external_editor: self.footer.external_editor_key,
edit_previous: Some(key_hint::plain(KeyCode::Esc).into()),
show_transcript: self.footer.show_transcript_key,
find_transcript: self.footer.find_transcript_key,
focus_activity: self.footer.focus_activity_key,
history_search: self.footer.history_search_key,
reasoning_down: self.footer.reasoning_down_key,
reasoning_up: self.footer.reasoning_up_key,
toggle_voice: self
.footer
.toggle_voice_key
.filter(|_| self.voice_command_enabled && !self.side_conversation_active),
},
active_agent_label: self.footer.active_agent_label.clone(),
}
}
/// Resolve the effective footer mode via a small priority waterfall.
///
/// The base mode is derived solely from whether the composer is empty:
/// `ComposerEmpty` iff empty, otherwise `ComposerHasDraft`. Transient
/// modes (Esc hint, overlay, quit reminder) can override that base when
/// their conditions are active.
pub(super) fn footer_mode(&self) -> FooterMode {
if self.history_search.is_some() || self.draft.textarea.vim_query().is_some() {
return FooterMode::HistorySearch;
}
let base_mode = if self.is_empty() {
FooterMode::ComposerEmpty
} else {
FooterMode::ComposerHasDraft
};
match self.footer.mode {
FooterMode::HistorySearch => FooterMode::HistorySearch,
FooterMode::EscHint => FooterMode::EscHint,
FooterMode::ShortcutOverlay => FooterMode::ShortcutOverlay,
FooterMode::QuitShortcutReminder if self.quit_shortcut_hint_visible() => {
FooterMode::QuitShortcutReminder
}
FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft
if self.quit_shortcut_hint_visible() =>
{
FooterMode::QuitShortcutReminder
}
FooterMode::QuitShortcutReminder => base_mode,
FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft => base_mode,
}
}
/// Override the footer hint items displayed beneath the composer. Passing
/// `None` restores the default shortcut footer.
pub(crate) fn set_footer_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
self.footer.hint_override = items;
}
/// Show the transient "press again to quit" hint for `key`.
///
/// The owner (`BottomPane`/`ChatWidget`) is responsible for scheduling a
/// redraw after [`super::super::QUIT_SHORTCUT_TIMEOUT`] so the hint can disappear
/// even when the UI is otherwise idle.
pub fn show_quit_shortcut_hint(&mut self, key: KeyBinding, has_focus: bool) {
self.footer.quit_shortcut_expires_at = Instant::now()
.checked_add(super::super::QUIT_SHORTCUT_TIMEOUT)
.or_else(|| Some(Instant::now()));
self.footer.quit_shortcut_key = key;
self.footer.mode = FooterMode::QuitShortcutReminder;
self.set_has_focus(has_focus);
}
/// Clear the "press again to quit" hint immediately.
///
/// Key routing calls this before dispatching ordinary input, so unrelated footer modes
/// such as shortcut help must remain available to their own toggle handlers.
pub fn clear_quit_shortcut_hint(&mut self, has_focus: bool) {
self.footer.quit_shortcut_expires_at = None;
if self.footer.mode == FooterMode::QuitShortcutReminder {
self.footer.mode = reset_mode_after_activity(self.footer.mode);
}
self.set_has_focus(has_focus);
}
/// Whether the quit shortcut hint should currently be shown.
///
/// This is time-based rather than event-based: it may become false without
/// any additional user input, so the UI schedules a redraw when the hint
/// expires.
pub(crate) fn quit_shortcut_hint_visible(&self) -> bool {
self.footer
.quit_shortcut_expires_at
.is_some_and(|expires_at| Instant::now() < expires_at)
}
pub(super) fn custom_footer_height(&self) -> Option<u16> {
if self.draft.textarea.vim_query().is_some() || self.footer.flash_visible() {
return Some(1);
}
self.footer
.hint_override
.as_ref()
.map(|items| if items.is_empty() { 0 } else { 1 })
}
pub(crate) fn empty_state_composer(
&self,
) -> Option<crate::empty_state_animation::ComposerState> {
use crate::empty_state_animation::ComposerState;
let composer = match self.footer_mode() {
FooterMode::ComposerEmpty if self.is_in_paste_burst() => Some(ComposerState::Draft),
FooterMode::ComposerEmpty => Some(ComposerState::Empty),
FooterMode::ComposerHasDraft => Some(ComposerState::Draft),
FooterMode::HistorySearch
| FooterMode::QuitShortcutReminder
| FooterMode::ShortcutOverlay
| FooterMode::EscHint => None,
};
match &self.popups.active {
ActivePopup::None => composer,
ActivePopup::Command(_)
| ActivePopup::File(_)
| ActivePopup::Skill(_)
| ActivePopup::MentionV2(_) => None,
}
}
pub(crate) fn resolve_render_options<'a>(
&self,
mut options: ComposerRenderOptions<'a>,
) -> ComposerRenderOptions<'a> {
options.footer = options.footer.filter(|footer| {
if (self.popups.active.is_above_composer()
&& options.command_popup_placement != CommandPopupPlacement::Hidden
&& footer.is_interactive)
|| self
.footer
.hint_override
.as_ref()
.is_some_and(|items| items.is_empty() || !footer.is_interactive)
|| self.history_search.is_some()
|| self.draft.textarea.vim_query().is_some()
|| self.quit_shortcut_hint_visible()
{
return false;
}
footer.is_interactive || self.footer_mode().shows_passive_line(self.is_task_running)
});
options
}
pub(crate) fn shortcut_overlay_visible(&self) -> bool {
self.footer_mode() == FooterMode::ShortcutOverlay
&& matches!(self.popups.active, ActivePopup::None)
&& self.custom_footer_height().is_none()
}
pub(super) fn shortcuts_above_composer(&self, options: ComposerRenderOptions<'_>) -> bool {
self.shortcut_overlay_visible() && options.footer.is_none()
}
pub(super) fn footer_hint_height(&self, width: u16, options: ComposerRenderOptions<'_>) -> u16 {
if self.shows_shared_status(options) {
return self.status_line_height(width, options);
}
if self.show_warning_notice(options) || self.shortcuts_above_composer(options) {
return 1;
}
options
.footer
.map_or_else(
|| {
self.custom_footer_height()
.unwrap_or_else(|| footer_height(&self.hint_footer_props(options), width))
},
|footer| footer.text.height().try_into().unwrap_or(u16::MAX),
)
.max(u16::from(options.separate_status_line))
}
pub(super) fn render_transcript_footer(
&self,
hint_area: Rect,
buf: &mut Buffer,
footer: &TranscriptFooter,
warning_area: Option<Rect>,
) {
let hint_area = warning_notice::before_warning(hint_area, warning_area);
let mut text = footer.text.clone();
if footer.cursor_column.is_none()
&& self.footer.flash_visible()
&& let Some(flash) = &self.footer.flash
&& let Some(line) = text.lines.last_mut()
{
*line = flash.line.clone();
}
if !footer.is_interactive
&& !self.footer.flash_visible()
&& self.footer_mode() == FooterMode::ComposerEmpty
&& !self.is_in_paste_burst()
&& let Some(key) = self.footer.toggle_shortcuts_key
&& let Some(line) = text.lines.last_mut()
{
let mut shortcuts = Line::default();
if line.width() > 0 {
shortcuts.push_span(" · ".set_style(secondary_text_style()));
}
shortcuts.extend(key.spans());
shortcuts.push_span(" shortcuts".set_style(secondary_text_style()));
if line.width() + shortcuts.width() <= usize::from(hint_area.width) {
line.extend(shortcuts.spans);
}
}
Paragraph::new(text).render(hint_area, buf);
}
pub(crate) fn footer_flash_delay(&self) -> Option<Duration> {
self.footer
.flash
.as_ref()
.and_then(|flash| flash.expires_at.checked_duration_since(Instant::now()))
}
pub(crate) fn show_footer_flash(&mut self, line: Line<'static>, duration: Duration) {
self.footer.show_flash(line, duration);
}
}
pub(super) struct FooterState {
pub(super) quit_shortcut_expires_at: Option<Instant>,
pub(super) quit_shortcut_key: KeyBinding,
pub(super) esc_backtrack_hint: bool,
pub(super) use_shift_enter_hint: bool,
pub(super) mode: FooterMode,
pub(super) hint_override: Option<Vec<(String, String)>>,
pub(super) flash: Option<FooterFlash>,
pub(super) context_window_percent: Option<i64>,
pub(super) context_window_used_tokens: Option<i64>,
pub(super) context_window_pending: bool,
pub(super) collaboration_mode_indicator: Option<CollaborationModeIndicator>,
pub(super) goal_status_indicator: Option<GoalStatusIndicator>,
pub(super) ide_context_active: bool,
pub(super) status_line_value: Option<FooterContent>,
// Available width and occupied height, shared by layout and cursor placement.
pub(super) measured_status_line: std::cell::Cell<Option<(u16, u16)>>,
pub(super) status_line_enabled: bool,
pub(super) side_conversation_context_label: Option<String>,
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) selection_revision: std::cell::Cell<(usize, bool)>,
pub(super) find_transcript_key: Option<ShortcutHint>,
pub(super) focus_activity_key: Option<ShortcutHint>,
pub(super) insert_newline_key: Option<ShortcutHint>,
pub(super) queue_key: Option<ShortcutHint>,
pub(super) toggle_shortcuts_key: Option<ShortcutHint>,
pub(super) history_search_key: Option<ShortcutHint>,
pub(super) reasoning_down_key: Option<ShortcutHint>,
pub(super) reasoning_up_key: Option<ShortcutHint>,
pub(super) toggle_voice_key: Option<ShortcutHint>,
}
#[derive(Clone, Debug)]
pub(super) struct FooterFlash {
pub(super) line: Line<'static>,
pub(super) expires_at: Instant,
}
impl FooterState {
pub(super) fn flash_visible(&self) -> bool {
self.flash
.as_ref()
.is_some_and(|flash| Instant::now() < flash.expires_at)
}
pub(super) fn show_flash(&mut self, line: Line<'static>, duration: Duration) {
let expires_at = Instant::now()
.checked_add(duration)
.unwrap_or_else(Instant::now);
self.flash = Some(FooterFlash { line, expires_at });
}
}
#[cfg(test)]
#[path = "footer_state_tests.rs"]
mod tests;

View File

@@ -0,0 +1,148 @@
//! Footer replacement keeps the existing layout and the focused editor's cursor together.
use super::*;
use crate::app_event::AppEvent;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::ChatComposer;
use crate::bottom_pane::footer::inset_footer_hint_area;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc::unbounded_channel;
fn composer() -> ChatComposer {
let (tx, _rx) = unbounded_channel::<AppEvent>();
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
AppEventSender::new(tx),
/*enhanced_keys_supported*/ false,
"Ask aKode".to_string(),
/*disable_paste_burst*/ true,
);
composer.set_status_line_enabled(/*enabled*/ true);
composer.set_status_line(Some(Line::from("MODEL STATUS").into()));
composer
}
fn render(
composer: &ChatComposer,
footer: Option<&TranscriptFooter>,
) -> (Buffer, Option<(u16, u16)>) {
let options = composer.resolve_render_options(ComposerRenderOptions {
footer,
..ComposerRenderOptions::default()
});
let width = 60;
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, composer.cursor_pos_with_options(area, options))
}
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_string()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn retained_command_suggestions_yield_paint_and_cursor_to_find() {
let mut composer = composer();
composer.draft.textarea.insert_str("/");
composer.sync_popups();
let original = render(&composer, /*footer*/ None);
let footer = TranscriptFooter {
text: vec![
Line::from("Find: needle"),
Line::from("Enter next · Esc close"),
]
.into(),
cursor_column: Some(8),
is_interactive: true,
};
let options = composer.resolve_render_options(ComposerRenderOptions {
footer: Some(&footer),
command_popup_placement: CommandPopupPlacement::Hidden,
..ComposerRenderOptions::default()
});
let mut frames = Vec::new();
for (width, height) in [(60, 8), (24, 8), (12, 3)] {
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let mut buffer = Buffer::empty(area);
composer.render_with_options(area, &mut buffer, /*mask_char*/ None, options);
let cursor = composer.cursor_pos_with_options(area, options);
let footer_area =
inset_footer_hint_area(composer.layout_with_options(area, options).footer);
assert_eq!(
cursor,
(footer_area.width > 8 && footer_area.height > 0)
.then_some((footer_area.x + 8, footer_area.y))
);
assert!(matches!(composer.popups.active, ActivePopup::Command(_)));
assert_eq!(composer.draft.textarea.text(), "/");
frames.push(format!(
"{width}x{height}, cursor {cursor:?}\n{}",
text(&buffer)
));
}
insta::assert_snapshot!(
"find_hides_retained_command_suggestions",
frames.join("\n\n")
);
assert_eq!(render(&composer, /*footer*/ None), original);
}
#[test]
fn copying_from_find_preserves_the_query_above_selection_feedback() {
let mut composer = composer();
let footer = TranscriptFooter {
text: vec![
Line::from("Find: needle"),
Line::from("Ctrl+C copy · Esc clear selection"),
]
.into(),
cursor_column: None,
is_interactive: true,
};
composer.show_footer_flash(
"Copied selection to clipboard".into(),
Duration::from_secs(/*secs*/ 3),
);
let (buffer, cursor) = render(&composer, Some(&footer));
assert_eq!(cursor, None);
insta::assert_snapshot!("transcript_find_copy_footer", text(&buffer));
}
#[test]
fn interactive_query_keeps_focus_over_underlying_hints_but_empty_override_wins() {
let mut composer = composer();
let footer = TranscriptFooter {
text: vec![
Line::from("Find: needle"),
Line::from("Enter next · Esc close"),
]
.into(),
cursor_column: Some(12),
is_interactive: true,
};
let expected = render(&composer, Some(&footer));
composer.set_footer_hint_override(Some(vec![("ctrl+c".to_string(), "quit".to_string())]));
assert_eq!(render(&composer, Some(&footer)), expected);
composer.set_footer_hint_override(Some(Vec::new()));
assert_eq!(
render(&composer, Some(&footer)),
render(&composer, /*footer*/ None)
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,74 @@
//! Read and update the saved composer draft while history search owns the visible preview.
//! Background edits are restored on cancellation and discarded when a history match is accepted.
//! The unchanged fallback preview is copied only before the first background edit.
//! Temporary restores preserve command eligibility; the actual background edit updates it.
use super::super::AttachmentState;
use super::super::ChatComposer;
use super::super::ComposerDraftSnapshot;
use super::super::TextArea;
use super::VimPersistentState;
impl ChatComposer {
pub(crate) fn draft_snapshot(&self) -> ComposerDraftSnapshot {
let draft = self.history_search.as_ref().map_or_else(
|| self.snapshot_draft(),
|search| search.original_draft.clone(),
);
let mut attachments = AttachmentState::default();
let mut textarea = TextArea::new();
attachments.set_remote_image_urls(draft.remote_image_urls.clone(), &mut textarea);
attachments.reset_local_images(draft.local_image_paths, &mut textarea);
ComposerDraftSnapshot {
vim_normal_mode: self.draft.textarea.is_vim_normal_mode(),
text: draft.text,
shell_mode: self
.config
.shell_commands_enabled
.then_some(draft.is_bash_mode),
cursor: draft.cursor,
text_elements: draft.text_elements,
local_images: attachments.local_images,
remote_image_urls: draft.remote_image_urls,
mention_bindings: draft.mention_bindings,
pending_pastes: draft.pending_pastes,
startup_local_history: self.history.startup_local_history().to_vec(),
last_composer_activity_at: None,
sparkle_draft: self.sparkle.draft.get(),
}
}
/// Apply incoming draft changes behind an active search, preserving its query and preview.
pub(in crate::bottom_pane) fn edit_stored_draft(&mut self, edit: impl FnOnce(&mut Self)) {
let Some(mut search) = self.history_search.take() else {
edit(self);
return;
};
search
.preview_draft
.get_or_insert_with(|| search.original_draft.clone());
let preview = self.snapshot_draft();
let preview_vim_history = std::mem::take(&mut self.vim_history);
let mut preview_vim_state = VimPersistentState::default();
self.draft
.textarea
.swap_vim_persistent_state(&mut preview_vim_state);
self.with_sparkle_history_preview(|composer| composer.restore_draft(search.original_draft));
self.draft
.textarea
.swap_vim_persistent_state(&mut search.original_vim_state);
self.vim_history = search.original_vim_history;
edit(self);
search.original_draft = self.snapshot_draft();
search.original_vim_history = std::mem::take(&mut self.vim_history);
self.draft
.textarea
.swap_vim_persistent_state(&mut search.original_vim_state);
self.history_search = Some(search);
self.with_sparkle_history_preview(|composer| composer.restore_draft(preview));
self.draft
.textarea
.swap_vim_persistent_state(&mut preview_vim_state);
self.vim_history = preview_vim_history;
}
}

View File

@@ -0,0 +1,216 @@
//! Pasted text edits the active history query while preserving the original draft.
use super::super::super::chat_composer_history::HistoryEntry;
use super::super::super::chat_composer_history::HistorySearchResult;
use super::super::ChatComposer;
use super::super::ComposerRenderOptions;
use super::super::InputResult;
use super::super::LARGE_PASTE_CHAR_THRESHOLD;
use crate::app_event_sender::AppEventSender;
use crate::render::renderable::Renderable;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use tokio::sync::mpsc::unbounded_channel;
fn composer_with_history() -> ChatComposer {
let (tx, _rx) = unbounded_channel();
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
AppEventSender::new(tx),
/*enhanced_keys_supported*/ false,
"Ask aKode to do anything".to_string(),
/*disable_paste_burst*/ false,
);
for entry in ["git status", "git log"] {
composer
.history
.record_local_submission(HistoryEntry::new(entry.to_string()));
}
composer.set_text_content("draft".to_string(), Vec::new(), Vec::new());
composer
}
fn render_composer(composer: &ChatComposer, width: u16) -> Terminal<TestBackend> {
let mut terminal = Terminal::new(TestBackend::new(width, /*height*/ 5)).unwrap();
terminal
.draw(|frame| composer.render(frame.area(), frame.buffer_mut()))
.unwrap();
terminal
}
#[test]
fn history_search_paste_appends_query_and_accepts_match() {
let mut composer = composer_with_history();
composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
assert!(composer.handle_paste("git".to_string()));
assert_eq!(composer.draft.textarea.text(), "git log");
composer.handle_key_event(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE));
let paste_target = composer.clipboard_paste_target(Some(KeyCode::Insert));
// A background history lookup changes the preview, not the query being edited.
composer.apply_history_search_result(HistorySearchResult::Found(HistoryEntry::new(
"git diff".into(),
)));
assert_eq!(
composer.clipboard_paste_target(Some(KeyCode::Insert)),
paste_target
);
assert!(composer.handle_paste("status".to_string()));
assert_ne!(
composer.clipboard_paste_target(Some(KeyCode::Insert)),
paste_target
);
assert_eq!(
composer.history_search.as_ref().unwrap().query,
"git status"
);
assert_eq!(composer.draft.textarea.text(), "git status");
let terminal = render_composer(&composer, /*width*/ 70);
insta::assert_snapshot!("history_search_pasted_query", terminal.backend());
let (result, _) = composer.handle_key_event(KeyCode::Enter.into());
assert!(matches!(result, InputResult::None));
assert!(!composer.history_search_active());
assert_eq!(composer.draft.textarea.text(), "git status");
}
#[test]
fn history_search_large_paste_clamps_cursor() {
let mut composer = composer_with_history();
composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
composer.handle_paste("x".repeat(usize::from(u16::MAX) + 1));
let terminal = render_composer(&composer, /*width*/ 80);
let cursor = composer.cursor_pos_with_options(
terminal.size().unwrap().into(),
ComposerRenderOptions::default(),
);
assert_eq!(cursor, Some((79, 4)));
insta::assert_snapshot!(
"history_search_large_paste_cursor",
format!("{}\nCursor: {cursor:?}", terminal.backend())
);
}
#[test]
fn history_search_empty_paste_preserves_selected_match() {
let mut composer = composer_with_history();
let reverse_search = KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL);
composer.handle_key_event(reverse_search);
composer.handle_paste("git".to_string());
assert_eq!(composer.draft.textarea.text(), "git log");
composer.handle_key_event(reverse_search);
assert_eq!(composer.draft.textarea.text(), "git status");
let selected_draft = composer.snapshot_draft();
for paste in ["", "\x1b[31m\x1b[0m"] {
composer.handle_paste(paste.to_string());
assert_eq!(composer.snapshot_draft(), selected_draft);
}
let terminal = render_composer(&composer, /*width*/ 70);
insta::assert_snapshot!("history_search_empty_paste", terminal.backend());
}
#[test]
fn history_search_paste_shows_separators_and_matches_original_query() {
let mut composer = composer_with_history();
for entry in ["foobarbaz", "foo↵bar⇥baz"] {
composer
.history
.record_local_submission(HistoryEntry::new(entry.to_string()));
}
let query = "foo\nbar\tbaz";
let reverse_search = KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL);
composer.handle_key_event(reverse_search);
composer.handle_paste(query.to_string());
assert_eq!(composer.history_search.as_ref().unwrap().query, query);
assert_eq!(composer.draft.textarea.text(), "draft");
let terminal = render_composer(&composer, /*width*/ 70);
let cursor = composer.cursor_pos_with_options(
terminal.size().unwrap().into(),
ComposerRenderOptions::default(),
);
assert_eq!(cursor, Some((31, 4)));
insta::assert_snapshot!(
"history_search_pasted_separators",
format!("{}\nCursor: {cursor:?}", terminal.backend())
);
composer.handle_key_event(KeyCode::Esc.into());
composer
.history
.record_local_submission(HistoryEntry::new(query.to_string()));
composer.handle_key_event(reverse_search);
composer.handle_paste(query.to_string());
composer.handle_key_event(KeyCode::Enter.into());
assert!(!composer.history_search_active());
assert_eq!(composer.draft.textarea.text(), query);
}
#[test]
fn history_search_paste_preserves_original_draft_on_miss_and_cancel() {
let mut composer = composer_with_history();
composer.handle_paste("x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1));
composer.draft.textarea.set_cursor(/*pos*/ 2);
let original_draft = composer.snapshot_draft();
for cancel_key in [
KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
] {
composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
composer.handle_paste("git".to_string());
assert_eq!(composer.draft.textarea.text(), "git log");
composer.handle_paste(" missing".to_string());
assert_eq!(composer.snapshot_draft(), original_draft);
assert_eq!(
composer.history_search.as_ref().unwrap().query,
"git missing"
);
composer.handle_key_event(cancel_key);
assert!(!composer.history_search_active());
assert_eq!(composer.snapshot_draft(), original_draft);
}
}
#[test]
fn history_search_paste_uses_full_sanitized_text() {
let temp = tempfile::tempdir().unwrap();
let image_path = temp.path().join("history.png");
image::RgbaImage::new(/*width*/ 1, /*height*/ 1)
.save(&image_path)
.unwrap();
let image_path = image_path.to_string_lossy().into_owned();
let large_paste = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1);
for (pasted, query) in [
(image_path.clone(), image_path),
(large_paste.clone(), large_paste),
(
"é\r\n中\r\x1b[31mtext\x1b[0m".to_string(),
"é\n中\ntext".to_string(),
),
] {
let mut composer = composer_with_history();
composer
.history
.record_local_submission(HistoryEntry::new(query.clone()));
composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
composer.handle_paste(pasted);
assert_eq!(composer.history_search.as_ref().unwrap().query, query);
assert_eq!(composer.draft.textarea.text(), query);
assert!(composer.attachments.local_image_paths().is_empty());
assert!(composer.draft.pending_pastes.is_empty());
assert!(composer.current_text_elements().is_empty());
}
}

View File

@@ -0,0 +1,211 @@
//! Embed the composer in question rows, resetting history navigation when drafts change.
//! Recovered appends cancel pending Vim commands before moving the cursor and stay out of dot repeat.
//! Normal-mode recovery is one undoable edit; active insert/replace sessions keep their grouping.
//! Paste payloads stay intact and sparkle stays dismissed.
//! Command prefixes become escaped, editable prompt text before answers are appended.
use super::super::textarea::VimPersistentState;
use super::*;
impl ComposerDraft {
pub(in crate::bottom_pane) fn text_with_pending(&self) -> String {
ChatComposer::expand_pending_pastes(
&self.text,
self.text_elements.clone(),
&self.pending_pastes,
)
.0
}
}
impl ChatComposer {
pub(in crate::bottom_pane) fn append_recovered_drafts(&mut self, drafts: &str) {
self.flush_pending_input();
self.dismiss_sparkle();
if self.draft.textarea.is_vim_operator_pending() {
self.draft.textarea.enter_vim_normal_mode();
}
self.finish_vim_edit();
let mut vim_state = VimPersistentState::default();
self.draft
.textarea
.swap_vim_persistent_state(&mut vim_state);
let started_vim_edit = self.begin_direct_vim_edit();
// Recovered answers turn the draft into a prompt, so escape any command prefix
// before appending them. Shell mode stores its `!` outside the textarea.
let text = self.draft.textarea.text();
let slash_command_draft = self.slash_input().should_parse_on_dequeue(text)
&& parse_slash_name(text.trim_start()).is_none_or(|(name, _, _)| !name.contains('/'));
if self.draft.is_bash_mode {
self.draft.is_bash_mode = false;
self.draft.textarea.insert_str_at(/*pos*/ 0, "\\!");
} else if self.is_bang_shell_command() || slash_command_draft {
let prefix_len =
self.draft.textarea.text().len() - self.draft.textarea.text().trim_start().len();
self.draft.textarea.insert_str_at(prefix_len, "\\");
}
self.move_cursor_to_end();
if !self.current_text().is_empty() {
self.insert_str("\n\n");
}
let char_count = drafts.chars().count();
if char_count > LARGE_PASTE_CHAR_THRESHOLD {
let placeholder = self.next_large_paste_placeholder(char_count);
self.draft.textarea.insert_element(&placeholder);
self.draft.pending_pastes.push((placeholder, drafts.into()));
self.sync_popups();
} else {
self.insert_str(drafts);
}
self.draft
.textarea
.swap_vim_persistent_state(&mut vim_state);
if started_vim_edit {
self.finish_vim_edit();
}
}
pub(in crate::bottom_pane) fn restore_inline_draft(&mut self, draft: ComposerDraft) {
self.history.reset_navigation();
self.restore_draft(draft);
}
pub(crate) fn inline_flash(&self) -> Option<Line<'static>> {
self.footer
.flash
.as_ref()
.filter(|_| self.footer.flash_visible())
.map(|flash| flash.line.clone())
}
pub(crate) fn reset_vim_mode(&mut self) {
self.vim_history = VimHistory::default();
self.draft.textarea.enter_vim_insert_mode();
}
/// Refresh at traversal start without resetting recalled entries or pending lookups.
pub(crate) fn copy_history_for_key(&mut self, composer: &Self, key: KeyEvent) {
let recall = self.is_empty()
&& !self.history.is_navigating()
&& if self.draft.textarea.is_vim_normal_mode() {
self.vim_normal_keymap.move_up.is_pressed(key)
|| self.vim_normal_keymap.move_down.is_pressed(key)
} else {
self.editor_keymap.move_up.is_pressed(key)
|| self.editor_keymap.move_down.is_pressed(key)
};
let search =
self.history_search_previous_keys.is_pressed(key) && !self.handles_key_as_editing(key);
if self.history_search.is_none() && (recall || search) {
self.history = composer.history.clone();
self.history.reset_navigation();
}
}
/// Give modal editing precedence over a containing view's submit/navigation keys.
/// Up/Down remain available to inline choices; j/k keep their Vim editing behavior.
pub(crate) fn handles_key_as_editing(&self, key: KeyEvent) -> bool {
self.history_search.is_some()
|| self.should_handle_vim_insert_escape(key)
|| self.draft.textarea.is_vim_operator_pending()
|| self.draft.textarea.wants_vim_search_key(key)
|| (self.draft.textarea.is_vim_normal_mode()
&& !matches!(key.code, KeyCode::Up | KeyCode::Down)
&& !self.submit_keys.is_pressed(key)
&& !self.queue_keys.is_pressed(key)
&& (self.vim_normal_keymap.move_up.is_pressed(key)
|| self.vim_normal_keymap.move_down.is_pressed(key)))
}
/// Integrate already-classified buffered typing before another answer takes over this editor.
pub(crate) fn flush_pending_input(&mut self) {
self.flush_pending_input_with_shell_prefix(ShellPrefixHandling::Interpret);
}
pub(in crate::bottom_pane) fn flush_pending_input_with_shell_prefix(
&mut self,
shell_prefix: ShellPrefixHandling,
) {
if let Some(text) = self.draft.paste_burst.flush_before_modified_input() {
self.apply_paste_with_shell_prefix(text, shell_prefix);
}
self.draft.paste_burst.clear_after_explicit_paste();
}
pub(crate) fn inline_input_height(&self, width: u16) -> u16 {
self.draft.textarea.desired_height(width.max(1))
+ u16::from(self.history_search.is_some() || self.draft.textarea.vim_query().is_some())
+ u16::from(self.footer.flash_visible())
}
pub(crate) fn inline_cursor_pos(&self, mut area: Rect) -> Option<(u16, u16)> {
area.height = area
.height
.saturating_sub(u16::from(self.footer.flash_visible()));
let query_area = Rect::new(
area.x,
area.bottom().saturating_sub(1),
area.width,
area.height.min(1),
);
if let Some(query) = self.draft.textarea.vim_query() {
return query.cursor_pos(query_area);
}
if self.history_search.is_some() {
return self.history_search_query_cursor_pos(query_area);
}
self.draft
.textarea
.cursor_pos_with_state(area, *self.draft.textarea_state.borrow())
}
pub(crate) fn render_inline_input(&self, area: Rect, buf: &mut Buffer) {
if area.is_empty() {
return;
}
ratatui::widgets::Clear.render(area, buf);
Block::default()
.style(Style::reset().patch(user_message_style()))
.render(area, buf);
let mut area = area;
if self.footer.flash_visible()
&& let Some(flash) = &self.footer.flash
{
area.height = area.height.saturating_sub(1);
flash.line.clone().render(
Rect::new(area.x, area.bottom(), area.width, /*height*/ 1),
buf,
);
}
if let Some(query) = self.draft.textarea.vim_query() {
area.height = area.height.saturating_sub(1);
query.render(
Rect::new(area.x, area.bottom(), area.width, /*height*/ 1),
buf,
);
} else if let Some(line) = self.history_search_footer_line() {
area.height = area.height.saturating_sub(1);
line.render(
Rect::new(area.x, area.bottom(), area.width, /*height*/ 1),
buf,
);
}
let mut state = self.draft.textarea_state.borrow_mut();
let highlights: Vec<_> = self
.history_search_highlight_ranges()
.into_iter()
.chain(self.draft.textarea.vim_search_highlights())
.map(|range| (range, Style::new().reversed().bold()))
.collect();
self.draft.textarea.render_ref_styled_with_highlights(
area,
buf,
&mut state,
Style::default(),
&highlights,
);
if self.draft.textarea.is_empty() {
Line::from(self.placeholder_text.as_str().dim()).render(area, buf);
}
}
}

View File

@@ -0,0 +1,240 @@
//! Production mention overlays retain the draft, status footer and editor cursor across scopes.
use super::*;
use pretty_assertions::assert_eq;
use ratatui::layout::Size;
use tokio::sync::mpsc::unbounded_channel;
fn composer() -> ChatComposer {
let (tx, _rx) = unbounded_channel::<AppEvent>();
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
AppEventSender::new(tx),
/*enhanced_keys_supported*/ false,
"Ask aKode".to_string(),
/*disable_paste_burst*/ true,
);
composer.set_status_line_enabled(/*enabled*/ true);
composer.set_status_line(Some("MODEL STATUS".into()));
composer.set_mentions_v2_enabled(/*enabled*/ true);
composer.set_plugin_mentions(Some(
(0..12)
.map(|index| PluginCapabilitySummary {
config_name: format!("plugin{index:02}@test"),
display_name: format!("Plugin{index:02}"),
plugin_namespace: None,
description: Some(format!("Plugin description {index:02}")),
has_skills: false,
mcp_server_names: Vec::new(),
})
.collect(),
));
composer.set_text_content("@".to_string(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor("@".len());
composer
}
fn render_overlay(
composer: &ChatComposer,
size: Size,
footer: &TranscriptFooter,
) -> (Buffer, Rect, Option<(u16, u16)>) {
let options = composer.resolve_render_options(ComposerRenderOptions {
command_popup_placement: CommandPopupPlacement::Overlay,
footer: Some(footer),
..Default::default()
});
let mut buffer = Buffer::empty(Rect::new(
/*x*/ 0,
/*y*/ 0,
size.width,
size.height,
));
let height = composer
.desired_height_with_options(size.width, options)
.min(size.height);
let area = Rect::new(/*x*/ 0, size.height - height, size.width, height);
for y in 0..area.y {
Line::from(format!("Transcript row {y:02}: behind the menu").magenta())
.render(Rect::new(/*x*/ 0, y, size.width, /*height*/ 1), &mut buffer);
}
composer.render_with_options(area, &mut buffer, /*mask_char*/ None, options);
(
buffer,
area,
composer.cursor_pos_with_options(area, options),
)
}
fn buffer_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_string()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn mention_scopes_overlay_history_without_moving_composer_or_footer() {
let footer = TranscriptFooter {
text: "TRANSCRIPT STATUS".into(),
cursor_column: None,
is_interactive: false,
};
for (width, height) in [(80, 32), (40, 32), (80, 12), (80, 7), (80, 6), (80, 5)] {
let mut composer = composer();
composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
let size = Size::new(width, height);
let (closed, composer_area, cursor) = render_overlay(&composer, size, &footer);
let composer_start = closed.index_of(composer_area.x, composer_area.y);
composer.popups.dismissed_mention_token = None;
composer.sync_popups();
let mut menu_row = None;
for scope in ["all", "filesystem", "plugins"] {
let (open, area, open_cursor) = render_overlay(&composer, size, &footer);
assert_eq!((area, open_cursor), (composer_area, cursor));
assert_eq!(
&open.content[composer_start..],
&closed.content[composer_start..],
);
if (1..=2).contains(&composer_area.y) && scope != "filesystem" {
assert!(buffer_text(&open).contains("Plugin00"));
}
if height == 32 {
assert_eq!(
&open.content[..usize::from(width)],
&closed.content[..usize::from(width)]
);
let current_menu_row = (0..composer_area.y).find(|y| {
(0..width)
.map(|x| open[(x, *y)].symbol())
.collect::<String>()
.contains("Mentions")
});
assert!(current_menu_row.is_some());
if let Some(previous) = menu_row {
assert_eq!(current_menu_row, Some(previous));
}
menu_row = current_menu_row;
// The popup owns exactly its measured height, including both overflow rows.
let ActivePopup::MentionV2(popup) = &composer.popups.active else {
panic!("expected unified mentions");
};
let first_popup_row = composer_area.y - popup.calculate_required_height(width);
assert!(current_menu_row.is_some_and(|row| row >= first_popup_row));
assert!((first_popup_row..composer_area.y).all(|y| {
!(0..width)
.map(|x| open[(x, y)].symbol())
.collect::<String>()
.contains("Transcript row")
}));
}
if (width, height) == (80, 32) && scope == "all" {
insta::assert_snapshot!("mention_scopes_overlay_history", buffer_text(&open));
}
composer.handle_key_event(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE));
}
composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert_eq!(
render_overlay(&composer, size, &footer),
(closed, composer_area, cursor)
);
}
}
#[test]
fn mention_menu_reserves_height_above_composer_and_owns_cursor_over_interactive_footer() {
let composer = composer();
let footer = TranscriptFooter {
text: "Find: needle".into(),
cursor_column: Some(6),
is_interactive: true,
};
let options = composer.resolve_render_options(ComposerRenderOptions {
footer: Some(&footer),
..Default::default()
});
assert!(options.footer.is_none());
let width = 80;
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);
let ComposerLayout {
composer: surface,
textarea,
popup,
footer,
..
} = composer.layout_with_options(area, options);
assert_eq!((popup.bottom(), surface.bottom()), (surface.y, footer.y));
assert_eq!(
composer.cursor_pos_with_options(area, options),
Some((3, textarea.y))
);
insta::assert_snapshot!("mention_menu_above_composer", buffer_text(&buffer));
}
#[test]
fn fallback_completions_keep_the_draft_cursor_and_footer_anchored() {
let footer = TranscriptFooter {
text: "TRANSCRIPT STATUS".into(),
cursor_column: None,
is_interactive: false,
};
for (width, height) in [(80, 24), (40, 16), (20, 5)] {
for token in ["$", "@"] {
let mut composer = composer();
composer.popups.active = ActivePopup::None;
composer.draft.textarea.set_text_clearing_elements(token);
let size = Size::new(width, height);
let (closed, composer_area, cursor) = render_overlay(&composer, size, &footer);
composer.popups.active = if token == "$" {
ActivePopup::Skill(SkillPopup::new(vec![MentionItem {
display_name: "Example skill".into(),
description: Some("Review this checkout".into()),
insert_text: "$example".into(),
search_terms: vec!["example".into()],
path: None,
category_tag: None,
sort_rank: 1,
}]))
} else {
let mut popup = FileSearchPopup::new();
popup.set_matches(
"",
vec![akode_file_search::FileMatch {
score: 1,
path: "src/example.rs".into(),
root: "/repo".into(),
match_type: akode_file_search::MatchType::File,
indices: None,
}],
);
ActivePopup::File(popup)
};
let (open, area, open_cursor) = render_overlay(&composer, size, &footer);
assert_eq!((area, open_cursor), (composer_area, cursor));
let start = open.index_of(area.x, area.y);
assert_eq!(&open.content[start..], &closed.content[start..]);
if height > 5 {
assert!(buffer_text(&open).contains(if token == "$" {
"Example skill"
} else {
"src/example.rs"
}));
}
}
}
}

View File

@@ -0,0 +1,168 @@
//! Mouse gestures flush pending typing before layout and hit testing. Left dragging selects
//! editable text using the textarea's last rendered viewport and hides completion suggestions.
//! Double/triple clicks select words/logical lines using the transcript's shared gesture rules.
//! Selection release follows the transcript/footer copy policy while keeping editable text selected.
//! Explicit copy preserves the draft and cursor, and clears after confirmed delivery.
//! Wheel browsing uses the current viewport without changing popup or selection ownership.
use super::*;
use crate::clipboard_copy::CopyStatus;
use crate::clipboard_copy::worker::CopyResult;
use crate::tui::SelectionCopy;
use crate::tui::TuiEvent;
use crossterm::event::MouseButton;
use crossterm::event::MouseEvent;
use crossterm::event::MouseEventKind;
/// The input that will receive clipboard text, independent of a search preview.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum ClipboardPasteTarget {
Draft(String, super::super::textarea::EditTarget),
HistorySearch(String),
VimSearch(String, super::super::textarea::EditTarget),
}
impl ChatComposer {
pub(crate) fn clipboard_paste_target(
&self,
shortcut: Option<KeyCode>,
) -> Option<ClipboardPasteTarget> {
let allowed = self.draft.input_enabled
&& !self.blocks_direct_input
&& (shortcut.is_some()
|| (self.history_search.is_none()
&& self.draft.textarea.vim_query().is_none()
&& self.draft.textarea.mouse_selection_range().is_none()));
if !allowed {
return None;
}
Some(if let Some(search) = &self.history_search {
ClipboardPasteTarget::HistorySearch(search.query.clone())
} else if let Some(search) = self.draft.textarea.vim_query() {
ClipboardPasteTarget::VimSearch(
search.editor.text().to_string(),
search.editor.edit_target(),
)
} else {
ClipboardPasteTarget::Draft(self.current_text(), self.draft.textarea.edit_target())
})
}
pub(in crate::bottom_pane) fn finish_copy(
&mut self,
completion: &(u64, crate::clipboard_copy::worker::CopyResult),
current: bool,
) -> Option<usize> {
self.draft.textarea.finish_copy(completion, current)
}
pub(crate) fn copy_selection(
&mut self,
event: &TuiEvent,
copy: impl FnOnce(&str) -> Result<CopyStatus, String>,
) -> Option<(usize, Result<CopyStatus, String>)> {
let copy_requested = matches!(event, TuiEvent::Key(key) if crate::text_selection::is_copy_key(*key))
|| matches!(event, TuiEvent::Mouse(mouse)
if mouse.kind == MouseEventKind::Down(MouseButton::Right)
&& self.draft.textarea.contains_mouse(*mouse));
if !copy_requested
|| !self.draft.input_enabled
|| self.history_search.is_some()
|| self.draft.textarea.vim_query().is_some()
{
return None;
}
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() {
self.apply_paste(pasted);
}
self.draft.paste_burst.clear_window_after_non_char();
let range = self.draft.textarea.mouse_selection_range()?;
self.end_mouse_drag();
let text = &self.draft.textarea.text()[range];
let char_count = text.chars().count();
let result = copy(text);
if let Ok(CopyStatus::Pending(id)) = result {
self.draft.textarea.defer_copy(id);
}
if result == Ok(CopyStatus::Confirmed) {
self.draft.textarea.set_cursor(self.draft.textarea.cursor());
}
Some((char_count, result))
}
pub(crate) fn copy_selection_on_release(
&mut self,
event: MouseEvent,
selection_copy: SelectionCopy,
copy: impl FnOnce(&str, SelectionCopy) -> (CopyResult, Option<std::sync::Arc<()>>),
) -> Option<(usize, Option<CopyResult>)> {
if event.kind != MouseEventKind::Up(MouseButton::Left) {
return None;
}
let range = self.draft.textarea.mouse_selection_range()?;
let text = &self.draft.textarea.text()[range];
let char_count = text.chars().count();
let (result, primary_owner) = copy(text, selection_copy);
self.draft.textarea.retain_primary(primary_owner);
if selection_copy.copies_clipboard() {
return Some((char_count, Some(result)));
}
Some((char_count, None))
}
pub(crate) fn clear_mouse_selection(&mut self) {
self.draft.textarea.set_cursor(self.draft.textarea.cursor());
}
pub(crate) fn end_mouse_drag(&mut self) {
self.draft.textarea.end_mouse_drag();
}
pub(crate) fn cancel_primary(&mut self) {
self.draft.textarea.cancel_primary();
}
pub(crate) fn prepare_mouse(&mut self, event: MouseEvent) -> bool {
if !self.draft.input_enabled
|| self.blocks_direct_input
|| self.history_search.is_some()
|| self.draft.textarea.vim_query().is_some()
{
self.end_mouse_drag();
return false;
}
if matches!(event.kind, MouseEventKind::Down(_)) {
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() {
self.apply_paste(pasted);
}
self.draft.paste_burst.clear_window_after_non_char();
}
true
}
/// Dispatch after preparation and rendering have refreshed the viewport.
pub(crate) fn handle_mouse(&mut self, event: MouseEvent) -> bool {
if self
.draft
.textarea
.scroll_mouse(event, &mut self.draft.textarea_state.borrow_mut())
{
return true;
}
let handled = self
.draft
.textarea
.handle_mouse(event, *self.draft.textarea_state.borrow());
if handled {
self.draft.skill_completion_space = None;
self.draft.textarea_state.borrow_mut().follow_cursor();
self.attachments.clear_remote_image_selection();
self.sync_popups();
}
handled
}
}
#[cfg(test)]
#[path = "mouse_tests.rs"]
mod tests;

View File

@@ -0,0 +1,336 @@
//! Mouse edits preserve buffered typing and keep placeholder payloads in sync.
use super::super::tests::new_test_composer;
use super::*;
use crossterm::event::MouseButton::Left;
use crossterm::event::MouseButton::Right;
use crossterm::event::MouseEventKind::Down;
use crossterm::event::MouseEventKind::Up;
use pretty_assertions::assert_eq;
fn mouse(composer: &mut ChatComposer, area: Rect, kind: MouseEventKind, column: u16, row: u16) {
let event = MouseEvent {
kind,
column,
row,
modifiers: KeyModifiers::NONE,
};
assert!(composer.prepare_mouse(event));
composer.render(area, &mut Buffer::empty(area));
assert!(composer.handle_mouse(event));
}
#[test]
fn composer_mouse_edits_flush_typing_and_reconcile_placeholders() {
let (mut composer, _rx) = new_test_composer();
composer.insert_str("hello");
composer
.draft
.paste_burst
.begin_with_retro_grabbed("\nworld".into(), Instant::now());
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 4,
);
composer.render(area, &mut Buffer::empty(area));
let (x, y) = composer.cursor_pos(area).unwrap();
mouse(&mut composer, area, Down(Left), x - 5, y);
composer.insert_str("X");
assert_eq!(composer.current_text(), "hello\nXworld");
composer.handle_paste("z".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1));
for path in [Some("first.png"), Some("second.png"), None] {
composer.render(area, &mut Buffer::empty(area));
let (x, y) = composer.cursor_pos(area).unwrap();
// Double-clicking inside the label selects the entire atomic element.
for kind in [Down(Left), Up(Left), Down(Left), Up(Left)] {
mouse(&mut composer, area, kind, x - 1, y);
}
if let Some(path) = path {
let path = PathBuf::from(path);
composer.attach_image(path.clone());
assert_eq!(composer.attachments.local_image_paths(), vec![path]);
} else {
composer.handle_key_event(KeyCode::Char('é').into());
assert!(composer.attachments.is_empty());
}
assert!(composer.draft.pending_pastes.is_empty());
}
}
#[test]
fn recovery_keeps_unselected_text_after_a_held_replace_key() {
for (text, expected) in [("abcd", "aXd"), ("!abcd", "!aXd")] {
let (mut composer, _rx) = new_test_composer();
composer.set_text_content(text.into(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor(/*pos*/ 0);
composer.set_vim_enabled(/*enabled*/ true);
composer.handle_key_event(KeyCode::Char('R').into());
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 4,
);
composer.render(area, &mut Buffer::empty(area));
let (x, y) = composer.cursor_pos(area).unwrap();
for (kind, column) in [
(Down(Left), x + 1),
(MouseEventKind::Drag(Left), x + 3),
(Up(Left), x + 3),
] {
mouse(&mut composer, area, kind, column, y);
}
let now = Instant::now();
composer.handle_input_basic_with_time(KeyCode::Char('X').into(), now);
let before = composer.draft_snapshot();
assert_eq!(composer.recovery_snapshot().text, expected);
assert_eq!(composer.draft_snapshot(), before);
assert!(composer.handle_paste_burst_flush(now + PasteBurst::recommended_flush_delay()));
assert_eq!(composer.current_text(), expected);
}
}
#[test]
fn backspace_deletes_a_body_selection_before_an_absorbed_prefix() {
let (mut composer, _rx) = new_test_composer();
composer.insert_str("!review text");
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 4,
);
composer.render(area, &mut Buffer::empty(area));
let (x, y) = composer.cursor_pos(area).unwrap();
for (kind, column) in [
(Down(Left), x),
(MouseEventKind::Drag(Left), x - "review text".len() as u16),
(Up(Left), x - "review text".len() as u16),
] {
mouse(&mut composer, area, kind, column, y);
}
composer.handle_key_event(KeyCode::Backspace.into());
assert_eq!(composer.current_text(), "!");
assert_eq!(composer.draft.textarea.mouse_selection_range(), None);
}
#[test]
fn selected_text_navigation_does_not_recall_history_or_select_images() {
for (key, remote) in [
(KeyCode::Up, false),
(KeyCode::Down, false),
(KeyCode::Up, true),
] {
let (mut composer, _rx) = new_test_composer();
for text in ["first", "second"] {
composer
.history
.record_local_submission(HistoryEntry::new(text.into()));
}
composer.handle_key_event(KeyCode::Up.into());
if remote {
composer.set_remote_image_urls(vec!["https://example.com/image.png".into()]);
}
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 10,
);
composer.render(area, &mut Buffer::empty(area));
let (x, y) = composer.cursor_pos(area).unwrap();
if remote {
composer.draft.textarea.set_cursor(/*pos*/ 0);
composer.handle_key_event(KeyCode::Up.into());
}
let (start, end) = if key == KeyCode::Up {
(x, x - 6)
} else {
(x - 6, x)
};
for (kind, column) in [
(Down(Left), start),
(MouseEventKind::Drag(Left), end),
(Up(Left), end),
] {
mouse(&mut composer, area, kind, column, y);
}
assert_eq!(composer.attachments.selected_remote_image_index, None);
composer.handle_key_event(key.into());
assert_eq!(
(
composer.current_text(),
composer.draft.textarea.mouse_selection_range(),
composer.attachments.selected_remote_image_index
),
("second".to_string(), None, None)
);
}
}
#[test]
fn right_click_copy_uses_the_refreshed_editor_bounds() {
let (mut composer, _rx) = new_test_composer();
composer.insert_str("hello world");
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 4,
);
composer.render(area, &mut Buffer::empty(area));
let (x, y) = composer.cursor_pos(area).unwrap();
for (kind, column) in [
(Down(Left), x - 11),
(MouseEventKind::Drag(Left), x - 6),
(Up(Left), x - 6),
] {
mouse(&mut composer, area, kind, column, y);
}
let click = MouseEvent {
kind: Down(Right),
column: x - 9,
row: y,
modifiers: KeyModifiers::NONE,
};
assert_eq!(
composer.copy_selection(&TuiEvent::Mouse(click), |text| {
assert_eq!(text, "hello");
Ok(CopyStatus::Unconfirmed)
}),
Some((5, Ok(CopyStatus::Unconfirmed)))
);
let shifted_area = Rect::new(
/*x*/ 0, /*y*/ 10, /*width*/ 20, /*height*/ 4,
);
assert!(composer.prepare_mouse(click));
composer.render(shifted_area, &mut Buffer::empty(shifted_area));
assert_eq!(
composer.copy_selection(&TuiEvent::Mouse(click), |_| unreachable!()),
None
);
let (_, row) = composer.cursor_pos(shifted_area).unwrap();
assert_eq!(
composer.copy_selection(&TuiEvent::Mouse(MouseEvent { row, ..click }), |text| {
assert_eq!(text, "hello");
Ok(CopyStatus::Unconfirmed)
}),
Some((5, Ok(CopyStatus::Unconfirmed)))
);
assert_eq!(composer.current_text(), "hello world");
let event = TuiEvent::Mouse(MouseEvent { row, ..click });
composer.copy_selection(&event, |_| Ok(CopyStatus::Pending(1)));
// A fresh pointer selection must not be cleared by the older copy.
for (kind, column) in [
(Down(Left), x - 11),
(MouseEventKind::Drag(Left), x - 6),
(Up(Left), x - 6),
] {
mouse(&mut composer, shifted_area, kind, column, row);
}
let selection = composer.draft.textarea.mouse_selection_range();
assert_eq!(
composer.finish_copy(&(1, Ok(CopyStatus::Confirmed)), /*current*/ true),
None
);
assert_eq!(composer.draft.textarea.mouse_selection_range(), selection);
let key = TuiEvent::Key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
composer.copy_selection(&key, |_| Ok(CopyStatus::Pending(2)));
let paste_target = composer.clipboard_paste_target(Some(KeyCode::Insert));
assert_eq!(
composer.finish_copy(&(2, Ok(CopyStatus::Confirmed)), /*current*/ true),
Some(5)
);
assert_eq!(composer.draft.textarea.mouse_selection_range(), None);
assert_ne!(
composer.clipboard_paste_target(Some(KeyCode::Insert)),
paste_target
);
}
#[test]
fn selection_release_copies_and_keeps_the_editable_selection() {
let (mut composer, _rx) = new_test_composer();
composer.insert_str("hello world");
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 4,
);
composer.render(area, &mut Buffer::empty(area));
let (x, y) = composer.cursor_pos(area).unwrap();
let release = MouseEvent {
kind: Up(Left),
column: x - 6,
row: y,
modifiers: KeyModifiers::NONE,
};
for (kind, column) in [
(Down(Left), x - 11),
(MouseEventKind::Drag(Left), x - 6),
(Up(Left), x - 6),
] {
mouse(&mut composer, area, kind, column, y);
}
let selection_copy = crate::tui::SelectionCopy::on_select(
/*clipboard*/ true, /*primary*/ true, /*clear_selection*/ false,
);
let owner = std::sync::Arc::new(());
let retained = std::sync::Arc::downgrade(&owner);
assert_eq!(
composer.copy_selection_on_release(release, selection_copy, |text, policy| {
assert_eq!((text, policy), ("hello", selection_copy));
(Ok(CopyStatus::Confirmed), Some(owner))
}),
Some((5, Some(Ok(CopyStatus::Confirmed))))
);
let mut buffer = Buffer::empty(area);
composer.render(area, &mut buffer);
let highlight = (x - 11..x)
.map(|column| {
buffer[(column, y)]
.modifier
.contains(ratatui::style::Modifier::REVERSED)
})
.collect::<Vec<_>>();
assert_eq!(
highlight,
vec![
true, true, true, true, true, false, false, false, false, false, false
]
);
assert!(retained.upgrade().is_some());
composer.insert_str("X");
assert_eq!(composer.current_text(), "X world");
assert!(retained.upgrade().is_none());
}
#[test]
fn selection_release_reports_only_clipboard_result() {
for (clipboard, expected) in [(true, Some(Ok(CopyStatus::Pending(7)))), (false, None)] {
let (mut composer, _rx) = new_test_composer();
composer.insert_str("hello world");
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 4,
);
composer.render(area, &mut Buffer::empty(area));
let (x, y) = composer.cursor_pos(area).unwrap();
let release = MouseEvent {
kind: Up(Left),
column: x - 6,
row: y,
modifiers: KeyModifiers::NONE,
};
for (kind, column) in [
(Down(Left), x - 11),
(MouseEventKind::Drag(Left), x - 6),
(Up(Left), x - 6),
] {
mouse(&mut composer, area, kind, column, y);
}
let selection = composer.draft.textarea.mouse_selection_range();
let policy = crate::tui::SelectionCopy::on_select(
clipboard, /*primary*/ true, /*clear_selection*/ false,
);
assert_eq!(
composer.copy_selection_on_release(release, policy, |text, actual| {
assert_eq!((text, actual), ("hello", policy));
(Ok(CopyStatus::Pending(7)), Some(std::sync::Arc::new(())))
}),
Some((5, expected))
);
composer.finish_copy(&(7, Ok(CopyStatus::Confirmed)), /*current*/ true);
assert_eq!(composer.draft.textarea.mouse_selection_range(), selection);
}
}

View File

@@ -0,0 +1,313 @@
//! Classify and integrate composer pastes and capture raw paste tabs before completion or submission.
//! Multiline pastes on a line beginning with `> ` continue that prefix after every newline,
//! including blank lines, but not after a single trailing newline. This happens before large pastes
//! are collapsed, so their expanded text retains the quoting. Two unquoted newlines after the
//! inserted text or placeholder leave the cursor in the next Markdown block, including in embedded
//! answer fields.
//! Provisional startup input, search queries, and shell input remain literal.
//! Paste classification and insertion share one textarea edit target, including selection replacement.
use super::*;
use crate::bottom_pane::paste_burst::FlushResult;
use crate::bottom_pane::textarea::EditTarget;
impl ChatComposer {
pub(crate) fn insert_str(&mut self, text: &str) {
self.insert_str_at_target(
self.draft.textarea.edit_target(),
text,
ShellPrefixHandling::Interpret,
);
}
fn insert_str_at_target(
&mut self,
target: EditTarget,
text: &str,
shell_prefix: ShellPrefixHandling,
) {
self.draft.skill_completion_space = None;
if !text.is_empty() && self.sparkle.draft.get() == sparkle::SparkleDraft::Untouched {
self.dismiss_sparkle();
}
let started_vim_edit = self.begin_direct_vim_edit();
let elements_before = target
.replaces_text()
.then(|| self.draft.textarea.element_payloads());
let inserts_shell_prefix = matches!(shell_prefix, ShellPrefixHandling::Interpret)
&& target.start() == 0
&& text.starts_with('!');
self.draft.textarea.insert_str_at_target(target, text);
if let Some(elements_before) = elements_before {
self.reconcile_deleted_elements(elements_before);
}
if inserts_shell_prefix {
self.sync_bash_mode_from_text();
}
self.sync_popups();
if started_vim_edit {
self.finish_vim_edit();
}
}
/// Include accepted but unflushed keys without changing live paste detection.
pub(crate) fn recovery_snapshot(&self) -> ComposerDraftSnapshot {
let mut snapshot = self.draft_snapshot();
let pending = self.draft.paste_burst.clone().flush_pending();
if matches!(pending, FlushResult::None) {
return snapshot;
}
let mut textarea = TextArea::new();
textarea.set_text_with_elements(&snapshot.text, &snapshot.text_elements);
match pending {
FlushResult::Typed(ch) if self.draft.textarea.is_vim_replace_mode() => {
textarea.set_cursor(snapshot.cursor);
if let Some(selection) = self.draft.textarea.mouse_selection_range() {
let offset = usize::from(self.draft.is_bash_mode);
textarea.replace_range(
selection.start + offset..selection.end + offset,
&ch.to_string(),
);
} else {
textarea.replace_vim_text(&ch.to_string());
}
}
FlushResult::Typed(ch) => {
if let Some(space) = self.draft.skill_completion_space_for_char(ch) {
let space = space + usize::from(self.draft.is_bash_mode);
textarea.replace_range(space..space + 1, &ch.to_string());
snapshot.cursor = space + ch.len_utf8();
} else {
textarea.insert_str_at(snapshot.cursor, &ch.to_string());
}
}
FlushResult::Paste(pasted) => textarea.insert_str_at(snapshot.cursor, &pasted),
FlushResult::None => {}
}
snapshot.text = textarea.text().to_owned();
snapshot.text_elements = textarea.text_elements();
snapshot
}
/// Classify an explicit paste before integrating text shared with the buffered key path.
pub fn handle_paste(&mut self, pasted: String) -> bool {
self.flush_pending_paste_burst();
self.note_sparkle_paste(&pasted);
self.apply_paste(pasted)
}
pub(crate) fn flush_pending_paste_burst(&mut self) {
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() {
self.apply_paste(pasted);
}
}
pub(in crate::bottom_pane) fn paste_handoff_deadline(&self) -> Option<Instant> {
if self.draft.disable_paste_burst {
return None;
}
self.draft.paste_burst.handoff_deadline()
}
/// Display flushed text without losing the window for its trailing paste keys.
pub(in crate::bottom_pane) fn flush_handoff_paste(&mut self, now: Instant) -> bool {
let deadline = self.paste_handoff_deadline();
let flushed = self.handle_paste_burst_flush(now);
if flushed && let Some(deadline) = deadline.filter(|deadline| *deadline >= now) {
self.draft.paste_burst.preserve_window_until(deadline);
}
flushed
}
/// Enable or disable paste-burst handling.
///
/// `disable_paste_burst` is an escape hatch for terminals/platforms where the burst heuristic
/// is unwanted or has already been handled elsewhere.
///
/// When transitioning from enabled → disabled, we "defuse" any in-flight burst state so it
/// cannot affect subsequent normal typing:
///
/// - First, flush held/buffered text via [`PasteBurst::flush_before_modified_input`] and
/// integrate it with [`Self::apply_paste`]. Its key events have already been classified;
/// [`Self::handle_paste`] classifies explicit terminal pastes before using the same
/// integration path (large-paste placeholders, image-path detection, and popup sync).
/// - Then clear the burst timing and Enter-suppression window via
/// [`PasteBurst::clear_after_explicit_paste`].
///
/// We intentionally do not use `clear_window_after_non_char()` here: it clears timing state
/// without emitting any buffered text, which can leave a non-empty buffer unable to flush
/// later (because `flush_if_due()` relies on `last_plain_char_time` to time out).
pub(crate) fn set_disable_paste_burst(&mut self, disabled: bool) {
let was_disabled = self.draft.disable_paste_burst;
self.draft.disable_paste_burst = disabled;
if disabled && !was_disabled {
self.flush_pending_paste_burst();
self.draft.paste_burst.clear_after_explicit_paste();
}
}
/// Applies any due `PasteBurst` flush at time `now`.
///
/// Converts [`PasteBurst::flush_if_due`] results into concrete textarea mutations.
/// Buffered keys have already been classified; paste results use [`Self::apply_paste`].
///
/// Callers:
///
/// - UI ticks via [`ChatComposer::flush_paste_burst_if_due`], so held first-chars can render.
/// - Input handling via [`ChatComposer::handle_input_basic`], so a due burst does not lag.
/// - Submission, before deciding whether Enter belongs to an active paste burst.
pub(super) fn handle_paste_burst_flush(&mut self, now: Instant) -> bool {
match self.draft.paste_burst.flush_if_due(now) {
FlushResult::Paste(pasted) => {
self.apply_paste(pasted);
true
}
FlushResult::Typed(ch) => {
let completion_space = self.draft.skill_completion_space_for_char(ch);
let started_vim_edit = completion_space.is_some() && self.begin_direct_vim_edit();
if let Some(space) = completion_space {
self.draft.textarea.replace_range(space..space + 1, "");
}
self.insert_str(ch.to_string().as_str());
if started_vim_edit {
self.finish_vim_edit();
}
true
}
FlushResult::None => false,
}
}
/// Integrate pasted text into the composer.
///
/// Both input paths integrate their text here:
///
/// - Real/explicit paste events surfaced by the terminal, and
/// - Non-bracketed "paste bursts" that
/// [`PasteBurst`](crate::bottom_pane::paste_burst::PasteBurst) buffers and later flushes here.
///
/// Behavior:
///
/// - If history search is active, inserts nonempty text into its query and ignores empty pastes.
/// - If Vim search is active, inserts text into its query.
/// - Otherwise, if the paste is larger than `LARGE_PASTE_CHAR_THRESHOLD` chars, inserts a
/// placeholder element (expanded on submit) and stores the full text in `pending_pastes`.
/// - Otherwise, if the paste looks like an image path, attaches the image and inserts a
/// trailing space so the user can keep typing naturally.
/// - Otherwise, inserts the pasted text directly into the textarea.
///
/// Composer edits clear paste-burst Enter suppression and sync popups.
pub(super) fn apply_paste(&mut self, pasted: String) -> bool {
self.apply_paste_with_shell_prefix(pasted, ShellPrefixHandling::Interpret)
}
pub(super) fn apply_paste_with_shell_prefix(
&mut self,
pasted: String,
shell_prefix: ShellPrefixHandling,
) -> bool {
self.draft.skill_completion_space = None;
let pasted = pasted.replace("\r\n", "\n").replace('\r', "\n");
let pasted = sanitize_user_text(pasted.into());
if self.history_search.is_some() {
if !pasted.is_empty() {
self.update_history_search_query(|query| query.push_str(&pasted));
}
return true;
}
if let Some(query) = self.draft.textarea.vim_query_mut() {
query.editor.insert_str(&pasted);
return true;
}
self.draft.textarea_state.get_mut().follow_cursor();
let started_vim_edit = self.begin_direct_vim_edit();
let elements_before = self.draft.textarea.element_payloads();
let target = self.draft.textarea.edit_target();
let before_cursor = &self.draft.textarea.text()[..target.start()];
let current_line = before_cursor.rsplit('\n').next().unwrap_or_default();
let is_blockquote = self.config.blockquote_paste_enabled
&& !self.is_bang_shell_command()
&& current_line.starts_with("> ")
&& pasted.contains('\n');
let pasted = if is_blockquote {
let pasted = pasted
.strip_suffix('\n')
.filter(|pasted| !pasted.is_empty())
.unwrap_or(pasted.as_ref());
std::borrow::Cow::Owned(pasted.replace('\n', "\n> "))
} else {
pasted
};
let char_count = pasted.chars().count();
if char_count > LARGE_PASTE_CHAR_THRESHOLD {
let placeholder = self.next_large_paste_placeholder(char_count);
self.draft
.textarea
.insert_element_at_target(target, &placeholder);
self.draft
.pending_pastes
.push((placeholder, pasted.into_owned()));
} else if char_count > 1
&& self.image_paste_enabled()
&& self.handle_paste_image_path(&pasted)
{
let cursor = self.draft.textarea.cursor();
self.draft.textarea.insert_str_at(cursor, " ");
} else {
self.insert_str_at_target(target, &pasted, shell_prefix);
}
if is_blockquote {
let textarea = &mut self.draft.textarea;
textarea.insert_str_at(textarea.cursor(), "\n\n");
}
self.draft.paste_burst.clear_after_explicit_paste();
self.reconcile_deleted_elements(elements_before);
self.sync_popups();
if started_vim_edit {
self.finish_vim_edit();
}
true
}
pub(super) fn handle_paste_tab(&mut self, key: KeyEvent, now: Instant) -> bool {
key.code == KeyCode::Tab
&& key.modifiers.is_empty()
&& self.append_recent_paste_separator('\t', now)
}
pub(super) fn append_recent_paste_separator(&mut self, separator: char, now: Instant) -> bool {
if self.draft.disable_paste_burst || !self.draft.textarea.allows_paste_burst() {
return false;
}
self.handle_paste_burst_flush(now);
if self
.draft
.paste_burst
.append_control_char_if_active(separator, now)
{
return true;
}
// Short non-ASCII prefixes are inserted directly, without a held first character.
if self
.draft
.paste_burst
.direct_insert_newline_should_insert(now)
{
self.draft
.paste_burst
.begin_with_retro_grabbed(String::new(), now);
return self
.draft
.paste_burst
.append_control_char_if_active(separator, now);
}
false
}
}
#[cfg(test)]
#[path = "blockquote_paste_tests.rs"]
mod blockquote_paste_tests;

View File

@@ -0,0 +1,168 @@
//! Composer paste handling for literal paths and raw tabs.
use super::tests::new_test_composer;
use super::*;
use pretty_assertions::assert_eq;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
#[cfg(unix)]
#[test]
fn pasting_fifo_path_keeps_it_editable() {
let dir = tempfile::tempdir().unwrap();
let name = "tty.usbserial-110";
let status = std::process::Command::new("mkfifo")
.arg(dir.path().join(name))
.status()
.unwrap();
assert!(status.success());
let (mut composer, _rx) = new_test_composer();
let prefix = shlex::try_quote(dir.path().to_str().unwrap()).unwrap();
composer.handle_paste(format!("{prefix}/{name}"));
composer.handle_key_event(KeyEvent::from(KeyCode::Backspace));
insta::assert_snapshot!(
composer.current_text().strip_prefix(prefix.as_ref()).unwrap(),
@"/tty.usbserial-11"
);
}
#[test]
fn paste_burst_tabs_preserve_multiline_draft() {
for running in [false, true] {
for first_line in ["x", "界", "first line\n"] {
let (mut composer, _rx) = new_test_composer();
composer.set_task_running(running);
let mut now = Instant::now();
let payload = format!("{first_line}\t\tsecond line\n\tthird line\n");
for ch in payload.chars() {
let (result, _) = match ch {
'\t' => {
assert!(composer.handle_paste_tab(KeyEvent::from(KeyCode::Tab), now));
(InputResult::None, true)
}
'\n' => composer.handle_submission_with_time(/*should_queue*/ false, now),
ch => composer
.handle_input_basic_with_time(KeyEvent::from(KeyCode::Char(ch)), now),
};
assert_eq!(result, InputResult::None);
now += Duration::from_millis(/*millis*/ 1);
}
composer.handle_paste_burst_flush(now + PasteBurst::recommended_active_flush_delay());
assert_eq!(composer.current_text(), payload);
if running && first_line == "first line\n" {
let mut terminal = Terminal::new(TestBackend::new(60, 8)).unwrap();
terminal
.draw(|frame| composer.render(frame.area(), frame.buffer_mut()))
.unwrap();
insta::assert_snapshot!("paste_burst_tab_indentation", terminal.backend());
}
let (result, _) = composer.handle_key_event(KeyEvent::from(KeyCode::Tab));
let expected = if running {
InputResult::Queued {
text: payload.trim().to_string(),
text_elements: Vec::new(),
action: QueuedInputAction::Plain,
pending_pastes: Vec::new(),
}
} else {
InputResult::Submitted {
text: payload.trim().to_string(),
text_elements: Vec::new(),
}
};
assert_eq!(result, expected);
}
}
}
#[test]
fn paste_burst_tabs_refresh_idle_timeout() {
for first_char in ['x', '界'] {
let (mut composer, _rx) = new_test_composer();
let mut now = Instant::now();
composer.handle_input_basic_with_time(KeyEvent::from(KeyCode::Char(first_char)), now);
assert!(composer.handle_paste_tab(KeyEvent::from(KeyCode::Tab), now));
for _ in 0..3 {
now += PasteBurst::recommended_active_flush_delay() / 2;
assert!(composer.handle_paste_tab(KeyEvent::from(KeyCode::Tab), now));
}
composer.handle_paste_burst_flush(now + PasteBurst::recommended_active_flush_delay());
assert_eq!(composer.current_text(), format!("{first_char}\t\t\t\t"));
assert!(!composer.handle_paste_tab(
KeyEvent::from(KeyCode::Tab),
now + PasteBurst::recommended_active_flush_delay()
));
}
}
#[test]
fn paste_burst_tab_does_not_accept_a_completion() {
let (mut composer, _rx) = new_test_composer();
composer.insert_str("/");
assert!(matches!(composer.popups.active, ActivePopup::Command(_)));
composer
.draft
.paste_burst
.begin_with_retro_grabbed("review this".to_string(), Instant::now());
let (result, _) = composer.handle_key_event(KeyEvent::from(KeyCode::Tab));
assert_eq!(result, InputResult::None);
let pasted = composer
.draft
.paste_burst
.flush_before_modified_input()
.unwrap();
composer.handle_paste(pasted);
assert_eq!(composer.current_text(), "/review this\t");
}
#[test]
fn paste_burst_expired_before_tab_still_queues() {
let (mut composer, _rx) = new_test_composer();
composer.set_task_running(/*running*/ true);
composer.handle_input_basic_with_time(
KeyEvent::from(KeyCode::Char('x')),
Instant::now() - Duration::from_secs(/*secs*/ 1),
);
let (result, _) = composer.handle_key_event(KeyEvent::from(KeyCode::Tab));
assert_eq!(
result,
InputResult::Queued {
text: "x".to_string(),
text_elements: Vec::new(),
action: QueuedInputAction::Plain,
pending_pastes: Vec::new(),
}
);
}
#[test]
fn paste_burst_modified_queue_binding_still_dispatches() {
let (mut composer, _rx) = new_test_composer();
composer.set_task_running(/*running*/ true);
composer.queue_keys = vec![key_hint::ctrl(KeyCode::Char('q'))];
composer.handle_input_basic_with_time(KeyEvent::from(KeyCode::Char('x')), Instant::now());
let (result, _) =
composer.handle_key_event(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::CONTROL));
assert_eq!(
result,
InputResult::Queued {
text: "x".to_string(),
text_elements: Vec::new(),
action: QueuedInputAction::Plain,
pending_pastes: Vec::new(),
}
);
}

View File

@@ -0,0 +1,134 @@
//! Popup lifecycle state for the chat composer.
//! Tracks the single active popup plus dismissal/query state used to synchronize it.
use crate::bottom_pane::command_popup::CommandPopup;
use crate::bottom_pane::file_search_popup::FileSearchPopup;
use crate::bottom_pane::mentions_v2::MentionV2Popup;
use crate::bottom_pane::skill_popup::SkillPopup;
use crate::bottom_pane::textarea::TextArea;
use std::ops::Range;
/// One token occurrence whose autocomplete popup should remain hidden.
pub(super) struct DismissedToken {
/// Popup query text for the token, excluding its leading sigil.
query: String,
/// Exact token text, including its sigil, captured when the popup was dismissed.
token: String,
/// Zero-based ordinal among identical token strings in the draft at dismissal time.
occurrence: usize,
}
impl DismissedToken {
/// Captures the stable identity of the token at `range`.
pub(super) fn new(textarea: &TextArea, range: Range<usize>, query: String) -> Self {
let text = textarea.text();
let token = text[range.clone()].to_string();
let occurrence = complete_token_occurrences_before(textarea, &token, range.start);
Self {
query,
token,
occurrence,
}
}
/// Returns whether `range` identifies the same token occurrence in the current draft.
///
/// Byte offsets may shift under offset-only edits, while the token text and its ordinal keep
/// later identical occurrences distinct.
pub(super) fn matches(&self, textarea: &TextArea, range: &Range<usize>, query: &str) -> bool {
let text = textarea.text();
if self.query != query || text.get(range.clone()) != Some(self.token.as_str()) {
return false;
}
complete_token_occurrences_before(textarea, &self.token, range.start) == self.occurrence
}
}
/// Counts complete editable-token occurrences before `before` in a single ordered pass.
///
/// Whitespace and atomic element edges delimit occurrences; bare nested sigils do not. This keeps
/// dismissal identity aligned with the completion resolver without rescanning every element for
/// each match.
fn complete_token_occurrences_before(textarea: &TextArea, token: &str, before: usize) -> usize {
let text = textarea.text();
let mut elements_ending_before_matches = textarea.text_element_ranges().peekable();
let mut elements_starting_after_matches = textarea.text_element_ranges().peekable();
text[..before]
.match_indices(token)
.filter(|(start, _)| {
let end = start + token.len();
while elements_ending_before_matches
.peek()
.is_some_and(|element| element.end < *start)
{
elements_ending_before_matches.next();
}
while elements_starting_after_matches
.peek()
.is_some_and(|element| element.start < end)
{
elements_starting_after_matches.next();
}
let ends_at_boundary = text[end..].chars().next().is_none_or(char::is_whitespace)
|| elements_starting_after_matches
.peek()
.is_some_and(|element| element.start == end);
let starts_at_boundary = *start == 0
|| text[..*start]
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| elements_ending_before_matches
.peek()
.is_some_and(|element| element.end == *start);
starts_at_boundary && ends_at_boundary
})
.count()
}
#[derive(Default)]
pub(super) struct PopupState {
pub(super) active: ActivePopup,
pub(super) dismissed_command_token: Option<String>,
pub(super) dismissed_file_token: Option<DismissedToken>,
pub(super) current_file_query: Option<String>,
pub(super) dismissed_mention_token: Option<DismissedToken>,
}
impl PopupState {
pub(super) fn active(&self) -> bool {
!matches!(self.active, ActivePopup::None)
}
}
/// Popup state - at most one can be visible at any time.
#[derive(Default)]
pub(super) enum ActivePopup {
#[default]
None,
Command(CommandPopup),
File(FileSearchPopup),
Skill(SkillPopup),
MentionV2(MentionV2Popup),
}
impl ActivePopup {
/// Shared suggestion menus render above the draft and retain its status footer.
pub(super) fn is_above_composer(&self) -> bool {
!matches!(self, Self::None)
}
pub(super) fn required_height(&self, width: u16, footer_total_height: u16) -> u16 {
match self {
Self::None => footer_total_height,
Self::Command(popup) => popup.calculate_required_height(width) + footer_total_height,
Self::File(popup) => popup.calculate_required_height() + footer_total_height,
Self::Skill(popup) => popup.calculate_required_height(width) + footer_total_height,
Self::MentionV2(popup) => popup.calculate_required_height(width) + footer_total_height,
}
}
}
#[cfg(test)]
#[path = "popup_state_tests.rs"]
mod tests;

View File

@@ -0,0 +1,60 @@
use super::*;
use crate::bottom_pane::textarea::TextArea;
use pretty_assertions::assert_eq;
#[test]
fn dismissed_tokens_after_adjacent_elements_are_occurrence_scoped() {
let first_bound = "$bound1";
let second_bound = "$bound2";
let token = "$other";
let text = format!("{first_bound}{token} {second_bound}{token}");
let first_start = first_bound.len();
let second_start = text.rfind(token).expect("second token");
let second_bound_start = text.find(second_bound).expect("second bound mention");
let mut textarea = TextArea::new();
textarea.insert_str(&text);
textarea.add_element_range(0..first_start);
textarea.add_element_range(second_bound_start..second_bound_start + second_bound.len());
let dismissed = DismissedToken::new(
&textarea,
first_start..first_start + token.len(),
"other".to_string(),
);
assert!(!dismissed.matches(
&textarea,
&(second_start..second_start + token.len()),
"other",
));
}
#[test]
fn nested_at_query_does_not_count_as_complete_dismissed_token() {
let text = "@ma@latest @ma";
let second_start = text.rfind("@ma").expect("second token");
let mut textarea = TextArea::new();
textarea.insert_str(text);
assert_eq!(
complete_token_occurrences_before(&textarea, "@ma", second_start),
0
);
}
#[test]
fn non_sigil_elements_delimit_dismissed_token_occurrences() {
let token = "$other";
let first_element = "[one]";
let text = format!("{token}{first_element} {token}");
let second_start = text.rfind(token).expect("second token");
let mut textarea = TextArea::new();
textarea.insert_str(&text);
textarea.add_element_range(token.len()..token.len() + first_element.len());
let dismissed = DismissedToken::new(&textarea, 0..token.len(), "other".to_string());
assert!(!dismissed.matches(
&textarea,
&(second_start..second_start + token.len()),
"other",
));
}

View File

@@ -0,0 +1,164 @@
//! Restricted editing retains drafts and allows local warnings, configuration, and quit commands.
//! Unavailable threads also allow recovery and other local commands.
//! Connected unavailable threads retain the empty-prompt agents shortcut.
//! Paste Enter handling is shared with normal submission so buffered newlines survive both paths.
//! In the draft-only handoff, a recent paste prefix can preserve a raw Enter as a newline.
//! The submit path still requires an established paste before treating Enter as a newline.
//! 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.
use super::*;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum RestrictedInputMode {
Disconnected,
UnavailableThread,
DraftHandoff,
}
impl ChatComposer {
/// Preserve Enter inside a paste burst without attempting submission.
pub(crate) fn handle_paste_enter(&mut self, now: Instant) -> bool {
let in_slash_context = self.slash_commands_enabled()
&& !self.draft.is_bash_mode
&& (matches!(self.popups.active, ActivePopup::Command(_))
|| self
.draft
.textarea
.text()
.lines()
.next()
.unwrap_or("")
.starts_with('/'));
!in_slash_context && self.append_paste_newline(now)
}
fn append_paste_newline(&mut self, now: Instant) -> bool {
if self.draft.disable_paste_burst {
return false;
}
if self.draft.paste_burst.is_active()
&& self
.draft
.paste_burst
.append_control_char_if_active('\n', now)
{
return true;
}
if self
.draft
.paste_burst
.newline_should_insert_instead_of_submit(now)
{
self.draft.textarea.insert_str("\n");
self.draft.paste_burst.extend_window(now);
return true;
}
false
}
pub(crate) fn handle_restricted_key(
&mut self,
key: KeyEvent,
mode: RestrictedInputMode,
) -> InputResult {
if mode == RestrictedInputMode::DraftHandoff {
if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
let now = tokio::time::Instant::now().into_std();
self.flush_handoff_paste(now);
// Completion does not own keys during the handoff.
self.popups.active = ActivePopup::None;
if self.draft.textarea.wants_vim_search_key(key) {
self.edit_restricted_draft(key);
} else if self.handle_vim_history_key(key) {
self.draft.textarea_state.get_mut().follow_cursor();
} else {
// Enter cannot submit here. Preserve a possible legacy paste
// newline after a directly inserted prefix, as we do for Tab.
let paste_separator = (key.code == KeyCode::Enter
&& key.modifiers.is_empty()
&& (self.append_paste_newline(now)
|| self.append_recent_paste_separator('\n', now)))
|| self.handle_paste_tab(key, now);
if !paste_separator
&& !self.submit_keys.is_pressed(key)
&& !self.queue_keys.is_pressed(key)
{
self.edit_restricted_draft(key);
}
}
// A paste flush can open a popup before the edit changes its text.
// Dismiss it before ordinary input resumes, even without a redraw.
self.popups.active = ActivePopup::None;
}
return InputResult::None;
}
if mode == RestrictedInputMode::UnavailableThread && self.handle_agents_navigation(key) {
return InputResult::None;
}
self.cancel_history_search();
self.attachments.clear_remote_image_selection();
self.popups.active = ActivePopup::None;
self.set_disable_paste_burst(/*disabled*/ true);
// Expand in reverse order so remaining ranges stay valid. Textarea replacement
// preserves the cursor and other elements, including images and mentions.
let pending_pastes = std::mem::take(&mut self.draft.pending_pastes);
if !pending_pastes.is_empty() {
for element in self.draft.textarea.text_elements().into_iter().rev() {
if let Some((_, text)) = pending_pastes.iter().find(|(placeholder, _)| {
element.placeholder(self.draft.textarea.text()) == Some(placeholder.as_str())
}) {
self.draft
.textarea
.replace_range(element.byte_range.start..element.byte_range.end, text);
}
}
}
if pending_pastes.is_empty()
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
&& self.submit_keys.is_pressed(key)
{
let input = self.slash_input();
let text = self.draft.textarea.text();
let command = input
.bare_command(text)
.or_else(|| input.inline_command(text).map(|command| command.command))
.filter(|_| text.trim().lines().count() == 1);
if matches!(command, Some(SlashCommandItem::Builtin(command))
if matches!(command, SlashCommand::Warnings | SlashCommand::Config | SlashCommand::Quit | SlashCommand::Exit)
|| mode == RestrictedInputMode::UnavailableThread && command.available_when_thread_unavailable())
{
return self
.try_dispatch_bare_slash_command()
.or_else(|| self.try_dispatch_slash_command_with_args())
.unwrap_or(InputResult::None);
}
}
// 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)
{
self.edit_restricted_draft(key);
}
InputResult::None
}
fn edit_restricted_draft(&mut self, key: KeyEvent) {
// Null is sent internally to clean up on disconnect or expand a paste.
let before = if key.code == KeyCode::Null {
None
} else {
self.draft.textarea_state.get_mut().follow_cursor();
self.before_sparkle_editor_key(key)
};
let (result, _) = self.handle_input_basic(key);
self.after_sparkle_key(before, &result);
}
}
#[cfg(test)]
#[path = "reconnect_tests.rs"]
mod tests;

View File

@@ -0,0 +1,310 @@
//! Offline edits retain the same attachment bookkeeping as ordinary text edits.
use super::super::tests::new_test_composer;
use super::*;
use crossterm::event::MouseEvent;
use crossterm::event::MouseEventKind;
use pretty_assertions::assert_eq;
#[tokio::test(start_paused = true)]
async fn draft_handoff_preserves_newline_after_short_unicode_prefix() {
let (mut composer, _) = new_test_composer();
for key in [KeyCode::Char('猫'), KeyCode::Enter, KeyCode::Char('犬')] {
assert_eq!(
composer.handle_restricted_key(key.into(), RestrictedInputMode::DraftHandoff),
InputResult::None,
);
}
tokio::time::advance(Duration::from_millis(/*millis*/ 100)).await;
composer.flush_handoff_paste(tokio::time::Instant::now().into_std());
composer.handle_restricted_key(KeyCode::Enter.into(), RestrictedInputMode::DraftHandoff);
insta::assert_snapshot!(composer.current_text(), @"猫
犬");
let (mut composer, _) = new_test_composer();
composer.handle_key_event(KeyCode::Char('猫').into());
let (result, _) = composer.handle_key_event(KeyCode::Enter.into());
assert!(matches!(result, InputResult::Submitted { text, .. } if text == "猫"));
}
#[tokio::test(start_paused = true)]
async fn handoff_edit_discards_stale_command_before_ordinary_enter() {
for bracketed_paste in [true, false] {
let (mut composer, _) = new_test_composer();
if bracketed_paste {
composer.handle_paste("/quit".into());
assert!(matches!(composer.popups.active, ActivePopup::Command(_)));
} else {
for ch in "/quit".chars() {
composer.handle_restricted_key(
KeyCode::Char(ch).into(),
RestrictedInputMode::DraftHandoff,
);
}
assert!(composer.draft.paste_burst.is_active());
}
composer.handle_restricted_key(
KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL),
RestrictedInputMode::DraftHandoff,
);
assert_eq!(composer.current_text(), "");
// A failed handoff can return to ordinary input before a redraw.
let (result, _) = composer.handle_key_event(KeyCode::Enter.into());
assert_eq!(result, InputResult::None);
}
}
#[test]
fn offline_delete_reveals_the_edited_row_without_moving_the_caret() {
let (mut composer, _) = new_test_composer();
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 8,
);
let options = ComposerRenderOptions {
max_height: Some(area.height),
..ComposerRenderOptions::default()
};
let text = (1..=20)
.map(|n| format!("line {n:02} abc"))
.collect::<Vec<_>>()
.join("\n");
composer.set_text_content(text.clone(), Vec::new(), Vec::new());
let cursor = text.len() - 2;
composer.draft.textarea.set_cursor(cursor);
let mut buffer = Buffer::empty(area);
composer.render_with_options(area, &mut buffer, /*mask_char*/ None, options);
let (x, y) = composer.cursor_pos_with_options(area, options).unwrap();
for _ in 0..3 {
assert!(composer.handle_mouse(MouseEvent {
kind: MouseEventKind::ScrollUp,
column: x,
row: y,
modifiers: KeyModifiers::NONE,
}));
}
// Disconnect cleanup and blocked submits must not count as edits.
for key in [KeyCode::Null, KeyCode::Enter, KeyCode::Tab] {
composer.handle_restricted_key(key.into(), RestrictedInputMode::Disconnected);
let mut buffer = Buffer::empty(area);
composer.render_with_options(area, &mut buffer, /*mask_char*/ None, options);
assert_eq!(composer.cursor_pos_with_options(area, options), None);
}
composer.handle_restricted_key(KeyCode::Delete.into(), RestrictedInputMode::Disconnected);
let mut buffer = Buffer::empty(area);
composer.render_with_options(area, &mut buffer, /*mask_char*/ None, options);
assert_eq!(
(composer.current_text(), composer.draft.textarea.cursor()),
(text.replace("line 20 abc", "line 20 ac"), cursor)
);
assert!(composer.cursor_pos_with_options(area, options).is_some());
let rows = buffer
.content
.chunks(usize::from(area.width))
.map(|row| {
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!("offline_delete_after_wheel", rows);
}
#[test]
fn reconnect_expands_pastes_preserving_images_and_cursor() {
let (mut composer, _) = new_test_composer();
let paste = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1);
composer.handle_paste(paste.clone());
composer.attach_image(PathBuf::from("local.png"));
composer.handle_paste(paste);
let expanded = composer.current_text_with_pending();
let images = composer.draft_snapshot().local_images;
composer.handle_restricted_key(
KeyEvent::new(KeyCode::Char('!'), KeyModifiers::NONE),
RestrictedInputMode::Disconnected,
);
let draft = composer.draft_snapshot();
assert_eq!(
(
draft.text,
draft.cursor,
draft.local_images,
draft.pending_pastes
),
(
format!("{expanded}!"),
expanded.len() + 1,
images,
Vec::new()
)
);
assert_eq!(draft.text_elements.len(), 1);
}
#[test]
fn reconnect_edit_removes_deleted_attachment_and_paste_metadata() {
let (mut composer, _) = new_test_composer();
composer.attach_image(PathBuf::from("local.png"));
composer.handle_paste("x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1));
composer.handle_restricted_key(
KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL),
RestrictedInputMode::Disconnected,
);
let draft = composer.draft_snapshot();
assert_eq!(
(draft.text, draft.local_images, draft.pending_pastes),
(String::new(), Vec::new(), Vec::new())
);
}
#[test]
fn reconnect_edit_cancels_history_preview_without_losing_original_draft() {
let (mut composer, _) = new_test_composer();
composer.set_text_content("original draft".into(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor(/*pos*/ 14);
composer.begin_history_search();
composer.apply_history_search_result(HistorySearchResult::Found(HistoryEntry::new(
"history preview".into(),
)));
composer.handle_restricted_key(
KeyEvent::new(KeyCode::Char('!'), KeyModifiers::NONE),
RestrictedInputMode::Disconnected,
);
assert_eq!(composer.current_text(), "original draft!");
assert!(!composer.history_search_active());
}
#[test]
fn unavailable_thread_dispatches_recovery_and_local_commands() {
for command in [
SlashCommand::New,
SlashCommand::Clear,
SlashCommand::Resume,
SlashCommand::Agents,
SlashCommand::MultiAgents,
SlashCommand::Quit,
SlashCommand::Exit,
SlashCommand::Status,
SlashCommand::DebugConfig,
SlashCommand::Pwd,
SlashCommand::Rollout,
SlashCommand::Copy,
SlashCommand::Raw,
] {
let (mut composer, _) = new_test_composer();
composer.set_text_content(format!("/{}", command.command()), Vec::new(), Vec::new());
assert_eq!(
composer.handle_restricted_key(
KeyEvent::from(KeyCode::Enter),
RestrictedInputMode::UnavailableThread,
),
InputResult::Command(command),
);
assert_eq!(composer.current_text(), "");
}
}
#[test]
fn disconnected_input_dispatches_local_config_command() {
let (mut composer, _) = new_test_composer();
composer.set_text_content("/config".into(), Vec::new(), Vec::new());
assert_eq!(
composer.handle_restricted_key(
KeyEvent::from(KeyCode::Enter),
RestrictedInputMode::Disconnected,
),
InputResult::Command(SlashCommand::Config),
);
assert_eq!(composer.current_text(), "");
}
#[test]
fn unavailable_thread_dispatches_inline_commands_with_configured_submit_key() {
for (text, command, args) in [
("/new recovery", SlashCommand::New, "recovery"),
("/clear recovery", SlashCommand::Clear, "recovery"),
("/resume saved", SlashCommand::Resume, "saved"),
("/raw on", SlashCommand::Raw, "on"),
] {
let (mut composer, _) = new_test_composer();
let key = KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL);
composer.submit_keys = vec![key_hint::ctrl(KeyCode::Char('s'))];
composer.set_text_content(text.into(), Vec::new(), Vec::new());
assert_eq!(
composer.handle_restricted_key(
KeyEvent::from(KeyCode::Enter),
RestrictedInputMode::UnavailableThread
),
InputResult::None,
);
assert_eq!(composer.current_text(), text);
assert_eq!(
composer.handle_restricted_key(key, RestrictedInputMode::UnavailableThread),
InputResult::CommandWithArgs(command, args.into(), Vec::new()),
);
}
}
#[test]
fn restricted_input_preserves_blocked_drafts_and_attachments() {
for mode in [
RestrictedInputMode::Disconnected,
RestrictedInputMode::UnavailableThread,
] {
for text in [
"keep my draft",
"!echo hello",
"/review",
"/rename changed",
"/compact",
"/voice",
"/unknown",
"/status extra",
"/status\nkeep my draft",
"/clear recovery\nkeep my draft",
"/new recovery\nkeep my draft",
"/resume saved\nkeep my draft",
] {
let (mut composer, _) = new_test_composer();
composer.set_text_content(text.into(), Vec::new(), Vec::new());
composer.attach_image(PathBuf::from("local.png"));
let before = composer.draft_snapshot();
for key in [KeyCode::Enter, KeyCode::Tab] {
assert_eq!(
composer.handle_restricted_key(key.into(), mode),
InputResult::None
);
assert_eq!(composer.draft_snapshot(), before);
}
}
}
for text in ["/status", "/new", "/clear", "/raw on"] {
let (mut composer, _) = new_test_composer();
composer.set_text_content(text.into(), Vec::new(), Vec::new());
assert_eq!(
composer
.handle_restricted_key(KeyCode::Enter.into(), RestrictedInputMode::Disconnected),
InputResult::None
);
assert_eq!(composer.current_text(), text);
}
}
#[test]
fn unavailable_thread_expands_pasted_commands_without_dispatching() {
let (mut composer, _) = new_test_composer();
let text = format!("/clear {}", "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1));
composer.handle_paste(text.clone());
assert_ne!(composer.current_text(), text);
assert_eq!(
composer.handle_restricted_key(
KeyCode::Enter.into(),
RestrictedInputMode::UnavailableThread,
),
InputResult::None
);
assert_eq!(composer.current_text(), text);
}

View File

@@ -0,0 +1,163 @@
#![cfg(test)]
//! Skill completion and its rendering in both mention pickers.
use super::tests::new_test_composer;
use super::tests::snapshot_composer_state;
use super::tests::test_skill_binding;
use super::tests::test_skill_metadata;
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn skill_completion_attaches_typed_punctuation_snapshot() {
snapshot_composer_state(
"skill_completion_attaches_typed_punctuation",
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_skill_mentions(Some(vec![test_skill_metadata("rustdoc")]));
composer.insert_str("请用 $ru");
composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
composer.handle_key_event(KeyEvent::new(KeyCode::Char('》'), KeyModifiers::NONE));
let recovered = composer.recovery_snapshot();
let expected = "请用 $rustdoc》";
assert_eq!(
(recovered.text.as_str(), recovered.cursor),
(expected, expected.len())
);
composer.handle_paste_burst_flush(
tokio::time::Instant::now().into_std() + PasteBurst::recommended_flush_delay(),
);
assert_eq!(
composer.current_text_elements(),
vec![TextElement::new((7..15).into(), Some("$rustdoc".into()))]
);
assert_eq!(
composer.mention_bindings(),
vec![test_skill_binding("rustdoc")]
);
},
);
}
#[test]
fn unified_skill_completion_keeps_draft_spacing_after_punctuation() {
for (suffix, ch, modifiers, expected) in [
("", ',', KeyModifiers::NONE, "$rustdoc,"),
("", '!', KeyModifiers::SHIFT, "$rustdoc!"),
(
" then continue",
'!',
KeyModifiers::SHIFT,
"$rustdoc! then continue",
),
(" ", '!', KeyModifiers::SHIFT, "$rustdoc !"),
("", '。', KeyModifiers::NONE, "$rustdoc。"),
("", ',', KeyModifiers::NONE, "$rustdoc,"),
("", '、', KeyModifiers::NONE, "$rustdoc、"),
("", '!', KeyModifiers::NONE, "$rustdoc!"),
("", '?', KeyModifiers::NONE, "$rustdoc?"),
("", '》', KeyModifiers::NONE, "$rustdoc》"),
("", '/', KeyModifiers::NONE, "$rustdoc /"),
("", '\\', KeyModifiers::NONE, "$rustdoc \\"),
] {
let (mut composer, _rx) = new_test_composer();
composer.set_mentions_v2_enabled(/*enabled*/ true);
composer.set_skill_mentions(Some(vec![test_skill_metadata("rustdoc")]));
composer.set_text_content(format!("@ru{suffix}"), Vec::new(), Vec::new());
composer.set_current_cursor("@ru".len());
composer.sync_popups();
composer.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
composer.handle_key_event(KeyEvent::new(KeyCode::Char(ch), modifiers));
composer.handle_paste_burst_flush(
tokio::time::Instant::now().into_std() + PasteBurst::recommended_flush_delay(),
);
assert_eq!(composer.current_text(), expected);
assert_eq!(
composer.mention_bindings(),
vec![test_skill_binding("rustdoc")]
);
}
}
#[test]
fn skill_completion_keeps_space_after_cursor_navigation() {
let (mut composer, _rx) = new_test_composer();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_skill_mentions(Some(vec![test_skill_metadata("rustdoc")]));
composer.insert_str("$ru");
for key in [
KeyCode::Tab,
KeyCode::Left,
KeyCode::Right,
KeyCode::Char(','),
] {
composer.handle_key_event(KeyEvent::new(key, KeyModifiers::NONE));
}
assert_eq!(composer.current_text(), "$rustdoc ,");
}
#[tokio::test(start_paused = true)]
async fn skill_completion_keeps_space_before_a_punctuation_paste_burst() {
for (ch, expected) in [(',', "$rustdoc ,x\n"), ('。', "$rustdoc 。x\n")] {
let (mut composer, _rx) = new_test_composer();
composer.set_skill_mentions(Some(vec![test_skill_metadata("rustdoc")]));
composer.insert_str("$ru");
for key in [
KeyCode::Tab,
KeyCode::Char(ch),
KeyCode::Char('x'),
KeyCode::Enter,
] {
let (result, _) = composer.handle_key_event(KeyEvent::new(key, KeyModifiers::NONE));
assert!(matches!(result, InputResult::None));
}
tokio::time::advance(PasteBurst::recommended_active_flush_delay()).await;
composer.flush_paste_burst_if_due();
assert_eq!(composer.current_text(), expected);
}
}
#[test]
fn default_unified_mention_popup_snapshot() {
snapshot_composer_state(
"default_unified_mention_popup",
/*enhanced_keys_supported*/ false,
|composer| {
let features = akode_features::Features::with_defaults();
composer.set_mentions_v2_enabled(features.enabled(akode_features::Feature::MentionsV2));
composer.set_skill_mentions(Some(vec![
SkillMetadata {
name: "sample-tools:search".to_string(),
plugin_id: Some("sample@test".to_string()),
..test_skill_metadata("sample-search")
},
SkillMetadata {
name: "sample:summarize".to_string(),
plugin_id: Some("sample@test".to_string()),
..test_skill_metadata("sample-summarize")
},
SkillMetadata {
name: "sample:notes".to_string(),
..test_skill_metadata("sample-notes")
},
SkillMetadata {
name: "sample:other".to_string(),
plugin_id: Some("sample@other-marketplace".to_string()),
..test_skill_metadata("sample-other")
},
]));
composer.set_text_content("@sa".to_string(), Vec::new(), Vec::new());
composer.set_plugin_mentions(Some(vec![PluginCapabilitySummary {
config_name: "sample@test".to_string(),
display_name: "Sample Plugin".to_string(),
plugin_namespace: Some("sample".to_string()),
description: Some("Plugin with skills and an MCP server".to_string()),
has_skills: true,
mcp_server_names: vec!["sample".to_string()],
}]));
},
);
}

View File

@@ -0,0 +1,766 @@
//! Slash-command input parsing, cursor detection, and completion helpers.
use std::ops::Range;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use crate::bottom_pane::command_popup::CommandItem;
use crate::bottom_pane::command_popup::CommandPopup;
use crate::bottom_pane::command_popup::CommandPopupFlags;
use crate::bottom_pane::prompt_args::parse_slash_name;
use crate::bottom_pane::slash_commands::BuiltinCommandFlags;
use crate::bottom_pane::slash_commands::ServiceTierCommand;
use crate::bottom_pane::slash_commands::SlashCommandItem;
use crate::bottom_pane::slash_commands::find_slash_command;
use crate::bottom_pane::slash_commands::has_slash_command_prefix;
use crate::slash_command::SlashCommand;
use akode_protocol::user_input::ByteRange;
use akode_protocol::user_input::TextElement;
use super::super::footer::reset_mode_after_activity;
use super::ActivePopup;
use super::ChatComposer;
use super::InputResult;
use super::QueuedInputAction;
use super::parent_owned_command_is_allowed;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SlashValidation {
Immediate,
Deferred,
}
pub(super) enum SubmissionValidation {
Valid,
UnknownCommand(String),
}
pub(super) struct InlineCommand<'a> {
pub(super) command: SlashCommandItem,
pub(super) rest: &'a str,
pub(super) rest_offset: usize,
}
pub(super) struct SlashInput<'a> {
enabled: bool,
is_bash_mode: bool,
command_flags: BuiltinCommandFlags,
service_tier_commands: &'a [ServiceTierCommand],
}
impl<'a> SlashInput<'a> {
pub(super) fn new(
enabled: bool,
is_bash_mode: bool,
command_flags: BuiltinCommandFlags,
service_tier_commands: &'a [ServiceTierCommand],
) -> Self {
Self {
enabled,
is_bash_mode,
command_flags,
service_tier_commands,
}
}
pub(super) fn validate_submission(
&self,
text: &str,
input_starts_with_space: bool,
) -> SubmissionValidation {
if !self.enabled {
return SubmissionValidation::Valid;
}
let Some((name, _rest, _rest_offset)) = parse_slash_name(text) else {
return SubmissionValidation::Valid;
};
if input_starts_with_space || name.contains('/') {
return SubmissionValidation::Valid;
}
if self.command(name).is_some() {
SubmissionValidation::Valid
} else {
SubmissionValidation::UnknownCommand(name.to_string())
}
}
pub(super) fn bare_command(&self, text: &str) -> Option<SlashCommandItem> {
if !self.enabled || self.is_bash_mode {
return None;
}
let first_line = text.lines().next().unwrap_or("");
let (name, rest, _rest_offset) = parse_slash_name(first_line)?;
if !rest.is_empty() {
return None;
}
let command = self.command(name)?;
if command.supports_inline_args()
&& parse_slash_name(text).is_some_and(|(_, full_rest, _)| !full_rest.is_empty())
{
return None;
}
Some(command)
}
pub(super) fn inline_command<'text>(&self, text: &'text str) -> Option<InlineCommand<'text>> {
if !self.enabled || self.is_bash_mode || text.starts_with(' ') {
return None;
}
let (name, rest, rest_offset) = parse_slash_name(text)?;
if rest.is_empty() || name.contains('/') {
return None;
}
let command = self.command(name)?;
command.supports_inline_args().then_some(InlineCommand {
command,
rest,
rest_offset,
})
}
pub(super) fn should_parse_on_dequeue(&self, text: &str) -> bool {
self.enabled && !text.starts_with(' ') && text.trim().starts_with('/')
}
pub(super) fn command_element_range(
&self,
first_line: &str,
cursor: usize,
) -> Option<Range<usize>> {
if self.is_bash_mode {
return None;
}
let (name, _rest, _rest_offset) = parse_slash_name(first_line)?;
if name.contains('/') {
return None;
}
let element_end = 1 + name.len();
// A draft tail can make an in-progress prefix look complete ("/re" + "view").
// Keep it editable until the cursor leaves the command name.
if cursor <= first_line.len() && (1..element_end).contains(&cursor) {
return None;
}
let has_space_after = first_line
.get(element_end..)
.and_then(|tail| tail.chars().next())
.is_some_and(char::is_whitespace);
if !has_space_after {
return None;
}
self.command(name).is_some().then_some(0..element_end)
}
pub(super) fn is_editing_command_name(&self, first_line: &str, cursor: usize) -> bool {
let Some((name, rest)) = command_under_cursor(first_line, cursor) else {
return false;
};
if !self.enabled {
return false;
}
if name.is_empty() {
return rest.is_empty();
}
has_slash_command_prefix(name, self.command_flags, self.service_tier_commands)
}
pub(super) fn command_popup(&self, filter_text: &str) -> CommandPopup {
let mut command_popup = CommandPopup::new(
CommandPopupFlags {
collaboration_modes_enabled: self.command_flags.collaboration_modes_enabled,
plugins_command_enabled: self.command_flags.plugins_command_enabled,
service_tier_commands_enabled: self.command_flags.service_tier_commands_enabled,
goal_command_enabled: self.command_flags.goal_command_enabled,
voice_command_enabled: self.command_flags.voice_command_enabled,
worktrees_enabled: self.command_flags.worktrees_enabled,
windows_degraded_sandbox_active: self.command_flags.allow_elevate_sandbox,
side_conversation_active: self.command_flags.side_conversation_active,
},
self.service_tier_commands.to_vec(),
);
command_popup.on_composer_text_change(filter_text.to_string());
command_popup
}
pub(super) fn command(&self, name: &str) -> Option<SlashCommandItem> {
find_slash_command(name, self.command_flags, self.service_tier_commands)
}
}
pub(super) fn queued_input_action(
prepared_text: &str,
defer_slash_validation: bool,
) -> QueuedInputAction {
if defer_slash_validation && prepared_text.starts_with('/') {
QueuedInputAction::ParseSlash
} else if prepared_text.starts_with('!') {
QueuedInputAction::RunShell
} else {
QueuedInputAction::Plain
}
}
impl ChatComposer {
pub(super) fn builtin_command_flags(&self) -> BuiltinCommandFlags {
BuiltinCommandFlags {
collaboration_modes_enabled: self.collaboration_modes_enabled,
plugins_command_enabled: self.plugins_command_enabled,
service_tier_commands_enabled: self.service_tier_commands_enabled,
goal_command_enabled: self.goal_command_enabled,
voice_command_enabled: self.voice_command_enabled,
worktrees_enabled: self.worktrees_enabled,
allow_elevate_sandbox: self.windows_degraded_sandbox_active,
side_conversation_active: self.side_conversation_active,
}
}
pub fn set_worktrees_enabled(&mut self, enabled: bool) {
self.update_slash_command_catalog(|composer| composer.worktrees_enabled = enabled);
}
/// Handle key event when the slash-command popup is visible.
pub(super) fn handle_key_event_with_slash_popup(
&mut self,
key_event: KeyEvent,
) -> (InputResult, bool) {
if self.handle_empty_prompt_shortcut(&key_event) {
return (InputResult::None, true);
}
if key_event.code == KeyCode::Esc {
// Always dismiss the popup without changing the draft.
let first_line = self.draft.textarea.text().lines().next().unwrap_or("");
self.popups.dismissed_command_token =
command_popup_filter_text(first_line, /*cursor*/ 0);
self.popups.active = ActivePopup::None;
return (InputResult::None, true);
}
self.footer.mode = reset_mode_after_activity(self.footer.mode);
let ActivePopup::Command(popup) = &mut self.popups.active else {
unreachable!();
};
match key_event {
KeyEvent {
code: KeyCode::Up, ..
}
| KeyEvent {
code: KeyCode::Char('p'),
modifiers: KeyModifiers::CONTROL,
..
} => {
popup.move_up();
(InputResult::None, true)
}
KeyEvent {
code: KeyCode::Down,
..
}
| KeyEvent {
code: KeyCode::Char('n'),
modifiers: KeyModifiers::CONTROL,
..
} => {
popup.move_down();
(InputResult::None, true)
}
KeyEvent {
code: KeyCode::Tab, ..
} => {
// Ensure popup filtering/selection reflects the latest composer text
// before applying completion.
let text = self.draft.textarea.text();
let first_line = text.lines().next().unwrap_or("").to_owned();
let cursor = self.draft.textarea.cursor();
let filter_text = command_popup_filter_text(&first_line, cursor)
.unwrap_or_else(|| first_line.clone());
popup.on_composer_text_change(filter_text);
let has_visible_items = !popup.filtered_items().is_empty();
let selected_item = popup.selected_item();
let has_selectable_item = selected_item.is_some();
if let Some(selected_cmd) = selected_item {
if selected_command_dispatches_immediately_on_tab(&selected_cmd)
&& let CommandItem::Builtin(cmd) = &selected_cmd
{
self.stage_selected_slash_command_history(&selected_cmd);
self.draft.textarea.set_text_clearing_elements("");
self.draft.is_bash_mode = false;
return (InputResult::Command(*cmd), true);
}
if self
.complete_selected_slash_command_preserving_existing_draft_tail_as_inline_args(
&selected_cmd,
)
{
return (InputResult::None, true);
}
if let Some(completed_text) =
selected_command_completion(&first_line, &selected_cmd)
{
self.draft
.textarea
.set_text_clearing_elements(&completed_text);
if !self.draft.textarea.text().is_empty() {
self.draft
.textarea
.set_cursor(self.draft.textarea.text().len());
}
return (InputResult::None, true);
}
}
if has_visible_items && !has_selectable_item {
return (InputResult::None, true);
}
if self.is_task_running {
return self.handle_submission(/*should_queue*/ true);
}
(InputResult::None, true)
}
KeyEvent {
code: KeyCode::Char('/'),
modifiers: KeyModifiers::NONE,
..
} => {
// Treat "/" as accepting the highlighted command as text completion
// while the slash-command popup is active.
let text = self.draft.textarea.text();
let first_line = text.lines().next().unwrap_or("").to_owned();
let cursor = self.draft.textarea.cursor();
let filter_text = command_popup_filter_text(&first_line, cursor)
.unwrap_or_else(|| first_line.clone());
popup.on_composer_text_change(filter_text);
if let Some(selected_cmd) = popup.selected_item() {
if self
.complete_selected_slash_command_preserving_existing_draft_tail_as_inline_args(
&selected_cmd,
)
{
return (InputResult::None, true);
}
if let Some(completed_text) =
selected_command_completion(&first_line, &selected_cmd)
{
self.draft
.textarea
.set_text_clearing_elements(&completed_text);
self.draft.is_bash_mode = false;
}
if !self.draft.textarea.text().is_empty() {
self.draft
.textarea
.set_cursor(self.draft.textarea.text().len());
}
return (InputResult::None, true);
}
self.handle_key_event_without_popup(key_event)
}
KeyEvent {
code: KeyCode::Enter,
modifiers: KeyModifiers::NONE,
..
} => {
if let Some(sel) = popup.selected_item() {
if self.blocks_direct_input {
let command_is_allowed = match &sel {
CommandItem::Builtin(cmd) => {
parse_slash_name(self.draft.textarea.text()).is_some_and(
|(_, args, _)| parent_owned_command_is_allowed(*cmd, args),
)
}
CommandItem::ServiceTier(_) => false,
};
if !command_is_allowed {
return (InputResult::ParentOwnedInputBlocked, true);
}
}
if self
.complete_selected_slash_command_preserving_existing_draft_tail_as_inline_args(
&sel,
)
&& let Some(result) = self.try_dispatch_slash_command_with_args()
{
return (result, true);
}
self.stage_selected_slash_command_history(&sel);
if !matches!(sel, CommandItem::Builtin(cmd) if cmd.requires_dispatch_validation())
{
self.draft.textarea.set_text_clearing_elements("");
self.draft.is_bash_mode = false;
}
return (
match sel {
CommandItem::Builtin(cmd) => InputResult::Command(cmd),
CommandItem::ServiceTier(command) => {
InputResult::ServiceTierCommand(command)
}
},
true,
);
}
// Fallback to default newline handling if no command selected.
self.handle_key_event_without_popup(key_event)
}
input => self.handle_input_basic(input),
}
}
fn complete_selected_slash_command_preserving_existing_draft_tail_as_inline_args(
&mut self,
selected_cmd: &CommandItem,
) -> bool {
let CommandItem::Builtin(cmd) = selected_cmd else {
return false;
};
if !cmd.supports_inline_args() {
return false;
}
let text = self.draft.textarea.text();
let first_line_end = text.find('\n').unwrap_or(text.len());
let cursor = self.draft.textarea.cursor();
if cursor > first_line_end || !text.starts_with('/') || !text.is_char_boundary(cursor) {
return false;
}
let command_token_end = text[1..first_line_end]
.find(char::is_whitespace)
.map(|idx| 1 + idx)
.unwrap_or(first_line_end);
let typed_command_name = &text[1..command_token_end];
let rest_after_token_is_empty = text[command_token_end..].trim().is_empty();
if rest_after_token_is_empty && (cursor <= 1 || cursor >= command_token_end) {
return false;
}
let replace_end =
if cursor <= 1 || (typed_command_name == cmd.command() && rest_after_token_is_empty) {
command_token_end
} else {
cursor
};
let tail = &text[replace_end..];
let tail_starts_with_whitespace = tail.chars().next().is_some_and(char::is_whitespace);
let selected_command_text = format!("/{}", cmd.command());
let replacement = if tail_starts_with_whitespace {
selected_command_text
} else {
format!("{selected_command_text} ")
};
let ranges_to_unmark = self
.draft
.textarea
.text_elements()
.into_iter()
.filter_map(|element| {
let range = element.byte_range.start..element.byte_range.end;
(range.start < replace_end && replace_end < range.end).then_some(range)
})
.collect::<Vec<_>>();
for range in ranges_to_unmark {
self.draft.textarea.remove_element_range(range);
}
self.draft
.textarea
.replace_range(0..replace_end, &replacement);
self.draft.is_bash_mode = false;
self.draft
.textarea
.set_cursor(self.draft.textarea.text().len());
true
}
/// Keep slash command elements aligned with the current first line.
pub(super) fn sync_slash_command_elements(&mut self) {
if !self.slash_commands_enabled() {
return;
}
let text = self.draft.textarea.text();
let first_line_end = text.find('\n').unwrap_or(text.len());
let first_line = &text[..first_line_end];
let cursor = self.draft.textarea.cursor();
let desired_range = self.slash_input().command_element_range(first_line, cursor);
// Slash commands are only valid at byte 0 of the first line.
// Any slash-shaped element not matching the current desired prefix is stale.
let mut has_desired = false;
let mut stale_ranges = Vec::new();
for elem in self.draft.textarea.text_elements() {
let Some(payload) = elem.placeholder(text) else {
continue;
};
if payload.strip_prefix('/').is_none() {
continue;
}
let range = elem.byte_range.start..elem.byte_range.end;
if desired_range.as_ref() == Some(&range) {
has_desired = true;
} else {
stale_ranges.push(range);
}
}
for range in stale_ranges {
self.draft.textarea.remove_element_range(range);
}
if let Some(range) = desired_range
&& !has_desired
{
self.draft.textarea.add_element_range(range);
}
}
}
pub(super) fn selected_command_dispatches_immediately_on_tab(command: &CommandItem) -> bool {
matches!(command, CommandItem::Builtin(SlashCommand::Skills))
}
pub(super) fn selected_command_completion(
first_line: &str,
command: &CommandItem,
) -> Option<String> {
let selected_command_text = format!("/{}", command.command());
(!first_line.trim_start().starts_with(&selected_command_text))
.then(|| format!("{selected_command_text} "))
}
pub(super) fn prepared_args(prepared_text: &str) -> Option<(&str, usize)> {
let (_, prepared_rest, prepared_rest_offset) = parse_slash_name(prepared_text)?;
Some((prepared_rest, prepared_rest_offset))
}
/// Translate full-text element ranges into command-argument ranges.
///
/// `rest_offset` is the byte offset where `rest` begins in the full text.
pub(super) fn args_elements(
rest: &str,
rest_offset: usize,
text_elements: &[TextElement],
) -> Vec<TextElement> {
if rest.is_empty() || text_elements.is_empty() {
return Vec::new();
}
text_elements
.iter()
.filter_map(|elem| {
if elem.byte_range.end <= rest_offset {
return None;
}
let start = elem.byte_range.start.saturating_sub(rest_offset);
let mut end = elem.byte_range.end.saturating_sub(rest_offset);
if start >= rest.len() {
return None;
}
end = end.min(rest.len());
(start < end).then_some(elem.map_range(|_| ByteRange { start, end }))
})
.collect()
}
pub(super) fn command_popup_filter_text(first_line: &str, cursor: usize) -> Option<String> {
let (name, _rest) = command_under_cursor(first_line, cursor)?;
Some(format!("/{name}"))
}
/// If the cursor is currently within a slash command on the first line,
/// extract the command fragment before the cursor and the rest of the line after it.
fn command_under_cursor(first_line: &str, cursor: usize) -> Option<(&str, &str)> {
if !first_line.starts_with('/') {
return None;
}
if cursor > first_line.len() || !first_line.is_char_boundary(cursor) {
return None;
}
let name_start = 1usize;
let name_end = first_line[name_start..]
.find(char::is_whitespace)
.map(|idx| name_start + idx)
.unwrap_or_else(|| first_line.len());
let cursor = if cursor <= name_start {
name_end
} else {
cursor
};
if cursor > name_end {
return None;
}
let name = &first_line[name_start..cursor];
let rest = &first_line[cursor..];
Some((name, rest))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app_event::AppEvent;
use crate::bottom_pane::AppEventSender;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc::unbounded_channel;
fn test_composer() -> ChatComposer {
let (tx, _rx) = unbounded_channel::<AppEvent>();
ChatComposer::new(
/*has_input_focus*/ true,
AppEventSender::new(tx),
/*enhanced_keys_supported*/ false,
"Ask aKode to do anything".to_string(),
/*disable_paste_burst*/ false,
)
}
fn press(composer: &mut ChatComposer, code: KeyCode) -> InputResult {
composer
.handle_key_event(KeyEvent::new(code, KeyModifiers::NONE))
.0
}
fn composer_with_text_at_cursor(text: &str, cursor: usize) -> ChatComposer {
let mut composer = test_composer();
composer.draft.textarea.set_text_clearing_elements(text);
composer.draft.textarea.set_cursor(cursor);
composer.sync_popups();
composer
}
fn composer_with_draft_tail(prefix: &str, draft: &str) -> ChatComposer {
composer_with_text_at_cursor(&format!("{prefix}{draft}"), prefix.len())
}
#[test]
fn unavailable_side_conversation_command_still_opens_popup() {
let mut composer = test_composer();
composer.set_side_conversation_active(/*active*/ true);
composer.draft.textarea.set_text_clearing_elements("/arch");
composer.draft.textarea.set_cursor(/*pos*/ 5);
composer.sync_popups();
assert!(matches!(composer.popups.active, ActivePopup::Command(_)));
}
#[test]
fn side_conversation_tab_completes_available_match_after_unavailable_rows() {
let mut composer = test_composer();
composer.set_side_conversation_active(/*active*/ true);
composer.draft.textarea.set_text_clearing_elements("/a");
composer.draft.textarea.set_cursor(/*pos*/ 2);
composer.sync_popups();
assert_eq!(press(&mut composer, KeyCode::Tab), InputResult::None);
assert_eq!(composer.draft.textarea.text(), "/agents ");
}
#[test]
fn side_conversation_tab_does_not_queue_unavailable_match_while_task_running() {
let mut composer = test_composer();
composer.set_side_conversation_active(/*active*/ true);
composer.set_task_running(/*running*/ true);
composer.draft.textarea.set_text_clearing_elements("/arch");
composer.draft.textarea.set_cursor(/*pos*/ 5);
composer.sync_popups();
assert_eq!(press(&mut composer, KeyCode::Tab), InputResult::None);
assert_eq!(composer.draft.textarea.text(), "/arch");
}
#[test]
fn side_conversation_tab_queues_exact_available_match_while_task_running() {
let mut composer = test_composer();
composer.set_side_conversation_active(/*active*/ true);
composer.set_task_running(/*running*/ true);
composer
.draft
.textarea
.set_text_clearing_elements("/agents");
composer.draft.textarea.set_cursor(/*pos*/ 7);
composer.sync_popups();
assert_eq!(
press(&mut composer, KeyCode::Tab),
InputResult::Queued {
text: "/agents".to_string(),
text_elements: Vec::new(),
action: QueuedInputAction::ParseSlash,
pending_pastes: Vec::new(),
}
);
assert!(composer.draft.textarea.is_empty());
}
#[test]
fn side_conversation_slash_is_inserted_after_unavailable_match() {
let mut composer = test_composer();
composer.set_side_conversation_active(/*active*/ true);
composer.set_disable_paste_burst(/*disabled*/ true);
composer.draft.textarea.set_text_clearing_elements("/new");
composer.draft.textarea.set_cursor(/*pos*/ 4);
composer.sync_popups();
assert_eq!(press(&mut composer, KeyCode::Char('/')), InputResult::None);
assert_eq!(composer.draft.textarea.text(), "/new/");
}
#[test]
fn esc_dismisses_slash_popup_while_idle() {
let mut composer = composer_with_text_at_cursor("/rev", "/rev".len());
assert!(composer.popup_active());
assert_eq!(press(&mut composer, KeyCode::Esc), InputResult::None);
assert!(!composer.popup_active());
assert_eq!(composer.draft.textarea.text(), "/rev");
}
#[test]
fn slash_completion_preserves_existing_draft_tail_for_inline_arg_commands() {
let draft = "view the diff";
let expected_text = "/review view the diff";
let mut composer = composer_with_draft_tail("/re", draft);
assert_eq!(press(&mut composer, KeyCode::Tab), InputResult::None);
assert_eq!(composer.draft.textarea.text(), expected_text);
assert_eq!(composer.draft.textarea.cursor(), expected_text.len());
let mut composer = composer_with_draft_tail("/re", draft);
assert_eq!(
press(&mut composer, KeyCode::Enter),
InputResult::CommandWithArgs(SlashCommand::Review, draft.to_string(), Vec::new())
);
assert_eq!(composer.draft.textarea.text(), expected_text);
}
#[test]
fn slash_completion_does_not_preserve_existing_draft_tail_for_other_commands() {
let mut composer = composer_with_draft_tail(
"/sta",
"preserve this draft only for opted-in slash commands",
);
assert_eq!(press(&mut composer, KeyCode::Tab), InputResult::None);
assert_eq!(composer.draft.textarea.text(), "/status ");
assert_eq!(composer.draft.textarea.cursor(), "/status ".len());
}
#[test]
fn slash_completion_does_not_turn_command_suffix_into_args() {
let mut composer = composer_with_text_at_cursor("/review", "/re".len());
assert_eq!(press(&mut composer, KeyCode::Tab), InputResult::None);
assert_eq!(composer.draft.textarea.text(), "/review ");
let mut composer = composer_with_text_at_cursor("/review", "/re".len());
assert_eq!(
press(&mut composer, KeyCode::Enter),
InputResult::Command(SlashCommand::Review)
);
assert_eq!(composer.draft.textarea.text(), "/review ");
}
}

View File

@@ -0,0 +1,157 @@
//! Snapshot coverage for draft text, plugin mentions, shortcuts, and live voice controls.
use super::tests::new_test_composer;
use super::tests::snapshot_composer_state_with_width;
use super::tests::test_plugin_summary;
use crate::bottom_pane::MentionBinding;
use crate::bottom_pane::footer::FooterMode;
use crate::key_hint;
use crate::key_hint::ShortcutHint;
use crate::keymap::RuntimeKeymap;
use crate::render::renderable::Renderable;
use akode_plugin::PluginCapabilitySummary;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
#[test]
fn plugin_mention_uses_display_name_for_opaque_id() {
snapshot_composer_state_with_width(
"plugin_mention_uses_display_name_for_opaque_id",
/*width*/ 100,
/*enhanced_keys_supported*/ false,
|composer| {
let plugin_name = "app-6a6b12e06c5c8191ac5d5252fa5f92c8";
composer.set_mentions_v2_enabled(/*enabled*/ true);
composer.set_plugin_mentions(Some(vec![PluginCapabilitySummary {
display_name: "Postman".to_string(),
..test_plugin_summary(plugin_name, "")
}]));
composer.set_text_content("@Postm".to_string(), Vec::new(), Vec::new());
composer.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
assert_eq!(
composer.mention_bindings(),
vec![MentionBinding {
sigil: '@',
mention: "Postman".to_string(),
path: format!("plugin://{plugin_name}@test"),
}]
);
},
);
}
#[test]
fn shortcut_footer_displays_configured_chords() {
use akode_config::types::KeybindingSpec;
use akode_config::types::KeybindingsSpec;
use akode_config::types::TuiKeymap;
let mut config = TuiKeymap::default();
config.global.open_external_editor = Some(KeybindingsSpec::One(KeybindingSpec(
"ctrl-g ctrl-g".to_string(),
)));
config.editor.insert_newline = Some(KeybindingsSpec::One(KeybindingSpec(
"ctrl-x enter".to_string(),
)));
let keymap = RuntimeKeymap::from_config(&config).expect("valid composer chords");
let (mut composer, _rx) = new_test_composer();
composer.set_keymap_bindings(&keymap);
composer.footer.mode = FooterMode::ShortcutOverlay;
let hints = composer.footer_props().key_hints;
assert_eq!(
hints.external_editor,
Some(ShortcutHint::Chord {
prefix: key_hint::ctrl(KeyCode::Char('g')),
completion: key_hint::ctrl(KeyCode::Char('g')),
})
);
assert_eq!(
hints.insert_newline,
Some(ShortcutHint::Chord {
prefix: key_hint::ctrl(KeyCode::Char('x')),
completion: key_hint::plain(KeyCode::Enter),
})
);
snapshot_composer_state_with_width(
"footer_mode_configured_key_chords",
/*width*/ 100,
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_keymap_bindings(&keymap);
composer.footer.mode = FooterMode::ShortcutOverlay;
},
);
}
#[test]
fn draft_and_voice_composer_snapshots() {
use crate::bottom_pane::voice_strip::VoiceStripPhase;
use crate::bottom_pane::voice_strip::VoiceStripState;
use crate::tui::FrameRequester;
crate::terminal_palette::with_test_default_colors(
crate::terminal_probe::DefaultColors {
fg: (230, 216, 255),
bg: (36, 27, 53),
},
|| {
for voice_active in [false, true] {
let (mut composer, _rx) = new_test_composer();
if voice_active {
composer.set_voice_strip(
Some(VoiceStripState {
mute_hint: None,
phase: VoiceStripPhase::Active,
microphone_live: true,
microphone_muted: false,
microphone_history: vec![0, 37, 73, 110, 146, 255],
speaker_history: vec![255, 146, 110, 73, 37, 0],
activity: "listening",
animations: false,
progress: true,
}),
FrameRequester::test_dummy(),
);
} else {
composer.set_text_content(
"Explore the night sky".to_string(),
Vec::new(),
Vec::new(),
);
}
let width = 60;
let area = Rect::new(
/*x*/ 0,
/*y*/ 0,
width,
composer.desired_height(width),
);
let mut buffer = Buffer::empty(area);
composer.render(area, &mut buffer);
let rows = buffer
.content
.chunks(usize::from(width))
.map(|row| {
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n");
let name = if voice_active {
"voice_composer"
} else {
"draft_composer"
};
insta::assert_snapshot!(name, rows);
}
},
);
}

View File

@@ -0,0 +1,28 @@
---
source: tui/src/bottom_pane/chat_composer/footer_state_tests.rs
assertion_line: 231
expression: "frames.join(\"\\n\\n\")"
---
60x8, cursor Some((10, 6))
› /
Find: needle
Enter next · Esc close
24x8, cursor Some((10, 6))
› /
Find: needle
Enter next · Esc close
12x3, cursor None
› /

View File

@@ -0,0 +1,9 @@
---
source: tui/src/bottom_pane/chat_composer/footer_state_tests.rs
expression: text(&buffer)
---
› Ask Codex
Find: needle
Copied selection to clipboard

View File

@@ -0,0 +1,10 @@
---
source: tui/src/bottom_pane/chat_composer/history_search_paste_tests.rs
assertion_line: 101
expression: terminal.backend()
---
" "
"› git status "
" "
" "
" reverse-i-search: git enter accept · esc cancel "

View File

@@ -0,0 +1,12 @@
---
source: tui/src/bottom_pane/chat_composer/history_search_paste_tests.rs
assertion_line: 75
expression: "format!(\"{}\\nCursor: {cursor:?}\", terminal.backend())"
---
" "
"› draft "
" "
" "
" reverse-i-search: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Cursor: Some((79, 4))

View File

@@ -0,0 +1,10 @@
---
source: tui/src/bottom_pane/chat_composer/history_search_paste_tests.rs
assertion_line: 51
expression: terminal.backend()
---
" "
"› git status "
" "
" "
" reverse-i-search: git status enter accept · esc cancel "

View File

@@ -0,0 +1,12 @@
---
source: tui/src/bottom_pane/chat_composer/history_search_paste_tests.rs
assertion_line: 125
expression: "format!(\"{}\\nCursor: {cursor:?}\", terminal.backend())"
---
" "
"› draft "
" "
" "
" reverse-i-search: foo↵bar⇥baz no match "
Cursor: Some((31, 4))

View File

@@ -0,0 +1,25 @@
---
source: tui/src/bottom_pane/chat_composer/mentions_layout_tests.rs
expression: buffer_text(&buffer)
---
Mentions
Files, directories, plugins, skills and tasks
All Results Filesystem Only Plugins
Type to search mentions
› Plugin00 Plugin description 00 Plugin
Plugin01 Plugin description 01 Plugin
Plugin02 Plugin description 02 Plugin
Plugin03 Plugin description 03 Plugin
Plugin04 Plugin description 04 Plugin
Plugin05 Plugin description 05 Plugin
Plugin06 Plugin description 06 Plugin
Plugin07 Plugin description 07 Plugin
↓
enter/tab insert · esc close · ↑/↓ select · ←/→ filter
› @
MODEL STATUS

View File

@@ -0,0 +1,36 @@
---
source: tui/src/bottom_pane/chat_composer/mentions_layout_tests.rs
expression: buffer_text(&open)
---
Transcript row 00: behind the menu
Transcript row 01: behind the menu
Transcript row 02: behind the menu
Transcript row 03: behind the menu
Transcript row 04: behind the menu
Transcript row 05: behind the menu
Transcript row 06: behind the menu
Transcript row 07: behind the menu
Transcript row 08: behind the menu
Transcript row 09: behind the menu
Transcript row 10: behind the menu
Mentions
Files, directories, plugins, skills and tasks
All Results Filesystem Only Plugins
Type to search mentions
› Plugin00 Plugin description 00 Plugin
Plugin01 Plugin description 01 Plugin
Plugin02 Plugin description 02 Plugin
Plugin03 Plugin description 03 Plugin
Plugin04 Plugin description 04 Plugin
Plugin05 Plugin description 05 Plugin
Plugin06 Plugin description 06 Plugin
Plugin07 Plugin description 07 Plugin
↓
enter/tab insert · esc close · ↑/↓ select · ←/→ filter
› @
TRANSCRIPT STATUS

View File

@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/chat_composer/paste_tests.rs
assertion_line: 38
expression: terminal.backend()
---
" "
"› first line "
" second line "
" third line "
" "
" "
" "
" tab to queue message 100% context left "

View File

@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/chat_composer/reconnect_tests.rs
assertion_line: 58
expression: rows
---
› line 16 abc ↑
line 17 abc
line 18 abc
line 19 abc
line 20 ac
100% context left

View File

@@ -0,0 +1,8 @@
---
source: tui/src/bottom_pane/chat_composer/snapshot_tests.rs
expression: rows
---
› Explore the night sky
100% context left

View File

@@ -0,0 +1,10 @@
---
source: tui/src/bottom_pane/chat_composer/snapshot_tests.rs
expression: rows
---
voice ● listening /voice mute /voice stop
› Ask Codex to do anything
? for shortcuts 100% context left

View File

@@ -0,0 +1,18 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
assertion_line: 561
expression: "format!(\"command during startup:\\n{}\\n\\nafter command:\\n{}\", text(&pending),\ntext(&completed))"
---
command during startup:
› /status show current session configuration and token usage
/statusline configure which items appear in the status line
› /status
100% context left
after command:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left

View File

@@ -0,0 +1,37 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
expires while open: false
initial:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
searching:
› stored draft
reverse-i-search: stored enter accept · esc cancel
after escape:
⠁ ⡀ ⠄ ⠄ ⠄
› Ask Codex to do anything ⠈
⠠ ⠠ ⢀ ⢀ ⡀ ⠄
? for shortcuts 100% context left
expires while open: true
initial:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
searching:
› stored draft
reverse-i-search: stored enter accept · esc cancel
after escape:
› Ask Codex to do anything
? for shortcuts 100% context left

View File

@@ -0,0 +1,9 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
assertion_line: 900
expression: "text(&draw(&pane.composer, 80, now).0)"
---
› Ask Codex to do anything
? for shortcuts 100% context left

View File

@@ -0,0 +1,27 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
gpt-6-astra
before disconnect:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
after typing and erasing without rendering:
› Ask Codex to do anything
? for shortcuts 100% context left
gpt-5.5
before disconnect:
› Ask Codex to do anything
? for shortcuts 100% context left
after typing and erasing without rendering:
› Ask Codex to do anything
? for shortcuts 100% context left

View File

@@ -0,0 +1,15 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
accept:
› Ask Codex to do anything
? for shortcuts 100% context left
escape:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left

View File

@@ -0,0 +1,37 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
gpt-6-astra
searching with an explicit pasted query:
› history prompt
reverse-i-search: history enter accept · esc cancel
after canceling and erasing the slash:
⠁ ⡀ ⠄ ⠄ ⠄
› Ask Codex to do anything ⠈
⠠ ⠠ ⢀ ⢀ ⡀ ⠄
? for shortcuts 100% context left
after /model selects Astra:
⠁ ⡀ ⠄ ⠄ ⠄
› Ask Codex to do anything ⠈
⠠ ⠠ ⢀ ⢀ ⡀ ⠄
? for shortcuts 100% context left
gpt-5.5
searching with an explicit pasted query:
› history prompt
reverse-i-search: history enter accept · esc cancel
after canceling and erasing the slash:
› Ask Codex to do anything
? for shortcuts 100% context left
after /model selects Astra:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left

View File

@@ -0,0 +1,27 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
gpt-6-astra
after immediately canceling the held slash:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
after /model:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
gpt-5.5
after immediately canceling the held slash:
› Ask Codex to do anything
? for shortcuts 100% context left
after /model:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left

View File

@@ -0,0 +1,75 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
expires during help: false
initial:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
shortcut help:
Keyboard shortcuts
Compose Session
/ Commands tab Send message
@ Mention files ⌥, Less reasoning
! Shell command ⌥. More reasoning
⌃j New line ⌥← / ⌥→ Subagents (empty prompt)
⌃v Paste image f4 Inspect activity
⌃g External editor ⌃c Quit
⌃r Search history
esc esc Edit last message Transcript (open first)
⌃t Open transcript
f3 Find text
pgup / pgdn Scroll
⌃space Start selection
⌃home / ⌃end Top / latest
⇧⌥, / ⇧⌥. Top / latest
/keymap customize
› Ask Codex to do anything
? / esc close
after closing:
⠁ ⡀ ⠄ ⠄ ⠄
› Ask Codex to do anything ⠈
⠠ ⠠ ⢀ ⢀ ⡀ ⠄
? for shortcuts 100% context left
expires during help: true
initial:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
shortcut help:
Keyboard shortcuts
Compose Session
/ Commands tab Send message
@ Mention files ⌥, Less reasoning
! Shell command ⌥. More reasoning
⌃j New line ⌥← / ⌥→ Subagents (empty prompt)
⌃v Paste image f4 Inspect activity
⌃g External editor ⌃c Quit
⌃r Search history
esc esc Edit last message Transcript (open first)
⌃t Open transcript
f3 Find text
pgup / pgdn Scroll
⌃space Start selection
⌃home / ⌃end Top / latest
⇧⌥, / ⇧⌥. Top / latest
/keymap customize
› Ask Codex to do anything
? / esc close
after closing:
› Ask Codex to do anything
? for shortcuts 100% context left

View File

@@ -0,0 +1,46 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
shortcut help:
Keyboard shortcuts
Compose Session
/ Commands tab Send message
@ Mention files ⌥, Less reasoning
! Shell command ⌥. More reasoning
⌃j New line ⌥← / ⌥→ Subagents (empty prompt)
⌃v Paste image f4 Inspect activity
⌃g External editor ⌃c Quit
⌃r Search history
esc esc Edit last message Transcript (open first)
⌃t Open transcript
f3 Find text
pgup / pgdn Scroll
⌃space Start selection
⌃home / ⌃end Top / latest
⇧⌥, / ⇧⌥. Top / latest
/keymap customize
› Ask Codex to do anything
? / esc close
after /model selects Astra:
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
literal pasted question mark:
› ?
100% context left
after clearing and selecting Astra:
› Ask Codex to do anything
? for shortcuts 100% context left

View File

@@ -0,0 +1,19 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "format!(\"before fade:\\n{}\\nfading:\\n{}\\nfinished:\\n{}\", text(&last),\ntext(&fading), text(&finished))"
---
before fade:
⠁ ⠄ ⢀ ⠈ ⠁ ⡀ ⠂ ⠄
› Ask Codex to do anything ⠈ ⠈ ⠂ ⠁ ⠂
⢀⠐ ⠄ ⠄ ⢀ ⠠ ⠄
? for shortcuts 100% context left
fading:
⠁ ⠄ ⢀ ⠈ ⠁ ⡀ ⠂ ⠄
› Ask Codex to do anything ⠈ ⠈ ⠂ ⠁
⠐ ⠄ ⠄ ⢀ ⠠ ⠄
? for shortcuts 100% context left
finished:
› Ask Codex to do anything
? for shortcuts 100% context left

View File

@@ -0,0 +1,25 @@
---
source: tui/src/bottom_pane/chat_composer/sparkle_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
40 columns, cursor Some((2, 1))
⠈ ⢀
›⠁Ask Codex to do anything ⠈
⢀ ⠠ ⠄ ⠠
? for shortcuts 100% context left
first input:
› x
100% context left
80 columns, cursor Some((2, 1))
⠈ ⢀ ⠁ ⠂
›⠁Ask Codex to do anything ⠈ ⠁
⢀ ⠠ ⠄ ⠠ ⢀ ⠠ ⡀
? for shortcuts 100% context left
first input:
› x
100% context left

View File

@@ -0,0 +1,87 @@
---
source: tui/src/bottom_pane/chat_composer/status_surface_tests.rs
expression: "snapshots.join(\"\\n---\\n\")"
---
"f4"
Keyboard shortcuts
Compose Session Transcript (open first)
/ Commands tab Send message ⌃t Open transcript
@ Mention files ⌥, Less reasoning f3 Find text
! Shell command ⌥. More reasoning pgup / pgdn Scroll
⌃j New line ⌥← / ⌥→ Subagents (empty prompt) ⌃space Start selection
⌃v Paste image f4 Inspect activity ⌃home / ⌃end Top / latest
⌃g External editor ⌃c Quit ⇧⌥, / ⇧⌥. Top / latest
⌃r Search history
esc esc Edit last message
/keymap customize
› Ask Codex
MODEL · ~/project · Context 20% used
? / esc close
---
"ctrl-x t"
Keyboard shortcuts
Compose Session Transcript (open first)
/ Commands tab Send message ⌃t Open transcript
@ Mention files ⌥, Less reasoning f3 Find text
! Shell command ⌥. More reasoning pgup / pgdn Scroll
⌃j New line ⌥← / ⌥→ Subagents (empty prompt) ⌃space Start selection
⌃v Paste image ⌃x t Inspect activity ⌃home / ⌃end Top / latest
⌃g External editor ⌃c Quit ⇧⌥, / ⇧⌥. Top / latest
⌃r Search history
esc esc Edit last message
/keymap customize
› Ask Codex
MODEL · ~/project · Context 20% used
? / esc close
---
[]
Keyboard shortcuts
Compose Session Transcript (open first)
/ Commands tab Send message ⌃t Open transcript
@ Mention files ⌥, Less reasoning f3 Find text
! Shell command ⌥. More reasoning pgup / pgdn Scroll
⌃j New line ⌥← / ⌥→ Subagents (empty prompt) ⌃space Start selection
⌃v Paste image ⌃c Quit ⌃home / ⌃end Top / latest
⌃g External editor ⇧⌥, / ⇧⌥. Top / latest
⌃r Search history
esc esc Edit last message
/keymap customize
› Ask Codex
MODEL · ~/project · Context 20% used
? / esc close

View File

@@ -0,0 +1,10 @@
---
source: tui/src/bottom_pane/chat_composer/status_surface_tests.rs
expression: shared
---
16 | Ready PR 12345
15 | Ready
15 | PR 12345
16 | Ready PR 12345
25 | Ready
25 | PR 12345 Plan mode

View File

@@ -0,0 +1,17 @@
---
source: tui/src/bottom_pane/chat_composer/status_surface_tests.rs
expression: wide
---
› Ask Codex
MODEL · ~/project · Context 20% used Plan mode (⇧tab to cycle)
? for shortcuts

View File

@@ -0,0 +1,59 @@
---
source: tui/src/bottom_pane/chat_composer/status_surface_tests.rs
expression: "states.join(\"\\n---\\n\")"
---
› Ask Codex
MODEL · ~/project · Context 20% used Plan mode
? for shortcuts
---
› Ask Codex
MODEL · ~/project · Context 20% used Plan mode
Copied selection
---
› Ask Codex
MODEL · ~/project · Context 20% used Plan mode
Ctrl+X waiting for chord
---
› Continue the task
MODEL · ~/project · Context 20% used Plan mode
tab to queue message

View File

@@ -0,0 +1,46 @@
---
source: tui/src/bottom_pane/chat_composer/status_surface_tests.rs
expression: text
---
Keyboard shortcuts
Compose
/ Commands
@ Mention files
! Shell command
⌃j New line
⌃v Paste image
⌃g External editor
⌃r Search history
esc esc Edit last message
Session
tab Send message
⌥, Less reasoning
⌥. More reasoning
⌥← / ⌥→ Subagents (empty prompt)
f4 Inspect activity
⌃c Quit
Transcript (open first)
⌃t Open transcript
f3 Find text
pgup / pgdn Scroll
⌃space Start selection
⌃home / ⌃end Top / latest
⇧⌥, / ⇧⌥. Top / latest
/keymap customize
› Ask Codex
MODEL · ~/project · Context 20% used
? / esc close

View File

@@ -0,0 +1,30 @@
---
source: tui/src/bottom_pane/chat_composer/status_surface_tests.rs
expression: text
---
Keyboard shortcuts
Compose Session Transcript (open first)
/ Commands tab Send message ⌃t Open transcript
@ Mention files ⌥, Less reasoning f3 Find text
! Shell command ⌥. More reasoning pgup / pgdn Scroll
⌃j New line ⌥← / ⌥→ Subagents (empty prompt) ⌃space Start selection
⌃v Paste image f4 Inspect activity ⌃home / ⌃end Top / latest
⌃g External editor ⌃c Quit ⇧⌥, / ⇧⌥. Top / latest
⌃r Search history
esc esc Edit last message
/keymap customize
› Ask Codex
MODEL · ~/project · Context 20% used
? / esc close

View File

@@ -0,0 +1,39 @@
---
source: tui/src/bottom_pane/chat_composer/status_surface_tests.rs
assertion_line: 344
expression: "format!(\"{buf:?}\")"
---
Buffer {
area: Rect { x: 0, y: 0, width: 80, height: 8 },
content: [
" /model choose what model and reasoning effort to use ",
"› /memories configure memory use and generation ",
" /mention mention a file ",
" /mcp list MCP tools; use /mcp verbose or /mcp login <name> ",
" ",
"› /m ",
" ",
" model · high · fast ",
],
styles: [
x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 3, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 13, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
x: 58, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED,
x: 13, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: REVERSED,
x: 48, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED,
x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 3, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 13, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
x: 27, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 3, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
x: 4, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 13, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
x: 66, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
x: 0, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
x: 1, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
]
}

View File

@@ -0,0 +1,13 @@
---
source: tui/src/bottom_pane/chat_composer/status_surface_tests.rs
expression: rows
---
[
" ",
"› a ",
" b ",
" c ",
" ",
" one… ",
" ",
]

View File

@@ -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,
]
}

View File

@@ -0,0 +1,426 @@
//! One short Astra flourish for a confirmed new task with an untouched prompt.
//!
//! Ordinary draft content ends the opportunity permanently; slash commands can still select Astra
//! if the flourish has never started. The original field fills blank composer cells without drawing
//! over the placeholder or normal terminal cursor, and hidden frames do not schedule work. The
//! separate field renderer only paints its buffer and has no input or scheduling state. History
//! search hides an active field while its original deadline continues; its query and previews do
//! not count as input before acceptance. Shortcut help on an empty composer also hides an active
//! field without restarting its deadline and leaves an unused opportunity intact. The disconnected
//! editor shares draft tracking but treats composer-only shortcuts as ordinary editor input. A key
//! that finishes a paste burst reconciles the draft even if it removes a held slash in the same edit.
use std::cell::Cell;
use std::cell::RefCell;
use std::time::Duration;
use std::time::Instant;
use akode_config::types::Tui;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use unicode_width::UnicodeWidthStr;
use super::ChatComposer;
use super::FooterMode;
use super::InputResult;
use crate::bottom_pane::BottomPane;
use crate::terminal_palette::StdoutColorLevel;
use crate::terminal_palette::default_fg;
use crate::terminal_palette::effective_stdout_color_level;
#[path = "sparkle_field.rs"]
mod field;
const FRAME_TICK: Duration = Duration::from_millis(/*millis*/ 150);
const IDLE_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 15);
const IDLE_FADE: Duration = Duration::from_secs(/*secs*/ 1);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum SparkleDraft {
#[default]
Untouched,
Command,
Dismissed,
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Phase {
#[default]
Unarmed,
Waiting,
Visible(Instant),
Finished,
}
pub(super) struct SparkleEditorState {
text: String,
paste_burst_active: bool,
}
pub(super) struct Sparkle {
pub(super) draft: Cell<SparkleDraft>,
/// Scoped to history's own replacements; other draft changes still count while search is open.
pub(super) history_preview: bool,
command_input: RefCell<String>,
phase: Cell<Phase>,
fresh: bool,
terminal_focused: bool,
}
impl Default for Sparkle {
fn default() -> Self {
Self {
draft: Cell::new(SparkleDraft::Untouched),
history_preview: false,
command_input: RefCell::new(String::new()),
phase: Cell::new(Phase::Unarmed),
fresh: false,
terminal_focused: true,
}
}
}
impl BottomPane {
pub(crate) fn is_sparkle_model(model: &str) -> bool {
model
.split(|ch: char| !ch.is_alphanumeric() && ch != '_')
.any(|part| part.eq_ignore_ascii_case("astra"))
}
pub(crate) fn mark_fresh_task_for_sparkle(&mut self, model: &str, settings: &Tui) {
self.composer.sparkle.fresh = true;
if matches!(
self.composer.sparkle.draft.get(),
SparkleDraft::Untouched | SparkleDraft::Command
) && self.composer.sparkle.phase.get() == Phase::Unarmed
&& settings.animations
&& settings.effects.starfield
&& Self::is_sparkle_model(model)
{
self.composer.sparkle.phase.set(Phase::Waiting);
self.request_redraw();
}
}
pub(crate) fn select_sparkle_model(&mut self, model: &str, settings: &Tui) {
if self.composer.sparkle.fresh {
self.mark_fresh_task_for_sparkle(model, settings);
}
}
pub(crate) fn stop_ineligible_sparkle(&self, model: &str, settings: &Tui) {
if !settings.animations || !settings.effects.starfield || !Self::is_sparkle_model(model) {
self.composer.stop_visible_sparkle();
}
}
pub(crate) fn dismiss_composer_sparkle(&self) {
self.composer.dismiss_sparkle();
}
pub(crate) fn prepare_composer_sparkle_key(&self, key: KeyEvent) {
if !self.has_active_view() {
self.composer.prepare_sparkle_key(key);
}
}
pub(crate) fn inherit_startup_sparkle(&self, draft: SparkleDraft) {
if self.composer.sparkle.draft.get() == SparkleDraft::Untouched
&& draft != SparkleDraft::Untouched
{
self.composer.sparkle.draft.set(draft);
if draft == SparkleDraft::Dismissed {
self.composer.stop_visible_sparkle();
}
}
}
pub(crate) fn set_sparkle_terminal_focus(&mut self, focused: bool) {
if self.composer.sparkle.terminal_focused != focused {
self.composer.sparkle.terminal_focused = focused;
self.request_redraw();
}
}
}
impl ChatComposer {
fn prepare_sparkle_key(&self, key: KeyEvent) {
if self.sparkle.draft.get() != SparkleDraft::Command
&& !(key.code == KeyCode::Char('/')
&& crate::key_hint::is_plain_text_key_event(key)
&& self.is_empty()
&& self.slash_commands_enabled())
{
self.stop_visible_sparkle();
}
}
fn stop_visible_sparkle(&self) {
if matches!(self.sparkle.phase.get(), Phase::Waiting | Phase::Visible(_)) {
self.sparkle.phase.set(Phase::Finished);
if let Some(requester) = &self.frame_requester {
requester.schedule_frame();
}
}
}
pub(super) fn dismiss_sparkle(&self) {
self.sparkle.draft.set(SparkleDraft::Dismissed);
self.sparkle.command_input.borrow_mut().clear();
self.stop_visible_sparkle();
}
pub(super) fn before_sparkle_key(&self, key: KeyEvent) -> Option<SparkleEditorState> {
if self.history_search.is_some()
|| (Self::is_history_search_key(&key, &self.history_search_previous_keys)
&& (self.popups.active() || !self.draft.textarea.wants_vim_search_key(key))
&& !self.wants_vim_history_key(key))
|| self.empty_prompt_shortcut_toggle(&key).is_some()
{
return None;
}
self.before_sparkle_editor_key(key)
}
pub(super) fn before_sparkle_editor_key(&self, key: KeyEvent) -> Option<SparkleEditorState> {
self.prepare_sparkle_key(key);
if self.draft.textarea.vim_query().is_some() {
return None;
}
if let KeyCode::Char(ch) = key.code
&& crate::key_hint::is_plain_text_key_event(key)
&& !key
.modifiers
.intersects(KeyModifiers::SUPER | KeyModifiers::HYPER | KeyModifiers::META)
&& !self.draft.textarea.is_vim_normal_mode()
{
match self.sparkle.draft.get() {
SparkleDraft::Untouched
if ch == '/' && self.is_empty() && self.slash_commands_enabled() =>
{
self.sparkle.draft.set(SparkleDraft::Command);
self.sparkle.command_input.replace(ch.to_string());
}
SparkleDraft::Command => {
let actual = self.current_text();
let mut projected = self.sparkle.command_input.borrow().clone();
let cursor = if actual == projected {
self.current_cursor()
} else {
projected.len()
};
projected.insert(cursor, ch);
if self.is_sparkle_command(&projected) {
self.sparkle.command_input.replace(projected);
} else {
self.dismiss_sparkle();
}
}
SparkleDraft::Untouched => self.dismiss_sparkle(),
SparkleDraft::Dismissed => {}
}
None
} else {
Some(SparkleEditorState {
text: self.current_text(),
paste_burst_active: self.is_in_paste_burst(),
})
}
}
pub(super) fn after_sparkle_key(
&self,
before: Option<SparkleEditorState>,
result: &InputResult,
) {
match result {
InputResult::Command(_) | InputResult::ServiceTierCommand(_) => {
if self.sparkle.draft.get() == SparkleDraft::Command {
self.sparkle.draft.set(SparkleDraft::Untouched);
self.sparkle.command_input.borrow_mut().clear();
}
}
InputResult::Submitted { .. }
| InputResult::Queued { .. }
| InputResult::ParentOwnedInputBlocked => self.dismiss_sparkle(),
InputResult::CommandWithArgs(_, _, _) | InputResult::None => {
if self.history_search.is_none() && self.draft.textarea.vim_query().is_none() {
let draft = self.current_text();
if before.is_some_and(|before| {
before.text != draft
|| (before.paste_burst_active && !self.is_in_paste_burst())
}) {
self.note_sparkle_replaced_text(&draft);
}
}
}
}
}
pub(super) fn note_sparkle_paste(&self, text: &str) {
if self.history_search.is_some() {
return;
}
if self.sparkle.draft.get() != SparkleDraft::Command
&& !(self.is_empty() && self.is_sparkle_command(text))
{
self.stop_visible_sparkle();
}
if !text.is_empty() && self.draft.textarea.vim_query().is_none() {
match self.sparkle.draft.get() {
SparkleDraft::Untouched if self.is_empty() && self.is_sparkle_command(text) => {
self.sparkle.draft.set(SparkleDraft::Command);
self.sparkle.command_input.replace(text.to_string());
}
SparkleDraft::Command => {
let mut projected = self.sparkle.command_input.borrow().clone();
let actual = self.current_text();
let cursor = if actual == projected {
self.current_cursor()
} else {
projected.len()
};
projected.insert_str(cursor, text);
if self.is_sparkle_command(&projected) {
self.sparkle.command_input.replace(projected);
} else {
self.dismiss_sparkle();
}
}
SparkleDraft::Untouched => self.dismiss_sparkle(),
SparkleDraft::Dismissed => {}
}
}
}
pub(super) fn note_sparkle_replaced_text(&self, text: &str) {
match self.sparkle.draft.get() {
SparkleDraft::Command if text.is_empty() => {
self.sparkle.draft.set(SparkleDraft::Untouched);
self.sparkle.command_input.borrow_mut().clear();
}
SparkleDraft::Command if self.is_sparkle_command(text) => {
self.sparkle.command_input.replace(text.to_string());
}
SparkleDraft::Untouched if text.is_empty() => {}
SparkleDraft::Untouched | SparkleDraft::Command => self.dismiss_sparkle(),
SparkleDraft::Dismissed => {}
}
}
fn is_sparkle_command(&self, text: &str) -> bool {
let Some(body) = text.strip_prefix('/') else {
return false;
};
if !self.slash_commands_enabled() || self.draft.is_bash_mode || text.contains(['\n', '\r'])
{
return false;
}
let split = body.find(char::is_whitespace).unwrap_or(body.len());
let (name, rest) = body.split_at(split);
if rest.is_empty() {
self.slash_input().is_editing_command_name(text, text.len())
|| self.slash_input().command(name).is_some()
} else {
self.slash_input()
.command(name)
.is_some_and(|command| rest.trim().is_empty() || command.supports_inline_args())
}
}
pub(super) fn render_sparkle(
&self,
area: Rect,
textarea: Rect,
cursor: Option<(u16, u16)>,
buf: &mut Buffer,
) {
self.render_sparkle_at(area, textarea, cursor, Instant::now(), buf);
}
fn render_sparkle_at(
&self,
area: Rect,
textarea: Rect,
cursor: Option<(u16, u16)>,
now: Instant,
buf: &mut Buffer,
) {
if self.history_search.is_none()
&& self.draft.textarea.vim_query().is_none()
&& !self.is_empty()
{
let is_command = self.sparkle.draft.get() == SparkleDraft::Command
&& self.is_sparkle_command(&self.current_text())
&& self.attachments.is_empty();
if !is_command {
self.dismiss_sparkle();
}
}
let since = match self.sparkle.phase.get() {
Phase::Visible(since) => Some(since),
Phase::Waiting => None,
Phase::Unarmed | Phase::Finished => return,
};
let elapsed = since.map_or(Duration::ZERO, |since| now.saturating_duration_since(since));
if elapsed >= IDLE_TIMEOUT {
self.stop_visible_sparkle();
return;
}
if !self.has_focus
|| !self.sparkle.terminal_focused
|| !self.is_empty()
|| self.sparkle.draft.get() == SparkleDraft::Command
|| self.draft.paste_burst.is_active()
|| !self.draft.input_enabled
|| self.is_task_running
|| self.voice_strip.is_some()
|| self.popup_active()
|| self.footer_mode() == FooterMode::ShortcutOverlay
|| area.height < 3
|| textarea.is_empty()
|| effective_stdout_color_level() != StdoutColorLevel::TrueColor
{
return;
}
let Some(foreground) = default_fg() else {
return;
};
if since.is_none() {
self.sparkle.phase.set(Phase::Visible(now));
}
let fade_start = IDLE_TIMEOUT - IDLE_FADE;
let visibility = if elapsed > fade_start {
(IDLE_TIMEOUT - elapsed).as_secs_f32() / IDLE_FADE.as_secs_f32()
} else {
1.0
};
let protected = Rect::new(
textarea.x,
textarea.y,
self.placeholder_text
.width()
.min(usize::from(textarea.width)) as u16,
/*height*/ 1,
);
field::render_stars(
area,
cursor,
Some(protected),
elapsed.min(fade_start),
foreground,
visibility,
buf,
);
if let Some(requester) = &self.frame_requester {
requester.schedule_frame_in(FRAME_TICK.min(IDLE_TIMEOUT - elapsed));
}
}
}
#[cfg(test)]
#[path = "sparkle_tests.rs"]
mod tests;

View File

@@ -0,0 +1,70 @@
//! Paint the deterministic Astra starfield without owning its eligibility, timer, or redraws.
//!
//! Only blank, unstyled true-color cells outside protected content and the terminal cursor can be
//! decorated. The caller supplies elapsed time and visibility to preserve the original appearance.
use std::time::Duration;
use ratatui::buffer::Buffer;
use ratatui::buffer::CellDiffOption;
use ratatui::layout::Position;
use ratatui::layout::Rect;
use ratatui::style::Color;
use unicode_width::UnicodeWidthStr;
use crate::color::blend;
use crate::terminal_palette::rgb_color;
pub(super) const DOTS: [&str; 8] = ["⠁", "⠂", "⠄", "⠈", "⠐", "⠠", "⡀", "⢀"];
pub(super) fn render_stars(
area: Rect,
cursor: Option<(u16, u16)>,
protected_area: Option<Rect>,
elapsed: Duration,
foreground: (u8, u8, u8),
visibility: f32,
buf: &mut Buffer,
) {
let time = elapsed.as_secs_f32();
for y in area.y..area.bottom() {
let mut occupied_until = area.x;
for x in area.x..area.right() {
let cell = &buf[(x, y)];
if x < occupied_until {
continue;
}
if cell.symbol() != " " {
occupied_until = x.saturating_add(cell.symbol().width() as u16);
continue;
}
if cursor == Some((x, y))
|| protected_area.is_some_and(|protected| protected.contains(Position::new(x, y)))
|| !cell.modifier.is_empty()
|| cell.diff_option != CellDiffOption::None
{
continue;
}
let Color::Rgb(r, g, b) = cell.bg else {
continue;
};
let mut hash = u64::from(y - area.y) * 65537 + u64::from(x - area.x);
hash = (hash ^ (hash >> 16)).wrapping_mul(/*rhs*/ 0x45d9f3b);
hash = (hash ^ (hash >> 16)).wrapping_mul(/*rhs*/ 0x45d9f3b);
hash ^= hash >> 16;
if hash % 5 != 0 {
continue;
}
let phase =
(time / (4.0 + (hash % 31) as f32 / 10.0) + (hash % 997) as f32 / 997.0).fract();
let brightness =
(phase * std::f32::consts::PI).sin().powi(/*n*/ 12) * 0.55 * visibility;
if brightness < 0.04 {
continue;
}
buf[(x, y)]
.set_symbol(DOTS[(hash / 161 % 8) as usize])
.set_fg(rgb_color(blend(foreground, (r, g, b), brightness)));
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,222 @@
//! Separate persistent transcript context from the composer's transient hint row.
//! Measurement, rendering, and cursor placement share the same reserved status rectangle.
//! Shortcut help grows above the input, preserving status and close rows below it even when clipped.
use super::*;
use ratatui::layout::Size;
const MAX_FOOTER_ROWS: u16 = 4;
impl ChatComposer {
pub(crate) fn set_status_line(&mut self, status_line: Option<FooterContent>) -> bool {
if self.footer.status_line_value == status_line {
return false;
}
if matches!(status_line, Some(FooterContent::Extension { .. })) {
self.effort_status_line_transition = None;
}
self.footer.measured_status_line.set(None);
self.footer.status_line_value = status_line;
true
}
pub(crate) fn set_status_line_enabled(&mut self, enabled: bool) -> bool {
if self.footer.status_line_enabled == enabled {
return false;
}
self.footer.status_line_enabled = enabled;
true
}
pub(crate) fn set_side_conversation_context_label(&mut self, label: Option<String>) -> bool {
if self.footer.side_conversation_context_label == label {
return false;
}
self.footer.side_conversation_context_label = label;
true
}
pub(super) fn has_separate_status(&self, options: ComposerRenderOptions<'_>) -> bool {
options.separate_status_line && self.footer.status_line_enabled
}
pub(super) fn shows_shared_status(&self, options: ComposerRenderOptions<'_>) -> bool {
!options.separate_status_line
&& options.footer.is_none()
&& self.custom_footer_height().is_none()
&& self.footer.status_line_enabled
&& self.footer_mode().shows_passive_line(self.is_task_running)
}
pub(super) fn status_surface_height(
&self,
width: u16,
options: ComposerRenderOptions<'_>,
) -> u16 {
if self.has_separate_status(options) {
self.status_line_height(width, options)
} else {
0
}
}
pub(super) fn status_line_height(&self, width: u16, options: ComposerRenderOptions<'_>) -> u16 {
// The unfocused composer paints one dim status line.
if options.unfocused {
return 1;
}
let Some(FooterContent::Extension { content }) = &self.footer.status_line_value else {
return 1;
};
let mut area = Rect::new(/*x*/ 0, /*y*/ 0, width, /*height*/ 1);
if !options.separate_status_line {
let warning = self.warning_notice_layout(inset_footer_hint_area(area), options);
area = warning_notice::before_warning(area, warning.map(|(rect, _)| rect));
}
let (_, width) = self.status_line_layout(area, options, content.measure_natural().width);
let cache = &self.footer.measured_status_line;
if let Some((previous_width, height)) = cache.get()
&& previous_width == width
{
return height;
}
let height = content
.measure(Size::new(width, MAX_FOOTER_ROWS))
.height
.max(1);
cache.set(Some((width, height)));
height
}
pub(super) fn hint_footer_props(&self, options: ComposerRenderOptions<'_>) -> FooterProps {
let mut props = self.footer_props();
if self.has_separate_status(options) {
props.status_line_enabled = false;
props.status_line_value = None;
props.active_agent_label = None;
}
props
}
fn status_line_layout(
&self,
area: Rect,
options: ComposerRenderOptions<'_>,
left_width: u16,
) -> (Option<Line<'static>>, u16) {
let show_cycle_hint = !self.is_task_running
&& if options.separate_status_line {
!self.blocks_direct_input
&& self.draft.input_enabled
&& !self.popup_active()
&& matches!(
self.footer_mode(),
FooterMode::ComposerEmpty | FooterMode::ComposerHasDraft
)
&& options.footer.is_none_or(|footer| !footer.is_interactive)
} else {
self.footer.collaboration_mode_indicator.is_some()
};
let right = if !options.separate_status_line
&& let Some(label) = &self.footer.side_conversation_context_label
{
Some(side_conversation_context_line(label))
} else if !options.separate_status_line
&& let Some(shell) = self.shell_mode_footer_line()
{
Some(shell)
} else if !options.separate_status_line
&& self
.effort_status_line_transition
.as_ref()
.is_some_and(|transition| !transition.is_finished())
{
None
} else {
let full = self.mode_indicator_line(show_cycle_hint);
let full_fits = full.as_ref().is_none_or(|right| {
let right_width = right.width() as u16;
(!options.separate_status_line || right_width <= inset_footer_hint_area(area).width)
&& can_show_left_with_context(area, left_width, right_width)
});
if full_fits {
full
} else {
self.mode_indicator_line(/*show_cycle_hint*/ false)
}
};
let right_width = right
.as_ref()
.map_or(/*default*/ 0, |line| line.width() as u16);
let width = max_left_width_for_right(area, right_width).unwrap_or_else(|| {
if options.separate_status_line {
inset_footer_hint_area(area).width
} else {
area.width.saturating_sub(FOOTER_INDENT_COLS as u16)
}
});
(right, width)
}
pub(super) fn render_status_surface(
&self,
area: Rect,
buf: &mut Buffer,
options: ComposerRenderOptions<'_>,
) {
if area.is_empty() {
return;
}
if options.unfocused {
if let Some(content) = self.status_line_content() {
crate::bottom_pane::footer::render_unfocused_status(
content.clone().into_hyperlink_line().line.to_string(),
area,
buf,
);
}
return;
}
let mut props = self.footer_props();
if options.separate_status_line {
// Persistent context is independent of help, queue, search, and quit modes.
props.mode = FooterMode::ComposerHasDraft;
props.is_task_running = false;
}
let line = passive_footer_status_line(&props);
let left_width = line.as_ref().map_or(/*default*/ 0, FooterContent::width);
let (right, width) = self.status_line_layout(area, options, left_width);
let transition = self
.effort_status_line_transition
.as_ref()
.filter(|transition| !transition.is_finished());
let content = if let Some(transition) = transition {
transition
.render_line(line.map(FooterContent::into_hyperlink_line), width)
.map(FooterContent::HyperlinkLine)
} else {
line
};
if let Some(content) = content {
content.render(
Rect {
width,
..inset_footer_hint_area(area)
},
buf,
);
}
if let Some(right) = right {
render_context_right(area, buf, &right);
}
if transition.is_some()
&& let Some(frame_requester) = &self.frame_requester
{
frame_requester.schedule_frame_in(EFFORT_STATUS_LINE_FRAME_TICK);
}
}
}
#[cfg(test)]
#[path = "status_surface_tests.rs"]
mod tests;

View File

@@ -0,0 +1,748 @@
//! Persistent status survives transient footer modes and suggestion overlays.
use super::*;
use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::osc8_hyperlink;
use crate::terminal_hyperlinks::strip_osc8;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc::unbounded_channel;
fn composer() -> ChatComposer {
let (tx, _rx) = unbounded_channel();
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
AppEventSender::new(tx),
/*enhanced_keys_supported*/ false,
"Ask aKode".to_string(),
/*disable_paste_burst*/ true,
);
composer.set_status_line_enabled(/*enabled*/ true);
composer.set_status_line(Some(
Line::from("MODEL · ~/project · Context 20% used").into(),
));
composer
}
#[test]
fn extension_status_line_clips_links_to_footer_layout() {
let mut composer = composer();
let tree: crate::ui_tree::UiTree = r#"{
"type": "row", "props": {"gap": 1}, "children": [
"plain",
{ "type": "row", "props": {"gap": 1}, "children": [
"·",
{ "type": "link", "props": { "href": "https://example.com/pr/42" }, "children": [
"PR #42"
] }
] }
]
}"#
.parse()
.unwrap();
composer.set_status_line(Some(FooterContent::from(tree)));
for separate_status_line in [false, true] {
for width in [12, 40] {
let options = composer.resolve_render_options(ComposerRenderOptions {
separate_status_line,
..ComposerRenderOptions::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);
let linked = buffer
.content
.iter()
.filter(|cell| cell.symbol().contains("https://example.com/pr/42"))
.collect::<Vec<_>>();
let linked_text: String = linked
.iter()
.map(|cell| strip_osc8(cell.symbol()))
.collect();
assert_eq!(
linked_text,
if width == 12 { "PR#" } else { "PR #42" },
"{buffer:?}"
);
assert!(linked.iter().all(|cell| !cell.symbol().contains('…')));
assert!(buffer.content.iter().any(|cell| cell.symbol() == "p"));
}
}
composer.set_active_agent_label(Some("bot".to_string()));
let (output, _) = render(&composer, /*width*/ 40, /*footer*/ None);
assert!(output.contains("plain"), "{output}");
assert!(!output.contains("bot"), "{output}");
}
fn status_rows(
composer: &ChatComposer,
area: Rect,
options: ComposerRenderOptions<'_>,
) -> Vec<String> {
let layout = composer.layout_with_options(area, options);
let status = if options.separate_status_line {
layout.status
} else {
layout.footer
};
let mut buf = Buffer::empty(area);
composer.render_with_options(area, &mut buf, /*mask_char*/ None, options);
(status.y..status.bottom())
.map(|y| {
(status.x..status.right())
.map(|x| buf[(x, y)].symbol())
.collect::<String>()
.trim()
.to_owned()
})
.collect()
}
#[test]
fn extension_layout_uses_the_width_left_by_the_mode_indicator_after_resize() {
let mut composer = composer();
composer.footer.show_warnings_key = None;
let tree: crate::ui_tree::UiTree =
r#"{"type":"row","props":{"wrap":"wrap","gap":1},"children":[
"Ready", {"type":"row","props":{"gap":1},"children":["PR",
{"type":"link","props":{"href":"https://example.com/pr/12345"},"children":["12345"]}]}]}"#
.parse()
.unwrap();
composer.set_status_line(Some(FooterContent::from(tree)));
composer.set_collaboration_modes_enabled(/*enabled*/ true);
let linked_number: String = "12345"
.chars()
.map(|digit| osc8_hyperlink("https://example.com/pr/12345", &digit.to_string()))
.collect();
let [shared, separate] = [false, true].map(|separate_status_line| {
let mut frames = Vec::new();
for (width, mode, warning_count) in [
(16, None, 0),
(15, None, 0),
(16, None, 0),
(25, Some(CollaborationModeIndicator::Plan), 0),
(19, None, 1),
] {
composer.set_collaboration_mode_indicator(mode);
let options = ComposerRenderOptions {
separate_status_line,
warning_count,
..Default::default()
};
let height = composer.desired_height_with_options(width, options);
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let rows = status_rows(&composer, area, options);
for row in &rows {
let text = strip_osc8(row);
assert_eq!(*row, text.replace("12345", &linked_number));
if warning_count == 0 {
frames.push(format!("{width} | {text}"));
}
}
if warning_count > 0 {
assert_eq!(
composer.footer.warning_notice_area.get().unwrap().bottom(),
height
);
assert_eq!(rows.len(), if separate_status_line { 1 } else { 2 });
let last = strip_osc8(rows.last().unwrap());
assert!(last.contains("PR 12345"));
assert_eq!(last.contains("⚠ 1"), !separate_status_line);
}
}
frames.join("\n")
});
assert_eq!(shared, separate);
insta::assert_snapshot!(shared);
}
#[test]
fn status_rows_yield_to_the_composer_and_shared_footer_overrides() {
let mut composer = composer();
let tree: crate::ui_tree::UiTree = r#""one\ntwo\nthree\nfour\nfive""#.parse().unwrap();
composer.set_status_line(Some(FooterContent::from(tree)));
composer.set_text_content("a\nb\nc".into(), Vec::new(), Vec::new());
for separate_status_line in [false, true] {
let options = ComposerRenderOptions {
separate_status_line,
..Default::default()
};
let short = if separate_status_line {
"one…"
} else {
"one\ntwo…"
};
for (height, expected) in [(12, "one\ntwo\nthree\nfour…"), (7, short)] {
let area = Rect::new(/*x*/ 0, /*y*/ 0, /*width*/ 7, height);
assert_eq!(status_rows(&composer, area, options).join("\n"), expected);
let input = composer.layout_with_options(area, options).textarea;
let mut buffer = Buffer::empty(area);
composer.render_with_options(area, &mut buffer, /*mask_char*/ None, options);
assert!(input.height >= 3);
let draft = [0, 1, 2].map(|dy| buffer[(input.x, input.y + dy)].symbol());
assert_eq!(draft, ["a", "b", "c"]);
let (x, y) = composer
.cursor_pos_with_options(area, options)
.expect("visible draft cursor");
assert!(input.contains((x, y).into()));
if separate_status_line && height == 7 {
let rows: Vec<String> = buffer
.content
.chunks(usize::from(area.width))
.map(|row| row.iter().map(ratatui::buffer::Cell::symbol).collect())
.collect();
insta::assert_debug_snapshot!(rows);
}
}
}
let tree: crate::ui_tree::UiTree = r#""x\ny""#.parse().unwrap();
composer.set_status_line(Some(FooterContent::from(tree)));
assert_eq!(
composer.footer_hint_height(/*width*/ 7, ComposerRenderOptions::default()),
2
);
composer.show_footer_flash("Copied".into(), Duration::from_secs(/*secs*/ 3));
assert_eq!(
composer.footer_hint_height(/*width*/ 7, ComposerRenderOptions::default()),
1
);
}
#[test]
fn sidebar_focus_collapses_extension_status_to_its_dim_line() {
let mut composer = composer();
composer.insert_str("draft");
let tree: crate::ui_tree::UiTree = r#""one\ntwo\nthree\nfour""#.parse().unwrap();
composer.set_status_line(Some(tree.into()));
let frames = [false, true, false].map(|unfocused| {
let options = ComposerRenderOptions {
separate_status_line: true,
unfocused,
..Default::default()
};
let height = composer.desired_height_with_options(/*width*/ 40, options);
status_rows(&composer, Rect::new(0, 0, 40, height), options).join("\n")
});
insta::assert_snapshot!(frames.join("\n---\n"), @"
one
two
three
four
---
one…
---
one
two
three
four
");
}
#[test]
fn extension_status_paints_with_the_current_theme_at_the_same_width() {
use crate::render::highlight::current_syntax_theme;
use crate::render::highlight::set_syntax_theme;
use ratatui::style::Color;
use syntect::highlighting::Color as ThemeColor;
let mut composer = composer();
let content: crate::ui_tree::UiTree =
r#"{"type":"text","props":{"color":"primary"},"children":["λ"]}"#
.parse()
.unwrap();
composer.set_status_line(Some(FooterContent::from(content)));
let previous = current_syntax_theme();
let colors = [1, 2].map(|index| {
let mut theme = previous.clone();
theme.settings.foreground = Some(ThemeColor {
r: index,
g: 0,
b: 0,
a: 0,
});
set_syntax_theme(theme);
let options = ComposerRenderOptions::default();
let width = 24;
let area = Rect::new(
0,
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
.content
.iter()
.find(|cell| cell.symbol() == "λ")
.unwrap()
.fg
});
set_syntax_theme(previous);
assert_eq!(colors, [Color::Red, Color::Green]);
}
#[test]
fn extension_status_keeps_its_rows_when_effort_changes() {
let mut composer = composer();
let tree: crate::ui_tree::UiTree = r#""one\ntwo\nthree""#.parse().unwrap();
composer.set_status_line(Some(FooterContent::from(tree)));
composer.set_active_reasoning_effort_baseline(/*effort*/ None);
composer.set_active_reasoning_effort(
Some(&ReasoningEffort::Max),
/*animations_enabled*/ true,
);
for separate_status_line in [false, true] {
let options = ComposerRenderOptions {
separate_status_line,
..Default::default()
};
let area = Rect::new(
/*x*/ 0, /*y*/ 0, /*width*/ 7, /*height*/ 12,
);
assert_eq!(
status_rows(&composer, area, options),
["one", "two", "three"]
);
}
}
fn render(
composer: &ChatComposer,
width: u16,
footer: Option<&TranscriptFooter>,
) -> (String, Option<(u16, u16)>) {
render_with_height(composer, width, footer, /*height*/ None)
}
fn render_with_height(
composer: &ChatComposer,
width: u16,
footer: Option<&TranscriptFooter>,
height: Option<u16>,
) -> (String, Option<(u16, u16)>) {
let options = composer.resolve_render_options(ComposerRenderOptions {
separate_status_line: true,
command_popup_placement: CommandPopupPlacement::Overlay,
footer,
..ComposerRenderOptions::default()
});
let height = height.unwrap_or_else(|| composer.desired_height_with_options(width, options));
let area = Rect::new(/*x*/ 0, /*y*/ 8, width, height);
let mut buf = Buffer::empty(Rect::new(/*x*/ 0, /*y*/ 0, width, area.bottom()));
composer.render_with_options(area, &mut buf, /*mask_char*/ None, options);
let text = buf
.content
.chunks(usize::from(width))
.map(|row| {
row.iter()
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim_end()
.to_string()
})
.collect::<Vec<_>>()
.join("\n");
(text, composer.cursor_pos_with_options(area, options))
}
#[test]
fn passive_activity_keeps_shortcuts_only_when_the_complete_hint_fits() {
let mut composer = composer();
let mut line = Line::from(key_hint::key_label_spans("ctrl+o t/f4"));
line.push_span(" inspect activity".dim());
let mut footer = TranscriptFooter {
text: line.into(),
cursor_column: None,
is_interactive: false,
};
for (width, expected) in [
(80, "ctrl+o t/f4 inspect activity · ? shortcuts"),
(40, "ctrl+o t/f4 inspect activity"),
] {
let (text, _) = render(&composer, width, Some(&footer));
assert_eq!(text.lines().last().map(str::trim), Some(expected));
}
footer.is_interactive = true;
let (text, _) = render(&composer, /*width*/ 80, Some(&footer));
assert_eq!(
text.lines().last().map(str::trim),
Some("ctrl+o t/f4 inspect activity")
);
footer.is_interactive = false;
composer.footer.toggle_shortcuts_key = None;
let (text, _) = render(&composer, /*width*/ 80, Some(&footer));
assert_eq!(
text.lines().last().map(str::trim),
Some("ctrl+o t/f4 inspect activity")
);
}
#[test]
fn fullscreen_plan_indicator_keeps_the_cycle_hint_when_it_fits() {
let mut composer = composer();
composer.set_collaboration_modes_enabled(/*enabled*/ true);
composer.set_collaboration_mode_indicator(Some(CollaborationModeIndicator::Plan));
let (wide, _) = render(&composer, /*width*/ 100, /*footer*/ None);
assert!(
wide.contains("Plan mode (⇧tab to cycle)"),
"idle fullscreen must explain how to leave Plan mode: {wide}"
);
insta::assert_snapshot!("fullscreen_plan_cycle_hint", wide);
let mut status = HyperlinkLine::from("project · ");
status.push_span("PR #42".underlined(), Some("https://example.com/pull/42"));
composer.set_status_line(Some(status.into()));
composer.set_active_agent_label(Some("reviewer".to_string()));
let (narrow, _) = render(&composer, /*width*/ 37, /*footer*/ None);
let row = narrow.lines().rev().nth(1).expect("persistent status row");
insta::assert_snapshot!(strip_osc8(row).trim(), @"project · PR #42 · rev… Plan mode");
composer.set_active_agent_label(/*active_agent_label*/ None);
composer.set_task_running(/*running*/ true);
let (running, _) = render(&composer, /*width*/ 100, /*footer*/ None);
assert!(running.contains("Plan mode"), "{running}");
assert!(!running.contains("⇧tab"), "{running}");
composer.set_task_running(/*running*/ false);
let footer = TranscriptFooter {
text: "Search: verify".into(),
cursor_column: Some(8),
is_interactive: true,
};
let (search, _) = render(&composer, /*width*/ 100, Some(&footer));
assert!(search.contains("Plan mode"), "{search}");
assert!(!search.contains("⇧tab"), "{search}");
// Configured items such as git-branch can have no value outside a repository.
composer.set_status_line(/*status_line*/ None);
let (empty_narrow, _) = render(&composer, /*width*/ 24, /*footer*/ None);
assert_eq!(
empty_narrow.lines().rev().nth(1).map(str::trim),
Some("Plan mode")
);
let (empty_wide, _) = render(&composer, /*width*/ 100, /*footer*/ None);
assert!(
empty_wide.contains("Plan mode (⇧tab to cycle)"),
"{empty_wide}"
);
composer.set_input_enabled(/*enabled*/ false, /*placeholder*/ None);
let (read_only, _) = render(&composer, /*width*/ 100, /*footer*/ None);
assert_eq!(
read_only.lines().rev().nth(1).map(str::trim),
Some("Plan mode")
);
composer.set_input_enabled(/*enabled*/ true, /*placeholder*/ None);
composer.set_parent_owned_thread();
let (parent_owned, _) = render(&composer, /*width*/ 100, /*footer*/ None);
assert_eq!(
parent_owned.lines().rev().nth(1).map(str::trim),
Some("Plan mode")
);
}
#[test]
fn shortcut_help_stays_above_the_prompt_and_bottom_status() {
let mut composer = composer();
composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
for (width, height, snapshot) in [
(130, None, Some("shortcut_help_above_wide")),
(80, None, None),
(40, None, Some("shortcut_help_above_narrow")),
(80, Some(12), None),
] {
let (text, cursor) = render_with_height(&composer, width, /*footer*/ None, height);
let rows: Vec<_> = text.lines().collect();
let help_row = rows
.iter()
.position(|line| line.contains("Keyboard shortcuts"))
.unwrap();
let prompt_row = rows
.iter()
.position(|line| line.contains("Ask aKode"))
.unwrap();
assert!(help_row < prompt_row);
assert!(
rows[..prompt_row]
.iter()
.any(|line| line.trim() == "/keymap customize")
);
assert_eq!(text.matches("? / esc close").count(), 1);
assert_eq!(
(
rows.last().map(|line| line.trim()),
rows[rows.len() - 2].trim(),
cursor,
),
(
Some("? / esc close"),
"MODEL · ~/project · Context 20% used",
Some((2, prompt_row as u16))
),
);
assert_eq!(prompt_row + 3, rows.len() - 1);
if let Some(name) = snapshot {
insta::assert_snapshot!(name, text);
}
}
}
#[test]
fn shortcut_help_keeps_bottom_anchored_composer_status_and_cursor_stable() {
let (width, available_height) = (40, 12);
let mut composer = composer();
let mut geometry = Vec::new();
for event in [
None,
Some(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE)),
Some(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)),
] {
if let Some(event) = event {
composer.handle_key_event(event);
}
let options = composer.resolve_render_options(ComposerRenderOptions {
separate_status_line: true,
..ComposerRenderOptions::default()
});
let height = composer
.desired_height_with_options(width, options)
.min(available_height);
let area = Rect::new(/*x*/ 3, 80 - height, width, height);
let ComposerLayout {
composer: surface,
footer,
status,
..
} = composer.layout_with_options(area, options);
geometry.push((
surface,
status,
footer,
composer.cursor_pos_with_options(area, options),
));
}
assert_eq!(geometry, vec![geometry[0]; 3]);
}
#[test]
fn shortcut_help_keeps_input_and_close_hint_visible_when_height_is_tiny() {
for status_enabled in [true, false] {
let mut composer = composer();
composer.set_status_line_enabled(status_enabled);
composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
let options = composer.resolve_render_options(ComposerRenderOptions {
separate_status_line: true,
..ComposerRenderOptions::default()
});
for height in 0..=7 {
let area = Rect::new(/*x*/ 3, /*y*/ 5, /*width*/ 40, height);
let mut buf = Buffer::empty(area);
composer.render_with_options(area, &mut buf, /*mask_char*/ None, options);
if let Some((x, y)) = composer.cursor_pos_with_options(area, options) {
assert!(x >= area.x && x < area.right() && y >= area.y && y < area.bottom());
}
if height >= 4 {
let ComposerLayout {
composer: surface,
footer,
..
} = composer.layout_with_options(area, options);
assert_eq!(
(surface.height, footer.height, footer.bottom()),
(3, 1, area.bottom())
);
let last_row = (area.x..area.right())
.map(|x| buf[(x, area.bottom() - 1)].symbol())
.collect::<String>();
assert_eq!(last_row.trim(), "? / esc close");
}
}
}
}
#[test]
fn shortcut_help_close_row_uses_runtime_binding_and_narrow_fallback() {
let chord = Some(key_hint::ShortcutHint::Chord {
prefix: key_hint::ctrl(KeyCode::Char('x')),
completion: key_hint::KeyBinding::new(
KeyCode::F(12),
KeyModifiers::CONTROL | KeyModifiers::SHIFT | KeyModifiers::ALT,
),
});
for (width, binding, expected) in [
(80, chord, "⌃x ⌃⇧⌥f12 / esc close"),
(22, chord, "esc close"),
(80, None, "esc close"),
] {
let mut composer = composer();
composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
composer.footer.toggle_shortcuts_key = binding;
let (text, _) = render_with_height(
&composer,
width,
/*footer*/ None,
/*height*/ Some(8),
);
assert_eq!(text.lines().last().map(str::trim), Some(expected));
assert_eq!(text.matches("close").count(), 1);
assert_eq!(text.matches("/keymap customize").count(), 1);
}
}
#[test]
fn status_survives_hints_feedback_and_queue() {
let mut composer = composer();
composer.set_collaboration_mode_indicator(Some(CollaborationModeIndicator::Plan));
let mut states = Vec::new();
states.push(render(&composer, /*width*/ 64, /*footer*/ None).0);
composer.footer.mode = FooterMode::ShortcutOverlay;
composer.show_footer_flash("Copied selection".into(), Duration::from_secs(/*secs*/ 3));
states.push(render(&composer, /*width*/ 64, /*footer*/ None).0);
composer.footer.flash = None;
composer.footer.mode = FooterMode::ComposerEmpty;
composer.set_footer_hint_override(Some(vec![("Ctrl+X".into(), "waiting for chord".into())]));
states.push(render(&composer, /*width*/ 64, /*footer*/ None).0);
composer.set_footer_hint_override(/*items*/ None);
composer.set_text_content("Continue the task".into(), Vec::new(), Vec::new());
composer.set_task_running(/*running*/ true);
states.push(render(&composer, /*width*/ 64, /*footer*/ None).0);
for popup in [
ActivePopup::File(FileSearchPopup::new()),
ActivePopup::Skill(SkillPopup::new(Vec::new())),
] {
composer.popups.active = popup;
let (text, _) = render(&composer, /*width*/ 64, /*footer*/ None);
assert!(text.contains("MODEL · ~/project · Context 20% used"));
assert_eq!(text.matches("Plan mode").count(), 1);
}
for state in &states {
assert_eq!(state.matches("Plan mode").count(), 1);
assert!(state.contains("MODEL · ~/project · Context 20% used"));
}
insta::assert_snapshot!("persistent_status_and_messages", states.join("\n---\n"));
}
#[test]
fn transcript_search_keeps_status_and_query_cursor() {
let composer = composer();
let footer = TranscriptFooter {
text: vec![
Line::from("Find: needle"),
Line::from("Enter next · Esc close"),
]
.into(),
cursor_column: Some(8),
is_interactive: true,
};
let (text, cursor) = render(&composer, /*width*/ 48, Some(&footer));
assert_eq!(cursor, Some((10, text.lines().count() as u16 - 2)));
assert!(text.contains("MODEL · ~/project · Context 20% used"));
}
#[test]
fn input_history_search_uses_the_final_row() {
let mut composer = composer();
composer.begin_history_search();
let (text, cursor) = render(&composer, /*width*/ 48, /*footer*/ None);
assert_eq!(
cursor.map(|(_, y)| y),
Some(text.lines().count() as u16 - 1)
);
}
#[test]
fn slash_popup_preserves_footer_and_selection_style() {
let (tx, _rx) = unbounded_channel::<AppEvent>();
let mut composer = ChatComposer::new(
/*has_input_focus*/ true,
AppEventSender::new(tx),
/*enhanced_keys_supported*/ false,
"Ask aKode to do anything".to_string(),
/*disable_paste_burst*/ true,
);
composer.set_status_line_enabled(/*enabled*/ true);
composer.set_status_line(Some("model · high · fast".into()));
for ch in ['/', 'm'] {
composer.handle_key_event(KeyEvent::from(KeyCode::Char(ch)));
}
composer.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
for (width, clipped) in [(80, false), (32, false), (80, true)] {
let height = if clipped {
6
} else {
composer.desired_height(width)
};
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
let mut buf = Buffer::empty(area);
composer.render(area, &mut buf);
let ComposerLayout {
composer: surface,
textarea,
popup,
footer,
..
} = composer.layout_with_options(area, ComposerRenderOptions::default());
assert_eq!(popup.bottom(), surface.y);
assert_eq!(surface.bottom(), footer.y);
assert_eq!(composer.cursor_pos(area), Some((4, textarea.y)));
let footer_text: String = (0..width).map(|x| buf[(x, height - 1)].symbol()).collect();
assert!(footer_text.contains("model · high · fast"));
if !clipped && width == 80 {
insta::assert_snapshot!("slash_popup_footer_wide", format!("{buf:?}"));
}
}
let footer = TranscriptFooter {
text: "transcript status".into(),
cursor_column: None,
is_interactive: false,
};
let options = composer.resolve_render_options(ComposerRenderOptions {
footer: Some(&footer),
..Default::default()
});
assert!(options.footer.is_some());
let width = 80;
let area = Rect::new(
/*x*/ 0,
/*y*/ 0,
width,
composer.desired_height_with_options(width, options),
);
let mut buf = Buffer::empty(area);
composer.render_with_options(area, &mut buf, /*mask_char*/ None, options);
let footer_text: String = (0..width)
.map(|x| buf[(x, area.bottom() - 1)].symbol())
.collect();
assert!(footer_text.contains("transcript status"));
}
#[test]
fn activity_shortcut_help_follows_runtime_binding() {
let mut snapshots = Vec::new();
for configured in [
serde_json::json!("f4"),
serde_json::json!("ctrl-x t"),
serde_json::json!([]),
] {
let config = serde_json::from_value(serde_json::json!({
"global": {"focus_activity": configured}
}))
.unwrap();
let keymap = crate::keymap::RuntimeKeymap::from_config(&config).unwrap();
let mut composer = composer();
composer.set_keymap_bindings(&keymap);
composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
let (text, _) = render(&composer, /*width*/ 130, /*footer*/ None);
snapshots.push(format!("{configured}\n{text}"));
}
insta::assert_snapshot!(snapshots.join("\n---\n"));
}

View File

@@ -0,0 +1,219 @@
//! Bounded Vim undo/redo history for the complete composer-owned draft.
//!
//! A textarea does not own pending paste payloads, image attachments, or mention targets. Keeping
//! edit transactions here lets one snapshot restore those values together with visible text. Keys
//! and direct composer-owned changes share the same bounded transaction state.
//! Committed snapshots share a byte budget. One pending edit snapshot has its own matching cap,
//! so canceled commands cannot evict committed history.
use std::collections::VecDeque;
use super::super::textarea::VimPersistentState;
use super::ChatComposer;
use super::ComposerDraft;
use crate::key_hint::KeyBindingListExt;
use crossterm::event::KeyEvent;
const MAX_VIM_UNDO_STEPS: usize = 64;
const MAX_VIM_UNDO_BYTES: usize = 1024 * 1024;
#[derive(Debug, Default)]
pub(super) struct VimHistory {
undo: VecDeque<ComposerDraft>,
redo: VecDeque<ComposerDraft>,
pending: Option<ComposerDraft>,
}
impl ComposerDraft {
fn vim_history_bytes(&self) -> usize {
let mut bytes = self.text.len()
+ self.text_elements.len()
* std::mem::size_of::<akode_protocol::user_input::TextElement>();
bytes += self.mention_ranges.len() * std::mem::size_of::<std::ops::Range<usize>>();
for path in &self.local_image_paths {
bytes += path.as_os_str().len();
}
for url in &self.remote_image_urls {
bytes += url.len();
}
for binding in &self.mention_bindings {
bytes += binding.mention.len() + binding.path.len();
}
for (placeholder, pasted) in &self.pending_pastes {
bytes += placeholder.len() + pasted.len();
}
bytes
}
}
impl VimHistory {
fn trim(&mut self) {
while self.undo.len() > MAX_VIM_UNDO_STEPS
|| self
.undo
.iter()
.chain(self.redo.iter())
.map(ComposerDraft::vim_history_bytes)
.sum::<usize>()
> MAX_VIM_UNDO_BYTES
{
if self.undo.pop_front().is_none() {
self.redo.pop_front();
}
}
}
}
impl ChatComposer {
pub(super) fn wants_vim_history_key(&self, event: KeyEvent) -> bool {
self.draft.textarea.is_vim_normal_mode()
&& !self.draft.textarea.is_vim_operator_pending()
&& !self.popups.active()
&& (self.vim_normal_keymap.redo.is_pressed(event)
|| self.vim_normal_keymap.undo.is_pressed(event))
}
/// Consume undo and redo before normal-mode commands, even when their history is empty.
pub(super) fn handle_vim_history_key(&mut self, event: KeyEvent) -> bool {
if !self.wants_vim_history_key(event) {
return false;
}
let redo = self.vim_normal_keymap.redo.is_pressed(event);
let snapshot = if redo {
self.vim_history.redo.pop_back()
} else {
self.vim_history.undo.pop_back()
};
if let Some(snapshot) = snapshot {
let current = self.snapshot_draft();
if redo {
self.vim_history.undo.push_back(current);
} else {
self.vim_history.redo.push_back(current);
}
let history = std::mem::take(&mut self.vim_history);
let mut vim_state = VimPersistentState::default();
self.draft
.textarea
.swap_vim_persistent_state(&mut vim_state);
self.restore_draft(snapshot);
self.draft
.textarea
.swap_vim_persistent_state(&mut vim_state);
self.vim_history = history;
self.draft.textarea.enter_vim_normal_mode();
self.vim_history.trim();
}
true
}
/// Snapshot only keys that can begin or complete a Vim edit transaction.
pub(super) fn begin_vim_edit(&mut self, event: KeyEvent) {
if !self.draft.textarea.is_vim_enabled()
|| self.vim_history.pending.is_some()
|| self.draft.textarea.is_vim_operator_pending()
{
return;
}
if self.draft.textarea.is_vim_normal_mode()
&& (self.vim_normal_keymap.move_left.is_pressed(event)
|| self.vim_normal_keymap.move_right.is_pressed(event)
|| self.vim_normal_keymap.move_up.is_pressed(event)
|| self.vim_normal_keymap.move_down.is_pressed(event)
|| self.vim_normal_keymap.move_word_forward.is_pressed(event)
|| self.vim_normal_keymap.move_word_backward.is_pressed(event)
|| self.vim_normal_keymap.move_word_end.is_pressed(event)
|| self.vim_normal_keymap.move_line_start.is_pressed(event)
|| self.vim_normal_keymap.move_line_end.is_pressed(event)
|| self.vim_normal_keymap.find_forward.is_pressed(event)
|| self.vim_normal_keymap.find_backward.is_pressed(event)
|| self.vim_normal_keymap.jump_top.is_pressed(event)
|| self.vim_normal_keymap.jump_bottom.is_pressed(event)
|| self.draft.textarea.wants_vim_search_key(event)
|| self.vim_normal_keymap.yank_line.is_pressed(event)
|| self.vim_normal_keymap.start_yank_operator.is_pressed(event)
|| self.vim_normal_keymap.cancel_operator.is_pressed(event))
{
return;
}
self.begin_vim_edit_transaction();
}
/// Start one standalone draft edit without splitting an active Vim command.
pub(super) fn begin_direct_vim_edit(&mut self) -> bool {
if !self.draft.textarea.is_vim_enabled()
|| self.draft.textarea.is_vim_operator_pending()
|| self.vim_history.pending.is_some()
|| self.history_search.is_some()
{
return false;
}
self.begin_vim_edit_transaction();
if self.vim_history.pending.is_none() {
return false;
}
let mut vim_state = VimPersistentState::default();
self.draft
.textarea
.swap_vim_persistent_state(&mut vim_state);
vim_state.commands.last_change.clear();
self.draft
.textarea
.swap_vim_persistent_state(&mut vim_state);
true
}
fn begin_vim_edit_transaction(&mut self) {
let visible_bytes = self.draft.textarea.text().len();
let paste_bytes = self
.draft
.pending_pastes
.iter()
.map(|(placeholder, pasted)| placeholder.len() + pasted.len())
.sum::<usize>();
if visible_bytes.saturating_add(paste_bytes) > MAX_VIM_UNDO_BYTES {
self.vim_history = VimHistory::default();
return;
}
let snapshot = self.snapshot_draft();
if snapshot.vim_history_bytes() <= MAX_VIM_UNDO_BYTES {
self.vim_history.pending = Some(snapshot);
self.vim_history.trim();
} else {
self.vim_history = VimHistory::default();
}
}
/// Commit a complete normal-mode command or one insert-mode session.
pub(super) fn finish_vim_edit(&mut self) {
if !self.draft.textarea.is_vim_normal_mode()
|| self.draft.textarea.is_vim_operator_pending()
{
return;
}
let Some(snapshot) = self.vim_history.pending.take() else {
return;
};
if snapshot.text == self.current_text() {
let mut current = self.snapshot_draft();
current.cursor = snapshot.cursor;
if snapshot == current {
return;
}
}
self.vim_history.redo.clear();
self.vim_history.undo.push_back(snapshot);
self.vim_history.trim();
}
}
#[cfg(test)]
#[path = "vim_history_tests.rs"]
mod tests;

View File

@@ -0,0 +1,875 @@
//! Composer undo/redo transactions preserve rich draft data and active Vim commands.
use std::path::PathBuf;
use akode_config::types::KeybindingSpec;
use akode_config::types::KeybindingsSpec;
use akode_config::types::TuiKeymap;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use super::super::super::chat_composer_history::HistoryEntry;
use super::super::ChatComposer;
use super::super::ComposerDraftSnapshot;
use super::super::InputResult;
use super::super::LARGE_PASTE_CHAR_THRESHOLD;
use super::super::PasteBurst;
use super::super::tests::new_test_composer;
use super::super::tests::snapshot_composer_state_with_width;
use crate::keymap::RuntimeKeymap;
use crate::slash_command::SlashCommand;
fn vim_composer(text: &str) -> ChatComposer {
let (mut composer, _receiver) = new_test_composer();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_text_content(text.to_owned(), Vec::new(), Vec::new());
composer.set_vim_enabled(/*enabled*/ true);
composer.draft.textarea.set_cursor(/*pos*/ 0);
composer
}
fn keys(composer: &mut ChatComposer, keys: &str) {
for key in keys.chars() {
let code = if key == '\n' {
KeyCode::Enter
} else {
KeyCode::Char(key)
};
let _ = composer.handle_key_event(KeyEvent::new(code, KeyModifiers::NONE));
}
}
fn escape(composer: &mut ChatComposer) {
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
}
fn ctrl_r(composer: &mut ChatComposer) {
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
}
#[test]
fn undo_and_redo_group_complete_vim_edits() {
for (original, command, edited) in [
("one two", "cwX", "X two"),
("abc", "iXYZ", "XYZabc"),
("", "i/review", "/review"),
("one two", "c/two\nX", "Xtwo"),
("one two", "d/two\n", "two"),
("abc-def", "df-", "def"),
("abc-def", "cf-X", "Xdef"),
] {
let mut composer = vim_composer(original);
keys(&mut composer, command);
if composer.popups.active() {
escape(&mut composer);
}
escape(&mut composer);
assert_eq!(composer.current_text(), edited);
assert_eq!(composer.vim_history.undo.len(), 1);
keys(&mut composer, "u");
assert_eq!(
(composer.current_text(), composer.cursor()),
(original.to_owned(), 0)
);
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), edited);
}
}
#[test]
fn recovered_answers_undo_as_one_vim_edit() {
for answer in [
"answer".to_owned(),
"x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1),
] {
let mut composer = vim_composer("abc");
keys(&mut composer, "iX");
escape(&mut composer);
let before = composer.draft_snapshot();
composer.append_recovered_drafts(&answer);
keys(&mut composer, "u");
assert_eq!(composer.draft_snapshot(), before);
keys(&mut composer, ".");
assert_eq!(composer.current_text(), "XXabc");
for (command, mode, edited) in [("iX", "Insert", "Xabc"), ("RX", "Replace", "Xbc")] {
let mut composer = vim_composer("abc");
let before = composer.draft_snapshot();
keys(&mut composer, command);
composer.append_recovered_drafts(&answer);
assert_eq!(
(
composer.current_text_with_pending(),
composer.draft.textarea.vim_mode_label(),
),
(format!("{edited}\n\n{answer}"), Some(mode))
);
escape(&mut composer);
let after = composer.draft_snapshot();
keys(&mut composer, "u");
assert_eq!(composer.draft_snapshot(), before);
ctrl_r(&mut composer);
assert_eq!(composer.draft_snapshot(), after);
keys(&mut composer, "u");
keys(&mut composer, ".");
assert_eq!(composer.current_text(), edited);
}
for command in ["", "d", "/draft", "?draft", "d/draft", "c?draft", "y/draft"] {
let mut composer = vim_composer("existing draft");
let before = composer.draft_snapshot();
keys(&mut composer, command);
composer.append_recovered_drafts(&answer);
assert_eq!(
(
composer.current_text_with_pending(),
composer.draft.textarea.vim_query().is_some(),
composer.draft.textarea.is_vim_operator_pending(),
),
(format!("existing draft\n\n{answer}"), false, false)
);
let after = composer.draft_snapshot();
keys(&mut composer, "u");
assert_eq!(composer.draft_snapshot(), before);
ctrl_r(&mut composer);
assert_eq!(composer.draft_snapshot(), after);
}
let mut composer = vim_composer("abc");
composer
.history
.record_local_submission(HistoryEntry::new("archived prompt".into()));
keys(&mut composer, "x");
let before = composer.draft_snapshot();
keys(&mut composer, "d");
ctrl_r(&mut composer);
keys(&mut composer, "archive");
composer.edit_stored_draft(|composer| composer.append_recovered_drafts(&answer));
assert_eq!(composer.current_text(), "archived prompt");
assert!(composer.history_search_active());
escape(&mut composer);
assert_eq!(
composer.current_text_with_pending(),
format!("bc\n\n{answer}")
);
let after = composer.draft_snapshot();
keys(&mut composer, "u");
assert_eq!(composer.draft_snapshot(), before);
ctrl_r(&mut composer);
assert_eq!(composer.draft_snapshot(), after);
}
for command in ["!echo", "/diff"] {
let mut composer = vim_composer(command);
let before = composer.draft_snapshot();
composer.append_recovered_drafts("answer");
assert_eq!(composer.current_text(), format!("\\{command}\n\nanswer"));
keys(&mut composer, "u");
assert_eq!(composer.draft_snapshot(), before);
}
let mut composer = vim_composer("echo");
composer.draft.is_bash_mode = true;
let before = composer.draft_snapshot();
composer.append_recovered_drafts("answer");
assert_eq!(composer.current_text(), "\\!echo\n\nanswer");
keys(&mut composer, "u");
assert_eq!(composer.draft_snapshot(), before);
snapshot_composer_state_with_width(
"recovered_answer_cancels_vim_search",
/*width*/ 40,
/*enhanced_keys_supported*/ false,
|composer| {
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_text_content("existing draft".into(), Vec::new(), Vec::new());
composer.set_vim_enabled(/*enabled*/ true);
keys(composer, "d/draft");
composer.append_recovered_drafts("answer");
},
);
}
#[test]
fn undo_preserves_repeat_and_pending_operator_bindings() {
let mut composer = vim_composer("alpha beta gamma");
keys(&mut composer, "dw.u");
assert_eq!(composer.current_text(), "beta gamma");
keys(&mut composer, "u.");
assert_eq!(composer.current_text(), "beta gamma");
let mut composer = vim_composer("one two");
let mut keymap = RuntimeKeymap::defaults();
keymap.vim_operator.motion_word_forward = vec![crate::key_hint::plain(KeyCode::Char('u'))];
composer.set_keymap_bindings(&keymap);
keys(&mut composer, "duu");
assert_eq!(composer.current_text(), "one two");
}
#[test]
fn undo_and_redo_preserve_confirmed_vim_search() {
let mut composer = vim_composer("alpha beta alpha");
keys(&mut composer, "/alpha\n0xun");
assert_eq!(
(composer.current_text(), composer.cursor()),
("alpha beta alpha".to_owned(), 11)
);
keys(&mut composer, "0");
composer.handle_paste("Z".to_owned());
keys(&mut composer, "n");
assert_eq!(
(composer.current_text(), composer.cursor()),
("Zalpha beta alpha".to_owned(), 12)
);
keys(&mut composer, "u");
ctrl_r(&mut composer);
keys(&mut composer, "n");
assert_eq!(
(composer.current_text(), composer.cursor()),
("Zalpha beta alpha".to_owned(), 1)
);
}
#[test]
fn externally_canceled_search_operator_finishes_the_undo_transaction() {
let mut composer = vim_composer("abc");
keys(&mut composer, "xd/");
assert!(composer.cancel_vim_search());
keys(&mut composer, "uxu");
assert_eq!(composer.current_text(), "abc");
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), "bc");
}
#[test]
fn normal_mode_explicit_paste_is_its_own_edit_and_replaces_stale_redo() {
let mut composer = vim_composer("abc");
keys(&mut composer, "x");
composer.handle_paste("Z".to_owned());
assert_eq!(composer.current_text(), "Zbc");
keys(&mut composer, "u");
assert_eq!(composer.current_text(), "bc");
keys(&mut composer, "u");
assert_eq!(composer.current_text(), "abc");
composer.handle_paste("Z".to_owned());
assert_eq!(composer.current_text(), "Zabc");
assert!(composer.vim_history.redo.is_empty());
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), "Zabc");
assert!(!composer.history_search_active());
keys(&mut composer, "u");
assert_eq!(composer.current_text(), "abc");
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), "Zabc");
}
#[test]
fn normal_mode_direct_insert_and_image_attachment_are_undoable() {
let mut composer = vim_composer("abc");
keys(&mut composer, "xu");
composer.insert_str("Z");
assert_eq!(composer.current_text(), "Zabc");
assert!(composer.vim_history.redo.is_empty());
keys(&mut composer, "u");
assert_eq!(composer.current_text(), "abc");
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), "Zabc");
keys(&mut composer, "u");
let path = PathBuf::from("example.png");
composer.attach_image(path.clone());
let with_image = composer.draft_snapshot();
assert_eq!(composer.local_image_paths(), vec![path]);
assert!(composer.vim_history.redo.is_empty());
keys(&mut composer, "u");
assert_eq!(composer.current_text(), "abc");
assert!(composer.local_image_paths().is_empty());
ctrl_r(&mut composer);
assert_eq!(composer.draft_snapshot(), with_image);
keys(&mut composer, "u\nABC");
assert_eq!(composer.current_text(), "ABC");
escape(&mut composer);
keys(&mut composer, "u");
assert!(composer.is_empty());
keys(&mut composer, "u");
assert!(composer.is_empty());
}
#[test]
fn deleting_a_selected_remote_image_is_one_undoable_vim_edit() {
for key in [KeyCode::Delete, KeyCode::Backspace] {
let mut composer = vim_composer("abc");
let url = "https://example.com/remote.png".to_owned();
composer.set_remote_image_urls(vec![url.clone()]);
keys(&mut composer, "xu");
assert_eq!(composer.vim_history.redo.len(), 1);
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
assert!(composer.vim_history.pending.is_none());
let _ = composer.handle_key_event(KeyEvent::new(key, KeyModifiers::NONE));
assert!(composer.remote_image_urls().is_empty());
assert!(composer.vim_history.redo.is_empty());
keys(&mut composer, "u");
assert_eq!(composer.remote_image_urls(), vec![url]);
assert_eq!(composer.current_text(), "abc");
ctrl_r(&mut composer);
assert!(composer.remote_image_urls().is_empty());
assert_eq!(composer.current_text(), "abc");
}
}
#[test]
fn direct_edits_join_the_active_vim_insert_transaction() {
let mut composer = vim_composer("abc");
composer.enable_vim_in_insert_mode();
composer.handle_paste("ABC".to_owned());
composer.attach_image(PathBuf::from("example.png"));
keys(&mut composer, "D");
escape(&mut composer);
let edited = composer.draft_snapshot();
assert_eq!(composer.vim_history.undo.len(), 1);
keys(&mut composer, "u");
assert_eq!(composer.current_text(), "abc");
assert!(composer.local_image_paths().is_empty());
ctrl_r(&mut composer);
assert_eq!(composer.draft_snapshot(), edited);
}
#[test]
fn vim_search_query_paste_does_not_invalidate_draft_redo() {
let mut composer = vim_composer("alpha beta alpha");
keys(&mut composer, "xu/");
composer.handle_paste("beta".to_owned());
assert_eq!(composer.current_text(), "alpha beta alpha");
assert_eq!(
composer.draft.textarea.vim_query().unwrap().editor.text(),
"beta"
);
assert!(composer.vim_history.pending.is_none());
escape(&mut composer);
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), "lpha beta alpha");
}
#[test]
fn vim_redo_keeps_its_binding_when_history_is_empty() {
let mut composer = vim_composer("abc");
let before = composer.draft_snapshot();
ctrl_r(&mut composer);
assert_eq!(composer.draft_snapshot(), before);
assert!(!composer.history_search_active());
keys(&mut composer, "xu");
assert_eq!(composer.current_text(), "abc");
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), "bc");
assert!(!composer.history_search_active());
let after = composer.draft_snapshot();
ctrl_r(&mut composer);
assert_eq!(composer.draft_snapshot(), after);
assert!(composer.draft.textarea.is_vim_normal_mode());
assert!(!composer.history_search_active());
super::super::tests::snapshot_composer_state_with_width(
"vim_empty_redo_stays_normal",
/*width*/ 60,
/*enhanced_keys_supported*/ true,
|target| *target = composer,
);
let original = "a".repeat(super::MAX_VIM_UNDO_BYTES / 2 + 1);
let mut composer = vim_composer(&original);
keys(&mut composer, "xu");
for command in ["d", "i"] {
keys(&mut composer, command);
escape(&mut composer);
assert_eq!(composer.vim_history.redo.len(), 1);
}
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), original[1..]);
assert!(!composer.history_search_active());
keys(&mut composer, "uiZ");
escape(&mut composer);
assert!(composer.vim_history.redo.is_empty());
keys(&mut composer, "x");
assert_eq!(composer.vim_history.undo.len(), 1);
keys(&mut composer, "u");
assert_eq!(composer.current_text(), format!("Z{original}"));
}
#[test]
fn ctrl_r_searches_history_in_insert_and_non_vim_modes() {
let mut composer = vim_composer("draft");
keys(&mut composer, "i");
ctrl_r(&mut composer);
assert!(composer.history_search_active());
escape(&mut composer);
assert_eq!(composer.draft.textarea.vim_mode_label(), Some("Insert"));
composer.set_vim_enabled(/*enabled*/ false);
ctrl_r(&mut composer);
assert!(composer.history_search_active());
}
#[test]
fn removing_the_shell_prefix_is_its_own_undoable_edit() {
let mut composer = vim_composer("");
keys(&mut composer, "!foo");
escape(&mut composer);
keys(&mut composer, "0");
let before = composer.draft_snapshot();
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
assert_eq!(composer.current_text(), "foo");
keys(&mut composer, "u");
assert_eq!(composer.draft_snapshot(), before);
}
#[test]
fn canceled_reverse_history_preview_preserves_vim_undo_and_repeat() {
let mut composer = vim_composer("alpha beta alpha");
let mut keymap = RuntimeKeymap::defaults();
keymap.vim_normal.redo.clear();
composer.set_keymap_bindings(&keymap);
composer
.history
.record_local_submission(HistoryEntry::new("archived prompt".to_owned()));
keys(&mut composer, "/alpha\n0x");
ctrl_r(&mut composer);
keys(&mut composer, "archive");
assert_eq!(composer.current_text(), "archived prompt");
escape(&mut composer);
assert_eq!(composer.current_text(), "lpha beta alpha");
keys(&mut composer, "u");
assert_eq!(composer.current_text(), "alpha beta alpha");
keys(&mut composer, ".");
assert_eq!(composer.current_text(), "lpha beta alpha");
keys(&mut composer, "n");
assert_eq!(composer.cursor(), 10);
}
#[test]
fn canceled_history_preview_preserves_active_vim_commands() {
for query in ["", "archive", "missing"] {
for (command, edited) in [
("iX", "XYalpha beta"),
("cwX", "XY beta"),
("RX", "XYpha beta"),
] {
let mut composer = vim_composer("alpha beta");
composer
.history
.record_local_submission(HistoryEntry::new("archived prompt".to_owned()));
keys(&mut composer, command);
ctrl_r(&mut composer);
keys(&mut composer, query);
escape(&mut composer);
if command == "RX" {
let _ = composer.handle_key_event(KeyEvent::from(KeyCode::Backspace));
assert_eq!(composer.current_text(), "alpha beta");
keys(&mut composer, "X");
}
keys(&mut composer, "Y");
escape(&mut composer);
assert_eq!(composer.current_text(), edited);
keys(&mut composer, "u.");
assert_eq!(composer.current_text(), edited);
}
}
}
#[test]
fn accepted_reverse_history_preview_starts_a_fresh_vim_edit_history() {
let mut composer = vim_composer("abc");
composer
.history
.record_local_submission(HistoryEntry::new("archived prompt".to_owned()));
keys(&mut composer, "xiX");
ctrl_r(&mut composer);
keys(&mut composer, "archive\n");
assert_eq!(composer.current_text(), "archived prompt");
assert!(!composer.history_search_active());
escape(&mut composer);
keys(&mut composer, "u.");
assert_eq!(composer.current_text(), "archived prompt");
}
#[test]
fn undo_and_redo_use_configured_bindings_and_support_unbinding() {
let mut composer = vim_composer("abc");
let mut keymap = RuntimeKeymap::defaults();
keymap.vim_normal.undo = vec![crate::key_hint::plain(KeyCode::Char('z'))];
keymap.vim_normal.redo = vec![crate::key_hint::plain(KeyCode::Char('v'))];
composer.set_keymap_bindings(&keymap);
keys(&mut composer, "xu");
assert_eq!(composer.current_text(), "bc");
keys(&mut composer, "z");
assert_eq!(composer.current_text(), "abc");
keys(&mut composer, "v");
assert_eq!(composer.current_text(), "bc");
keys(&mut composer, "z");
keymap.vim_normal.undo.clear();
keymap.vim_normal.redo.clear();
composer.set_keymap_bindings(&keymap);
keys(&mut composer, "xzv");
assert_eq!(composer.current_text(), "bc");
let mut config = TuiKeymap::default();
config.composer.history_search_previous =
Some(KeybindingsSpec::One(KeybindingSpec("u".to_owned())));
composer.set_keymap_bindings(&RuntimeKeymap::from_config(&config).unwrap());
keys(&mut composer, "u");
assert!(composer.history_search_active());
escape(&mut composer);
config.vim_normal.undo = Some(KeybindingsSpec::One(KeybindingSpec("u".to_owned())));
composer.set_keymap_bindings(&RuntimeKeymap::from_config(&config).unwrap());
keys(&mut composer, "u");
assert!(!composer.history_search_active());
let mut composer = vim_composer("abc");
keys(&mut composer, "xu");
let mut config = TuiKeymap::default();
config.composer.history_search_previous =
Some(KeybindingsSpec::One(KeybindingSpec("ctrl-r".to_owned())));
composer.set_keymap_bindings(&RuntimeKeymap::from_config(&config).unwrap());
ctrl_r(&mut composer);
assert!(composer.history_search_active());
escape(&mut composer);
config.vim_normal.redo = Some(KeybindingsSpec::One(KeybindingSpec("ctrl-r".to_owned())));
composer.set_keymap_bindings(&RuntimeKeymap::from_config(&config).unwrap());
ctrl_r(&mut composer);
assert!(!composer.history_search_active());
assert_eq!(composer.current_text(), "bc");
ctrl_r(&mut composer);
assert!(!composer.history_search_active());
let mut composer = vim_composer("abc");
let mut config = TuiKeymap::default();
config.composer.submit = Some(KeybindingsSpec::One(KeybindingSpec("u".to_owned())));
composer.set_keymap_bindings(&RuntimeKeymap::from_config(&config).unwrap());
assert_eq!(
composer
.handle_key_event(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::NONE))
.0,
InputResult::Submitted {
text: "abc".to_owned(),
text_elements: Vec::new()
}
);
}
#[test]
fn undo_and_redo_restore_deleted_large_paste_payload() {
let mut composer = vim_composer("alpha ");
composer.draft.textarea.set_cursor("alpha ".len());
keys(&mut composer, "i");
let pasted = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1);
composer.handle_paste(pasted.clone());
escape(&mut composer);
let before = composer.draft_snapshot();
keys(&mut composer, "x");
assert_eq!(composer.current_text(), "alpha ");
assert!(composer.draft.pending_pastes.is_empty());
keys(&mut composer, "u");
assert_eq!(composer.draft_snapshot(), before);
assert_eq!(
composer.current_text_with_pending(),
format!("alpha {pasted}")
);
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), "alpha ");
assert!(composer.draft.pending_pastes.is_empty());
}
#[test]
fn undo_and_redo_restore_deleted_image_attachment() {
let mut composer = vim_composer("alpha ");
composer.draft.textarea.set_cursor("alpha ".len());
composer.attach_image(PathBuf::from("example.png"));
composer.draft.textarea.set_cursor("alpha ".len());
let before = composer.draft_snapshot();
keys(&mut composer, "RX");
ctrl_r(&mut composer);
escape(&mut composer);
let _ = composer.handle_key_event(KeyEvent::from(KeyCode::Backspace));
assert_eq!(
composer.draft_snapshot(),
ComposerDraftSnapshot {
vim_normal_mode: false,
..before.clone()
}
);
escape(&mut composer);
composer.draft.textarea.set_cursor("alpha ".len());
keys(&mut composer, "x");
assert_eq!(composer.current_text(), "alpha ");
assert!(composer.local_image_paths().is_empty());
keys(&mut composer, "u");
assert_eq!(composer.draft_snapshot(), before);
ctrl_r(&mut composer);
assert_eq!(composer.current_text(), "alpha ");
assert!(composer.local_image_paths().is_empty());
}
#[test]
fn vim_replace_yank_preserves_existing_image_and_recovers_atomically() {
let mut composer = vim_composer("");
keys(&mut composer, "i");
composer.attach_image(PathBuf::from("killed.png"));
composer.handle_key_event(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
composer.attach_image(PathBuf::from("existing.png"));
keys(&mut composer, "abcdefghij");
let before = (composer.current_text(), composer.local_image_paths());
escape(&mut composer);
keys(&mut composer, "0R");
composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
composer.handle_key_event(KeyEvent::from(KeyCode::Backspace));
assert_eq!(
(composer.current_text(), composer.local_image_paths()),
before
);
}
#[test]
fn find_jump_and_search_navigation_never_snapshot_the_draft() {
let mut composer = vim_composer("alpha beta\nalpha gamma");
for key in ['f', 'F', 'G', '/', '?', 'n', 'N'] {
composer.begin_vim_edit(KeyEvent::new(KeyCode::Char(key), KeyModifiers::NONE));
assert!(
composer.vim_history.pending.is_none(),
"navigation binding {key:?} snapshotted the draft"
);
}
let (code, modifiers) = composer
.vim_normal_keymap
.jump_top
.first()
.expect("native jump-top chord")
.parts();
composer.begin_vim_edit(KeyEvent::new(code, modifiers));
assert!(composer.vim_history.pending.is_none());
for command in ["llwbh0$", "fb", "Fa", "G", "/beta\nnN", "?alpha\n"] {
let text = "alpha beta\nalpha gamma";
let mut composer = vim_composer(text);
for key in command.chars() {
keys(&mut composer, &key.to_string());
assert!(
composer.vim_history.pending.is_none(),
"navigation command {command:?} snapshotted the draft"
);
assert!(composer.vim_history.undo.is_empty());
}
assert_eq!(composer.current_text(), text);
}
let mut keymap = RuntimeKeymap::defaults();
keymap.vim_normal.redo.clear();
composer.set_keymap_bindings(&keymap);
composer
.history
.record_local_submission(HistoryEntry::new("alpha archived".to_owned()));
ctrl_r(&mut composer);
keys(&mut composer, "alpha");
assert_eq!(composer.current_text(), "alpha archived");
assert!(composer.vim_history.pending.is_none());
assert!(composer.vim_history.undo.is_empty());
escape(&mut composer);
assert_eq!(composer.current_text(), "alpha beta\nalpha gamma");
}
#[test]
fn vim_replace_preserves_slash_completion_and_dispatch() {
let mut composer = vim_composer("");
keys(&mut composer, "R/dif");
let _ = composer.handle_key_event(KeyEvent::from(KeyCode::Tab));
assert_eq!(composer.current_text(), "/diff ");
let (result, _) = composer.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert_eq!(result, InputResult::Command(SlashCommand::Diff));
}
#[test]
fn vim_replace_backspace_restores_characters_in_new_slash_element() {
snapshot_composer_state_with_width(
"vim_replace_slash_recovery",
/*width*/ 100,
/*enhanced_keys_supported*/ true,
|composer| {
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_text_content("abcde tail".into(), Vec::new(), Vec::new());
composer.set_vim_enabled(/*enabled*/ true);
composer.draft.textarea.set_cursor(/*pos*/ 0);
keys(composer, "R/diff");
assert_eq!(composer.draft.textarea.element_payloads(), vec!["/diff"]);
for expected in [("/dife tail", 4), ("/dide tail", 3)] {
let _ = composer.handle_key_event(KeyEvent::from(KeyCode::Backspace));
assert_eq!(
(composer.current_text(), composer.current_cursor()),
(expected.0.to_string(), expected.1)
);
}
},
);
}
#[test]
fn vim_replace_delete_backward_restores_characters_hidden_by_prompt_prefixes() {
let mut composer = vim_composer("ébc");
keys(&mut composer, "R!");
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL));
assert_eq!(
(composer.current_text(), composer.current_cursor()),
("ébc".to_owned(), 0)
);
}
#[test]
fn vim_editing_modes_use_the_same_large_and_image_paste_handling() {
let temporary = tempfile::tempdir().expect("create image directory");
let path = temporary.path().join("image.png");
image::RgbaImage::new(/*width*/ 1, /*height*/ 1)
.save(&path)
.expect("write image");
for pasted in [
"x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1),
path.to_string_lossy().into_owned(),
] {
let mut insert = vim_composer("next");
keys(&mut insert, "i");
insert.handle_paste(pasted.clone());
let mut replace = vim_composer("next");
keys(&mut replace, "R");
replace.handle_paste(pasted);
assert_eq!(replace.draft_snapshot(), insert.draft_snapshot());
}
}
#[test]
fn vim_replace_paste_bursts_preserve_overwritten_text_and_repeat() {
for pasted in ["XYZ", "日\u{3000}語"] {
let mut composer = vim_composer("abcd");
keys(&mut composer, "R");
composer.set_disable_paste_burst(/*disabled*/ false);
let now = std::time::Instant::now();
for ch in pasted.chars() {
let _ = composer.handle_input_basic_with_time(KeyEvent::from(KeyCode::Char(ch)), now);
}
assert!(composer.is_in_paste_burst());
composer.handle_paste_burst_flush(now + PasteBurst::recommended_active_flush_delay());
assert_eq!(composer.current_text(), format!("{pasted}d"));
escape(&mut composer);
keys(&mut composer, "u.");
assert_eq!(composer.current_text(), format!("{pasted}d"));
}
}
#[test]
fn vim_replace_completion_preserves_suffix() {
snapshot_composer_state_with_width(
"vim_replace_completion_suffix",
/*width*/ 100,
/*enhanced_keys_supported*/ true,
|composer| {
composer.set_disable_paste_burst(/*disabled*/ true);
for (text, cursor, command, path) in [
("@ma next", 3, "R", "src/main.rs"),
("abc next", 0, "R@ma", "ma"),
] {
composer.set_vim_enabled(/*enabled*/ true);
composer.set_text_content(text.into(), Vec::new(), Vec::new());
composer.draft.textarea.set_cursor(cursor);
keys(composer, command);
composer.insert_selected_file_path(0.."@ma".len(), path);
composer.sync_popups();
assert_eq!(
(composer.current_text(), composer.current_cursor()),
(format!("{path} next"), path.len() + 1)
);
let _ = composer.handle_key_event(KeyEvent::from(KeyCode::Backspace));
assert_eq!(
(composer.current_text(), composer.current_cursor()),
(format!("{path} next"), path.len())
);
}
},
);
}
#[test]
fn external_editor_import_preserves_replace_backspace_recovery() {
let mut composer = vim_composer("old");
keys(&mut composer, "RX");
composer.apply_external_edit("abc".into());
composer.draft.textarea.set_cursor(/*pos*/ 1);
let _ = composer.handle_key_event(KeyEvent::from(KeyCode::Backspace));
assert_eq!(composer.current_text(), "bc");
for code in [KeyCode::Char('X'), KeyCode::Backspace] {
let _ = composer.handle_key_event(KeyEvent::from(code));
}
let textarea = &composer.draft.textarea;
assert_eq!(
(textarea.text(), textarea.vim_mode_label()),
("bc", Some("Replace"))
);
}
#[test]
fn repeated_deletion_leaves_exposed_bang_literal() {
let mut composer = vim_composer("Yes! I agree.");
keys(&mut composer, "x..");
let literal = composer.snapshot_draft();
keys(&mut composer, "u");
ctrl_r(&mut composer);
assert_eq!(composer.snapshot_draft(), literal);
assert_eq!(composer.current_text(), "! I agree.");
assert!(!composer.draft.is_bash_mode);
keys(&mut composer, "x");
assert_eq!(composer.current_text(), " I agree.");
}
#[test]
fn cancelled_history_search_preserves_literal_bang_draft() {
let mut composer = vim_composer("x!echo hello");
composer.set_vim_enabled(/*enabled*/ false);
composer.handle_key_event(KeyEvent::new(KeyCode::Delete, KeyModifiers::NONE));
let literal = composer.snapshot_draft();
ctrl_r(&mut composer);
escape(&mut composer);
assert_eq!(composer.snapshot_draft(), literal);
assert_eq!(
composer
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
.0,
InputResult::Queued {
text: "!echo hello".to_owned(),
text_elements: Vec::new(),
action: super::super::QueuedInputAction::Literal,
pending_pastes: Vec::new(),
}
);
}
#[test]
fn editor_actions_insert_shell_prefixes() {
let mut composer = vim_composer("x!echo hi");
composer.set_vim_enabled(/*enabled*/ false);
for (code, modifiers) in [
(KeyCode::Right, KeyModifiers::NONE),
(KeyCode::Char('k'), KeyModifiers::CONTROL),
(KeyCode::Backspace, KeyModifiers::NONE),
(KeyCode::Char('y'), KeyModifiers::CONTROL),
] {
composer.handle_key_event(KeyEvent::new(code, modifiers));
}
assert_eq!(
(composer.current_text(), composer.draft.is_bash_mode),
("!echo hi".to_owned(), true)
);
for (commands, expected) in [("r!", "!xecho hi"), ("lr!0.", "!!echo hi")] {
let mut composer = vim_composer("xxecho hi");
keys(&mut composer, commands);
assert_eq!(
(composer.current_text(), composer.draft.is_bash_mode),
(expected.to_owned(), true)
);
}
}

View File

@@ -0,0 +1,165 @@
//! Composer payloads for the textarea's single-entry register. Copy captures original targets;
//! paste allocates fresh element identities and placeholder labels, without re-resolving targets.
//! Captured Ctrl-Y actions retain their original register generation through dot-repeat and undo.
//! The live register travels with composer replacement; repeat/undo generations stay local.
//! Like the text register, this state survives draft clears and undo, but is not a system clipboard.
use crate::bottom_pane::textarea::TextElementSnapshot;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Weak;
use super::ChatComposer;
use super::draft_state::ComposerMentionBinding;
use crate::bottom_pane::LocalImageAttachment;
use crate::bottom_pane::textarea::register::RegisterEvent;
use akode_protocol::models::local_image_label_text;
#[derive(Clone)]
enum RegisterPayload {
Mention(ComposerMentionBinding),
Image(PathBuf),
Paste(String),
}
type RegisterGeneration = (
Weak<Vec<TextElementSnapshot>>,
HashMap<u64, RegisterPayload>,
);
#[derive(Default)]
pub(super) struct VimRegister {
payloads: Vec<RegisterGeneration>,
}
/// The live register only, paired with the exact range generation that owns its payloads.
pub(crate) struct KillBufferSnapshot {
textarea: crate::bottom_pane::textarea::KillBufferSnapshot,
payloads: HashMap<u64, RegisterPayload>,
}
pub(super) fn take_snapshot(composer: &mut ChatComposer) -> KillBufferSnapshot {
sync(composer);
let textarea = composer.draft.textarea.take_kill_buffer_snapshot();
let source = Arc::downgrade(&textarea.elements);
let payloads = composer
.vim_register
.payloads
.iter()
.find(|(key, _)| key.ptr_eq(&source))
.map(|(_, payloads)| payloads.clone())
.unwrap_or_default();
KillBufferSnapshot { textarea, payloads }
}
pub(super) fn restore_snapshot(composer: &mut ChatComposer, snapshot: KillBufferSnapshot) {
composer.vim_register.payloads.push((
Arc::downgrade(&snapshot.textarea.elements),
snapshot.payloads,
));
composer
.draft
.textarea
.restore_kill_buffer_snapshot(snapshot.textarea);
}
pub(super) fn sync(composer: &mut ChatComposer) {
// Generations stay alive only while the live register or a repeat transaction needs them.
composer
.vim_register
.payloads
.retain(|(source, _)| source.strong_count() > 0);
if let Some(event) = composer.draft.textarea.take_register_event() {
match event {
RegisterEvent::Copied(elements) => {
let payloads = elements
.iter()
.filter_map(|element| {
let payload = if let Some(binding) =
composer.draft.mention_bindings.get(&element.id)
{
RegisterPayload::Mention(binding.clone())
} else if let Some(image) = composer
.attachments
.local_images
.iter()
.find(|image| image.placeholder == element.text)
{
RegisterPayload::Image(image.path.clone())
} else if let Some((_, pasted)) = composer
.draft
.pending_pastes
.iter()
.find(|(placeholder, _)| *placeholder == element.text)
{
RegisterPayload::Paste(pasted.clone())
} else {
return None;
};
Some((element.id, payload))
})
.collect();
composer
.vim_register
.payloads
.push((Arc::downgrade(&elements), payloads));
}
RegisterEvent::Pasted(elements, ids) => {
let source = Arc::downgrade(&elements);
let Some((_, payloads)) = composer
.vim_register
.payloads
.iter()
.find(|(key, _)| key.ptr_eq(&source))
else {
return;
};
let payloads: Vec<_> = ids
.into_iter()
.filter_map(|(source, destination)| {
payloads
.get(&source)
.cloned()
.map(|payload| (destination, payload))
})
.collect();
for (destination, payload) in payloads {
match payload {
RegisterPayload::Mention(binding) => {
composer.draft.mention_bindings.insert(destination, binding);
}
RegisterPayload::Image(path) => {
let placeholder = local_image_label_text(
composer.attachments.remote_image_urls.len()
+ composer.attachments.local_images.len()
+ 1,
);
composer
.draft
.textarea
.replace_element_payload_by_id(destination, &placeholder);
composer
.attachments
.local_images
.push(LocalImageAttachment { placeholder, path });
}
RegisterPayload::Paste(pasted) => {
let placeholder =
composer.next_large_paste_placeholder(pasted.chars().count());
composer
.draft
.textarea
.replace_element_payload_by_id(destination, &placeholder);
composer.draft.pending_pastes.push((placeholder, pasted));
}
}
}
}
}
}
}
#[cfg(test)]
#[path = "vim_register_tests.rs"]
mod tests;

View File

@@ -0,0 +1,439 @@
#![cfg(test)]
//! Rich register coverage through real composer input and submission preparation.
use super::super::ChatComposer;
use super::super::LARGE_PASTE_CHAR_THRESHOLD;
use super::super::tests::new_test_composer;
use super::super::tests::snapshot_composer_state_with_width;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
fn key(composer: &mut ChatComposer, code: KeyCode) {
let _ = composer.handle_key_event(KeyEvent::new(code, KeyModifiers::NONE));
}
fn commands(composer: &mut ChatComposer, text: &str) {
for ch in text.chars() {
key(composer, KeyCode::Char(ch));
}
}
fn rich_composer() -> ChatComposer {
let (mut composer, _) = new_test_composer();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_vim_enabled(/*enabled*/ true);
composer.insert_selected_mention(0..0, "$skill", Some("/original/skill/SKILL.md"));
composer.attach_image(PathBuf::from("/original/photo.png"));
composer.handle_paste("z".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1));
composer.popups.active = super::super::ActivePopup::None;
key(&mut composer, KeyCode::Esc);
commands(&mut composer, "0");
composer
}
#[test]
fn yank_and_repeated_paste_create_fresh_rich_objects() {
let mut composer = rich_composer();
let original = composer.current_text_with_pending();
commands(&mut composer, "y$p.");
assert_eq!(composer.draft.textarea.text_elements().len(), 9);
assert_eq!(
composer.local_image_paths(),
vec![PathBuf::from("/original/photo.png"); 3]
);
assert_eq!(composer.draft.pending_pastes.len(), 3);
assert_eq!(composer.mention_bindings().len(), 3);
assert!(
composer
.mention_bindings()
.iter()
.all(|binding| binding.path == "/original/skill/SKILL.md")
);
assert_eq!(
composer.current_text_with_pending().matches('z').count(),
original.matches('z').count() * 3
);
let ids: std::collections::HashSet<_> = composer
.draft
.textarea
.text_element_snapshots()
.into_iter()
.map(|element| element.id)
.collect();
assert_eq!(ids.len(), 9);
}
#[test]
fn deleted_rich_register_survives_clear_and_linewise_paste() {
let mut composer = rich_composer();
let original = composer.current_text_with_pending();
commands(&mut composer, "dd");
assert_eq!(composer.local_image_paths(), Vec::<PathBuf>::new());
assert_eq!(
composer.draft.pending_pastes,
Vec::<(String, String)>::new()
);
composer.set_text_content("new".to_owned(), Vec::new(), Vec::new());
commands(&mut composer, "p");
assert_eq!(
composer.current_text_with_pending(),
format!("new\n{original}")
);
assert_eq!(
composer.local_image_paths(),
vec![PathBuf::from("/original/photo.png")]
);
assert_eq!(
composer.mention_bindings()[0].path,
"/original/skill/SKILL.md"
);
}
#[test]
fn composer_handoff_preserves_only_the_live_rich_register() {
let mut previous = rich_composer();
commands(&mut previous, "y$A");
let _ = previous.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
key(&mut previous, KeyCode::Esc);
commands(&mut previous, "yy");
// The captured Ctrl-Y still owns the old generation, distinct from the current yank.
assert_eq!(previous.vim_register.payloads.len(), 2);
let original = previous.current_text_with_pending();
let (mut composer, _) = new_test_composer();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_vim_enabled(/*enabled*/ true);
composer.set_text_content("new".to_owned(), Vec::new(), Vec::new());
composer.restore_kill_buffer_snapshot(previous.take_kill_buffer_snapshot());
drop(previous);
assert_eq!(composer.vim_register.payloads.len(), 1);
key(&mut composer, KeyCode::Esc);
commands(&mut composer, "u.");
assert_eq!(composer.current_text(), "new");
commands(&mut composer, "p");
assert_eq!(
composer.current_text_with_pending(),
format!("new\n{original}")
);
assert_eq!(composer.draft.textarea.text_elements().len(), 6);
assert_eq!(
composer.local_image_paths(),
vec![PathBuf::from("/original/photo.png"); 2]
);
assert_eq!(composer.draft.pending_pastes.len(), 2);
assert_eq!(composer.mention_bindings().len(), 2);
assert!(
composer
.mention_bindings()
.iter()
.all(|binding| binding.path == "/original/skill/SKILL.md")
);
}
#[test]
fn insert_yank_and_dot_preserve_rich_payloads() {
for mode in ["i", "R"] {
let mut composer = rich_composer();
commands(&mut composer, "d$");
commands(&mut composer, mode);
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
commands(&mut composer, " foo");
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL));
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
key(&mut composer, KeyCode::Esc);
let edited = composer.current_text_with_pending();
commands(&mut composer, "u");
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
assert_eq!(composer.current_text_with_pending(), edited);
commands(&mut composer, "0.");
assert_eq!(
composer.local_image_paths(),
vec![PathBuf::from("/original/photo.png"); 2]
);
assert_eq!(composer.draft.pending_pastes.len(), 2);
assert_eq!(composer.mention_bindings().len(), 2);
assert!(
composer
.mention_bindings()
.iter()
.all(|binding| binding.path == "/original/skill/SKILL.md")
);
assert_eq!(
composer.current_text_with_pending().matches("foo").count(),
if mode == "i" { 2 } else { 1 }
);
}
}
#[test]
fn insert_yank_repeat_keeps_original_text_after_word_deletion() {
let (mut composer, _) = new_test_composer();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_vim_enabled(/*enabled*/ true);
composer.set_text_content("foo bar".to_owned(), Vec::new(), Vec::new());
commands(&mut composer, "0y$");
composer.set_text_content("_".to_owned(), Vec::new(), Vec::new());
commands(&mut composer, "0i");
for ch in ['y', 'w'] {
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::CONTROL));
}
key(&mut composer, KeyCode::Esc);
assert_eq!(composer.current_text(), "foo _");
commands(&mut composer, "0.");
assert_eq!(composer.current_text(), "foo foo _");
commands(&mut composer, "p");
assert!(composer.current_text().contains("bar"));
}
#[test]
fn plain_delete_replaces_rich_register() {
let mut composer = rich_composer();
commands(&mut composer, "y$");
composer.set_text_content("abc".to_owned(), Vec::new(), Vec::new());
commands(&mut composer, "0xp");
assert_eq!(composer.current_text(), "bac");
assert_eq!(composer.draft.textarea.text_elements(), Vec::new());
assert_eq!(composer.local_image_paths(), Vec::<PathBuf>::new());
assert_eq!(composer.mention_bindings(), Vec::new());
}
#[test]
fn rich_paste_renders_unique_image_and_paste_labels() {
snapshot_composer_state_with_width(
"vim_rich_register",
/*width*/ 100,
/*enhanced_keys_supported*/ false,
|composer| {
let mut previous = rich_composer();
commands(&mut previous, "y$");
*composer = rich_composer();
composer.restore_kill_buffer_snapshot(previous.take_kill_buffer_snapshot());
commands(composer, "p");
},
);
}
#[test]
fn replace_yank_inserts_rich_objects_without_stale_character_recovery() {
for existing_element in [false, true] {
let mut composer = rich_composer();
commands(&mut composer, "y$");
composer.set_text_content("abcdefghij".to_owned(), Vec::new(), Vec::new());
if existing_element {
composer.draft.textarea.set_cursor(/*pos*/ 0);
composer.attach_image(PathBuf::from("/original/other.png"));
}
commands(&mut composer, "0R");
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
assert_eq!(
composer.mention_bindings()[0].path,
"/original/skill/SKILL.md"
);
assert_eq!(
composer.local_image_paths().len(),
1 + usize::from(existing_element)
);
key(&mut composer, KeyCode::Backspace);
assert_eq!(
composer.draft.pending_pastes,
Vec::<(String, String)>::new()
);
assert!(composer.current_text().ends_with("abcdefghij"));
assert_eq!(composer.mention_bindings().len(), 1);
}
}
#[test]
fn equal_length_plain_replace_yank_records_dot() {
let (mut composer, _) = new_test_composer();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_vim_enabled(/*enabled*/ true);
composer.set_text_content("xyz".to_owned(), Vec::new(), Vec::new());
commands(&mut composer, "0y$");
composer.set_text_content("abcdefghi".to_owned(), Vec::new(), Vec::new());
commands(&mut composer, "0R");
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
key(&mut composer, KeyCode::Esc);
commands(&mut composer, "l.");
assert_eq!(composer.current_text(), "xyzxyzghi");
}
#[test]
fn empty_insert_and_replace_yanks_do_not_replay_a_later_register() {
for mode in ["i", "R"] {
let (mut composer, _) = new_test_composer();
composer.set_disable_paste_burst(/*disabled*/ true);
composer.set_vim_enabled(/*enabled*/ true);
commands(&mut composer, mode);
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
commands(&mut composer, "x");
key(&mut composer, KeyCode::Esc);
commands(&mut composer, "0yl.");
assert_eq!(
composer.current_text(),
if mode == "i" { "xx" } else { "x" }
);
}
}
#[test]
fn linewise_rich_paste_preserves_the_cursor_on_the_leading_element() {
let mut states = Vec::new();
for image in [false, true] {
let (mut composer, _) = new_test_composer();
composer.set_vim_enabled(/*enabled*/ true);
if image {
composer.attach_image(PathBuf::from("/original/photo.png"));
} else {
composer.handle_paste("z".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1));
}
key(&mut composer, KeyCode::Esc);
commands(&mut composer, "0yyp");
let mut marked = composer.current_text().to_owned();
marked.insert(composer.draft.textarea.cursor(), '|');
states.push(marked);
}
insta::assert_snapshot!(states.join("\n\n"), @r###"
[Pasted Content 1001 chars]
|[Pasted Content 1001 chars] #2
[Image #1]
|[Image #2]
"###);
}
fn select(composer: &mut ChatComposer, start: u16, end: u16) {
use crossterm::event::MouseButton;
use crossterm::event::MouseEvent;
use crossterm::event::MouseEventKind;
use ratatui::widgets::StatefulWidgetRef;
let area = ratatui::layout::Rect::new(0, 0, 100, 4);
let mut state = super::super::super::textarea::TextAreaState::default();
let mut buffer = ratatui::buffer::Buffer::empty(area);
(&composer.draft.textarea).render_ref(area, &mut buffer, &mut state);
for (kind, column) in [
(MouseEventKind::Down(MouseButton::Left), start),
(MouseEventKind::Drag(MouseButton::Left), end),
(MouseEventKind::Up(MouseButton::Left), end),
] {
composer.draft.textarea.handle_mouse(
MouseEvent {
kind,
column,
row: 0,
modifiers: KeyModifiers::NONE,
},
state,
);
}
assert_eq!(
composer.draft.textarea.mouse_selection_range(),
Some(usize::from(start)..usize::from(end))
);
}
#[test]
fn yank_replaces_selection_without_recording_pointer_edits() {
for rich in [false, true] {
for mode in ["nonvim", "i", "R"] {
let mut composer = rich_composer();
if !rich {
composer.set_text_content("xyz".to_owned(), Vec::new(), Vec::new());
}
commands(&mut composer, "0y$");
let copied = composer.current_text_with_pending();
composer.set_text_content("abcdef".to_owned(), Vec::new(), Vec::new());
if mode == "nonvim" {
composer.set_vim_enabled(/*enabled*/ false);
} else {
commands(&mut composer, mode);
}
select(&mut composer, /*start*/ 1, /*end*/ 3);
let _ =
composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
assert_eq!(
composer.current_text_with_pending(),
format!("a{copied}def")
);
assert_eq!(composer.mention_bindings().len(), usize::from(rich));
assert_eq!(composer.local_image_paths().len(), usize::from(rich));
if mode != "nonvim" {
key(&mut composer, KeyCode::Esc);
assert!(composer.draft.textarea.vim_repeat_actions().is_none());
}
}
}
}
#[test]
fn normal_dot_clears_pointer_selection_before_each_replay() {
let mut composer = rich_composer();
composer.set_text_content("abcdef".to_owned(), Vec::new(), Vec::new());
commands(&mut composer, "0iX");
key(&mut composer, KeyCode::Esc);
select(&mut composer, /*start*/ 1, /*end*/ 3);
commands(&mut composer, ".");
assert_eq!(composer.current_text(), "XabXcdef");
commands(&mut composer, ".");
assert_eq!(composer.current_text(), "XabXXcdef");
}
#[test]
fn plain_replace_yank_preserves_previous_backspace_recovery() {
let mut composer = rich_composer();
composer.set_text_content("xyz".to_owned(), Vec::new(), Vec::new());
commands(&mut composer, "0y$");
composer.set_text_content("abcdefghi".to_owned(), Vec::new(), Vec::new());
commands(&mut composer, "0RQ");
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
assert_eq!(composer.current_text(), "Qxyzefghi");
for _ in 0..4 {
key(&mut composer, KeyCode::Backspace);
}
assert_eq!(composer.current_text(), "abcdefghi");
}
#[test]
fn internal_snapshot_restores_exact_mention_identity() {
let (mut composer, _) = new_test_composer();
composer.set_vim_enabled(/*enabled*/ true);
for path in [None, Some("plugin://first"), Some("plugin://second")] {
let id = composer.draft.textarea.insert_element("@plugin");
if let Some(path) = path {
composer.draft.mention_bindings.insert(
id,
super::super::ComposerMentionBinding {
sigil: '@',
mention: "plugin".into(),
path: path.into(),
},
);
}
}
key(&mut composer, KeyCode::Esc);
commands(&mut composer, "0lyl");
let original = composer.snapshot_draft();
commands(&mut composer, "p");
let pasted = composer.snapshot_draft();
assert_eq!(
pasted.mention_bindings,
vec![
original.mention_bindings[0].clone(),
original.mention_bindings[0].clone(),
original.mention_bindings[1].clone(),
]
);
commands(&mut composer, "u");
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL));
assert_eq!(composer.snapshot_draft(), pasted);
commands(&mut composer, "ui");
key(&mut composer, KeyCode::Delete);
key(&mut composer, KeyCode::Home);
let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::CONTROL));
key(&mut composer, KeyCode::Esc);
commands(&mut composer, "u");
assert_eq!(composer.snapshot_draft(), original);
}

Some files were not shown because too many files have changed in this diff Show More