Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Improve `wt select` UI and UX
Maximilian Roos952927f5dc9e
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex 71059966e..ed4280452 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -120,11 +120,11 @@ mod ci_status;pub(crate) mod collect;mod collect_progressive_impl;mod columns;-mod layout;+pub(crate) mod layout;pub mod model;pub mod progressive;mod progressive_table;-mod render;+pub(crate) mod render;#[cfg(test)]mod spacing_test;diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex 7c087f117..8ba336ddd 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -548,16 +548,6 @@ pub struct StatusSymbols {}impl StatusSymbols {- /// Render symbols with full alignment (all positions)- ///- /// This is used for the display fields in JSON output. Skipped on Windows- /// to avoid an unused/dead-code warning in clippy (the interactive selector- /// that calls this exists only on Unix).- #[cfg(unix)]- pub fn render(&self) -> String {- self.render_with_mask(&PositionMask::FULL)- }-/// Render symbols with selective alignment based on position mask////// Only includes positions present in the mask. This ensures verticaldiff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex 8d625b6db..80fdc3ae7 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -337,8 +337,13 @@ impl LayoutConfig {}pub fn format_header_line(&self) -> String {+ self.render_header_line().render()+ }++ /// Render header line as StyledLine (for extracting both plain and styled text)+ pub fn render_header_line(&self) -> StyledLine {let style = Style::new().bold();- let line = self.render_line(|column| {+ self.render_line(|column| {let mut cell = StyledLine::new();if !column.header.is_empty() {// Diff columns have right-aligned values, so right-align headers too@@ -356,9 +361,7 @@ impl LayoutConfig {cell.push_styled(column.header.to_string(), style);}cell- });-- line.render()+ })}pub fn format_list_item_line(@@ -367,17 +370,26 @@ impl LayoutConfig {current_worktree_path: Option<&std::path::PathBuf>,previous_branch: Option<&str>,) -> String {+ self.render_list_item_line(item, current_worktree_path, previous_branch)+ .render()+ }++ /// Render list item line as StyledLine (for extracting both plain and styled text)+ pub fn render_list_item_line(+ &self,+ item: &ListItem,+ current_worktree_path: Option<&std::path::PathBuf>,+ previous_branch: Option<&str>,+ ) -> StyledLine {let ctx = ListRowContext::new(item, current_worktree_path, previous_branch);- let line = self.render_line(|column| {+ self.render_line(|column| {column.render_cell(&ctx,&self.status_position_mask,&self.common_prefix,self.max_message_len,)- });-- line.render()+ })}/// Render a skeleton row showing known data (branch, path) with placeholders for other columnsdiff --git a/src/commands/select.rs b/src/commands/select.rsindex 2de965037..fd7ca1f45 100644--- a/src/commands/select.rs+++ b/src/commands/select.rs@@ -10,7 +10,7 @@ use worktrunk::git::Repository;use super::list::collect;use super::list::model::ListItem;use super::worktree::handle_switch;-use crate::output::{blank_line, handle_switch_output};+use crate::output::handle_switch_output;/// Preview modes for the interactive selector///@@ -75,6 +75,21 @@ impl Drop for PreviewState {}}+/// Header item for column names (non-selectable)+struct HeaderSkimItem {+ text: String,+}++impl SkimItem for HeaderSkimItem {+ fn text(&self) -> Cow<'_, str> {+ Cow::Borrowed(&self.text)+ }++ fn output(&self) -> Cow<'_, str> {+ Cow::Borrowed("") // Headers produce no output if selected+ }+}+/// Wrapper to implement SkimItem for ListItemstruct WorktreeSkimItem {display_text: String,@@ -250,7 +265,7 @@ impl WorktreeSkimItem {}}-pub fn handle_select() -> anyhow::Result<()> {+pub fn handle_select(is_directive_mode: bool) -> anyhow::Result<()> {let repo = Repository::current();// Initialize preview mode state file (auto-cleanup on drop)@@ -270,49 +285,32 @@ pub fn handle_select() -> anyhow::Result<()> {return Ok(());};- // Calculate max branch name length for alignment- let max_branch_len = list_data- .items- .iter()- .map(|item| item.branch_name().len())- .max()- .unwrap_or(20);+ // Get current worktree path for styling+ let current_worktree_path = repo.worktree_root().ok();++ // Use the same layout system as `wt list` for proper column alignment+ let layout = super::list::layout::calculate_layout_from_basics(+ &list_data.items,+ false, // show_full+ false, // fetch_ci+ );- // Convert to skim items - store full ListItem for preview rendering- let items: Vec<Arc<dyn SkimItem>> = list_data+ // Render header using layout system+ let header_line = layout.render_header_line();+ let header_text = header_line.render();++ // Convert to skim items using the layout system for rendering+ let mut items: Vec<Arc<dyn SkimItem>> = list_data.items.into_iter().map(|item| {let branch_name = item.branch_name().to_string();- let commit_details = item.commit_details();- let commit_msg = commit_details.commit_message.lines().next().unwrap_or("");-- // Build display text with aligned columns- // We need two versions: one with ANSI codes for display, one stripped for matching- let mut display_text = format!("{:<width$}", branch_name, width = max_branch_len);- let mut display_text_with_ansi = display_text.clone();-- // Add status symbols- // For the styled version, we need to pad based on visible width, not byte length- let (status_plain, status_styled) =- if let Some(ref status_symbols) = item.status_symbols {- let rendered = status_symbols.render();- let stripped = worktrunk::styling::strip_ansi_codes(&rendered);- let visible_width = worktrunk::styling::visual_width(&stripped);- let padding_needed = 8usize.saturating_sub(visible_width);- let styled_with_padding = format!("{}{}", rendered, " ".repeat(padding_needed));- (format!("{:<8}", stripped), styled_with_padding)- } else {- (" ".to_string(), " ".to_string())- };- display_text.push_str(&status_plain);- display_text_with_ansi.push_str(&status_styled);-- // Add commit message- display_text.push_str(" ");- display_text.push_str(commit_msg);- display_text_with_ansi.push_str(" ");- display_text_with_ansi.push_str(commit_msg);++ // Use layout system to render the line - this handles all column alignment+ let rendered_line =+ layout.render_list_item_line(&item, current_worktree_path.as_ref(), None);+ let display_text_with_ansi = rendered_line.render();+ let display_text = rendered_line.plain_text();Arc::new(WorktreeSkimItem {display_text,@@ -323,12 +321,20 @@ pub fn handle_select() -> anyhow::Result<()> {}).collect();+ // Insert header row at the beginning (will be non-selectable via header_lines option)+ items.insert(+ 0,+ Arc::new(HeaderSkimItem { text: header_text }) as Arc<dyn SkimItem>,+ );+// Get state path for key bindingslet state_path_str = _state.path.display().to_string();// Configure skim options with Rust-based preview and mode switching keybindingslet options = SkimOptionsBuilder::default().height("50%".to_string())+ .layout("reverse".to_string())+ .header_lines(1) // Make first line (header) non-selectable.multi(false).preview(Some("".to_string())) // Enable preview (empty string means use SkimItem::preview()).preview_window("right:50%".to_string())@@ -352,10 +358,13 @@ pub fn handle_select() -> anyhow::Result<()> {// Preview scrolling"ctrl-u:preview-page-up".to_string(),"ctrl-d:preview-page-down".to_string(),+ // Preview toggle (ctrl-p is universally supported, unlike ctrl-/)+ "ctrl-p:toggle-preview".to_string(),]).header(Some(- "1: working | 2: history | 3: diff | ctrl-u/d: scroll | ctrl-/: toggle".to_string(),+ "1: working | 2: history | 3: diff | ctrl-u/d: scroll | ctrl-p: preview".to_string(),))+ .no_clear(true) // Prevent skim from clearing screen, we'll do it manually.build().map_err(|e| anyhow::anyhow!(format!("Failed to build skim options: {}", e)))?;@@ -387,12 +396,14 @@ pub fn handle_select() -> anyhow::Result<()> {let (result, resolved_branch) =handle_switch(&identifier, false, None, false, false, &config)?;- // Skim leaves the prompt on the same line, so insert a blank line before our messages- blank_line()?;+ // Clear the terminal screen after skim exits to prevent artifacts+ use crossterm::{execute, terminal};+ use std::io::stdout;+ execute!(stdout(), terminal::Clear(terminal::ClearType::All))?;+ execute!(stdout(), crossterm::cursor::MoveTo(0, 0))?;- // Show success message (show shell integration hint if not configured)- // select is always interactive (TUI), so is_directive_mode is false- handle_switch_output(&result, &resolved_branch, false, false)?;+ // Show success message; emit cd directive if in directive mode+ handle_switch_output(&result, &resolved_branch, false, is_directive_mode)?;}Ok(())diff --git a/src/main.rs b/src/main.rsindex ea5c09aff..1f2fd00ba 100644--- a/src/main.rs+++ b/src/main.rs@@ -540,7 +540,7 @@ fn main() {},#[cfg(unix)]Commands::Beta { action } => match action {- BetaCommand::Select => handle_select(),+ BetaCommand::Select => handle_select(cli.internal),},Commands::List {format,diff --git a/src/output/directive.rs b/src/output/directive.rsindex 8acceecb5..48903be8f 100644--- a/src/output/directive.rs+++ b/src/output/directive.rs@@ -76,12 +76,6 @@ impl OutputHandler for DirectiveOutput {Ok(())}- #[cfg(unix)]- fn blank_line(&mut self) -> io::Result<()> {- // Blank lines are only meaningful in interactive mode; no-op here to avoid empty directives- Ok(())- }-// Note: raw() uses the default which calls write_message_line() -> stderr// This is correct for directive mode where stdout is reserved for directivesdiff --git a/src/output/global.rs b/src/output/global.rsindex e83dc36a9..87e979eab 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -116,12 +116,6 @@ pub fn error(message: impl Into<String>) -> io::Result<()> {with_output(|h| h.error(message.into()))}-/// Insert a blank line between UI output and worktrunk messages-#[cfg(unix)]-pub fn blank_line() -> io::Result<()> {- with_output(|h| h.blank_line())-}-/// Emit gutter-formatted content////// Gutter content has its own visual structure (column 0 gutter + content),diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 0aca47a63..02a9102fc 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -5,6 +5,7 @@ use crate::commands::worktree::{RemoveResult, SwitchResult};use crate::output::global::format_switch_success;use worktrunk::git::{branch_deletion_failed, worktree_removal_failed};use worktrunk::path::format_path_for_display;+use worktrunk::shell::Shell;use worktrunk::styling::{CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, WARNING_BOLD, format_with_gutter,};@@ -99,11 +100,14 @@ pub fn handle_switch_output())?;}SwitchResult::Existing(path) => {- if is_directive_mode || has_execute_command {- // Shell integration active or --execute provided - show success+ // Check if we can cd or if shell integration is at least configured+ let is_configured = Shell::is_integration_configured().ok().flatten().is_some();++ if is_directive_mode || has_execute_command || is_configured {+ // Shell integration active, --execute provided, or configured - show successsuper::success(format_switch_success(branch, path, false, None))?;} else {- // No shell integration - show warning that we can't cd+ // Shell integration not configured - show warning and setup hintlet bold = worktrunk::styling::AnstyleStyle::new().bold();super::warning(format!("{WARNING}Worktree for {bold}{branch}{bold:#}{WARNING} at {bold}{}{bold:#}{WARNING}; cannot cd (no shell integration){WARNING:#}",@@ -124,7 +128,7 @@ pub fn handle_switch_output(*created_branch,base_branch.as_deref(),))?;- // Show hint if no shell integration and no --execute+ // Show setup hint if shell integration not activeif !is_directive_mode && !has_execute_command {super::shell_integration_hint(shell_integration_hint())?;}diff --git a/src/output/interactive.rs b/src/output/interactive.rsindex 4ba88232b..1a453a86b 100644--- a/src/output/interactive.rs+++ b/src/output/interactive.rs@@ -45,13 +45,6 @@ impl OutputHandler for InteractiveOutput {self.hint(message)}- #[cfg(unix)]- fn blank_line(&mut self) -> io::Result<()> {- // Ensure subsequent output starts on a fresh line after interactive UIs like skim- println!();- stdout().flush()- }-fn change_directory(&mut self, path: &Path) -> io::Result<()> {// In interactive mode, we can't actually change directory// Just store the target for execute commandsdiff --git a/src/output/mod.rs b/src/output/mod.rsindex ee64bb994..019663252 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -67,11 +67,6 @@ pub use global::{hint, info, initialize, progress, raw, raw_terminal, shell_integration_hint, success,terminate_output, warning,};--// blank_line is only used by select command which is Unix-only-#[cfg(unix)]-pub use global::blank_line;-// Re-export output handlerspub use handlers::{execute_command_in_worktree, execute_user_command, handle_remove_output, handle_switch_output,diff --git a/src/output/traits.rs b/src/output/traits.rsindex 12740de79..f04fc1774 100644--- a/src/output/traits.rs+++ b/src/output/traits.rs@@ -97,12 +97,6 @@ pub trait OutputHandler {/// Interactive shows it, Directive suppresses itfn shell_integration_hint(&mut self, message: String) -> io::Result<()>;- /// Insert a blank line- ///- /// Interactive prints newline, Directive is no-op- #[cfg(unix)]- fn blank_line(&mut self) -> io::Result<()>;-/// Request directory change////// Interactive stores path, Directive emits directivediff --git a/src/shell.rs b/src/shell.rsindex 76a9a86a9..70ff365f4 100644--- a/src/shell.rs+++ b/src/shell.rs@@ -235,9 +235,15 @@ impl Shell {let reader = BufReader::new(file);for line in reader.lines().map_while(Result::ok) {let trimmed = line.trim();- // Match: eval "$(anything init bash/zsh/etc)"- // This catches both wt and custom prefixes- if (trimmed.starts_with("eval \"$(") || trimmed.starts_with("eval '$("))+ // Skip comments+ if trimmed.starts_with('#') {+ continue;+ }+ // Match lines containing: eval "$(... init ...)" or eval '$(... init ...)'+ // This catches both the direct pattern and the guarded pattern:+ // eval "$(wt config shell init bash)"+ // if command -v wt ...; then eval "$(command wt config shell init zsh)"; fi+ if (trimmed.contains("eval \"$(") || trimmed.contains("eval '$("))&& trimmed.contains(" init "){return Ok(Some(path));diff --git a/src/styling/line.rs b/src/styling/line.rsindex 5590defd1..826970159 100644--- a/src/styling/line.rs+++ b/src/styling/line.rs@@ -133,6 +133,11 @@ impl StyledLine {self.segments.iter().map(|s| s.render()).collect()}+ /// Returns the plain text without any styling+ pub fn plain_text(&self) -> String {+ self.segments.iter().map(|s| s.text.as_str()).collect()+ }+/// Truncate if the line exceeds the given width, preserving ANSI codes./// Returns a new StyledLine with truncated content and ellipsis.pub fn truncate_to_width(self, max_width: usize) -> StyledLine {diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex f0abbded5..edf0b5b9d 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -7,6 +7,7 @@ use insta_cmd::assert_cmd_snapshot;use std::fs;use std::thread;use std::time::Duration;+use tempfile::TempDir;/// Wait duration when checking file absence (testing command did NOT run)./// Must be long enough that a background command would have started and created@@ -16,10 +17,15 @@ const SLEEP_FOR_ABSENCE_CHECK: Duration = Duration::from_millis(500);/// Helper to create snapshot with normalized paths and SHAs////// Tests should write to repo.test_config_path() to pre-approve commands.+/// Uses an isolated HOME to prevent tests from being affected by developer's shell config.fn snapshot_switch(test_name: &str, repo: &TestRepo, args: &[&str]) {+ // Create isolated HOME to ensure test determinism+ let temp_home = TempDir::new().unwrap();+let settings = setup_snapshot_settings(repo);settings.bind(|| {let mut cmd = make_snapshot_cmd(repo, "switch", args, None);+ cmd.env("HOME", temp_home.path());assert_cmd_snapshot!(test_name, cmd);});}diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 5bb371c44..063a011e9 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1,6 +1,7 @@use crate::common::{TestRepo, make_snapshot_cmd_with_global_flags, setup_snapshot_settings};use insta_cmd::assert_cmd_snapshot;use std::path::Path;+use tempfile::TempDir;/// Common setup for switch tests - creates repo with initial commitfn setup_switch_repo() -> TestRepo {@@ -25,6 +26,10 @@ fn snapshot_switch_with_global_flags(}/// Helper that also allows setting a custom HOME directory and global flags+///+/// IMPORTANT: Always uses an isolated HOME to prevent tests from being affected+/// by the developer's real shell configuration (e.g., shell integration in ~/.zshrc).+/// Pass `temp_home` to use a specific HOME (e.g., with shell integration configured).fn snapshot_switch_with_home(test_name: &str,repo: &TestRepo,@@ -32,12 +37,14 @@ fn snapshot_switch_with_home(temp_home: Option<&Path>,global_flags: &[&str],) {+ // Create isolated HOME if not provided to ensure test determinism+ let default_home = TempDir::new().unwrap();+ let home = temp_home.unwrap_or_else(|| default_home.path());+let settings = setup_snapshot_settings(repo);settings.bind(|| {let mut cmd = make_snapshot_cmd_with_global_flags(repo, "switch", args, None, global_flags);- if let Some(home) = temp_home {- cmd.env("HOME", home);- }+ cmd.env("HOME", home);assert_cmd_snapshot!(test_name, cmd);});}@@ -116,6 +123,40 @@ fn test_switch_existing_branch() {snapshot_switch("switch_existing_branch", &repo, &["feature-z"]);}+/// Test switching to existing worktree when shell integration is configured but not active.+///+/// When shell integration is configured in user's rc files (e.g., .zshrc) but the user+/// runs `wt switch` directly (not through the shell wrapper), we should show success+/// with a hint to use `wt switch` for cd, not a warning about missing shell integration.+#[test]+fn test_switch_existing_with_shell_integration_configured() {+ use std::fs;++ let temp_home = TempDir::new().unwrap();+ let mut repo = setup_switch_repo();++ // Simulate shell integration configured in user's shell rc files+ let zshrc_path = temp_home.path().join(".zshrc");+ fs::write(+ &zshrc_path,+ "# Existing user zsh config\nif command -v wt >/dev/null 2>&1; then eval \"$(command wt config shell init zsh)\"; fi\n",+ )+ .unwrap();++ // Create a worktree first+ repo.add_worktree("shell-configured", "shell-configured");++ // Switch to existing worktree - should show success + "cd with: wt switch" hint+ // NOT the warning about "cannot cd (no shell integration)"+ snapshot_switch_with_home(+ "switch_existing_with_shell_configured",+ &repo,+ &["shell-configured"],+ Some(temp_home.path()),+ &[],+ );+}+#[test]fn test_switch_with_base_branch() {let repo = TestRepo::new();diff --git a/tests/snapshots/integration__integration_tests__switch__switch_existing_with_shell_configured.snap b/tests/snapshots/integration__integration_tests__switch__switch_existing_with_shell_configured.snapnew file mode 100644index 000000000..6d9ec3c4e--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_existing_with_shell_configured.snap@@ -0,0 +1,27 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - shell-configured+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: true+exit_code: 0+----- stdout -----+✅ [32mSwitched to worktree for [1m[32mshell-configured[0m[32m at [1m[32m[WORKTREE_SHELL_CONFIGURED][0m[0m++----- stderr -----