Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(switch): run the interactive picker on Windows (#3217)
Maximilian Roosc70eedf152a1
diff --git a/Cargo.toml b/Cargo.tomlindex 601ee1162..1352dcb2e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -235,7 +235,12 @@ petname = { version = "=3.0.0", default-features = false, features = ["default-wtempfile = "3.27"wait-timeout = "0.2"-[target.'cfg(unix)'.dependencies]+# Interactive picker (`wt switch`) TUI stack, pulled in only by the `cli`+# feature's `dep:` entries. These are platform-neutral (skim 4.x is the+# ratatui/crossterm rewrite, which supports Windows), so they live in the main+# table — not under `[target.'cfg(unix)']` — or the picker fails to compile on+# Windows.+## skim 4.x is the ratatui-based rewrite; the 0.20 line used the now-abandoned# tuikit backend (we previously vendored a patched skim-tuikit fork). The# picker feeds rows as a custom `SkimItem` whose `display()` returns a ratatui@@ -262,6 +267,11 @@ ansi-to-tui = { version = "8.0.1", optional = true }# collect mutates rows in place — skim 4.x renders on demand, not on a heartbeat.# `Runtime::new()` needs `rt-multi-thread`; `event_sender()` is a `sync::mpsc`.tokio = { version = "1.52.3", optional = true, default-features = false, features = ["rt-multi-thread", "sync"] }++[target.'cfg(unix)'.dependencies]+# Unix-only syscall crates: `nix` (process/signal) backs the fsmonitor reap and+# `signal-hook` forwards Ctrl-C to child process groups. Gating keeps both out of+# the Windows dependency graph.nix = { version = "0.31.3", default-features = false, features = ["process", "signal"] }signal-hook = "0.4.1"diff --git a/benches/picker_preview.rs b/benches/picker_preview.rsindex fdcba6c30..f6924b09f 100644--- a/benches/picker_preview.rs+++ b/benches/picker_preview.rs@@ -1,10 +1,10 @@// Benchmarks for the `wt switch` picker's preview pre-compute workload//-// Unix-only: `wt switch` (no branch arg) only routes to the interactive-// picker on Unix; on Windows it prints "interactive picker unavailable"-// and exits with code 2 before `WORKTRUNK_PREVIEW_BENCH` is consulted.-// Gating with `cfg(unix)` keeps `cargo bench` runnable on Windows by-// emitting an empty `main` there.+// Unix-gated by choice, not capability: the picker now runs on Windows too+// (the `WORKTRUNK_PREVIEW_BENCH` path bypasses skim's TTY check on every+// platform), but standing up the `wt_perf` fixtures and subprocess harness+// below on Windows isn't worth it for a non-required bench. `cfg(unix)` emits+// an empty `main` there so `cargo bench` still builds.//// What this measures// ------------------diff --git a/docs/content/faq.md b/docs/content/faq.mdindex a2046a6b4..01921f0d3 100644--- a/docs/content/faq.md+++ b/docs/content/faq.md@@ -254,7 +254,7 @@ Yes. Core commands, shell integration, and tab completion work in both Git Bash**Git for Windows required** — Hooks use bash syntax and execute via Git Bash, so [Git for Windows](https://gitforwindows.org/) must be installed even when PowerShell is the interactive shell.-**`wt switch` interactive picker unavailable** — Uses [skim](https://github.com/skim-rs/skim), which doesn't support Windows. Use `wt list` and `wt switch <branch>` instead.+The `wt switch` interactive picker runs on Windows too, on [skim](https://github.com/skim-rs/skim)'s crossterm backend.## How does Worktrunk determine the default branch?diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.mdindex 02477de2f..899b56c26 100644--- a/skills/worktrunk/reference/faq.md+++ b/skills/worktrunk/reference/faq.md@@ -247,7 +247,7 @@ Yes. Core commands, shell integration, and tab completion work in both Git Bash**Git for Windows required** — Hooks use bash syntax and execute via Git Bash, so [Git for Windows](https://gitforwindows.org/) must be installed even when PowerShell is the interactive shell.-**`wt switch` interactive picker unavailable** — Uses [skim](https://github.com/skim-rs/skim), which doesn't support Windows. Use `wt list` and `wt switch <branch>` instead.+The `wt switch` interactive picker runs on Windows too, on [skim](https://github.com/skim-rs/skim)'s crossterm backend.## How does Worktrunk determine the default branch?diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex a5647b452..0eca527e2 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -72,6 +72,7 @@use std::fmt::Write as _;use std::path::{Path, PathBuf};+use crate::commands::picker::preview_cache;use anyhow::Context;use color_print::cformat;use path_slash::PathExt as _;@@ -91,38 +92,6 @@ use crate::display::format_relative_time_short;use crate::help_pager::show_help_in_pager;use crate::summary::CachedSummary;-// ==================== Picker preview cache shims ====================-//-// `commands::picker` is gated `#[cfg(unix)]` (see `commands/mod.rs`), so its-// preview cache module disappears entirely on Windows. The bundled "git-// commands cache" category still needs to compile and report consistent-// counts on every platform — these shims forward to the picker cache on-// unix and return 0 / `Ok(0)` elsewhere so call sites stay platform-agnostic.--fn picker_preview_count(repo: &Repository) -> usize {- #[cfg(unix)]- {- crate::commands::picker::preview_cache::count_all(repo)- }- #[cfg(not(unix))]- {- let _ = repo;- 0- }-}--fn picker_preview_clear(repo: &Repository) -> anyhow::Result<usize> {- #[cfg(unix)]- {- crate::commands::picker::preview_cache::clear_all(repo)- }- #[cfg(not(unix))]- {- let _ = repo;- Ok(0)- }-}-// ==================== Log Management ====================/// Top-level files created by `-vv` under `wt_logs_dir()`.@@ -1150,7 +1119,7 @@ fn clear_summary_reported(repo: &Repository) -> anyhow::Result<bool> {/// upstream-diff). Surfaced as one user-facing category — see the parity/// docstring at the top of this file.fn clear_git_commands_reported(repo: &Repository) -> anyhow::Result<bool> {- let cleared = sha_cache::clear_all(repo)? + picker_preview_clear(repo)?;+ let cleared = sha_cache::clear_all(repo)? + preview_cache::clear_all(repo)?;if cleared > 0 {eprintln!("{}",@@ -1306,7 +1275,7 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {"ci_status": ci_status,"max_pr_number": MaxPrNumber::read(repo),"summaries": summaries,- "git_commands_cache": sha_cache::count_all(repo) + picker_preview_count(repo),+ "git_commands_cache": sha_cache::count_all(repo) + preview_cache::count_all(repo),"vars": vars_data,"command_log": command_log,"hook_output": hook_output,@@ -1471,7 +1440,7 @@ fn handle_cache_get_json(repo: &Repository) -> anyhow::Result<()> {"ci_status": ci_status_json(repo),"max_pr_number": MaxPrNumber::read(repo),"summaries": summaries_json(repo),- "git_commands_cache": sha_cache::count_all(repo) + picker_preview_count(repo),+ "git_commands_cache": sha_cache::count_all(repo) + preview_cache::count_all(repo),"hints": repo.list_shown_hints(),});@@ -1554,7 +1523,7 @@ fn render_summary_section(out: &mut String, repo: &Repository) -> anyhow::Result/// regardless of which module owns the entries.fn render_git_commands_section(out: &mut String, repo: &Repository) -> anyhow::Result<()> {writeln!(out, "{}", format_heading("GIT COMMANDS CACHE", None))?;- let cache_count = sha_cache::count_all(repo) + picker_preview_count(repo);+ let cache_count = sha_cache::count_all(repo) + preview_cache::count_all(repo);if cache_count == 0 {writeln!(out, "{}", format_with_gutter("(none)", None))?;} else {diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rsindex 46460ba03..2f9f09964 100644--- a/src/commands/list/ci_status/github.rs+++ b/src/commands/list/ci_status/github.rs@@ -301,8 +301,7 @@ impl GitHubPrInfo {/// treatment [`detect_github`] produces per branch. PR rows have no local/// checkout to diff against, so the result is never marked stale.///- /// Only the `--prs` picker calls this, and the picker is unix-only.- #[cfg(unix)]+ /// Only the `--prs` picker calls this.pub(crate) fn open_pr_status(&self) -> PrStatus {let ci_status = if self.merge_state_status.as_deref() == Some("DIRTY") {CiStatus::Conflicts@@ -392,7 +391,6 @@ mod tests {/// A `DIRTY` merge state (merge conflicts) reports `Conflicts` regardless of/// the check rollup — the `--prs` picker's CI column treatment.- #[cfg(unix)]#[test]fn open_pr_status_dirty_merge_state_reports_conflicts() {let pr = GitHubPrInfo {diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsindex 745cc0def..d92ea904c 100644--- a/src/commands/list/ci_status/mod.rs+++ b/src/commands/list/ci_status/mod.rs@@ -83,8 +83,7 @@ impl CiBranchName {// Re-export public typespub(crate) use cache::{CachedCiStatus, MaxPrNumber};-// Only the `--prs` picker consumes this re-export, and the picker is unix-only.-#[cfg(unix)]+// Only the `--prs` picker consumes this re-export.pub(crate) use github::GitHubPrInfo;/// Maximum number of PRs/MRs to fetch when filtering by source repository.diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 4d7beb46a..934fde900 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -460,7 +460,6 @@ fn worktree_branch_set(worktrees: &[WorktreeInfo]) -> HashSet<&str> {/// The handler receives pre-rendered strings so it doesn't need to share the/// layout across threads (`LayoutConfig` is `!Sync` via an interior/// `Cell<&'static str>`).-#[cfg_attr(not(unix), allow(dead_code))]pub trait PickerProgressHandler: Send + Sync {/// Fired once after items are initialized and layout is computed, but/// before any task results arrive. `rendered` is one entry per item,@@ -512,7 +511,6 @@ pub trait PickerProgressHandler: Send + Sync {}/// Controls how show flags (branches/remotes/full) are determined in [`collect`].-#[cfg_attr(not(unix), allow(dead_code))]pub enum ShowConfig {/// Flags already resolved by the caller (used by the picker).Resolved {diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex 16be5f3e4..ba69b72ce 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -316,7 +316,6 @@ impl DiffDisplayConfig {////// Numbers are right-aligned within a 3-digit column width./// Returns empty spaces if both values are zero.- #[cfg(unix)] // Only used by picker module which is unix-onlypub fn format_aligned(&self, positive: usize, negative: usize) -> String {const DIGITS: usize = 3;let positive_width = 1 + DIGITS; // symbol + digits@@ -532,16 +531,11 @@ pub struct LayoutConfig {/// threads, so renderers running outside `collect` — the picker's `--prs`/// thread — take this snapshot to place their cells on the same grid as the/// worktree rows.-// The grid is built on every platform (`collect` hands it to `on_skeleton`),-// but only the unix-only `--prs` picker reads its columns to align PR rows — so-// the fields/accessor are dead on non-unix.-#[cfg_attr(not(unix), allow(dead_code))]#[derive(Clone, Debug, Default)]pub struct ColumnGrid {pub columns: Vec<GridColumn>,}-#[cfg_attr(not(unix), allow(dead_code))]#[derive(Clone, Copy, Debug)]pub struct GridColumn {pub kind: ColumnKind,@@ -550,7 +544,6 @@ pub struct GridColumn {}impl ColumnGrid {- #[cfg_attr(not(unix), allow(dead_code))]pub fn column(&self, kind: ColumnKind) -> Option<GridColumn> {self.columns.iter().copied().find(|col| col.kind == kind)}diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex a05cfffa4..d7d2bcb7c 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -623,7 +623,6 @@ mod tests {}#[test]- #[cfg(unix)] // format_aligned is unix-onlyfn test_format_aligned_produces_fixed_width_output() {use super::super::columns::DiffVariant;@@ -668,7 +667,6 @@ mod tests {}#[test]- #[cfg(unix)] // format_aligned is unix-onlyfn test_format_aligned_handles_single_side() {use super::super::columns::DiffVariant;diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 906d5b6a2..9b981a33d 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -17,7 +17,6 @@ pub(crate) mod hooks;pub(crate) mod init;pub(crate) mod list;pub(crate) mod merge;-#[cfg(unix)]pub(crate) mod picker;pub(crate) mod pipeline_spec;pub(crate) mod process;@@ -54,7 +53,6 @@ pub(crate) use hook_commands::{HookCliArgs, handle_hook_show, run_hook};pub(crate) use init::{handle_completions, handle_init};pub(crate) use list::handle_list;pub(crate) use merge::{MergeFlagOverrides, MergeOptions, handle_merge};-#[cfg(unix)]pub(crate) use picker::handle_picker;pub(crate) use remove::handle_remove_command;pub(crate) use repository_ext::RemoveTarget;@@ -83,20 +81,6 @@ pub(crate) fn flag_pair(positive: bool, negative: bool) -> Option<bool> {}}-#[cfg(not(unix))]-pub(crate) fn print_windows_picker_unavailable() {- use worktrunk::styling::{error_message, hint_message};-- eprintln!(- "{}",- error_message("Interactive picker is not available on Windows")- );- eprintln!(- "{}",- hint_message(cformat!("Specify a branch: <underline>wt switch BRANCH</>"))- );-}-/// Format command execution label with optional command name.////// Examples:diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rsindex dd4d9e096..ba9a3177e 100644--- a/src/commands/picker/items.rs+++ b/src/commands/picker/items.rs@@ -491,7 +491,7 @@ impl WorktreeSkimItem {/// Render the full preview pane (tab bar + mode content) for an explicit/// `mode`. Split out of [`SkimItem::preview`] so the dispatch — including/// the `pr` tab's `render_pr_pane` call — is testable with a given mode- /// rather than the per-process picker-state file.+ /// rather than the process-wide picker mode.fn render_preview(&self, mode: PreviewMode, width: usize, height: usize) -> String {// Build preview: tabs header + content. `has_upstream` and// `summaries_enabled` are synchronous skeleton-time facts (see@@ -1427,9 +1427,10 @@ mod tests {"description gutter: {pr_pane:?}");- // `SkimItem::preview` reads the default mode (no per-process state file in- // tests → WorkingTree) and delegates to `render_preview`, exercising the- // wrapper and the non-pr dispatch arm (cache miss → loading placeholder).+ // `SkimItem::preview` reads the default in-memory mode (WorkingTree, since+ // no tab switch happens in this test) and delegates to `render_preview`,+ // exercising the wrapper and the non-pr dispatch arm (cache miss → loading+ // placeholder).let ctx = PreviewContext {query: "",cmd_query: "",diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 715001c4c..3f16a1362 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -107,7 +107,7 @@ use std::path::{Path, PathBuf};use std::rc::Rc;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex, OnceLock};-use std::time::{Duration, Instant};+use std::time::Instant;use ansi_str::AnsiStr;use anyhow::Context;@@ -131,7 +131,7 @@ use crate::output::{BackgroundFallbackMode, handle_remove_output};use worktrunk::git::{BranchDeletionMode, delete_branch_if_safe};use items::{PreviewCache, WORKTREE_OUTPUT_PREFIX};-use preview::{PreviewLayout, PreviewMode, PreviewState};+use preview::{PreviewLayout, PreviewMode, PreviewState, PreviewStateData};use preview_orchestrator::PreviewOrchestrator;/// Drain stashed warnings to stderr. Called after skim has released the@@ -649,7 +649,8 @@ pub fn handle_picker(.map(|(terminal_size::Width(w), terminal_size::Height(h))| (w as usize, h as usize)).unwrap_or((80, 24));- // Initialize preview mode state file (auto-cleanup on drop)+ // Reset the preview tab to working-tree and select the layout from the+ // terminal size.let state = PreviewState::new(PreviewLayout::for_dimensions(term_width as f64,term_height as f64,@@ -814,15 +815,11 @@ pub fn handle_picker(render_tx: Arc::clone(&render_tx),};- // Get state path for key bindings (shell-escaped for safety)- let state_path_display = state.path.display().to_string();- let state_path_str = shell_escape::unix::escape(state_path_display.into()).into_owned();-// Half-page preview scroll: half of skim's usable height.let half_page = (preview::available_height(term_height) / 2).max(5);// Configure skim options with Rust-based preview and mode switching keybindings- let options = SkimOptionsBuilder::default()+ let mut options = SkimOptionsBuilder::default().height("90%".to_string()).reverse(true)// Fill the whole selected row with the `current` background (set via@@ -878,85 +875,12 @@ pub fn handle_picker(.color("fg:-1,bg:-1,header:-1,matched:108,current:237,current_bg:251,current_match:108").cmd_collector(Rc::new(RefCell::new(collector)) as Rc<RefCell<dyn CommandCollector>>).bind(vec![- // Preview-tab switching. Bare digits 1-7 are intentionally NOT- // bound — they flow to the query input so a number can be typed- // (a PR number, or digits within a branch name). Two ways to- // switch tabs remain:- // * alt-1..alt-7 jump straight to a tab. skim 4.x parses- // `alt-<digit>` natively via crossterm; an unparsable bind is- // just logged and dropped.- // * tab / shift-tab cycle forward / backward (below).- format!(- "alt-1:execute-silent(echo 1 > {0})+refresh-preview",- state_path_str- ),- format!(- "alt-2:execute-silent(echo 2 > {0})+refresh-preview",- state_path_str- ),- format!(- "alt-3:execute-silent(echo 3 > {0})+refresh-preview",- state_path_str- ),- format!(- "alt-4:execute-silent(echo 4 > {0})+refresh-preview",- state_path_str- ),- format!(- "alt-5:execute-silent(echo 5 > {0})+refresh-preview",- state_path_str- ),- format!(- "alt-6:execute-silent(echo 6 > {0})+refresh-preview",- state_path_str- ),- format!(- "alt-7:execute-silent(echo 7 > {0})+refresh-preview",- state_path_str- ),- // Cycle tabs with tab / shift-tab. The state file holds the current- // digit; `tr` rotates it (1→2→…→7→1 forward, the reverse for btab)- // with wraparound, via a temp file + rename so the read and write- // don't race on one path. Two hard constraints shape this:- // * Paren-free — skim 4.x parses an `execute-silent(…)` body by- // splitting at the first `(` and trimming the trailing `)`, and- // splits the action chain on `+`. So the body must contain no- // `+` and must not end in `)`; `$(...)` / `$(( ))` would do both.- // Keeping it paren-free entirely (the embedded `{0}` temp path- // is — `std::env::temp_dir()` paths have none) satisfies this,- // which the alt-r/alt-N bindings share.- // * Shell-agnostic — skim runs it under the user's $SHELL- // (fish/zsh/sh), so no shell-specific syntax: `tr` + `mv` are- // external and behave identically everywhere.- // This overrides skim's default Tab (toggle-select + cursor down)- // and Shift-Tab (toggle-select + cursor up); `bind` replaces the- // chain wholesale, and both are inert in this single-select picker.+ // Preview-tab switching (alt-1..alt-7 jump to a tab; tab / shift-tab+ // cycle) is installed natively below via `install_preview_tab_keybindings`+ // rather than here — those keys run Rust callbacks, not shell commands.+ // Bare digits 1-7 stay unbound so they flow to the query input (a PR+ // number, or digits within a branch name).//- // Shift-Tab needs three bindings, not one. skim parses `btab` to- // `KeyEvent{BackTab, NONE}`, but crossterm delivers Shift-Tab with- // the SHIFT modifier set, so that lone bind never matches and skim's- // built-in Shift-Tab (cursor up) wins — a back-cycle that silently- // moved the selection instead. skim's own default keymap hedges the- // same ambiguity across `BackTab+SHIFT`, `Tab+SHIFT`, and- // `BackTab+all()`; we bind every representation crossterm might- // report (`btab` / `shift-btab` / `shift-tab`) so the override holds- // regardless of terminal. (Plain Tab is unambiguous — `Tab+NONE`.)- format!(- "tab:execute-silent(tr 1234567 2345671 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",- state_path_str- ),- format!(- "btab:execute-silent(tr 1234567 7123456 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",- state_path_str- ),- format!(- "shift-btab:execute-silent(tr 1234567 7123456 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",- state_path_str- ),- format!(- "shift-tab:execute-silent(tr 1234567 7123456 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",- state_path_str- ),// Create new worktree with query as branch name (alt-c for "create")"alt-c:accept(create)".to_string(),// Remove selected worktree: `reload(remove {})` hands the selected@@ -978,6 +902,10 @@ pub fn handle_picker(// Legend/controls moved to preview window tabs (render_preview_tabs).build().map_err(|e| anyhow::anyhow!("Failed to build skim options: {}", e))?;+ // `.build()` parsed the string binds above into `options.keymap`; layer the+ // preview-tab switches on top as native `Action::Custom` callbacks (skim's+ // string bind API can't express a custom action).+ install_preview_tab_keybindings(&mut options.keymap);worktrunk::trace::instant("Picker skim options built");let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();@@ -1147,7 +1075,7 @@ pub fn handle_picker(// network tasks, and joining would block exit for up to DRAIN_TIMEOUT// (120s). Process exit terminates the bg thread; its git subprocesses// are read-only.- let output = run_skim(options, rx, &render_tx, &state.path);+ let output = run_skim(options, rx, &render_tx);drop(bg_handle);// Same rationale as `bg_handle`: don't join — the forge call may still be// in flight, and process exit terminates the thread (its `gh`/`glab`@@ -1164,7 +1092,7 @@ pub fn handle_picker(// a user cancel is `Ok` with `is_abort` set. Surface a real failure.let out = output?;- // Handle selection (signal file cleaned up by PreviewState::Drop)+ // Handle selectionif !out.is_abort {// Determine action: create (alt-c) or switch (enter)// Remove is handled inline via reload — it never reaches accept.@@ -1225,75 +1153,77 @@ pub fn handle_picker(Ok(())}-/// Background poller that nudges skim to re-run its preview when the-/// preview-mode state file changes. See [`run_skim`] for why; it lives only for-/// one picker session and stops when [`ModeWatcher::stop`] is called.-struct ModeWatcher {- stop: Arc<AtomicBool>,- handle: Option<std::thread::JoinHandle<()>>,-}--impl ModeWatcher {- fn spawn(event_tx: tokio::sync::mpsc::Sender<Event>, path: PathBuf) -> Self {- let stop = Arc::new(AtomicBool::new(false));- let stop_thread = Arc::clone(&stop);- let handle = std::thread::Builder::new()- .name("picker-mode-watcher".into())- .spawn(move || {- // Seed with the current contents so the initial mode isn't- // treated as a change.- let mut last = std::fs::read(&path).ok();- while !stop_thread.load(Ordering::Relaxed) {- std::thread::sleep(Duration::from_millis(20));- let current = std::fs::read(&path).ok();- if current != last {- last = current;- // Channel closed (skim exited) just makes this a no-op;- // the loop then ends on the next `stop` check.- let _ = event_tx.try_send(Event::RunPreview);- }- }- })- .ok();- Self { stop, handle }+/// Install the preview-tab switches into skim's keymap: alt-1…alt-7 jump to a+/// tab, tab / shift-tab cycle forward / backward.+///+/// skim's string bind API only maps keys to its built-in actions, so these go+/// in as `Action::Custom` callbacks that set the process-wide+/// [`PreviewStateData`] mode and return `Event::RunPreview` to repaint. They're+/// native rather than `execute-silent` shell commands, so they behave+/// identically everywhere — the previous `echo`/`tr`/`mv` keybind bodies ran+/// through skim's shell, which on Windows is cmd.exe and has neither `tr` nor+/// `mv`. This is also what lets `wt switch` run its picker on Windows at all.+///+/// Keys are resolved with skim's own `parse_key` so they match exactly what its+/// keymap lookup expects (`KeyMap` is keyed by the crossterm `KeyEvent`+/// `parse_key` produces). Shift-Tab is bound under every spelling crossterm+/// might report (`btab` / `shift-btab` / `shift-tab`), mirroring skim's default+/// keymap, so the cycle-back override holds regardless of terminal.+fn install_preview_tab_keybindings(keymap: &mut skim::binds::KeyMap) {+ use skim::binds::parse_key;++ // alt-N jumps to tab N (1-indexed, matching PreviewMode's discriminant).+ let switch_to = |mode: PreviewMode| {+ Action::Custom(ActionCallback::new_sync(move |_app| {+ PreviewStateData::set_mode(mode);+ Ok(vec![Event::RunPreview])+ }))+ };+ for digit in 1..=7u8 {+ if let Ok(key) = parse_key(&format!("alt-{digit}")) {+ keymap.insert(key, vec![switch_to(PreviewMode::from_u8(digit))]);+ }}- fn stop(mut self) {- self.stop.store(true, Ordering::Relaxed);- if let Some(handle) = self.handle.take() {- let _ = handle.join();+ let cycle = |forward: bool| {+ Action::Custom(ActionCallback::new_sync(move |_app| {+ PreviewStateData::rotate(forward);+ Ok(vec![Event::RunPreview])+ }))+ };+ if let Ok(key) = parse_key("tab") {+ keymap.insert(key, vec![cycle(true)]);+ }+ for back in ["btab", "shift-btab", "shift-tab"] {+ if let Ok(key) = parse_key(back) {+ keymap.insert(key, vec![cycle(false)]);}}}/// Run skim to completion, exposing its event sender for progressive repaints.///-/// This inlines what `Skim::run_with` does, with two additions: after the TUI is-/// initialized we publish `Skim::event_sender()` into `render_tx`, and we start-/// a [`ModeWatcher`]. skim 4.x renders on demand, so the background collect-/// thread's in-place row mutations stay invisible until something wakes the-/// event loop — the handler pushes `Event::Render` through that sender (see-/// `progressive_handler`).-///-/// `preview_mode_path` is the file the alt-1…5 / tab keybinds rewrite to switch-/// preview tabs; `ModeWatcher` re-runs the preview once the write lands, fixing-/// the one-step tab lag skim 0.20's heartbeat used to mask.+/// This inlines what `Skim::run_with` does, plus one addition: after the TUI is+/// initialized we publish `Skim::event_sender()` into `render_tx`. skim 4.x+/// renders on demand, so the background collect thread's in-place row mutations+/// stay invisible until something wakes the event loop — the handler pushes+/// `Event::Render` through that sender (see `progressive_handler`), and the+/// preview-tab keybindings return `Event::RunPreview` from their callbacks.////// `wt` runs no outer tokio runtime, so skim's event loop runs on a fresh/// multi-thread `Runtime` — the same one `run_with` builds in that case. A user/// cancel is `Ok(SkimOutput)` with `is_abort` set; only a genuine init //// event-loop failure is an `Err`.///-/// Injecting `Event::Render` / `Event::RunPreview` from the handler and the-/// watcher is safe against clobbering the recorded selection: skim's `Accept` /-/// `Abort` set `should_quit` in the same `tick` that records them as-/// `final_event`, and `run()` breaks before the next `tick`, so a trailing-/// injected event is never processed after the terminal action.+/// Injecting `Event::Render` / `Event::RunPreview` is safe against clobbering+/// the recorded selection: skim's `Accept` / `Abort` set `should_quit` in the+/// same `tick` that records them as `final_event`, and `run()` breaks before+/// the next `tick`, so a trailing injected event is never processed after the+/// terminal action.fn run_skim(options: SkimOptions,rx: SkimItemReceiver,render_tx: &Arc<OnceLock<tokio::sync::mpsc::Sender<Event>>>,- preview_mode_path: &Path,) -> anyhow::Result<SkimOutput> {let mut skim: Skim = Skim::init(options, Some(rx)).map_err(|e| anyhow::anyhow!("failed to initialize picker: {e}"))?;@@ -1308,21 +1238,14 @@ fn run_skim(.map_err(|e| anyhow::anyhow!("failed to initialize picker TUI: {e}"))?;// event_sender() requires init_tui(); publish it before entering the// loop so the handler's in-place updates can request repaints.- let event_tx = skim.event_sender();- let _ = render_tx.set(event_tx.clone());+ let _ = render_tx.set(skim.event_sender());- // Build the runtime before spawning the watcher: it's the only fallible- // step here, and ordering it first keeps the infallible spawn paired- // with the unconditional `watcher.stop()` below (no early return can- // leak the watcher thread).let runtime =tokio::runtime::Runtime::new().context("failed to start picker event-loop runtime")?;- let watcher = ModeWatcher::spawn(event_tx, preview_mode_path.to_path_buf());let result = runtime.block_on(async {skim.enter().await?;skim.run().await});- watcher.stop();result.map_err(|e| anyhow::anyhow!("interactive picker failed: {e}"))?;}@@ -1362,10 +1285,10 @@ fn resolve_identifier(#[cfg(test)]pub mod tests {use super::items::WorktreeSkimItem;- use super::preview::{PreviewMode, PreviewStateData};use super::{PickerAction, PickerCollector, PickerRemovalTarget, drain_stashed_warnings,- parse_reload_remove_token, picker_item_identifier, resolve_identifier,+ install_preview_tab_keybindings, parse_reload_remove_token, picker_item_identifier,+ resolve_identifier,};use crate::commands::list::model::{ItemKind, ListItem, WorktreeData};use crate::commands::worktree::RemoveResult;@@ -1398,27 +1321,34 @@ pub mod tests {}#[test]- fn test_preview_state_data_roundtrip() {- let state_path = PreviewStateData::state_path();-- // Write and read back various modes- let _ = fs::write(&state_path, "1");- assert_eq!(PreviewStateData::read_mode(), PreviewMode::WorkingTree);-- let _ = fs::write(&state_path, "2");- assert_eq!(PreviewStateData::read_mode(), PreviewMode::Log);-- let _ = fs::write(&state_path, "3");- assert_eq!(PreviewStateData::read_mode(), PreviewMode::BranchDiff);-- let _ = fs::write(&state_path, "4");- assert_eq!(PreviewStateData::read_mode(), PreviewMode::UpstreamDiff);-- let _ = fs::write(&state_path, "5");- assert_eq!(PreviewStateData::read_mode(), PreviewMode::Summary);-- // Cleanup- let _ = fs::remove_file(&state_path);+ fn test_install_preview_tab_keybindings() {+ use skim::binds::{KeyMap, parse_key};+ use skim::prelude::Action;++ // The native preview-tab switches replace skim's default bindings for+ // these keys with exactly one custom action each. This asserts the+ // wiring (keyed via skim's own `parse_key` so the lookup matches its+ // event loop). Which tab each callback selects can't be asserted here+ // (`Action::Custom` has no `Eq`), but the callbacks are built by a+ // uniform `from_u8` loop — `from_u8`/`next`/`prev` are unit-tested in+ // `preview`, and the `switch_picker` PTY tests drive the keys end-to-end.+ let mut keymap = KeyMap::default();+ install_preview_tab_keybindings(&mut keymap);++ let mut specs: Vec<String> = (1..=7).map(|d| format!("alt-{d}")).collect();+ specs.extend(["tab", "btab", "shift-btab", "shift-tab"].map(String::from));+ for spec in specs {+ let key = parse_key(&spec).expect("known key spec parses");+ let chain = keymap+ .get(&key)+ .unwrap_or_else(|| panic!("{spec} not bound"));+ assert_eq!(chain.len(), 1, "{spec} should bind a single action");+ assert!(+ matches!(chain[0], Action::Custom(_)),+ "{spec} should bind a native custom action, got {:?}",+ chain[0]+ );+ }}#[test]diff --git a/src/commands/picker/preview.rs b/src/commands/picker/preview.rsindex b594efacd..5575490c7 100644--- a/src/commands/picker/preview.rs+++ b/src/commands/picker/preview.rs@@ -1,10 +1,9 @@//! Preview mode and layout management.//!-//! Handles preview modes, layout selection, and preview-state persistence for-//! the interactive selector.+//! Tracks the active preview tab (in process memory) and selects the preview+//! layout for the interactive selector.-use std::fs;-use std::path::PathBuf;+use std::sync::atomic::{AtomicU8, Ordering};/// Preview modes for the interactive selector///@@ -54,6 +53,16 @@ impl PreviewMode {_ => Self::WorkingTree,}}++ /// The next tab, wrapping `Comments` → `WorkingTree` (tab key).+ pub(super) fn next(self) -> Self {+ Self::from_u8(if self as u8 >= 7 { 1 } else { self as u8 + 1 })+ }++ /// The previous tab, wrapping `WorkingTree` → `Comments` (shift-tab key).+ pub(super) fn prev(self) -> Self {+ Self::from_u8(if self as u8 <= 1 { 7 } else { self as u8 - 1 })+ }}/// Typical terminal character aspect ratio (width/height).@@ -199,61 +208,60 @@ impl PreviewLayout {}}-/// Preview state persistence (mode only; layout is derived per session, not persisted)+/// The active preview tab, shared across the picker session.+///+/// One picker runs per process, so a single process-wide value is the source of+/// truth: `WorktreeSkimItem::preview` / `PrSkimItem::preview` read it to choose+/// what to render, and the keymap's `Action::Custom` callbacks (installed in+/// `super::install_preview_tab_keybindings`) write it on alt-1…alt-7 / tab /+/// shift-tab, then re-run the preview.///-/// State file format: Single digit representing preview mode (1-6)+/// It lives in memory rather than on disk. Tab switching used to write a digit+/// to a per-process temp file via `echo`/`tr`/`mv` keybind commands, because+/// skim runs keybind commands through a shell and a shell command was the only+/// way to react to a keypress. The native `Action::Custom` path removes that+/// constraint — and with it the file, whose `tr`/`mv` commands skim's Windows+/// shell (cmd.exe) cannot run.+static PREVIEW_MODE: AtomicU8 = AtomicU8::new(PreviewMode::WorkingTree as u8);+pub(super) struct PreviewStateData;impl PreviewStateData {- pub(super) fn state_path() -> PathBuf {- // Use per-process temp file to avoid race conditions when running multiple instances.- // The leaf stays dot-free (the pid is numeric), so the sibling `.tmp`- // file (tab/btab rotate scratch) derived via `with_extension(...)`- // appends rather than replaces an extension, matching the shell- // `{0}.tmp` the keybindings write.- std::env::temp_dir().join(format!("wt-picker-state-{}", std::process::id()))+ /// The active preview tab.+ pub(super) fn read_mode() -> PreviewMode {+ PreviewMode::from_u8(PREVIEW_MODE.load(Ordering::Relaxed))}- /// Read current preview mode from state file- pub(super) fn read_mode() -> PreviewMode {- let state_path = Self::state_path();- fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree)+ /// Jump to a specific tab (alt-1…alt-7).+ pub(super) fn set_mode(mode: PreviewMode) {+ PREVIEW_MODE.store(mode as u8, Ordering::Relaxed);}- pub(super) fn write_mode(mode: PreviewMode) {- let state_path = Self::state_path();- let _ = fs::write(&state_path, format!("{}", mode as u8));+ /// Cycle to the next (`forward`) / previous tab, wrapping around (tab /+ /// shift-tab). Runs on skim's single event-loop thread, so the+ /// load-then-store needs no compare-and-swap.+ pub(super) fn rotate(forward: bool) {+ let current = Self::read_mode();+ Self::set_mode(if forward {+ current.next()+ } else {+ current.prev()+ });}}-/// RAII wrapper for preview state file lifecycle management+/// Per-session preview state: the initial layout (selected once from the+/// terminal size in `handle_picker`). Constructing it also resets+/// [`PreviewStateData`] to the working-tree tab so every picker opens on the+/// same tab.pub(super) struct PreviewState {- pub(super) path: PathBuf,pub(super) initial_layout: PreviewLayout,}impl PreviewState {pub(super) fn new(initial_layout: PreviewLayout) -> Self {- let path = PreviewStateData::state_path();- PreviewStateData::write_mode(PreviewMode::WorkingTree);- Self {- path,- initial_layout,- }- }-}--impl Drop for PreviewState {- fn drop(&mut self) {- let _ = fs::remove_file(&self.path);- // Clean up the rotate scratch file used by tab/shift-tab cycling- // (`tr … > {path}.tmp; mv …` in the keybindings); normally already- // renamed away, but a failed `mv` could leave it behind.- let _ = fs::remove_file(self.path.with_extension("tmp"));+ PreviewStateData::set_mode(PreviewMode::WorkingTree);+ Self { initial_layout }}}@@ -419,68 +427,32 @@ mod tests {}#[test]- fn test_preview_state_data_read_default() {- // Use unique path to avoid interference from parallel tests- let state_path = std::env::temp_dir().join("wt-test-read-default");- let _ = fs::remove_file(&state_path);-- // When state file doesn't exist, read returns default- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::WorkingTree);- }-- #[test]- fn test_preview_state_data_roundtrip() {- // Use unique path to avoid interference from parallel tests- let state_path = std::env::temp_dir().join("wt-test-roundtrip");-- // Write and read back various modes- let _ = fs::write(&state_path, "1");- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::WorkingTree);-- let _ = fs::write(&state_path, "2");- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::Log);-- let _ = fs::write(&state_path, "3");- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::BranchDiff);-- let _ = fs::write(&state_path, "4");- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::UpstreamDiff);-- let _ = fs::write(&state_path, "5");- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::Summary);-- // Cleanup- let _ = fs::remove_file(&state_path);+ fn test_preview_mode_rotation() {+ // tab cycles forward through all seven tabs and wraps; shift-tab is the+ // exact inverse. These drive the tab / shift-tab keybindings.+ let forward: Vec<PreviewMode> =+ std::iter::successors(Some(PreviewMode::WorkingTree), |m| {+ let next = m.next();+ (next != PreviewMode::WorkingTree).then_some(next)+ })+ .collect();+ assert_eq!(+ forward,+ vec![+ PreviewMode::WorkingTree,+ PreviewMode::Log,+ PreviewMode::BranchDiff,+ PreviewMode::UpstreamDiff,+ PreviewMode::Summary,+ PreviewMode::Pr,+ PreviewMode::Comments,+ ]+ );+ assert_eq!(PreviewMode::Comments.next(), PreviewMode::WorkingTree);+ assert_eq!(PreviewMode::WorkingTree.prev(), PreviewMode::Comments);+ for mode in forward {+ assert_eq!(mode.next().prev(), mode);+ }}#[test]diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex 8331ec988..e23ebce1c 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -1680,7 +1680,7 @@ mod tests {#[test]fn preview_renders_tabs_and_placeholder_off_the_pr_tab() {- // With no per-process preview-state file, `read_mode()` returns the+ // No tab switch happens here, so the in-memory `read_mode()` is its// default (WorkingTree) — empty on a --prs row — so `preview()` renders// the shared tab bar plus the "not checked out" placeholder. Drives the// real `SkimItem::preview` (the `--prs` streaming path is too async todiff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex c386b5e50..bab1f7553 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -95,7 +95,6 @@ pub use resolve::{compute_worktree_path, is_worktree_at_expected_path, path_mismatch, resolve_worktree_arg,worktree_display_name,};-#[cfg(unix)]pub(crate) use switch::SwitchPipeline;pub use switch::handle_switch_command;pub use types::{MergeOperations, RemoveResult, SwitchBranchInfo, SwitchResult};diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 5186c94a0..4bd7b42f1 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -1865,26 +1865,14 @@ pub fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()>let change_dir_flag = flag_pair(args.cd, args.no_cd);let Some(branch) = args.branch else {- #[cfg(unix)]- {- return crate::commands::handle_picker(- args.branches,- args.remotes,- args.prs,- change_dir_flag,- args.format,- );- }-- #[cfg(not(unix))]- {- use worktrunk::git::WorktrunkError;- // Suppress unused variable warnings on Windows- let _ = (args.branches, args.remotes, args.prs, change_dir_flag);-- crate::commands::print_windows_picker_unavailable();- return Err(WorktrunkError::AlreadyDisplayed { exit_code: 2 }.into());- }+ // No branch argument: open the interactive picker.+ return crate::commands::handle_picker(+ args.branches,+ args.remotes,+ args.prs,+ change_dir_flag,+ args.format,+ );};run_switch(diff --git a/src/main.rs b/src/main.rsindex e1cdd2500..fbc603702 100644--- a/src/main.rs+++ b/src/main.rs@@ -36,7 +36,6 @@ pub(crate) use invocation::{pub(crate) use crate::cli::{OutputFormat, StatuslineFormat};use commands::commit::HookGate;-#[cfg(unix)]use commands::handle_picker;use commands::worktree::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};use commands::{@@ -668,7 +667,6 @@ fn handle_list_command(args: ListArgs) -> anyhow::Result<()> {}}-#[cfg(unix)]fn handle_select_command(branches: bool, remotes: bool) -> anyhow::Result<()> {// Deprecated: show warning and delegate to handle_pickerwarn_select_deprecated();@@ -676,14 +674,6 @@ fn handle_select_command(branches: bool, remotes: bool) -> anyhow::Result<()> {handle_picker(branches, remotes, false, None, SwitchFormat::Text)}-#[cfg(not(unix))]-fn handle_select_command(_branches: bool, _remotes: bool) -> anyhow::Result<()> {- use worktrunk::git::WorktrunkError;- warn_select_deprecated();- commands::print_windows_picker_unavailable();- Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into())-}-/// Rayon thread count sized for mixed git+network I/O workloads.////// `wt list` and the picker's preview pre-compute both run git subprocessesdiff --git a/src/summary.rs b/src/summary.rsindex ded081539..010b2ef0e 100644--- a/src/summary.rs+++ b/src/summary.rs@@ -332,7 +332,6 @@ pub(crate) fn generate_summary_core(////// This is the TUI-friendly wrapper that returns a formatted string for all cases,/// including errors and "no changes" — suitable for `wt switch` preview pane.-#[cfg_attr(windows, allow(dead_code))] // Called from picker module (unix-only)pub(crate) fn generate_summary(branch: &str,head: &str,diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rsindex 918bfc78a..7f8e763ff 100644--- a/tests/integration_tests/switch_picker.rs+++ b/tests/integration_tests/switch_picker.rs@@ -1141,9 +1141,9 @@ fn test_switch_picker_prs_shows_loading_marker(mut repo: TestRepo) {#[rstest]fn test_switch_picker_preview_cycle_tab_forward(mut repo: TestRepo) {// Tab cycles the preview tab forward. From the default HEAD± tab (1), one- // Tab lands on the log tab (2), proving the `tr 123456 234561` rotation in- // the keybinding runs under the real shell. (alt-1..alt-6 jump directly; the- // panel tests above cover those — this covers the cycle path.)+ // Tab lands on the log tab (2), exercising the native `PreviewMode::next`+ // rotation behind the tab key's `Action::Custom` binding. (alt-1..alt-7 jump+ // directly; the panel tests above cover those — this covers the cycle path.)repo.remove_fixture_worktrees();repo.run_git(&["remote", "remove", "origin"]);let feature_path = repo.add_worktree("feature");@@ -1196,8 +1196,8 @@ fn test_switch_picker_preview_cycle_tab_forward(mut repo: TestRepo) {#[rstest]fn test_switch_picker_preview_cycle_tab_forward_wraps(mut repo: TestRepo) {// Forward cycling wraps 7 → 1: from the comments tab (reached via Alt-7), one- // Tab returns to the HEAD± tab. This covers the `7 → 1` end of the- // `tr 1234567 2345671` map, the half most easily typo'd away.+ // Tab returns to the HEAD± tab. This covers the `7 → 1` wraparound in+ // `PreviewMode::next`, the half most easily typo'd away.repo.remove_fixture_worktrees();repo.run_git(&["remote", "remove", "origin"]);let feature_path = repo.add_worktree("feature");@@ -1255,7 +1255,7 @@ fn test_switch_picker_preview_cycle_tab_forward_wraps(mut repo: TestRepo) {fn test_switch_picker_preview_cycle_shift_tab_wraps(mut repo: TestRepo) {// Shift-Tab cycles backward and wraps: from the default HEAD± tab (1), one// Shift-Tab lands on the comments tab (7), exercising the reverse rotation- // `tr 1234567 7123456` including the 1 → 7 wraparound.+ // `PreviewMode::prev` including the 1 → 7 wraparound.repo.remove_fixture_worktrees();repo.run_git(&["remote", "remove", "origin"]);let feature_path = repo.add_worktree("feature");