ππΌββοΈ 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: draw the popup cursor on the row it is actually on (#149)
Fynn Fluegge2a1a3999bae5
diff --git a/CLAUDE.md b/CLAUDE.mdindex 169722a..9cd8fd6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -378,6 +378,14 @@ the input thread, per keystroke, is what it avoids.the two cannot drift, and a real-tmux test asserts the captures are **byte-identical**: theyparse different things (a process's stdout against reassembled `%begin`/`%end` payload lines) andthe popup would happily draw a subtly wrong frame without failing.+ - **The cursor's row is resolved at trim time, not at draw time.** `trim_content_to_cursor` cuts+ the unused buffer below the cursor off the capture, so the last cached line is no longer the+ pane's last row and `total_lines - pane_height` under-counts by however many rows it dropped.+ It therefore returns the cursor's line index alongside the content and `ShellPopup::cursor_line`+ carries it to the renderer. A pane with **no scrollback hides the error** β the subtraction+ saturates at 0 β so this only ever showed as a drifting cursor under agents that stay on the+ normal screen and accumulate history (codex), and never under one that lives on the alternate+ screen (claude), which is what made it look agent-specific rather than arithmetic.- The format literal is **single-quoted, not `tmux_quote`d**: tmux performs no replacements insidesingle quotes, so `#{cursor_x}` reaches `display-message` intact instead of being escaped to aliteral `\#{cursor_x}`. Verified on 3.5a that `-t` is honoured for the expansion, so a clientdiff --git a/src/tmux/operations.rs b/src/tmux/operations.rsindex b3fab8c..aafdac8 100644--- a/src/tmux/operations.rs+++ b/src/tmux/operations.rs@@ -191,12 +191,11 @@ pub struct PaneSnapshot {}impl PaneMetrics {- /// Where the cursor is, for rendering it in the popup.- pub fn cursor(&self) -> (usize, usize, usize) {- (self.cursor_x, self.cursor_y, self.pane_height)- }-/// What [`trim_content_to_cursor`](crate::tui::shell_popup::trim_content_to_cursor) needs.+ ///+ /// It returns the cursor's line index along with the trimmed content: the+ /// row cannot be recovered from the metrics afterwards, because trimming+ /// changes how many lines lie between the cursor and the end.pub fn trim_bounds(&self) -> (usize, usize) {(self.cursor_y, self.pane_height)}diff --git a/src/tui/app.rs b/src/tui/app.rsindex 2a867d3..d45abe3 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -1311,6 +1311,7 @@ impl App {content,lines,metrics,+ cursor_line,} => {let Some(popup) = self.state.shell_popup.as_mut() else {return Ok(false);@@ -1326,7 +1327,7 @@ impl App {if popup.cached_content == content && popup.metrics == metrics {return Ok(false);}- popup.set_content(content, lines);+ popup.set_content(content, lines, cursor_line);popup.metrics = metrics;Ok(true)}@@ -7503,10 +7504,10 @@ impl App {popup.last_pane_size = Some((pane_width, pane_height));std::thread::sleep(std::time::Duration::from_millis(200));}- let (content, metrics) =+ let (content, metrics, cursor_line) =capture_tmux_pane_snapshot(&orch_target, 500, self.state.tmux_ops.as_ref());let lines = parse_ansi_to_lines(&content);- popup.set_content(content, lines);+ popup.set_content(content, lines, cursor_line);popup.metrics = metrics;let _ = self.state.input_sink.flush();self.state.shell_popup = Some(popup);@@ -7588,10 +7589,10 @@ impl App {.resize_window(&orch_target, pane_width, pane_height);popup.last_pane_size = Some((pane_width, pane_height));}- let (content, metrics) =+ let (content, metrics, cursor_line) =capture_tmux_pane_snapshot(&orch_target, 500, self.state.tmux_ops.as_ref());let lines = parse_ansi_to_lines(&content);- popup.set_content(content, lines);+ popup.set_content(content, lines, cursor_line);popup.metrics = metrics;let _ = self.state.input_sink.flush();self.state.shell_popup = Some(popup);@@ -7686,10 +7687,10 @@ impl App {// Leaving them to the first refresh left a window in which// `has_scrollback()` fell back to its `true` default and the// scroll keys moved a buffer that could not move.- let (content, metrics) =+ let (content, metrics, cursor_line) =capture_tmux_pane_snapshot(&target, 500, self.state.tmux_ops.as_ref());let lines = parse_ansi_to_lines(&content);- popup.set_content(content, lines);+ popup.set_content(content, lines, cursor_line);popup.metrics = metrics;// A popup opening changes the target; nothing queued for the@@ -9185,7 +9186,7 @@ fn capture_tmux_pane_snapshot(window_name: &str,history_lines: i32,tmux_ops: &dyn TmuxOperations,-) -> (Vec<u8>, Option<crate::tmux::PaneMetrics>) {+) -> PaneCapture {let content = tmux_ops.capture_pane_with_history(window_name, history_lines);// Get the cursor position and pane height to know where the "real" content ends@@ -9195,19 +9196,21 @@ fn capture_tmux_pane_snapshot(trim_pane_snapshot(crate::tmux::PaneSnapshot { content, metrics })}+/// A trimmed pane capture: what the popup draws, plus where the cursor is in it.+///+/// The cursor's row travels with the content because trimming is what makes it+/// underivable later β see [`ShellPopup::cursor_line`].+type PaneCapture = (Vec<u8>, Option<crate::tmux::PaneMetrics>, Option<usize>);+/// Cut the unused pane buffer below the cursor off a capture.////// Shared by both capture paths so they cannot disagree about what the popup is/// shown β the whole point of the control-mode path is to be indistinguishable/// from the subprocess one apart from its cost.-fn trim_pane_snapshot(- snapshot: crate::tmux::PaneSnapshot,-) -> (Vec<u8>, Option<crate::tmux::PaneMetrics>) {+fn trim_pane_snapshot(snapshot: crate::tmux::PaneSnapshot) -> PaneCapture {let trim_info = snapshot.metrics.map(|m| m.trim_bounds());- (- shell_popup::trim_content_to_cursor(snapshot.content, trim_info),- snapshot.metrics,- )+ let (content, cursor_line) = shell_popup::trim_content_to_cursor(snapshot.content, trim_info);+ (content, snapshot.metrics, cursor_line)}/// Capture a pane for the popup: over the input broker's control connection when@@ -9223,7 +9226,7 @@ fn capture_pane_for_popup(history_lines: i32,input_sink: &dyn PaneInputSink,tmux_ops: &dyn TmuxOperations,-) -> (Vec<u8>, Option<crate::tmux::PaneMetrics>) {+) -> PaneCapture {match input_sink.capture(window_name, crate::tmux::CaptureSpec::popup(history_lines)) {Some(snapshot) => trim_pane_snapshot(snapshot),None => capture_tmux_pane_snapshot(window_name, history_lines, tmux_ops),@@ -9774,6 +9777,8 @@ enum Wake {/// Parsed on the watcher thread β see `ShellPopup::cached_lines`.lines: Vec<Line<'static>>,metrics: Option<crate::tmux::PaneMetrics>,+ /// Where the cursor is in `content` β see `ShellPopup::cursor_line`.+ cursor_line: Option<usize>,},}@@ -10109,7 +10114,7 @@ fn spawn_pane_watcher(attach_pane_push(push, &target, &watch, tmux_ops.as_ref(), &mut push_retry_at);let captured_at = Instant::now();- let (content, metrics) = capture_pane_for_popup(+ let (content, metrics, cursor_line) = capture_pane_for_popup(&target,history_lines,input_sink.as_ref(),@@ -10127,6 +10132,7 @@ fn spawn_pane_watcher(content,lines,metrics,+ cursor_line,}).is_err(){diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex fe03905..5221378 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -1156,7 +1156,7 @@ fn the_popup_renders_the_lines_the_watcher_parsed() {let content = b"\x1b[31mred\x1b[0m\nplain\n".to_vec();let lines = parse_ansi_to_lines(&content);assert_eq!(lines.len(), 2);- popup.set_content(content.clone(), lines);+ popup.set_content(content.clone(), lines, Some(1));assert_eq!(popup.cached_content, content);assert_eq!(popup.cached_lines.len(), 2);// Scrolling still reads the byte side, so the two must describe one pane.@@ -1273,7 +1273,8 @@ fn test_capture_tmux_pane_snapshot() {})});- let (content, metrics) = capture_tmux_pane_snapshot("test-window", 500, &mock_tmux);+ let (content, metrics, _cursor_line) =+ capture_tmux_pane_snapshot("test-window", 500, &mock_tmux);// Content should be trimmed to cursor positionassert!(!content.is_empty());@@ -1326,7 +1327,8 @@ fn the_popup_capture_prefers_the_input_connection() {}),}));- let (content, metrics) = capture_pane_for_popup("test-window", 500, &sink, &mock_tmux);+ let (content, metrics, _cursor_line) =+ capture_pane_for_popup("test-window", 500, &sink, &mock_tmux);// Trimmed to the cursor, exactly as the subprocess path is.assert_eq!(content, b"from control".to_vec());assert_eq!(metrics.map(|m| m.history_size), Some(7));@@ -1351,7 +1353,7 @@ fn the_popup_capture_falls_back_to_the_subprocess_path() {})});- let (content, metrics) =+ let (content, metrics, _cursor_line) =capture_pane_for_popup("test-window", 500, &CapturingSink(None), &mock_tmux);assert_eq!(content, b"from subprocess".to_vec());assert_eq!(metrics.map(|m| m.history_size), Some(3));diff --git a/src/tui/shell_popup.rs b/src/tui/shell_popup.rsindex 189bebd..8785e1d 100644--- a/src/tui/shell_popup.rs+++ b/src/tui/shell_popup.rs@@ -29,6 +29,16 @@ pub struct ShellPopup {pub last_content_refresh: Instant,/// Cursor position inside the visible tmux pane and its pane height.pub metrics: Option<crate::tmux::PaneMetrics>,+ /// Index into [`cached_lines`](Self::cached_lines) of the row the tmux+ /// cursor sits on.+ ///+ /// Carried rather than recomputed at draw time, because+ /// [`trim_content_to_cursor`] drops trailing rows: the last cached line is+ /// then no longer the pane's last row, and `total_lines - pane_height`+ /// under-counts by however many were dropped. That error is invisible for a+ /// pane with no scrollback β the subtraction saturates at 0 β which is why+ /// it only ever showed up under agents that stay on the normal screen.+ pub cursor_line: Option<usize>,}impl ShellPopup {@@ -45,6 +55,7 @@ impl ShellPopup {fullscreen: false,last_content_refresh: Instant::now(),metrics: None,+ cursor_line: None,}}@@ -53,9 +64,15 @@ impl ShellPopup {/// One setter so the two cannot drift: rendering from lines that do not match/// the bytes change detection compares would show a frame that is never/// corrected, because the next capture would compare equal.- pub fn set_content(&mut self, content: Vec<u8>, lines: Vec<Line<'static>>) {+ pub fn set_content(+ &mut self,+ content: Vec<u8>,+ lines: Vec<Line<'static>>,+ cursor_line: Option<usize>,+ ) {self.cached_content = content;self.cached_lines = lines;+ self.cursor_line = cursor_line;}/// Scroll up into history, clamped to content bounds.@@ -246,37 +263,39 @@ pub const MAX_TRAILING_EMPTY_LINES: usize = 3;/// * `cursor_info` - Optional (cursor_y, pane_height) from tmux////// # Returns-/// Trimmed content with empty buffer space removed-pub fn trim_content_to_cursor(content: Vec<u8>, cursor_info: Option<(usize, usize)>) -> Vec<u8> {+/// Trimmed content with empty buffer space removed, and the index of the line+/// the cursor is on β which the caller must keep, because trimming is what+/// makes it underivable afterwards.+pub fn trim_content_to_cursor(+ content: Vec<u8>,+ cursor_info: Option<(usize, usize)>,+) -> (Vec<u8>, Option<usize>) {let content_str = String::from_utf8_lossy(&content);let lines: Vec<&str> = content_str.lines().collect();let total_lines = lines.len();if total_lines == 0 {- return content;+ return (content, None);}+ // Where the cursor is, in the *untrimmed* capture. Trimming only ever drops+ // lines from the end, so this stays valid for the trimmed content too.+ let cursor_line = cursor_info.and_then(|(cursor_y, pane_height)| {+ (pane_height > 0).then(|| total_lines.saturating_sub(pane_height) + cursor_y)+ });+// First pass: use cursor position if available- let end_line_from_cursor = if let Some((cursor_y, pane_height)) = cursor_info {- if pane_height > 0 {- // The captured content ends at the bottom of the visible pane- // visible_pane_start = where the visible pane begins in our capture- // cursor position in capture = visible_pane_start + cursor_y- let visible_pane_start = total_lines.saturating_sub(pane_height);- let cursor_line_in_capture = visible_pane_start + cursor_y;- let trim_at = (cursor_line_in_capture + 1).min(total_lines);-- // Only trim at cursor if everything below it is blank.- // TUI apps (OpenCode, Gemini) place the cursor mid-screen with- // real content below β trimming there would cut the UI in half.- let has_content_below = lines[trim_at..].iter().any(|l| !l.trim().is_empty());- if has_content_below {- total_lines- } else {- trim_at- }- } else {+ let end_line_from_cursor = if let Some(cursor_line_in_capture) = cursor_line {+ let trim_at = (cursor_line_in_capture + 1).min(total_lines);++ // Only trim at cursor if everything below it is blank.+ // TUI apps (OpenCode, Gemini) place the cursor mid-screen with+ // real content below β trimming there would cut the UI in half.+ let has_content_below = lines[trim_at..].iter().any(|l| !l.trim().is_empty());+ if has_content_below {total_lines+ } else {+ trim_at}} else {total_lines@@ -288,7 +307,7 @@ pub fn trim_content_to_cursor(content: Vec<u8>, cursor_info: Option<(usize, usizlet end_line = trim_trailing_empty_lines(lines_after_cursor_trim);let trimmed: String = lines[..end_line].join("\n");- trimmed.into_bytes()+ (trimmed.into_bytes(), cursor_line)}/// Trim excessive trailing empty lines, keeping a small buffer for the prompt area.@@ -415,7 +434,7 @@ pub fn render_shell_popup(let visible_height = popup_chunks[2].height as usize;// Use the testable helper to compute visible lines- let (visible_lines, start_line, total_lines) =+ let (visible_lines, start_line, _total_lines) =compute_visible_lines(styled_lines, visible_height, popup.scroll_offset);let content = Paragraph::new(visible_lines);@@ -423,10 +442,14 @@ pub fn render_shell_popup(// A captured pane is text-only; explicitly restore tmux's live cursor when// it falls inside the current (non-scrolled) viewport.+ //+ // The row comes from `popup.cursor_line`, fixed when the capture was+ // trimmed, and *not* from `total_lines - pane_height`: trimming drops+ // trailing rows, so the last cached line is not the pane's last row.if popup.scroll_offset >= 0 {- if let Some((cursor_x, cursor_y, pane_height)) = popup.metrics.map(|m| m.cursor()) {- let pane_start = total_lines.saturating_sub(pane_height);- let cursor_line = pane_start.saturating_add(cursor_y);+ if let (Some(cursor_line), Some(cursor_x)) =+ (popup.cursor_line, popup.metrics.map(|m| m.cursor_x))+ {if cursor_line >= start_line && cursor_line < start_line + visible_height {let x = popup_chunks[2].x.saturating_add(cursor_x.min(popup_chunks[2].width.saturating_sub(1) as usize) as u16,diff --git a/tests/shell_popup_tests.rs b/tests/shell_popup_tests.rsindex 492ab03..b2bf283 100644--- a/tests/shell_popup_tests.rs+++ b/tests/shell_popup_tests.rs@@ -508,7 +508,8 @@ fn test_trim_trailing_empty_lines_whitespace_only() {#[test]fn test_trim_content_to_cursor_no_metrics() {let content = b"line 1\nline 2\n\n\n\n\n\n\n\n\n".to_vec();- let result = trim_content_to_cursor(content, None);+ let (result, cursor_line) = trim_content_to_cursor(content, None);+ assert_eq!(cursor_line, None);let result_str = String::from_utf8_lossy(&result);// Count newlines + 1 to avoid lines() quirk with trailing newlineslet line_count = result_str.matches('\n').count() + 1;@@ -525,7 +526,7 @@ fn test_trim_content_to_cursor_with_metrics() {// Lines below cursor are empty (unused pane buffer) β trimmed at cursorlet content = b"line 0\nline 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\n\n".to_vec();let metrics = Some((2, 5)); // cursor_y=2, pane_height=5- let result = trim_content_to_cursor(content, metrics);+ let (result, _) = trim_content_to_cursor(content, metrics);let result_str = String::from_utf8_lossy(&result);let lines: Vec<&str> = result_str.lines().collect();@@ -541,7 +542,7 @@ fn test_trim_content_to_cursor_tui_cursor_mid_screen() {let content =b"header\nstatus bar\n\ninput field\n\noutput area\nmore output\nbottom bar".to_vec();let metrics = Some((3, 8)); // cursor_y=3 (mid-screen), pane_height=8- let result = trim_content_to_cursor(content, metrics);+ let (result, _) = trim_content_to_cursor(content, metrics);let result_str = String::from_utf8_lossy(&result);let lines: Vec<&str> = result_str.lines().collect();@@ -556,7 +557,7 @@ fn test_trim_content_to_cursor_cursor_at_bottom_with_empty() {// Should trim the empty lines via second passlet content = b"line 0\nline 1\nline 2\n\n\n\n\n".to_vec();let metrics = Some((6, 7)); // cursor at line 6 of 7-line pane (bottom)- let result = trim_content_to_cursor(content, metrics);+ let (result, _) = trim_content_to_cursor(content, metrics);let result_str = String::from_utf8_lossy(&result);// Count newlines + 1 to avoid lines() quirk with trailing newlineslet line_count = result_str.matches('\n').count() + 1;@@ -569,17 +570,86 @@ fn test_trim_content_to_cursor_cursor_at_bottom_with_empty() {#[test]fn test_trim_content_to_cursor_empty_content() {let content = b"".to_vec();- let result = trim_content_to_cursor(content.clone(), Some((0, 10)));+ let (result, cursor_line) = trim_content_to_cursor(content.clone(), Some((0, 10)));+ assert_eq!(cursor_line, None);assert_eq!(result, content);}#[test]fn test_trim_content_to_cursor_zero_pane_height() {let content = b"line 1\nline 2\n\n\n\n".to_vec();- let result = trim_content_to_cursor(content, Some((0, 0)));+ let (result, cursor_line) = trim_content_to_cursor(content, Some((0, 0)));+ assert_eq!(cursor_line, None);let result_str = String::from_utf8_lossy(&result);// Count newlines + 1 to avoid lines() quirk with trailing newlineslet line_count = result_str.matches('\n').count() + 1;// pane_height=0 should fall through to second pass onlyassert_eq!(line_count, 2 + MAX_TRAILING_EMPTY_LINES);}++/// The cursor is drawn on the row it is *on*, even after the capture was+/// trimmed.+///+/// `trim_content_to_cursor` drops trailing rows, so the last cached line is no+/// longer the pane's last row and `total_lines - pane_height` under-counts by+/// however many were dropped. A pane with no scrollback hides that β the+/// subtraction saturates at 0 β which is why the cursor only ever drifted under+/// agents that stay on the normal screen and accumulate history (codex), and+/// never under one that lives on the alternate screen (claude).+#[test]+fn the_cursor_lands_on_its_own_row_after_the_capture_is_trimmed() {+ // 5 rows of scrollback + a 10-row pane. The pane's last content row is the+ // prompt the cursor sits on; the four rows under it are unused buffer, so+ // trimming drops one of them (it keeps MAX_TRAILING_EMPTY_LINES).+ let pane_height = 10usize;+ let mut rows: Vec<String> = (0..5).map(|i| format!("history {i}")).collect();+ rows.extend((0..5).map(|i| format!("output {i}")));+ rows.push("> prompt".to_string());+ rows.extend(std::iter::repeat_n(String::new(), 4));+ assert_eq!(rows.len(), 5 + pane_height);+ let capture = format!("{}\n", rows.join("\n")).into_bytes();++ // cursor_y is the row *within the pane*: index 10 of the capture.+ let (trimmed, cursor_line) = trim_content_to_cursor(capture, Some((5, pane_height)));+ assert_eq!(cursor_line, Some(10));+ let lines: Vec<&str> = std::str::from_utf8(&trimmed).unwrap().lines().collect();+ assert_eq!(lines.len(), 11, "trimming must have dropped trailing rows");++ let popup = ShellPopup {+ cached_content: trimmed.clone(),+ cursor_line,+ metrics: Some(agtx::tmux::PaneMetrics {+ cursor_x: 2,+ cursor_y: 5,+ pane_height,+ history_size: 5,+ }),+ ..ShellPopup::new("Task".to_string(), "window".to_string())+ };++ // Borders (2) + title (1) + footer (1) around a content area the size of+ // the pane, as the popup sizes it.+ let area = Rect::new(0, 0, 40, pane_height as u16 + 4);+ let styled: Vec<Line<'static>> = lines+ .iter()+ .map(|l| Line::from(Span::raw(l.to_string())))+ .collect();+ let mut terminal = Terminal::new(TestBackend::new(area.width, area.height)).unwrap();+ terminal+ .draw(|frame| {+ render_shell_popup(&popup, frame, area, &styled, &ShellPopupColors::default());+ })+ .unwrap();++ let cursor = terminal.backend_mut().get_cursor_position().unwrap();+ let row: String = (0..area.width)+ .map(|x| terminal.backend().buffer()[(x, cursor.y)].symbol())+ .collect();+ assert!(+ row.contains("> prompt"),+ "cursor drawn on row {} which reads {row:?}, not the prompt it is on",+ cursor.y+ );+ // The content area starts one column in, past the popup border.+ assert_eq!(cursor.x, 3, "column comes straight from tmux");+}