Skip to content

armgit / agtx

Public Imported from GitHub
0

🏄🏼‍♂️ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.

fix tmux and popup size sync (#6)

Fynn Flüggee2414b532e87
diff --git a/src/operations.rs b/src/operations.rs
index 74da1d4..23cbd52 100644
--- a/src/operations.rs
+++ b/src/operations.rs
@@ -23,6 +23,9 @@ pub trait TmuxOperations {
/// Capture pane content
fn capture_pane(&self, target: &str) -> Result<String>;
+
+ /// Resize a tmux window
+ fn resize_window(&self, target: &str, width: u16, height: u16) -> Result<()>;
}
/// Operations for git worktree management
@@ -86,6 +89,16 @@ impl TmuxOperations for RealTmuxOps {
.output()?;
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
+
+ fn resize_window(&self, target: &str, width: u16, height: u16) -> Result<()> {
+ std::process::Command::new("tmux")
+ .args(["-L", crate::tmux::AGENT_SERVER])
+ .args(["resize-window", "-t", target])
+ .args(["-x", &width.to_string()])
+ .args(["-y", &height.to_string()])
+ .output()?;
+ Ok(())
+ }
}
/// Real implementation using actual git commands
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 7847e7a..8023194 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -13,11 +13,13 @@ use crate::agent;
use crate::config::{GlobalConfig, MergedConfig, ProjectConfig, ThemeConfig};
use crate::db::{Database, Task, TaskStatus};
use crate::git;
+use crate::operations::{RealTmuxOps, TmuxOperations};
use crate::tmux;
use crate::AppMode;
use super::board::BoardState;
use super::input::InputMode;
+use super::shell_popup::{self, ShellPopup};
/// Helper to convert hex color string to ratatui Color
fn hex_to_color(hex: &str) -> Color {
@@ -28,6 +30,11 @@ fn hex_to_color(hex: &str) -> Color {
type Terminal = ratatui::Terminal<CrosstermBackend<Stdout>>;
+/// Shell popup dimensions - used for both rendering and tmux window sizing
+const SHELL_POPUP_WIDTH: u16 = 82; // Total width including borders
+const SHELL_POPUP_CONTENT_WIDTH: u16 = 80; // Content width (SHELL_POPUP_WIDTH - 2 for borders)
+const SHELL_POPUP_HEIGHT_PERCENT: u16 = 75; // Percentage of terminal height
+
/// Application state (separate from terminal for borrow checker)
struct AppState {
mode: AppMode,
@@ -137,14 +144,6 @@ struct PrConfirmPopup {
generating: bool, // true while Claude is generating description
}
-/// State for the shell popup that shows a detached tmux window
-#[derive(Debug, Clone)]
-struct ShellPopup {
- task_title: String,
- window_name: String,
- scroll_offset: i32, // Negative means scroll up (see more history)
-}
-
/// Info about a project for the sidebar
#[derive(Debug, Clone)]
struct ProjectInfo {
@@ -315,6 +314,11 @@ impl App {
}
}
+ // Refresh shell popup content periodically (every poll cycle when open)
+ if let Some(ref mut popup) = self.state.shell_popup {
+ popup.cached_content = capture_tmux_pane_with_history(&popup.window_name, 500);
+ }
+
// Periodically refresh session status
self.refresh_sessions()?;
}
@@ -617,87 +621,7 @@ impl App {
// Shell popup overlay
if let Some(popup) = &state.shell_popup {
- let popup_area = centered_rect_fixed_width(82, 75, area); // +2 for border
- frame.render_widget(Clear, popup_area);
-
- // Draw border around the popup
- let border_block = Block::default()
- .borders(Borders::ALL)
- .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)));
- let inner_area = border_block.inner(popup_area);
- frame.render_widget(border_block, popup_area);
-
- // Resize tmux pane to match popup dimensions for proper display
- let pane_width = inner_area.width;
- let pane_height = inner_area.height.saturating_sub(2); // -2 for title and footer
- let _ = std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["resize-pane", "-t", &popup.window_name])
- .args(["-x", &pane_width.to_string()])
- .args(["-y", &pane_height.to_string()])
- .output();
-
- // Capture tmux pane content with more history
- let pane_content = capture_tmux_pane_with_history(&popup.window_name, 500);
-
- // Layout: header, content, footer (inside the border)
- let popup_chunks = Layout::default()
- .direction(Direction::Vertical)
- .constraints([
- Constraint::Length(1), // Title bar
- Constraint::Min(0), // Shell content
- Constraint::Length(1), // Footer
- ])
- .split(inner_area);
-
- // Title bar
- let title = format!(" {} ", popup.task_title);
- let title_bar = Paragraph::new(title)
- .style(Style::default().fg(Color::Black).bg(hex_to_color(&state.config.theme.color_popup_header)));
- frame.render_widget(title_bar, popup_chunks[0]);
-
- // Shell content - parse ANSI escape sequences for colors
- let styled_lines = parse_ansi_to_lines(&pane_content);
- let visible_height = popup_chunks[1].height as usize;
-
- // Filter out trailing empty lines to find actual content
- let non_empty_count = styled_lines.iter()
- .rposition(|line| !line.spans.is_empty() &&
- !line.spans.iter().all(|s| s.content.trim().is_empty()))
- .map(|i| i + 1)
- .unwrap_or(styled_lines.len());
-
- let total_lines = non_empty_count.max(1);
-
- // Apply scroll offset
- let start_line = if popup.scroll_offset < 0 {
- // Scrolling up into history
- total_lines.saturating_sub(visible_height).saturating_sub((-popup.scroll_offset) as usize)
- } else {
- // At bottom (current)
- total_lines.saturating_sub(visible_height)
- };
-
- let visible_lines: Vec<Line> = styled_lines
- .into_iter()
- .take(non_empty_count)
- .skip(start_line)
- .take(visible_height)
- .collect();
-
- let content = Paragraph::new(visible_lines)
- .wrap(Wrap { trim: false });
- frame.render_widget(content, popup_chunks[1]);
-
- // Footer with scroll indicator
- let scroll_indicator = if popup.scroll_offset < 0 {
- format!(" [Ctrl+j/k] scroll [Ctrl+d/u] page [Ctrl+g] bottom [Ctrl+q] close | Line {} ", start_line + 1)
- } else {
- " [Ctrl+j/k] scroll [Ctrl+d/u] page [Ctrl+q] close | At bottom ".to_string()
- };
- let footer = Paragraph::new(scroll_indicator)
- .style(Style::default().fg(Color::Black).bg(hex_to_color(&state.config.theme.color_dimmed)));
- frame.render_widget(footer, popup_chunks[2]);
+ Self::draw_shell_popup(popup, frame, area, &state.config.theme);
}
// Task search popup
@@ -1081,6 +1005,24 @@ impl App {
}
}
+ fn draw_shell_popup(popup: &ShellPopup, frame: &mut Frame, area: Rect, theme: &ThemeConfig) {
+ let popup_area = centered_rect_fixed_width(SHELL_POPUP_WIDTH, SHELL_POPUP_HEIGHT_PERCENT, area);
+
+ // Parse ANSI escape sequences for colors
+ let styled_lines = parse_ansi_to_lines(&popup.cached_content);
+
+ // Build colors from theme
+ let colors = shell_popup::ShellPopupColors {
+ border: hex_to_color(&theme.color_popup_border),
+ header_fg: Color::Black,
+ header_bg: hex_to_color(&theme.color_popup_header),
+ footer_fg: Color::Black,
+ footer_bg: hex_to_color(&theme.color_dimmed),
+ };
+
+ shell_popup::render_shell_popup(popup, frame, popup_area, styled_lines, &colors);
+ }
+
fn draw_task_card(frame: &mut Frame, task: &Task, area: Rect, is_selected: bool, theme: &ThemeConfig) {
let border_style = if is_selected {
Style::default().fg(hex_to_color(&theme.color_selected))
@@ -1703,33 +1645,35 @@ impl App {
}
// Scroll up with Ctrl+k or Ctrl+p or Ctrl+Up
KeyCode::Char('k') | KeyCode::Char('p') | KeyCode::Up if has_ctrl => {
- popup.scroll_offset -= 5;
+ popup.scroll_up(5);
}
// Scroll down with Ctrl+j or Ctrl+n or Ctrl+Down
KeyCode::Char('j') | KeyCode::Char('n') | KeyCode::Down if has_ctrl => {
- popup.scroll_offset = (popup.scroll_offset + 5).min(0);
+ popup.scroll_down(5);
}
// Page up with Ctrl+u or PageUp
KeyCode::Char('u') if has_ctrl => {
- popup.scroll_offset -= 20;
+ popup.scroll_up(20);
}
KeyCode::PageUp => {
- popup.scroll_offset -= 20;
+ popup.scroll_up(20);
}
// Page down with Ctrl+d or PageDown
KeyCode::Char('d') if has_ctrl => {
- popup.scroll_offset = (popup.scroll_offset + 20).min(0);
+ popup.scroll_down(20);
}
KeyCode::PageDown => {
- popup.scroll_offset = (popup.scroll_offset + 20).min(0);
+ popup.scroll_down(20);
}
// Ctrl+g = go to bottom (current)
KeyCode::Char('g') if has_ctrl => {
- popup.scroll_offset = 0;
+ popup.scroll_to_bottom();
}
_ => {
// Forward all other keys to tmux window (including Esc)
send_key_to_tmux(&window_name, key.code);
+ // After sending a key, refresh content to show the result
+ popup.cached_content = capture_tmux_pane_with_history(&window_name, 500);
}
}
}
@@ -2336,14 +2280,6 @@ impl App {
.args(["sh", "-c", &claude_cmd])
.output()?;
- // Resize the new window to fill the popup area
- // Using 180 width to maximize horizontal space usage
- let target = format!("{}:{}", self.state.project_name, window_name);
- std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["resize-pane", "-t", &target, "-x", "180", "-y", "50"])
- .output()?;
-
// Wait for Claude to show the bypass warning prompt, then accept it and rename session
// Poll until we see "Yes, I accept" option or timeout after 5 seconds
let target_clone = target.clone();
@@ -2538,29 +2474,26 @@ impl App {
fn open_selected_task(&mut self) -> Result<()> {
if let Some(task) = self.state.board.selected_task() {
if let Some(window_name) = &task.session_name.clone() {
- // Calculate popup dimensions based on terminal size
- // Popup is 75% of terminal size, content area is 2 less (for borders)
- if let Ok((term_width, term_height)) = crossterm::terminal::size() {
- let popup_width = (term_width as u32 * 75 / 100) as u16;
- let popup_height = (term_height as u32 * 75 / 100) as u16;
- let pane_width = popup_width.saturating_sub(2);
- let pane_height = popup_height.saturating_sub(4);
-
- // Resize tmux pane to match popup dimensions
- let _ = std::process::Command::new("tmux")
- .args(["-L", tmux::AGENT_SERVER])
- .args(["resize-pane", "-t", window_name])
- .args(["-x", &pane_width.to_string()])
- .args(["-y", &pane_height.to_string()])
- .output();
+ let mut popup = ShellPopup::new(task.title.clone(), window_name.clone());
+
+ // Resize tmux window to match popup dimensions (uses same constants as draw_shell_popup)
+ if let Ok((_term_width, term_height)) = crossterm::terminal::size() {
+ let pane_width = SHELL_POPUP_CONTENT_WIDTH;
+ let popup_height = (term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;
+ let pane_height = popup_height.saturating_sub(4); // -4 for borders + header/footer
+
+ let target = format!("{}:{}", self.state.project_name, window_name);
+ // TODO the resize should be done on target which is
+ // session_name:window_name, but for some reason that doesn't work
+ // doing tmux -L agtx resize-window -t session:window -x 30 -y 30 works
+ let _ = RealTmuxOps.resize_window(&window_name, pane_width, pane_height);
+ popup.last_pane_size = Some((pane_width, pane_height));
}
- // Open shell popup to view/control the detached tmux window
- self.state.shell_popup = Some(ShellPopup {
- task_title: task.title.clone(),
- window_name: window_name.clone(),
- scroll_offset: 0,
- });
+ // Capture initial content
+ popup.cached_content = capture_tmux_pane_with_history(window_name, 500);
+
+ self.state.shell_popup = Some(popup);
}
}
Ok(())
@@ -2739,13 +2672,42 @@ fn capture_tmux_pane_with_history(window_name: &str, history_lines: i32) -> Vec<
// -e: include escape sequences (colors)
// -S: start line (negative = history)
// -J: join wrapped lines (helps with varying pane widths)
- std::process::Command::new("tmux")
+ let content = std::process::Command::new("tmux")
.args(["-L", tmux::AGENT_SERVER])
.args(["capture-pane", "-t", window_name, "-p", "-e", "-J"])
.args(["-S", &format!("-{}", history_lines)])
.output()
.map(|o| o.stdout)
- .unwrap_or_default()
+ .unwrap_or_default();
+
+ // Get the cursor position and pane height to know where the "real" content ends
+ // Lines below the cursor are unused pane buffer space
+ let cursor_info = get_tmux_cursor_info(window_name);
+
+ // Trim content to only include lines up to cursor position
+ shell_popup::trim_content_to_cursor(content, cursor_info)
+}
+
+/// Get cursor Y position and pane height from tmux
+/// Returns (cursor_y, pane_height) - both 0-indexed
+fn get_tmux_cursor_info(window_name: &str) -> Option<(usize, usize)> {
+ // Get both values in a single tmux call for efficiency
+ let output = std::process::Command::new("tmux")
+ .args(["-L", tmux::AGENT_SERVER])
+ .args(["display", "-p", "-t", window_name, "#{cursor_y} #{pane_height}"])
+ .output()
+ .ok()?;
+
+ if output.status.success() {
+ let output_str = String::from_utf8_lossy(&output.stdout);
+ let parts: Vec<&str> = output_str.trim().split_whitespace().collect();
+ if parts.len() == 2 {
+ let cursor_y: usize = parts[0].parse().ok()?;
+ let pane_height: usize = parts[1].parse().ok()?;
+ return Some((cursor_y, pane_height));
+ }
+ }
+ None
}
/// Check if a PR is merged
diff --git a/src/tui/mod.rs b/src/tui/mod.rs
index 698cf3d..d041e94 100644
--- a/src/tui/mod.rs
+++ b/src/tui/mod.rs
@@ -1,5 +1,7 @@
mod app;
pub mod board;
mod input;
+pub mod shell_popup;
pub use app::App;
+pub use shell_popup::ShellPopup;
diff --git a/src/tui/shell_popup.rs b/src/tui/shell_popup.rs
new file mode 100644
index 0000000..a7408d3
--- /dev/null
+++ b/src/tui/shell_popup.rs
@@ -0,0 +1,274 @@
+use ratatui::prelude::*;
+use ratatui::widgets::{Block, Borders, Clear, Paragraph};
+
+/// State for the shell popup that shows a detached tmux window
+#[derive(Debug, Clone)]
+pub struct ShellPopup {
+ pub task_title: String,
+ pub window_name: String,
+ pub scroll_offset: i32, // Negative means scroll up (see more history)
+ /// Cached pane content - updated periodically, not on every frame
+ pub cached_content: Vec<u8>,
+ /// Last known pane dimensions for resize detection
+ pub last_pane_size: Option<(u16, u16)>,
+}
+
+impl ShellPopup {
+ pub fn new(task_title: String, window_name: String) -> Self {
+ Self {
+ task_title,
+ window_name,
+ scroll_offset: 0,
+ cached_content: Vec::new(),
+ last_pane_size: None,
+ }
+ }
+
+ /// Scroll up into history
+ pub fn scroll_up(&mut self, lines: i32) {
+ self.scroll_offset -= lines;
+ }
+
+ /// Scroll down toward current content
+ pub fn scroll_down(&mut self, lines: i32) {
+ self.scroll_offset = (self.scroll_offset + lines).min(0);
+ }
+
+ /// Jump to bottom (current content)
+ pub fn scroll_to_bottom(&mut self) {
+ self.scroll_offset = 0;
+ }
+
+ /// Check if we're at the bottom
+ pub fn is_at_bottom(&self) -> bool {
+ self.scroll_offset >= 0
+ }
+}
+
+/// Computed view data for rendering - separates computation from rendering
+#[derive(Debug)]
+pub struct ShellPopupView<'a> {
+ pub title: String,
+ pub lines: Vec<Line<'a>>,
+ pub start_line: usize,
+ pub total_lines: usize,
+ pub is_at_bottom: bool,
+}
+
+/// Compute the visible lines for the shell popup
+/// This is the core testable logic, separated from rendering
+pub fn compute_visible_lines<'a>(
+ styled_lines: Vec<Line<'a>>,
+ visible_height: usize,
+ scroll_offset: i32,
+) -> (Vec<Line<'a>>, usize, usize) {
+ let total_input_lines = styled_lines.len();
+
+ // When at bottom (scroll_offset >= 0), show all lines including trailing empty ones
+ // so the user can see where the cursor/prompt is.
+ // When scrolled up, trim trailing empty lines for cleaner history view.
+ let effective_line_count = if scroll_offset >= 0 {
+ // At bottom - keep all lines to show cursor position
+ total_input_lines
+ } else {
+ // Scrolled up - trim trailing empty lines for cleaner view
+ styled_lines
+ .iter()
+ .rposition(|line| {
+ !line.spans.is_empty() && !line.spans.iter().all(|s| s.content.trim().is_empty())
+ })
+ .map(|i| i + 1)
+ .unwrap_or(total_input_lines)
+ };
+
+ let total_lines = effective_line_count.max(1);
+
+ // Apply scroll offset
+ let start_line = if scroll_offset < 0 {
+ // Scrolling up into history
+ total_lines
+ .saturating_sub(visible_height)
+ .saturating_sub((-scroll_offset) as usize)
+ } else {
+ // At bottom (current)
+ total_lines.saturating_sub(visible_height)
+ };
+
+ let visible_lines: Vec<Line<'a>> = styled_lines
+ .into_iter()
+ .take(effective_line_count)
+ .skip(start_line)
+ .take(visible_height)
+ .collect();
+
+ (visible_lines, start_line, total_lines)
+}
+
+/// Build the footer text for the shell popup
+pub fn build_footer_text(scroll_offset: i32, start_line: usize) -> String {
+ if scroll_offset < 0 {
+ format!(
+ " [Ctrl+j/k] scroll [Ctrl+d/u] page [Ctrl+g] bottom [Ctrl+q] close | Line {} ",
+ start_line + 1
+ )
+ } else {
+ " [Ctrl+j/k] scroll [Ctrl+d/u] page [Ctrl+q] close | At bottom ".to_string()
+ }
+}
+
+/// Maximum number of trailing empty lines to keep after content
+pub const MAX_TRAILING_EMPTY_LINES: usize = 3;
+
+/// Trim captured content to only include lines up to the cursor position.
+/// This removes unused pane buffer space below the cursor.
+///
+/// # Arguments
+/// * `content` - Raw captured pane content as bytes
+/// * `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> {
+ 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;
+ }
+
+ // 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;
+
+ // Keep lines up to and including the cursor line
+ (cursor_line_in_capture + 1).min(total_lines)
+ } else {
+ total_lines
+ }
+ } else {
+ total_lines
+ };
+
+ // Second pass: also trim excessive trailing empty lines
+ // This handles cases where cursor is at bottom but there's no real content there
+ let lines_after_cursor_trim = &lines[..end_line_from_cursor];
+ let end_line = trim_trailing_empty_lines(lines_after_cursor_trim);
+
+ let trimmed: String = lines[..end_line].join("\n");
+ trimmed.into_bytes()
+}
+
+/// Trim excessive trailing empty lines, keeping a small buffer for the prompt area.
+///
+/// # Arguments
+/// * `lines` - Slice of line strings to process
+///
+/// # Returns
+/// The number of lines to keep (index to slice up to)
+pub fn trim_trailing_empty_lines(lines: &[&str]) -> usize {
+ if lines.is_empty() {
+ return 0;
+ }
+
+ // Find the last non-empty line
+ let last_content_line = lines
+ .iter()
+ .rposition(|line| !line.trim().is_empty());
+
+ match last_content_line {
+ Some(idx) => {
+ // Keep the content plus a small buffer for prompt area
+ (idx + 1 + MAX_TRAILING_EMPTY_LINES).min(lines.len())
+ }
+ None => {
+ // All lines are empty, keep just a few
+ MAX_TRAILING_EMPTY_LINES.min(lines.len())
+ }
+ }
+}
+
+/// Colors used for rendering the shell popup
+#[derive(Debug, Clone)]
+pub struct ShellPopupColors {
+ pub border: Color,
+ pub header_fg: Color,
+ pub header_bg: Color,
+ pub footer_fg: Color,
+ pub footer_bg: Color,
+}
+
+impl Default for ShellPopupColors {
+ fn default() -> Self {
+ Self {
+ border: Color::Green,
+ header_fg: Color::Black,
+ header_bg: Color::Cyan,
+ footer_fg: Color::Black,
+ footer_bg: Color::Gray,
+ }
+ }
+}
+
+/// Render the shell popup to the frame
+///
+/// This function handles the complete rendering of the shell popup:
+/// - Border with title
+/// - Header bar with task title
+/// - Content area with parsed terminal output
+/// - Footer with scroll status and keybindings
+pub fn render_shell_popup(
+ popup: &ShellPopup,
+ frame: &mut Frame,
+ popup_area: Rect,
+ styled_lines: Vec<Line<'_>>,
+ colors: &ShellPopupColors,
+) {
+ frame.render_widget(Clear, popup_area);
+
+ // Draw border around the popup
+ let border_block = Block::default()
+ .borders(Borders::ALL)
+ .border_style(Style::default().fg(colors.border));
+ let inner_area = border_block.inner(popup_area);
+ frame.render_widget(border_block, popup_area);
+
+ // Layout: header, content, footer (inside the border)
+ let popup_chunks = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([
+ Constraint::Length(1), // Title bar
+ Constraint::Min(0), // Shell content
+ Constraint::Length(1), // Footer
+ ])
+ .split(inner_area);
+
+ // Title bar (pad to fill width)
+ let title = format!(" {} ", popup.task_title);
+ let padded_title = format!("{:<width$}", title, width = popup_chunks[0].width as usize);
+ let title_bar = Paragraph::new(padded_title)
+ .style(Style::default().fg(colors.header_fg).bg(colors.header_bg));
+ frame.render_widget(title_bar, popup_chunks[0]);
+
+ // Shell content
+ let visible_height = popup_chunks[1].height as usize;
+
+ // Use the testable helper to compute visible lines
+ let (visible_lines, start_line, _total_lines) =
+ compute_visible_lines(styled_lines, visible_height, popup.scroll_offset);
+
+ let content = Paragraph::new(visible_lines);
+ frame.render_widget(content, popup_chunks[1]);
+
+ // Footer with scroll indicator (pad to fill width)
+ let footer_text = build_footer_text(popup.scroll_offset, start_line);
+ let padded_footer = format!("{:<width$}", footer_text, width = popup_chunks[2].width as usize);
+ let footer = Paragraph::new(padded_footer)
+ .style(Style::default().fg(colors.footer_fg).bg(colors.footer_bg));
+ frame.render_widget(footer, popup_chunks[2]);
+}
diff --git a/tests/shell_popup_tests.rs b/tests/shell_popup_tests.rs
new file mode 100644
index 0000000..6246c56
--- /dev/null
+++ b/tests/shell_popup_tests.rs
@@ -0,0 +1,457 @@
+use agtx::tui::shell_popup::{
+ compute_visible_lines, build_footer_text, render_shell_popup,
+ trim_content_to_cursor, trim_trailing_empty_lines,
+ ShellPopup, ShellPopupColors, MAX_TRAILING_EMPTY_LINES,
+};
+use ratatui::backend::TestBackend;
+use ratatui::prelude::*;
+use ratatui::Terminal;
+
+#[test]
+fn test_shell_popup_new() {
+ let popup = ShellPopup::new("Test Task".to_string(), "test-window".to_string());
+
+ assert_eq!(popup.task_title, "Test Task");
+ assert_eq!(popup.window_name, "test-window");
+ assert_eq!(popup.scroll_offset, 0);
+ assert!(popup.cached_content.is_empty());
+ assert!(popup.last_pane_size.is_none());
+}
+
+#[test]
+fn test_shell_popup_scroll_up() {
+ let mut popup = ShellPopup::new("Test".to_string(), "window".to_string());
+ assert_eq!(popup.scroll_offset, 0);
+
+ popup.scroll_up(5);
+ assert_eq!(popup.scroll_offset, -5);
+
+ popup.scroll_up(10);
+ assert_eq!(popup.scroll_offset, -15);
+}
+
+#[test]
+fn test_shell_popup_scroll_down_clamped() {
+ let mut popup = ShellPopup::new("Test".to_string(), "window".to_string());
+ popup.scroll_offset = -20;
+
+ popup.scroll_down(5);
+ assert_eq!(popup.scroll_offset, -15);
+
+ popup.scroll_down(20);
+ assert_eq!(popup.scroll_offset, 0); // Clamped to 0
+}
+
+#[test]
+fn test_shell_popup_scroll_down_from_zero() {
+ let mut popup = ShellPopup::new("Test".to_string(), "window".to_string());
+ assert_eq!(popup.scroll_offset, 0);
+
+ // Scrolling down when already at bottom should stay at 0
+ popup.scroll_down(10);
+ assert_eq!(popup.scroll_offset, 0);
+}
+
+#[test]
+fn test_shell_popup_scroll_to_bottom() {
+ let mut popup = ShellPopup::new("Test".to_string(), "window".to_string());
+ popup.scroll_offset = -100;
+
+ popup.scroll_to_bottom();
+ assert_eq!(popup.scroll_offset, 0);
+}
+
+#[test]
+fn test_shell_popup_is_at_bottom() {
+ let mut popup = ShellPopup::new("Test".to_string(), "window".to_string());
+ assert!(popup.is_at_bottom());
+
+ popup.scroll_up(5);
+ assert!(!popup.is_at_bottom());
+
+ popup.scroll_to_bottom();
+ assert!(popup.is_at_bottom());
+}
+
+#[test]
+fn test_compute_visible_lines_empty() {
+ let lines: Vec<Line> = vec![];
+ let (visible, start, total) = compute_visible_lines(lines, 10, 0);
+
+ assert!(visible.is_empty());
+ assert_eq!(start, 0);
+ assert_eq!(total, 1); // Minimum 1
+}
+
+#[test]
+fn test_compute_visible_lines_fewer_than_height() {
+ let lines: Vec<Line> = vec![
+ Line::from("line 1"),
+ Line::from("line 2"),
+ Line::from("line 3"),
+ ];
+ let (visible, start, total) = compute_visible_lines(lines, 10, 0);
+
+ assert_eq!(visible.len(), 3);
+ assert_eq!(start, 0);
+ assert_eq!(total, 3);
+}
+
+#[test]
+fn test_compute_visible_lines_exact_height() {
+ let lines: Vec<Line> = (0..10).map(|i| Line::from(format!("line {}", i))).collect();
+
+ let (visible, start, total) = compute_visible_lines(lines, 10, 0);
+
+ assert_eq!(visible.len(), 10);
+ assert_eq!(start, 0);
+ assert_eq!(total, 10);
+}
+
+#[test]
+fn test_compute_visible_lines_scrolled_up() {
+ let lines: Vec<Line> = (0..20).map(|i| Line::from(format!("line {}", i))).collect();
+
+ // Visible height 10, scrolled up by 5 lines
+ let (visible, start, total) = compute_visible_lines(lines, 10, -5);
+
+ assert_eq!(visible.len(), 10);
+ assert_eq!(start, 5); // 20 - 10 - 5 = 5
+ assert_eq!(total, 20);
+}
+
+#[test]
+fn test_compute_visible_lines_at_bottom() {
+ let lines: Vec<Line> = (0..20).map(|i| Line::from(format!("line {}", i))).collect();
+
+ let (visible, start, total) = compute_visible_lines(lines, 10, 0);
+
+ assert_eq!(visible.len(), 10);
+ assert_eq!(start, 10); // Shows last 10 lines
+ assert_eq!(total, 20);
+}
+
+#[test]
+fn test_compute_visible_lines_keeps_trailing_empty_at_bottom() {
+ let mut lines: Vec<Line> = (0..10).map(|i| Line::from(format!("line {}", i))).collect();
+ // Add trailing empty lines (simulating cursor on empty line)
+ lines.push(Line::from(""));
+ lines.push(Line::from(" "));
+ lines.push(Line::from(""));
+
+ // At bottom (scroll_offset = 0) - should keep trailing empty lines
+ let (_visible, _start, total) = compute_visible_lines(lines, 20, 0);
+
+ assert_eq!(total, 13); // Keeps all lines including trailing empty
+}
+
+#[test]
+fn test_compute_visible_lines_strips_trailing_empty_when_scrolled() {
+ let mut lines: Vec<Line> = (0..10).map(|i| Line::from(format!("line {}", i))).collect();
+ // Add trailing empty lines
+ lines.push(Line::from(""));
+ lines.push(Line::from(" "));
+ lines.push(Line::from(""));
+
+ // Scrolled up (scroll_offset < 0) - should trim trailing empty for cleaner history
+ let (_visible, _start, total) = compute_visible_lines(lines, 20, -5);
+
+ assert_eq!(total, 10); // Trims trailing empty when scrolled up
+}
+
+#[test]
+fn test_compute_visible_lines_scrolled_to_top() {
+ let lines: Vec<Line> = (0..30).map(|i| Line::from(format!("line {}", i))).collect();
+
+ // Scroll up enough to be at top
+ let (visible, start, total) = compute_visible_lines(lines, 10, -20);
+
+ assert_eq!(visible.len(), 10);
+ assert_eq!(start, 0); // At the very top
+ assert_eq!(total, 30);
+}
+
+#[test]
+fn test_build_footer_text_at_bottom() {
+ let footer = build_footer_text(0, 10);
+ assert!(footer.contains("At bottom"));
+ assert!(!footer.contains("Line"));
+}
+
+#[test]
+fn test_build_footer_text_scrolled_up() {
+ let footer = build_footer_text(-5, 10);
+ assert!(footer.contains("Line 11")); // start_line + 1
+ assert!(footer.contains("bottom")); // Ctrl+g option visible
+}
+
+#[test]
+fn test_build_footer_text_at_top() {
+ let footer = build_footer_text(-100, 0);
+ assert!(footer.contains("Line 1"));
+}
+
+// === Rendering Tests ===
+
+#[test]
+fn test_render_shell_popup_basic() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+
+ let mut popup = ShellPopup::new("Test Task".to_string(), "test-window".to_string());
+ popup.cached_content = b"Hello, World!\nLine 2\nLine 3".to_vec();
+
+ let colors = ShellPopupColors::default();
+ let lines: Vec<Line> = vec![
+ Line::from("Hello, World!"),
+ Line::from("Line 2"),
+ Line::from("Line 3"),
+ ];
+
+ terminal.draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ }).unwrap();
+
+ // Verify the popup was rendered by checking the buffer
+ let buffer = terminal.backend().buffer();
+
+ // Check that the title is rendered somewhere in the buffer
+ let buffer_content: String = buffer.content().iter().map(|c| c.symbol()).collect();
+ assert!(buffer_content.contains("Test Task"));
+}
+
+#[test]
+fn test_render_shell_popup_with_content() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+
+ let popup = ShellPopup::new("My Task".to_string(), "window".to_string());
+ let colors = ShellPopupColors::default();
+
+ let lines: Vec<Line> = vec![
+ Line::from("$ echo hello"),
+ Line::from("hello"),
+ Line::from("$ "),
+ ];
+
+ terminal.draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ }).unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let buffer_content: String = buffer.content().iter().map(|c| c.symbol()).collect();
+
+ // Should contain task title
+ assert!(buffer_content.contains("My Task"));
+ // Should contain "At bottom" since scroll_offset is 0
+ assert!(buffer_content.contains("At bottom"));
+}
+
+#[test]
+fn test_render_shell_popup_scrolled_up() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+
+ let mut popup = ShellPopup::new("Scrolled Task".to_string(), "window".to_string());
+ popup.scroll_up(10); // Scroll up into history
+
+ let colors = ShellPopupColors::default();
+ let lines: Vec<Line> = (0..30).map(|i| Line::from(format!("Line {}", i))).collect();
+
+ terminal.draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ }).unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let buffer_content: String = buffer.content().iter().map(|c| c.symbol()).collect();
+
+ // Should show "Line X" indicator since we scrolled up
+ assert!(buffer_content.contains("Line"));
+ // Should show the bottom shortcut since we're not at bottom
+ assert!(buffer_content.contains("bottom"));
+}
+
+#[test]
+fn test_render_shell_popup_empty_content() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+
+ let popup = ShellPopup::new("Empty Task".to_string(), "window".to_string());
+ let colors = ShellPopupColors::default();
+ let lines: Vec<Line> = vec![];
+
+ terminal.draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ }).unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let buffer_content: String = buffer.content().iter().map(|c| c.symbol()).collect();
+
+ // Should still render title and footer
+ assert!(buffer_content.contains("Empty Task"));
+ assert!(buffer_content.contains("At bottom"));
+}
+
+#[test]
+fn test_render_shell_popup_custom_colors() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+
+ let popup = ShellPopup::new("Colored Task".to_string(), "window".to_string());
+
+ let colors = ShellPopupColors {
+ border: Color::Red,
+ header_fg: Color::White,
+ header_bg: Color::Blue,
+ footer_fg: Color::Yellow,
+ footer_bg: Color::Magenta,
+ };
+
+ let lines: Vec<Line> = vec![Line::from("content")];
+
+ terminal.draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ }).unwrap();
+
+ // Just verify it doesn't crash with custom colors
+ let buffer = terminal.backend().buffer();
+ let buffer_content: String = buffer.content().iter().map(|c| c.symbol()).collect();
+ assert!(buffer_content.contains("Colored Task"));
+}
+
+#[test]
+fn test_render_shell_popup_small_area() {
+ let backend = TestBackend::new(40, 10);
+ let mut terminal = Terminal::new(backend).unwrap();
+
+ let popup = ShellPopup::new("Small Popup".to_string(), "window".to_string());
+ let colors = ShellPopupColors::default();
+ let lines: Vec<Line> = vec![Line::from("test")];
+
+ terminal.draw(|frame| {
+ let area = Rect::new(0, 0, 40, 10);
+ render_shell_popup(&popup, frame, area, lines, &colors);
+ }).unwrap();
+
+ // Should handle small areas gracefully
+ let buffer = terminal.backend().buffer();
+ let buffer_content: String = buffer.content().iter().map(|c| c.symbol()).collect();
+ assert!(buffer_content.contains("Small Popup"));
+}
+
+// === Trimming Tests ===
+
+#[test]
+fn test_trim_trailing_empty_lines_no_empty() {
+ let lines = vec!["line 1", "line 2", "line 3"];
+ let result = trim_trailing_empty_lines(&lines);
+ assert_eq!(result, 3); // Keep all lines
+}
+
+#[test]
+fn test_trim_trailing_empty_lines_few_empty() {
+ let lines = vec!["line 1", "line 2", "", ""];
+ let result = trim_trailing_empty_lines(&lines);
+ // Last content at index 1, so keep 1 + 1 + MAX_TRAILING = 2 + 3 = 5, but only 4 lines exist
+ assert_eq!(result, 4);
+}
+
+#[test]
+fn test_trim_trailing_empty_lines_many_empty() {
+ let lines = vec!["line 1", "line 2", "", "", "", "", "", "", "", ""];
+ let result = trim_trailing_empty_lines(&lines);
+ // Last content at index 1, keep up to index 1 + 1 + MAX_TRAILING = 5
+ assert_eq!(result, 2 + MAX_TRAILING_EMPTY_LINES);
+}
+
+#[test]
+fn test_trim_trailing_empty_lines_all_empty() {
+ let lines = vec!["", "", "", "", "", "", "", "", "", ""];
+ let result = trim_trailing_empty_lines(&lines);
+ // All empty, keep just MAX_TRAILING
+ assert_eq!(result, MAX_TRAILING_EMPTY_LINES);
+}
+
+#[test]
+fn test_trim_trailing_empty_lines_empty_input() {
+ let lines: Vec<&str> = vec![];
+ let result = trim_trailing_empty_lines(&lines);
+ assert_eq!(result, 0);
+}
+
+#[test]
+fn test_trim_trailing_empty_lines_whitespace_only() {
+ let lines = vec!["line 1", " ", "\t", " \t "];
+ let result = trim_trailing_empty_lines(&lines);
+ // " ", "\t", " \t " are all whitespace-only, treated as empty
+ // Last real content at index 0
+ assert_eq!(result, 1 + MAX_TRAILING_EMPTY_LINES);
+}
+
+#[test]
+fn test_trim_content_to_cursor_no_cursor_info() {
+ 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_str = String::from_utf8_lossy(&result);
+ // Count newlines + 1 to avoid lines() quirk with trailing newlines
+ let line_count = result_str.matches('\n').count() + 1;
+ // Should fall back to trimming empty lines
+ // 2 content lines + MAX_TRAILING empty lines
+ assert_eq!(line_count, 2 + MAX_TRAILING_EMPTY_LINES);
+}
+
+#[test]
+fn test_trim_content_to_cursor_with_cursor_info() {
+ // Simulate: 10 lines captured, pane_height=5, cursor at line 2 of visible area
+ // visible_pane_start = 10 - 5 = 5
+ // cursor_in_capture = 5 + 2 = 7
+ // Should keep lines 0-7 (8 lines)
+ let content = b"line 0\nline 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9".to_vec();
+ let cursor_info = Some((2, 5)); // cursor_y=2, pane_height=5
+ let result = trim_content_to_cursor(content, cursor_info);
+ let result_str = String::from_utf8_lossy(&result);
+ let lines: Vec<&str> = result_str.lines().collect();
+
+ assert_eq!(lines.len(), 8); // Lines 0-7
+ assert_eq!(lines[0], "line 0");
+ assert_eq!(lines[7], "line 7");
+}
+
+#[test]
+fn test_trim_content_to_cursor_cursor_at_bottom_with_empty() {
+ // Cursor at bottom of pane, but those lines are empty
+ // Should trim the empty lines via second pass
+ let content = b"line 0\nline 1\nline 2\n\n\n\n\n".to_vec();
+ let cursor_info = Some((6, 7)); // cursor at line 6 of 7-line pane (bottom)
+ let result = trim_content_to_cursor(content, cursor_info);
+ let result_str = String::from_utf8_lossy(&result);
+ // Count newlines + 1 to avoid lines() quirk with trailing newlines
+ let line_count = result_str.matches('\n').count() + 1;
+
+ // Content has 3 real lines, then empty
+ // Second pass should trim to 3 + MAX_TRAILING
+ assert_eq!(line_count, 3 + MAX_TRAILING_EMPTY_LINES);
+}
+
+#[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)));
+ 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_str = String::from_utf8_lossy(&result);
+ // Count newlines + 1 to avoid lines() quirk with trailing newlines
+ let line_count = result_str.matches('\n').count() + 1;
+ // pane_height=0 should fall through to second pass only
+ assert_eq!(line_count, 2 + MAX_TRAILING_EMPTY_LINES);
+}