ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
fix(tui): keep cursor visible past first wrapped line in task wizard (#109)
leesungbin69d824cff8a0
diff --git a/src/tui/app.rs b/src/tui/app.rsindex f9747e2..d8f3156 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -1290,11 +1290,21 @@ impl App {};let step_labels = ["Title", "Plugin", "Prompt"];- let mut lines: Vec<Line> = Vec::new();+ let mut lines: Vec<Line<'static>> = Vec::new();+ // Pre-wrap every line we push so `lines.len()` always reflects the+ // exact visual-row count. The cursor anchor below depends on this:+ // if any preceding line wrapped silently in the Paragraph, the+ // cursor would land one row too high.+ let wrap_width = input_area.width.saturating_sub(2) as usize;+ let push_wrapped = |dst: &mut Vec<Line<'static>>, spans: Vec<Span<'static>>| {+ for visual in wrap_spans(spans, wrap_width) {+ dst.push(visual);+ }+ };// Step indicator breadcrumb- let mut breadcrumb_spans: Vec<Span> = Vec::new();- breadcrumb_spans.push(Span::raw(" "));+ let mut breadcrumb_spans: Vec<Span<'static>> = Vec::new();+ breadcrumb_spans.push(Span::raw(" ".to_string()));for (i, label) in step_labels.iter().enumerate() {let style = if i == step {Style::default()@@ -1305,41 +1315,63 @@ impl App {} else {Style::default().fg(dimmed_color)};- breadcrumb_spans.push(Span::styled(*label, style));+ breadcrumb_spans.push(Span::styled((*label).to_string(), style));if i < step_labels.len() - 1 {- breadcrumb_spans.push(Span::styled(" βΊ ", Style::default().fg(dimmed_color)));+ breadcrumb_spans.push(Span::styled(+ " βΊ ".to_string(),+ Style::default().fg(dimmed_color),+ ));}}- lines.push(Line::from(breadcrumb_spans));+ push_wrapped(&mut lines, breadcrumb_spans);// Separatorlet inner_width = input_area.width.saturating_sub(4) as usize;- lines.push(Line::from(Span::styled(- format!(" {}", "β".repeat(inner_width.saturating_sub(2))),- Style::default().fg(dimmed_color),- )));- lines.push(Line::from(""));+ push_wrapped(+ &mut lines,+ vec![Span::styled(+ format!(" {}", "β".repeat(inner_width.saturating_sub(2))),+ Style::default().fg(dimmed_color),+ )],+ );+ lines.push(Line::from(String::new()));// Completed fields shown as read-only contextif step >= 1 {- lines.push(Line::from(vec![- Span::styled(" Title: ", Style::default().fg(dimmed_color)),- Span::styled(&state.pending_task_title, Style::default().fg(text_color)),- ]));+ push_wrapped(+ &mut lines,+ vec![+ Span::styled(+ " Title: ".to_string(),+ Style::default().fg(dimmed_color),+ ),+ Span::styled(+ state.pending_task_title.clone(),+ Style::default().fg(text_color),+ ),+ ],+ );}if step >= 2 {let plugin_name = state.wizard_plugin_options.get(state.wizard_selected_plugin).map(|o| o.label.as_str())- .unwrap_or("agtx");- lines.push(Line::from(vec![- Span::styled(" Plugin: ", Style::default().fg(dimmed_color)),- Span::styled(plugin_name, Style::default().fg(text_color)),- ]));+ .unwrap_or("agtx")+ .to_string();+ push_wrapped(+ &mut lines,+ vec![+ Span::styled(+ " Plugin: ".to_string(),+ Style::default().fg(dimmed_color),+ ),+ Span::styled(plugin_name, Style::default().fg(text_color)),+ ],+ );}if step >= 1 {- lines.push(Line::from(""));+ lines.push(Line::from(String::new()));}// Active area content. Track the insertion point so the native@@ -1350,23 +1382,29 @@ impl App {let cursor_line_start = lines.len();match state.input_mode {InputMode::InputTitle => {- let (buf_col, buf_row) =- cursor_display_pos(&state.input_buffer, state.input_cursor);let prefix_cols = Span::raw(" Title: ").width();- let col = prefix_cols + buf_col;- cursor_display = Some((col as u16, (cursor_line_start + buf_row) as u16));- lines.push(Line::from(vec![- Span::styled(- " Title: ",- Style::default()- .fg(selected_color)- .add_modifier(Modifier::BOLD),- ),- Span::styled(- state.input_buffer.clone(),- Style::default().fg(text_color),- ),- ]));+ let (col, row) = wrapped_cursor_pos(+ &state.input_buffer,+ state.input_cursor,+ prefix_cols,+ wrap_width,+ );+ cursor_display = Some((col as u16, (cursor_line_start + row) as u16));+ push_wrapped(+ &mut lines,+ vec![+ Span::styled(+ " Title: ".to_string(),+ Style::default()+ .fg(selected_color)+ .add_modifier(Modifier::BOLD),+ ),+ Span::styled(+ state.input_buffer.clone(),+ Style::default().fg(text_color),+ ),+ ],+ );}InputMode::SelectPlugin => {let active_plugin = state.config.workflow_plugin.as_deref().unwrap_or("");@@ -1383,26 +1421,36 @@ impl App {} else {Style::default().fg(text_color)};- lines.push(Line::from(vec![- Span::styled(marker, name_style),- Span::styled(format!("{:<14}", &opt.label), name_style),- Span::styled(&opt.description, Style::default().fg(desc_color)),- Span::styled(check, Style::default().fg(Color::Green)),- ]));+ push_wrapped(+ &mut lines,+ vec![+ Span::styled(marker.to_string(), name_style),+ Span::styled(format!("{:<14}", &opt.label), name_style),+ Span::styled(+ opt.description.clone(),+ Style::default().fg(desc_color),+ ),+ Span::styled(+ check.to_string(),+ Style::default().fg(Color::Green),+ ),+ ],+ );}}InputMode::InputDescription => {- let (buf_col, buf_row) =- cursor_display_pos(&state.input_buffer, state.input_cursor);let prefix_cols = Span::raw(" Prompt: ").width();- let col = if buf_row == 0 {- prefix_cols + buf_col- } else {- buf_col- };- cursor_display = Some((col as u16, (cursor_line_start + buf_row) as u16));+ let (col, row) = wrapped_cursor_pos(+ &state.input_buffer,+ state.input_cursor,+ prefix_cols,+ wrap_width,+ );+ cursor_display = Some((col as u16, (cursor_line_start + row) as u16));let full_text = format!(" Prompt: {}", state.input_buffer);- // Split on newlines to handle multi-line descriptions+ // Split on newlines to handle multi-line descriptions.+ // Each logical line is then pre-wrapped via push_wrapped so+ // visual layout matches wrapped_cursor_pos exactly.for part in full_text.split('\n') {if !state.highlighted_references.is_empty() {let styled = build_highlighted_text(@@ -1417,22 +1465,27 @@ impl App {.into_iter().map(|s| Span::styled(s.content.into_owned(), s.style)).collect();- lines.push(Line::from(owned_spans));+ push_wrapped(&mut lines, owned_spans);}} else {- lines.push(Line::from(Span::styled(- part.to_string(),- Style::default().fg(text_color),- )));+ push_wrapped(+ &mut lines,+ vec![Span::styled(+ part.to_string(),+ Style::default().fg(text_color),+ )],+ );}}}_ => {}}+ // No `.wrap(...)` β `lines` is already pre-wrapped by `wrap_spans`+ // to fit `wrap_width`. Letting Ratatui re-wrap would re-introduce+ // the two-source-of-truth bug between renderer and cursor.let content = Paragraph::new(Text::from(lines)).style(Style::default().fg(text_color))- .wrap(Wrap { trim: false }).block(Block::default().title(block_title)@@ -7488,18 +7541,102 @@ fn parse_sgr(seq: &str, mut style: Style) -> Style {style}-/// Map a byte offset in `text` to the (column, row) of the terminal cell it-/// renders on. Column uses Unicode display width so wide chars (CJK, emoji)-/// take two cells β a plain byte/char count would misplace the cursor.-fn cursor_display_pos(text: &str, cursor_byte: usize) -> (usize, usize) {- let end = cursor_byte.min(text.len());- let before = &text[..end];- let row = before.bytes().filter(|b| *b == b'\n').count();- let last_line = before.rsplit('\n').next().unwrap_or("");- let col = ratatui::text::Span::raw(last_line).width();+/// Display width of a single character, matching what the renderer draws.+fn char_display_width(ch: char) -> usize {+ ratatui::text::Span::raw(ch.to_string()).width()+}++/// Map a byte offset in `text` to the (col, row) of the terminal cell it+/// will render on, using the same char-by-char wrap rule as `wrap_spans`.+///+/// - `prefix_width` is the display width preceding `text` on the first visual+/// row (e.g. the `" Prompt: "` label). It is consumed only on row 0; after+/// any wrap or `'\n'`, the next visual row starts at column 0.+/// - `wrap_width` is the inner width of the block (border-subtracted). A+/// width of 0 short-circuits to (prefix_width, 0).+/// - `'\n'` in `text` is treated as a hard line break.+///+/// This function and `wrap_spans` MUST stay in lock-step: any change to the+/// wrap rule has to land in both, otherwise the cursor drifts off what was+/// actually drawn. Both use lazy wrap (wrap only when the next char would+/// overflow), so a cursor at end-of-row sits at col=wrap_width on that row+/// β which is still inside the inner area (wrap_width = area.width - 2).+fn wrapped_cursor_pos(+ text: &str,+ cursor_byte: usize,+ prefix_width: usize,+ wrap_width: usize,+) -> (usize, usize) {+ let cursor_byte = cursor_byte.min(text.len());+ let mut col = prefix_width;+ let mut row = 0usize;+ if wrap_width == 0 {+ return (col, row);+ }+ let mut byte = 0usize;+ for ch in text.chars() {+ if byte >= cursor_byte {+ break;+ }+ if ch == '\n' {+ row += 1;+ col = 0;+ } else {+ let w = char_display_width(ch);+ if col + w > wrap_width {+ row += 1;+ col = 0;+ }+ col += w;+ }+ byte += ch.len_utf8();+ }(col, row)}+/// Pre-wrap a sequence of styled spans into visual `Line`s by display width.+///+/// Char-by-char lazy wrap (no word-boundary detection). This makes our layout+/// authoritative: each produced `Line` has display width β€ `wrap_width`, so+/// `Paragraph::wrap(Wrap { trim: false })` leaves it untouched and the cursor+/// position computed by `wrapped_cursor_pos` lines up exactly with what was+/// drawn β no two-source-of-truth between renderer and cursor.+///+/// Span styles are preserved across wrap points by splitting the span text+/// at the wrap boundary and re-emitting both halves with the same style.+/// `'\n'` inside span content is NOT handled here β callers split on `'\n'`+/// before calling so each invocation wraps a single logical line.+fn wrap_spans(spans: Vec<Span<'static>>, wrap_width: usize) -> Vec<Line<'static>> {+ if wrap_width == 0 || spans.is_empty() {+ return vec![Line::from(spans)];+ }+ let mut visual: Vec<Vec<Span<'static>>> = vec![Vec::new()];+ let mut col = 0usize;+ for span in spans {+ let style = span.style;+ let mut chunk = String::new();+ for ch in span.content.chars() {+ let w = char_display_width(ch);+ if col + w > wrap_width {+ if !chunk.is_empty() {+ visual+ .last_mut()+ .unwrap()+ .push(Span::styled(std::mem::take(&mut chunk), style));+ }+ visual.push(Vec::new());+ col = 0;+ }+ chunk.push(ch);+ col += w;+ }+ if !chunk.is_empty() {+ visual.last_mut().unwrap().push(Span::styled(chunk, style));+ }+ }+ visual.into_iter().map(Line::from).collect()+}+/// Snap `pos` back to the nearest UTF-8 char boundary at or before it./// Cursor arithmetic tracks bytes, but String indexing panics mid-codepoint β/// callers use this to stay valid after moving across multi-byte chars.diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex b301b52..1bd1ff1 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -4810,63 +4810,273 @@ fn test_delete_removes_whole_multibyte_char_in_description() {assert_eq!(app.state.input_cursor, 0);}-// --- Cursor display position (for IME composition anchoring) ---+// --- Wrapped cursor position (for IME composition anchoring under wrap) ---#[test]-fn test_cursor_display_pos_ascii_only() {- // "hello", cursor at byte 3 β col 3, row 0- let (col, row) = super::cursor_display_pos("hello", 3);+fn test_wrapped_cursor_pos_ascii_no_wrap() {+ let (col, row) = super::wrapped_cursor_pos("hello", 3, 0, 20);assert_eq!((col, row), (3, 0));}#[test]-fn test_cursor_display_pos_korean_is_wide() {- // "κ°λ", cursor at byte 6 (end) β col 4 (2 wide chars * 2 cols), row 0- let (col, row) = super::cursor_display_pos("κ°λ", 6);+fn test_wrapped_cursor_pos_with_prefix() {+ // prefix occupies 10 cols, cursor after 3 chars β col 13, row 0+ let (col, row) = super::wrapped_cursor_pos("hello", 3, 10, 40);+ assert_eq!((col, row), (13, 0));+}++#[test]+fn test_wrapped_cursor_pos_korean_is_wide() {+ // "κ°λ" at end β 4 cells, row 0+ let (col, row) = super::wrapped_cursor_pos("κ°λ", 6, 0, 20);assert_eq!((col, row), (4, 0));}#[test]-fn test_cursor_display_pos_korean_mid() {- // "κ°λ", cursor at byte 3 (between κ° and λ) β col 2, row 0- let (col, row) = super::cursor_display_pos("κ°λ", 3);+fn test_wrapped_cursor_pos_korean_mid() {+ let (col, row) = super::wrapped_cursor_pos("κ°λ", 3, 0, 20);assert_eq!((col, row), (2, 0));}#[test]-fn test_cursor_display_pos_mixed_ascii_korean() {- // "aκ°b" bytes: a(1) + κ°(3) + b(1) = 5 bytes- // cursor after κ° (byte 4) β col 3 (1 + 2), row 0- let (col, row) = super::cursor_display_pos("aκ°b", 4);+fn test_wrapped_cursor_pos_mixed_ascii_korean() {+ // "aκ°b": cursor after κ° (byte 4) β col 1 (a) + 2 (κ°) = 3+ let (col, row) = super::wrapped_cursor_pos("aκ°b", 4, 0, 20);assert_eq!((col, row), (3, 0));}#[test]-fn test_cursor_display_pos_with_newline() {+fn test_wrapped_cursor_pos_hard_newline() {// "κ°λ\nλ€", cursor at end (byte 10) β col 2 (just λ€), row 1- let (col, row) = super::cursor_display_pos("κ°λ\nλ€", 10);+ let (col, row) = super::wrapped_cursor_pos("κ°λ\nλ€", 10, 0, 20);assert_eq!((col, row), (2, 1));}#[test]-fn test_cursor_display_pos_at_start() {- let (col, row) = super::cursor_display_pos("hello", 0);- assert_eq!((col, row), (0, 0));+fn test_wrapped_cursor_pos_hard_newline_drops_prefix() {+ // After a hard newline, the next visual row starts at column 0, NOT prefix.+ // "a\nb", cursor at byte 3 (after b) β row 1, col 1+ let (col, row) = super::wrapped_cursor_pos("a\nb", 3, 10, 20);+ assert_eq!((col, row), (1, 1));+}++#[test]+fn test_wrapped_cursor_pos_at_start() {+ // Empty buffer with prefix β cursor sits at prefix_width on row 0+ let (col, row) = super::wrapped_cursor_pos("hello", 0, 10, 20);+ assert_eq!((col, row), (10, 0));}#[test]-fn test_cursor_display_pos_empty_string() {- let (col, row) = super::cursor_display_pos("", 0);+fn test_wrapped_cursor_pos_empty_string() {+ let (col, row) = super::wrapped_cursor_pos("", 0, 0, 20);assert_eq!((col, row), (0, 0));}#[test]-fn test_cursor_display_pos_emoji_is_wide() {- // "π" is 4 bytes UTF-8, display width 2. Cursor at end β col 2.- let (col, row) = super::cursor_display_pos("π", 4);+fn test_wrapped_cursor_pos_emoji_is_wide() {+ let (col, row) = super::wrapped_cursor_pos("π", 4, 0, 20);assert_eq!((col, row), (2, 0));}+#[test]+fn test_wrapped_cursor_pos_soft_wrap_long_run() {+ // wrap_width=15, prefix=10: row 0 fits 5 chars (cols 10..15), then wrap.+ // "xxxxxxxxxx" (10 x's), cursor at end β 5 chars on row 0, 5 chars on row 1+ let (col, row) = super::wrapped_cursor_pos("xxxxxxxxxx", 10, 10, 15);+ assert_eq!((col, row), (5, 1));+}++#[test]+fn test_wrapped_cursor_pos_soft_wrap_cjk() {+ // "κ°λλ€" with wrap_width=4: κ°λ (4 cells) fills row 0, λ€ starts row 1+ let (col, row) = super::wrapped_cursor_pos("κ°λλ€", 9, 0, 4);+ assert_eq!((col, row), (2, 1));+}++#[test]+fn test_wrapped_cursor_pos_at_exact_wrap_edge_stays_on_row() {+ // Lazy wrap: cursor at end of a buffer that exactly fills wrap_width+ // stays at (wrap_width, 0). The next typed char triggers wrap.+ let (col, row) = super::wrapped_cursor_pos("xxxxx", 5, 0, 5);+ assert_eq!((col, row), (5, 0));+}++#[test]+fn test_wrapped_cursor_pos_cursor_past_end_clamps() {+ // cursor_byte > text.len() should clamp to text.len()+ let (col, row) = super::wrapped_cursor_pos("hi", 999, 0, 20);+ assert_eq!((col, row), (2, 0));+}++#[test]+fn test_wrapped_cursor_pos_zero_wrap_width_short_circuits() {+ let (col, row) = super::wrapped_cursor_pos("anything", 4, 7, 0);+ assert_eq!((col, row), (7, 0));+}++// --- wrap_spans (authoritative pre-wrap for cursor/render consistency) ---++fn line_width(line: &ratatui::text::Line<'static>) -> usize {+ line.spans+ .iter()+ .map(|s| ratatui::text::Span::raw(s.content.to_string()).width())+ .sum()+}++#[test]+fn test_wrap_spans_no_wrap_when_fits() {+ let spans = vec![ratatui::text::Span::raw("hello".to_string())];+ let lines = super::wrap_spans(spans, 20);+ assert_eq!(lines.len(), 1);+ assert_eq!(line_width(&lines[0]), 5);+}++#[test]+fn test_wrap_spans_wraps_long_ascii() {+ let spans = vec![ratatui::text::Span::raw("xxxxxxxxxx".to_string())]; // 10 x's+ let lines = super::wrap_spans(spans, 5);+ assert_eq!(lines.len(), 2);+ assert_eq!(line_width(&lines[0]), 5);+ assert_eq!(line_width(&lines[1]), 5);+}++#[test]+fn test_wrap_spans_preserves_styles_across_wrap() {+ use ratatui::style::{Color, Style};+ let red = Style::default().fg(Color::Red);+ let blue = Style::default().fg(Color::Blue);+ let spans = vec![+ ratatui::text::Span::styled("aaa".to_string(), red),+ ratatui::text::Span::styled("bbbb".to_string(), blue),+ ];+ // wrap_width=5: row 0 = "aaa"+"bb" (3+2), row 1 = "bb"+ let lines = super::wrap_spans(spans, 5);+ assert_eq!(lines.len(), 2);+ // Row 0 has two distinct styled spans+ assert_eq!(lines[0].spans.len(), 2);+ assert_eq!(lines[0].spans[0].content, "aaa");+ assert_eq!(lines[0].spans[0].style, red);+ assert_eq!(lines[0].spans[1].content, "bb");+ assert_eq!(lines[0].spans[1].style, blue);+ // Row 1 has the remainder, still styled blue+ assert_eq!(lines[1].spans.len(), 1);+ assert_eq!(lines[1].spans[0].content, "bb");+ assert_eq!(lines[1].spans[0].style, blue);+}++#[test]+fn test_wrap_spans_cjk_wraps_at_cell_width() {+ let spans = vec![ratatui::text::Span::raw("κ°λλ€".to_string())];+ let lines = super::wrap_spans(spans, 4);+ // κ°λ fits exactly (4 cells); λ€ wraps to row 1+ assert_eq!(lines.len(), 2);+ assert_eq!(line_width(&lines[0]), 4);+ assert_eq!(line_width(&lines[1]), 2);+}++#[test]+fn test_wrap_spans_wide_char_does_not_split() {+ // wrap_width=3, "κ°λ": κ° fits (col 0β2), λ needs 2 but only 1 left,+ // so λ wraps whole to next row.+ let spans = vec![ratatui::text::Span::raw("κ°λ".to_string())];+ let lines = super::wrap_spans(spans, 3);+ assert_eq!(lines.len(), 2);+ assert_eq!(line_width(&lines[0]), 2);+ assert_eq!(line_width(&lines[1]), 2);+}++#[test]+fn test_wrap_spans_zero_width_passthrough() {+ let spans = vec![ratatui::text::Span::raw("anything".to_string())];+ let lines = super::wrap_spans(spans.clone(), 0);+ assert_eq!(lines.len(), 1);+ assert_eq!(line_width(&lines[0]), 8);+}++#[test]+fn test_wrap_spans_empty_input() {+ let lines = super::wrap_spans(Vec::new(), 10);+ assert_eq!(lines.len(), 1);+ assert_eq!(line_width(&lines[0]), 0);+}++// --- Invariant: wrap_spans and wrapped_cursor_pos agree on layout ---+//+// This is the contract that makes the cursor appear where the text was drawn.+// For any text + wrap_width, the cursor's reported (col, row) at the end of+// the text must match the (width, count-1) of the wrapped visual lines.++fn assert_cursor_matches_wrap(text: &str, prefix: usize, wrap_width: usize) {+ let mut combined = String::with_capacity(prefix + text.len());+ for _ in 0..prefix {+ combined.push(' ');+ }+ combined.push_str(text);+ let spans = vec![ratatui::text::Span::raw(combined)];+ let lines = super::wrap_spans(spans, wrap_width);++ let (col, row) =+ super::wrapped_cursor_pos(text, text.len(), prefix, wrap_width);++ assert_eq!(+ row,+ lines.len() - 1,+ "row mismatch for text={text:?} prefix={prefix} wrap_width={wrap_width}"+ );+ assert_eq!(+ col,+ line_width(&lines[lines.len() - 1]),+ "col mismatch for text={text:?} prefix={prefix} wrap_width={wrap_width}"+ );+}++#[test]+fn test_invariant_ascii_no_wrap() {+ assert_cursor_matches_wrap("hello", 0, 20);+}++#[test]+fn test_invariant_ascii_with_prefix() {+ assert_cursor_matches_wrap("hello world", 10, 30);+}++#[test]+fn test_invariant_ascii_wraps() {+ assert_cursor_matches_wrap("aaaaaaaaaaaa", 0, 5);+}++#[test]+fn test_invariant_ascii_with_prefix_wraps() {+ assert_cursor_matches_wrap("aaaaaaaaaa", 10, 15);+}++#[test]+fn test_invariant_cjk_wraps_evenly() {+ assert_cursor_matches_wrap("κ°λλ€λΌ", 0, 4);+}++#[test]+fn test_invariant_cjk_wide_char_no_split() {+ // odd wrap_width forces a wide char to wrap whole+ assert_cursor_matches_wrap("κ°λλ€", 0, 3);+}++#[test]+fn test_invariant_emoji() {+ assert_cursor_matches_wrap("πππ", 0, 3);+}++#[test]+fn test_invariant_long_buffer_with_prefix() {+ // exactly the failing-bug scenario: long sentence after a prefix+ assert_cursor_matches_wrap(+ "this is a fairly long sentence that should wrap to multiple lines",+ 10,+ 20,+ );+}+// --- Footer text ---#[test]