Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(tests): give the picker's directive files a temp directory of their own, and make a PTY failure explain itself (#3619)

Maximilian Roos951dac773fe8
diff --git a/src/output/global.rs b/src/output/global.rs
index 2b43deb14..cbfc7e8a2 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -55,6 +55,7 @@ use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Stdio;
+use anyhow::Context as _;
use color_print::cformat;
use std::sync::{Mutex, OnceLock};
@@ -333,7 +334,23 @@ fn warn_exec_scrubbed_once(command: &str) {
}
/// Append a line to a directive file.
-fn append_line(path: &Path, line: &str) -> io::Result<()> {
+///
+/// `what` names the payload for the failure message ("the command", "the cd
+/// command"). The raw `io::Error` names neither the file nor what didn't get
+/// written, and this write runs *last* — after the operation the user asked for
+/// has already landed — so `✗ No such file or directory (os error 2)` on its own
+/// reads as if the command or the worktree were the thing that's missing. These
+/// files belong to the shell wrapper, so the message has to point there.
+fn append_line(path: &Path, line: &str, what: &str) -> anyhow::Result<()> {
+ append_line_io(path, line).with_context(|| {
+ format!(
+ "Failed to write {what} to the directive file {}",
+ path.display()
+ )
+ })
+}
+
+fn append_line_io(path: &Path, line: &str) -> io::Result<()> {
let mut file = OpenOptions::new().append(true).open(path)?;
writeln!(file, "{}", line)?;
file.flush()
@@ -344,7 +361,14 @@ fn append_line(path: &Path, line: &str) -> io::Result<()> {
/// write semantics mean the last writer wins, which matches how overlapping
/// `change_directory()` calls should resolve (hook emits a cd after switch
/// emits its own → hook wins).
-fn write_cd_path(file: &Path, path: &Path) -> io::Result<()> {
+///
+/// A failure names the file, for the reason [`append_line`] does.
+fn write_cd_path(file: &Path, path: &Path) -> anyhow::Result<()> {
+ write_cd_path_io(file, path)
+ .with_context(|| format!("Failed to write the cd directive file {}", file.display()))
+}
+
+fn write_cd_path_io(file: &Path, path: &Path) -> io::Result<()> {
let mut f = OpenOptions::new()
.write(true)
.create(true)
@@ -386,7 +410,9 @@ fn escape_legacy_cd(path: &Path) -> String {
/// a shell `cd '...'` command to the legacy file (legacy compat). In
/// interactive mode (no wrapper), just buffers the target so that a later
/// `execute()` can use it as the child's working directory.
-pub fn change_directory(path: impl AsRef<Path>) -> io::Result<()> {
+///
+/// A write failure names the file it couldn't write — see [`append_line`].
+pub fn change_directory(path: impl AsRef<Path>) -> anyhow::Result<()> {
let path = path.as_ref();
let mode = {
let mut guard = state().lock().expect("OUTPUT_STATE lock poisoned");
@@ -397,12 +423,11 @@ pub fn change_directory(path: impl AsRef<Path>) -> io::Result<()> {
match mode {
DirectiveMode::Interactive => Ok(()),
DirectiveMode::NewProtocol { cd_file, .. } => {
- let directive_path = to_logical_path(path);
- write_cd_path(&cd_file, &directive_path)
+ write_cd_path(&cd_file, &to_logical_path(path))
}
DirectiveMode::Legacy { file } => {
- let directive_path = to_logical_path(path);
- append_line(&file, &escape_legacy_cd(&directive_path))
+ let directive = escape_legacy_cd(&to_logical_path(path));
+ append_line(&file, &directive, "the cd command")
}
}
}
@@ -438,6 +463,8 @@ pub fn was_cwd_removed() -> bool {
/// land here when running inside an alias or hook body, where `Cmd` scrubbed
/// the EXEC var to keep arbitrary shell from reaching the parent session.
/// - Legacy: appends the command to the single legacy directive file.
+///
+/// A failed append names the file it couldn't write — see [`append_line`].
pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
let command = command.into();
@@ -451,20 +478,14 @@ pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
DirectiveMode::NewProtocol {
exec_file: Some(file),
..
- } => {
- append_line(&file, &command)?;
- Ok(())
- }
+ } => append_line(&file, &command, "the command"),
DirectiveMode::NewProtocol {
exec_file: None, ..
} => {
warn_exec_scrubbed_once(&command);
Ok(())
}
- DirectiveMode::Legacy { file } => {
- append_line(&file, &command)?;
- Ok(())
- }
+ DirectiveMode::Legacy { file } => append_line(&file, &command, "the command"),
}
}
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index 502216c25..7bac9932f 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -791,24 +791,45 @@ pub trait TestRepoBase {
}
}
-/// Create a pair of temporary files for directive output (cd + exec).
+/// Create a pair of temporary files for directive output (cd + exec), in a
+/// directory of their own.
///
/// The shell wrapper creates temp files and sets `WORKTRUNK_DIRECTIVE_CD_FILE`
/// and `WORKTRUNK_DIRECTIVE_EXEC_FILE` before running wt. Use
/// `configure_directive_files()` to set these on a Command for testing.
///
-/// Returns `(cd_path, exec_path, guards)`. The guards must be kept alive for
-/// the duration of the test — when dropped the temp files are cleaned up.
-pub fn directive_files() -> (PathBuf, PathBuf, (tempfile::TempPath, tempfile::TempPath)) {
- let cd = tempfile::NamedTempFile::new().expect("failed to create cd temp file");
- let exec = tempfile::NamedTempFile::new().expect("failed to create exec temp file");
- let cd_path = cd.path().to_path_buf();
- let exec_path = exec.path().to_path_buf();
- (
- cd_path,
- exec_path,
- (cd.into_temp_path(), exec.into_temp_path()),
- )
+/// Returns `(cd_path, exec_path, guard)`. The guard must be kept alive for the
+/// duration of the test — dropping it removes the directory and both files.
+pub fn directive_files() -> (PathBuf, PathBuf, TempDir) {
+ let dir = directive_temp_dir();
+ let cd_path = create_empty(dir.path().join("cd"));
+ let exec_path = create_empty(dir.path().join("exec"));
+ (cd_path, exec_path, dir)
+}
+
+/// A private directory for a test's directive files.
+///
+/// Why not `NamedTempFile::new()` (which is what these helpers used to call):
+/// `tempfile` retries a name collision only when it surfaces as
+/// `AlreadyExists`, and on Windows `create_new` against a name already held by
+/// a *directory* — or by a file in delete-pending state — returns
+/// `PermissionDenied` instead, which it hands straight back. A full
+/// suite run leaves the shared temp directory full of `.tmpXXXXXX` entries
+/// (every `TestRepo` creates one), and under that load the call failed ~1% of
+/// the time on Windows CI: `failed to create cd temp file: … Os { code: 5 …
+/// "Access is denied." }`. `TempDir::new` isn't exposed to it — a directory
+/// collision surfaces as `AlreadyExists`, which `tempfile` retries — and the
+/// files inside carry fixed names, which nothing else can collide with.
+fn directive_temp_dir() -> TempDir {
+ TempDir::new().expect("failed to create directive temp dir")
+}
+
+/// Create `path` as an empty file, as the shell wrapper's `mktemp` would, and
+/// return it. wt appends to the exec file rather than creating it, so it has to
+/// exist before wt runs.
+fn create_empty(path: PathBuf) -> PathBuf {
+ std::fs::File::create(&path).expect("failed to create a directive file in its own temp dir");
+ path
}
/// Configure a Command to use the new split directive-file protocol.
@@ -828,14 +849,15 @@ pub fn configure_directive_cd_only(cmd: &mut Command, cd_path: &Path) {
cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", cd_path);
}
-/// Create a temporary file for legacy single-file directive output.
+/// Create a temporary file for legacy single-file directive output, in a
+/// directory of its own (see `directive_temp_dir` for why).
///
/// Used to test the legacy fallback path where an old shell wrapper sets
/// `WORKTRUNK_DIRECTIVE_FILE`. Returns `(path, guard)`.
-pub fn legacy_directive_file() -> (PathBuf, tempfile::TempPath) {
- let file = tempfile::NamedTempFile::new().expect("failed to create temp file");
- let path = file.path().to_path_buf();
- (path, file.into_temp_path())
+pub fn legacy_directive_file() -> (PathBuf, TempDir) {
+ let dir = directive_temp_dir();
+ let path = create_empty(dir.path().join("directive"));
+ (path, dir)
}
/// Configure a Command to use the legacy single-file directive protocol.
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.md
index 68ee3edc6..ea4934725 100644
--- a/tests/CLAUDE.md
+++ b/tests/CLAUDE.md
@@ -273,6 +273,9 @@ Tests run once. Worktrunk configures no nextest `retries` and writes no retry lo
- A racy assertion is a timing bug. Make it deterministic, per Timing Tests above: poll for the event, or drive it causally through a callback.
- Resource pressure is a concurrency bug. Windows process creation intermittently fails with STATUS_DLL_INIT_FAILED (exit `-1073741502`) when many tests spawn git/wt children at once. Bound how many heavy tests run together; that removes the pressure instead of retrying past it.
+- A shared namespace is a collision bug. **Never `NamedTempFile::new()`** for a file a test needs by name: `tempfile` retries a name collision only when it surfaces as `AlreadyExists`, and on Windows `create_new` against a name already held by a *directory* — or by a file in delete-pending state — comes back `PermissionDenied`, which it hands straight back to the caller. A full suite run leaves the temp directory full of `.tmpXXXXXX` entries (every `TestRepo` makes one), and under that load the call fails ~1% of the time with `Access is denied.` — a panic that has nothing to do with what the test asserts. Take a `TempDir` and give the files fixed names inside it (`worktrunk::testing::directive_files` is the pattern); a directory collision surfaces as `AlreadyExists`, which tempfile retries.
+
+**Reproducing a Windows-only flake** means reproducing its *neighbours*, not starving it: run the suspect tests in a loop on a Windows runner with a full `cargo nextest run` going alongside. Pinning the CPU instead models the wrong thing whenever the failing run's own timing was normal (compare its duration against the same test passing — nextest prints it, and the `test` job uploads `junit.xml` with every test's time). Measured both ways on the same five tests: 80 iterations under a concurrent full suite reproduced a 1-in-100 Windows failure that no local run had ever shown, while pinning all four cores with busy loops instead just pushed nearly every iteration past the 30s waits — artificial failures that say nothing about the flake.
## Testing with --execute Commands
diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rs
index fd7f9a428..d93281a89 100644
--- a/tests/integration_tests/directives.rs
+++ b/tests/integration_tests/directives.rs
@@ -210,6 +210,66 @@ fn test_switch_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
});
}
+/// A failed EXEC-directive write names the file and the write.
+///
+/// This write is the last thing a `--switch --execute` does, after the switch
+/// has already landed and after `◎ Executing (--execute):`, so the bare
+/// `io::Error` it used to propagate (`✗ No such file or directory (os error 2)`)
+/// read as if the *command* were missing. The paths come from the shell wrapper,
+/// so the message has to point there.
+#[rstest]
+fn test_exec_directive_write_failure_names_the_file(#[from(repo_with_remote)] mut repo: TestRepo) {
+ let _feature_wt = repo.add_worktree("feature");
+ let (cd_path, exec_path, _guard) = directive_files();
+ // A path under a directory that doesn't exist: the open fails, and nothing
+ // about it depends on platform or timing.
+ let unwritable_exec = exec_path.parent().unwrap().join("no-such-dir").join("exec");
+
+ let mut cmd = repo.wt_command();
+ configure_directive_files(&mut cmd, &cd_path, &unwritable_exec);
+ let output = cmd
+ .args(["switch", "feature", "--execute", "echo hi"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !output.status.success(),
+ "an unwritable exec directive file must fail the command.\nstderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("Failed to write the command to the directive file"),
+ "the error must name the write and the file.\nstderr:\n{stderr}"
+ );
+}
+
+/// A failed CD-directive write names the file too, for the same reason.
+#[rstest]
+fn test_cd_directive_write_failure_names_the_file(#[from(repo_with_remote)] mut repo: TestRepo) {
+ let _feature_wt = repo.add_worktree("feature");
+ let (cd_path, exec_path, _guard) = directive_files();
+ let unwritable_cd = cd_path.parent().unwrap().join("no-such-dir").join("cd");
+
+ let mut cmd = repo.wt_command();
+ configure_directive_files(&mut cmd, &unwritable_cd, &exec_path);
+ let output = cmd
+ .args(["switch", "feature"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !output.status.success(),
+ "an unwritable cd directive file must fail the command.\nstderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("Failed to write the cd directive file"),
+ "the error must name the write and the file.\nstderr:\n{stderr}"
+ );
+}
+
#[rstest]
fn test_merge_directive_file(mut repo_with_remote_and_feature: TestRepo) {
let repo = &mut repo_with_remote_and_feature;
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index 437cdf00f..c3198a01f 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -32,7 +32,7 @@ use insta::assert_snapshot;
use portable_pty::CommandBuilder;
use rstest::rstest;
use std::io::Write;
-use std::path::{Path, PathBuf};
+use std::path::Path;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -53,14 +53,23 @@ const READY_TIMEOUT: Duration = Duration::from_secs(30);
const STABILIZE_TIMEOUT: Duration = Duration::from_secs(30);
/// Maximum time to wait for the picker child to exit after the terminating
-/// keystroke (Enter to switch, Escape to abort) before force-killing it. A clean
-/// switch or abort exits in well under a second, but under heavy CI parallelism
-/// the final git work (or skim's Windows terminal teardown) can lag; killing a
-/// still-finishing child reports exit 1 on Windows, turning a successful-but-slow
-/// switch into a spurious failure. Generous like `READY_TIMEOUT`/`STABILIZE_TIMEOUT`
-/// for the same reason — fast polling means the common case still returns at once.
+/// keystroke (Enter to switch, Escape to abort). A clean switch or abort exits in
+/// well under a second, but under heavy CI parallelism the final git work (or
+/// skim's Windows terminal teardown) can lag. Generous like
+/// `READY_TIMEOUT`/`STABILIZE_TIMEOUT` for the same reason — fast polling means
+/// the common case still returns at once. Reaching it is a hang, and
+/// [`wait_for_exit`] panics rather than reporting an exit code for it.
const CHILD_EXIT_TIMEOUT: Duration = Duration::from_secs(30);
+/// How long the PTY must stay silent after the child exits before its final
+/// frame counts as complete. Long enough that a loaded runner's last flush lands
+/// in the parser; short enough to add no meaningful cost per test.
+const POST_EXIT_QUIET: Duration = Duration::from_millis(250);
+
+/// Ceiling on the post-exit drain, in case something else on the PTY keeps
+/// writing (a detached background hook shares the terminal).
+const POST_EXIT_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
+
/// How long screen must be unchanged to consider it "stable".
/// Must be long enough for preview content to load (preview commands run async).
/// 500ms balances reliability (allows preview to complete) with speed.
@@ -85,6 +94,23 @@ const CURSOR_REISSUE_INTERVAL: Duration = Duration::from_secs(1);
const LIST_WIDTH: u16 = 59;
const PREVIEW_START_COL: u16 = 60;
+/// Full screen content as rows of text.
+///
+/// Trailing whitespace is trimmed from each row because `vt100::rows()` pads
+/// rows to the full column width with spaces. This padding is terminal buffer
+/// fill, not meaningful content, and varies across platforms. Trailing empty
+/// lines are also removed (unwritten terminal rows become empty after trim).
+fn screen_text(parser: &vt100::Parser) -> String {
+ parser
+ .screen()
+ .rows(0, TERM_COLS)
+ .map(|row| row.trim_end().to_string())
+ .collect::<Vec<_>>()
+ .join("\n")
+ .trim_end()
+ .to_string()
+}
+
/// Result of executing a command in a PTY, holding the parsed terminal state.
struct PtyResult {
parser: vt100::Parser,
@@ -92,21 +118,9 @@ struct PtyResult {
}
impl PtyResult {
- /// Full screen content as rows of text.
- ///
- /// Trailing whitespace is trimmed from each row because `vt100::rows()` pads
- /// rows to the full column width with spaces. This padding is terminal buffer
- /// fill, not meaningful content, and varies across platforms. Trailing empty
- /// lines are also removed (unwritten terminal rows become empty after trim).
+ /// Full screen content as rows of text — see [`screen_text`].
fn screen(&self) -> String {
- self.parser
- .screen()
- .rows(0, TERM_COLS)
- .map(|row| row.trim_end().to_string())
- .collect::<Vec<_>>()
- .join("\n")
- .trim_end()
- .to_string()
+ screen_text(&self.parser)
}
/// List and preview panel content, split at the skim border column.
@@ -311,22 +325,58 @@ fn abort_and_exit_code(
}
drop(writer);
+ // Teardown bytes are discarded rather than parsed, so this waits with a
+ // sink parser — the caller's frame was captured before the Escape.
+ let mut sink = vt100::Parser::new(TERM_ROWS, TERM_COLS, 0);
+ wait_for_exit(&mut child, &rx, &mut sink, "Escape")
+}
+
+/// Wait for the picker child to exit, then drain its final output into `parser`
+/// and return its exit code.
+///
+/// A child still running after [`CHILD_EXIT_TIMEOUT`] is hung, and the harness
+/// must not turn that into an exit code: `Child::kill` on Windows is
+/// `TerminateProcess(proc, 1)`, so a killed hang and a wt that failed on its own
+/// both report 1 — the ambiguity that had a *correct* picker-create reported as a
+/// mysterious Windows "self-exit 1" (#3427). Panic on the hang instead, so every
+/// exit code a caller asserts on is one the child chose.
+///
+/// `terminator` names the keystroke that should have ended the session, for the
+/// panic message.
+fn wait_for_exit(
+ child: &mut Box<dyn portable_pty::Child + Send + Sync>,
+ rx: &mpsc::Receiver<Vec<u8>>,
+ parser: &mut vt100::Parser,
+ terminator: &str,
+) -> i32 {
let start = Instant::now();
- // Generous like the keystroke-driven helpers: a slow-but-successful exit that
- // gets killed reports exit 1 on Windows — see `CHILD_EXIT_TIMEOUT`.
- let timeout = CHILD_EXIT_TIMEOUT;
- loop {
- while rx.try_recv().is_ok() {} // discard chunks
+ let mut exited = false;
+ while start.elapsed() < CHILD_EXIT_TIMEOUT {
if child.try_wait().unwrap().is_some() {
+ exited = true;
break;
}
- if start.elapsed() >= timeout {
- let _ = child.kill();
- break;
- }
- std::thread::sleep(Duration::from_millis(10));
+ std::thread::sleep(POLL_INTERVAL);
+ }
+
+ if !exited {
+ let _ = child.kill();
+ let _ = child.wait();
+ drain_until_quiet(rx, parser);
+ panic!(
+ "Picker child did not exit within {CHILD_EXIT_TIMEOUT:?} of {terminator}.\n\
+ Screen content:\n{}",
+ screen_text(parser)
+ );
}
+ // Drain to quiet, not once: `try_wait` reports the child reaped, but its
+ // final writes can still be in the PTY (and in the reader thread) at that
+ // moment, so a single non-blocking sweep drops the tail — which is exactly
+ // where a failing run's explanation lives (wt's error line, the last
+ // warning). Without this the captured frame reads as a silent exit.
+ drain_until_quiet(rx, parser);
+
child.wait().unwrap().exit_code() as i32
}
@@ -367,13 +417,6 @@ fn exec_in_pty_with_input_expectations(
mut parser,
} = boot_picker_pty(command, args, working_dir, env_vars);
- // Helper to drain available output from the channel (non-blocking)
- let drain_output = |rx: &mpsc::Receiver<Vec<u8>>, parser: &mut vt100::Parser| {
- while let Ok(chunk) = rx.try_recv() {
- parser.process(&chunk);
- }
- };
-
// Send each input and wait for screen to stabilize after each
for (input, expected_content) in inputs {
send_input_awaiting_content(&writer, &rx, &mut parser, input, *expected_content);
@@ -381,29 +424,37 @@ fn exec_in_pty_with_input_expectations(
// Release the main thread's writer handle. The reader thread holds the
// other Arc clone until the PTY drains, so this no longer drives stdin EOF.
- // The picker exits on Accept/Escape, or the kill below.
+ // The picker exits on Accept/Escape.
drop(writer);
- // Poll for process exit (fast polling, long timeout for CI)
- let start = std::time::Instant::now();
- let timeout = CHILD_EXIT_TIMEOUT;
- while start.elapsed() < timeout {
- if child.try_wait().unwrap().is_some() {
- break;
- }
- std::thread::sleep(Duration::from_millis(10));
- }
- let _ = child.kill(); // Kill if still running after timeout
-
- // Drain any remaining output
- drain_output(&rx, &mut parser);
-
- let exit_status = child.wait().unwrap();
- let exit_code = exit_status.exit_code() as i32;
+ let exit_code = wait_for_exit(&mut child, &rx, &mut parser, "the last input");
PtyResult { parser, exit_code }
}
+/// Drain the PTY into `parser` until the child's output goes quiet — nothing new
+/// for [`POST_EXIT_QUIET`], or [`POST_EXIT_DRAIN_TIMEOUT`] elapsed.
+///
+/// Used after the child exits, where the goal is a complete final frame rather
+/// than a stable one. The bound keeps a still-chatty PTY (a detached background
+/// hook writing to the same terminal) from holding the test.
+fn drain_until_quiet(rx: &mpsc::Receiver<Vec<u8>>, parser: &mut vt100::Parser) {
+ let start = Instant::now();
+ let mut last_chunk = Instant::now();
+ while start.elapsed() < POST_EXIT_DRAIN_TIMEOUT && last_chunk.elapsed() < POST_EXIT_QUIET {
+ match rx.recv_timeout(POLL_INTERVAL) {
+ Ok(chunk) => {
+ parser.process(&chunk);
+ last_chunk = Instant::now();
+ }
+ Err(mpsc::RecvTimeoutError::Timeout) => {}
+ // Reader thread hit PTY EOF and dropped its sender: nothing more is
+ // coming, and the channel is already empty.
+ Err(mpsc::RecvTimeoutError::Disconnected) => break,
+ }
+ }
+}
+
/// Execute a command in a PTY, capture screen state, then abort with Escape.
///
/// This is the key fix for flaky abort snapshot tests. The problem: snapshotting
@@ -2475,20 +2526,6 @@ fn test_switch_picker_create_validates_templates_before_worktree(mut repo: TestR
);
}
-/// Helper to create temporary directive files for PTY tests.
-/// Returns (cd_path, exec_path, guards) — guards keep the temp files alive.
-fn directive_files_for_pty() -> (PathBuf, PathBuf, (tempfile::TempPath, tempfile::TempPath)) {
- let cd = tempfile::NamedTempFile::new().expect("failed to create cd temp file");
- let exec = tempfile::NamedTempFile::new().expect("failed to create exec temp file");
- let cd_path = cd.path().to_path_buf();
- let exec_path = exec.path().to_path_buf();
- (
- cd_path,
- exec_path,
- (cd.into_temp_path(), exec.into_temp_path()),
- )
-}
-
#[rstest]
fn test_switch_picker_emits_cd_directive_by_default(mut repo: TestRepo) {
repo.remove_fixture_worktrees();
@@ -2497,7 +2534,7 @@ fn test_switch_picker_emits_cd_directive_by_default(mut repo: TestRepo) {
// Create a worktree to switch to
repo.add_worktree("target-branch");
- let (cd_path, exec_path, _guard) = directive_files_for_pty();
+ let (cd_path, exec_path, _guard) = worktrunk::testing::directive_files();
let mut env_vars = repo.test_env_vars();
env_vars.push((
@@ -2516,21 +2553,25 @@ fn test_switch_picker_emits_cd_directive_by_default(mut repo: TestRepo) {
repo.root_path(),
&env_vars,
&[
- // Gate on the preview-pane text that's emitted only once skim's
- // selection has moved to target-branch. Under heavy macOS load
- // skim's matcher (and the row redraw it drives) can lag the typed
- // query, but the preview pane tracks the selection cursor — and
- // Enter acts on the cursor, not on which rows are painted. Gating
- // on the preview text rides that lag instead of racing it
- // (#2334/#2729/#2767).
- ("target", Some("target-branch has no uncommitted changes")),
+ // Cursor-navigation select, gated on the list-pane `>` pointer: the
+ // picker sorts the current worktree first, so one Down lands on
+ // `target-branch`. Typing a query instead would tie the selection to
+ // skim's matcher, whose filtered item list is swapped in during a
+ // *render* while `Accept` reads the cursor's slot directly — so a
+ // query gate can only ever assert what was painted, not what Enter
+ // will act on. The pointer comes from the same render state as the
+ // accept (see `wait_for_cursor_on_row`), and an async row refresh
+ // that resets the cursor is absorbed by the re-issued arrow.
+ ("\x1b[B", Some("target-branch")),
("\r", None), // Enter to switch
],
);
assert_eq!(
- result.exit_code, 0,
- "Expected exit code 0 for successful switch"
+ result.exit_code,
+ 0,
+ "Expected exit code 0 for successful switch.\nScreen:\n{}",
+ result.screen()
);
// Verify CD file DOES contain a path (default behavior)
@@ -2550,7 +2591,7 @@ fn test_switch_picker_no_cd_switches_without_cd_directive(mut repo: TestRepo) {
// Create a worktree to switch to
repo.add_worktree("target-branch");
- let (cd_path, exec_path, _guard) = directive_files_for_pty();
+ let (cd_path, exec_path, _guard) = worktrunk::testing::directive_files();
let mut env_vars = repo.test_env_vars();
env_vars.push((
@@ -2572,21 +2613,21 @@ fn test_switch_picker_no_cd_switches_without_cd_directive(mut repo: TestRepo) {
repo.root_path(),
&env_vars,
&[
- // Preview-pane gate: see test_switch_picker_emits_cd_directive_by_default
- // for the rationale (matcher-driven row redraw can lag the cursor).
- ("target", Some("target-branch has no uncommitted changes")),
+ // Cursor-navigation select: see test_switch_picker_emits_cd_directive_by_default
+ // for why the `>` pointer is the gate rather than a typed query.
+ ("\x1b[B", Some("target-branch")),
("\r", None), // Enter to switch
],
);
+ let screen = result.screen();
assert_eq!(
result.exit_code, 0,
- "Expected exit code 0 for --no-cd switch"
+ "Expected exit code 0 for --no-cd switch.\nScreen:\n{screen}"
);
// The structured result reaches stdout only after execute_switch — the
// old print-only path emitted a bare branch name and never reached it.
- let screen = result.screen();
assert!(
screen.contains("\"action\""),
"Expected --format=json switch result on screen.\nScreen:\n{}",
@@ -2614,7 +2655,7 @@ fn test_switch_picker_runs_execute_command(mut repo: TestRepo) {
repo.run_git(&["remote", "remove", "origin"]);
repo.add_worktree("target-branch");
- let (cd_path, exec_path, _guard) = directive_files_for_pty();
+ let (cd_path, exec_path, _guard) = worktrunk::testing::directive_files();
let mut env_vars = repo.test_env_vars();
env_vars.push((
@@ -2635,18 +2676,21 @@ fn test_switch_picker_runs_execute_command(mut repo: TestRepo) {
repo.root_path(),
&env_vars,
&[
- // Preview-pane gate: see test_switch_picker_emits_cd_directive_by_default.
- ("target", Some("target-branch has no uncommitted changes")),
+ // Cursor-navigation select: see test_switch_picker_emits_cd_directive_by_default.
+ ("\x1b[B", Some("target-branch")),
("\r", None), // Enter to switch
],
);
+ let exec_contents = std::fs::read_to_string(&exec_path).unwrap_or_default();
assert_eq!(
- result.exit_code, 0,
- "Expected exit code 0 for picker switch with --execute"
+ result.exit_code,
+ 0,
+ "Expected exit code 0 for picker switch with --execute.\n\
+ EXEC file: {exec_contents:?}\nScreen:\n{}",
+ result.screen()
);
- let exec_contents = std::fs::read_to_string(&exec_path).unwrap_or_default();
assert!(
exec_contents.contains("picker-exec-ran"),
"EXEC file should contain the --execute command after a picker switch, got: {}",
@@ -2667,7 +2711,7 @@ fn test_switch_picker_execute_base_resolves_to_source(mut repo: TestRepo) {
repo.run_git(&["remote", "remove", "origin"]);
repo.add_worktree("target-branch");
- let (cd_path, exec_path, _guard) = directive_files_for_pty();
+ let (cd_path, exec_path, _guard) = worktrunk::testing::directive_files();
let mut env_vars = repo.test_env_vars();
env_vars.push((
@@ -2686,15 +2730,18 @@ fn test_switch_picker_execute_base_resolves_to_source(mut repo: TestRepo) {
repo.root_path(),
&env_vars,
&[
- ("target", Some("target-branch has no uncommitted changes")),
+ // Cursor-navigation select: see test_switch_picker_emits_cd_directive_by_default.
+ ("\x1b[B", Some("target-branch")),
("\r", None), // Enter to switch
],
);
assert_eq!(
- result.exit_code, 0,
+ result.exit_code,
+ 0,
"picker `-x '{{{{ base }}}}'` should succeed, not error on an undefined \
- value after the switch"
+ value after the switch.\nScreen:\n{}",
+ result.screen()
);
let exec_contents = std::fs::read_to_string(&exec_path).unwrap_or_default();
@@ -2737,8 +2784,8 @@ fn test_switch_picker_pre_switch_hook_requires_approval(mut repo: TestRepo) {
repo.root_path(),
&env_vars,
&[
- // Preview-pane gate: see test_switch_picker_emits_cd_directive_by_default.
- ("target", Some("target-branch has no uncommitted changes")),
+ // Cursor-navigation select: see test_switch_picker_emits_cd_directive_by_default.
+ ("\x1b[B", Some("target-branch")),
("\r", Some("needs approval")), // Enter; wait for the approval prompt
// Decline. The line terminator is CR, not LF: once skim releases the
// terminal, the approval prompt's `read_line` runs in the OS line
@@ -2859,19 +2906,9 @@ fn drive_alt_x_then_switch(
send(&writer, b"\r");
drop(writer);
- // Let the switch finish and the process exit on its own; the kill is a
- // hung-child backstop. The wait is generous because a slow-but-successful
- // exit that gets killed reports exit 1 on Windows — see `CHILD_EXIT_TIMEOUT`.
- let start = Instant::now();
- while start.elapsed() < CHILD_EXIT_TIMEOUT {
- if child.try_wait().unwrap().is_some() {
- break;
- }
- std::thread::sleep(Duration::from_millis(10));
- }
- let _ = child.kill();
- drain(&rx, &mut parser);
- let exit_code = child.wait().unwrap().exit_code() as i32;
+ // Let the switch finish and the process exit on its own — a hang panics
+ // rather than being killed into an exit code (see `wait_for_exit`).
+ let exit_code = wait_for_exit(&mut child, &rx, &mut parser, "Enter");
(row2.to_string(), parser.screen().contents(), exit_code)
}