Skip to content

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

fix(plugin): make the Codex Windows hook commands parse in PowerShell (#4241)

Worktrunk Bot957d4afd5e0f
diff --git a/plugins/worktrunk/.codex-plugin/plugin.json b/plugins/worktrunk/.codex-plugin/plugin.json
index 14905e3d2..8c398e732 100644
--- a/plugins/worktrunk/.codex-plugin/plugin.json
+++ b/plugins/worktrunk/.codex-plugin/plugin.json
@@ -17,7 +17,7 @@
{
"type": "command",
"command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker set πŸ€– || true",
- "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker set πŸ€– || exit /b 0"
+ "commandWindows": "cmd /d /c call \"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker set πŸ€–"
}
]
}
@@ -29,7 +29,7 @@
{
"type": "command",
"command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker set πŸ’¬ || true",
- "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker set πŸ’¬ || exit /b 0"
+ "commandWindows": "cmd /d /c call \"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker set πŸ’¬"
}
]
}
@@ -40,7 +40,7 @@
{
"type": "command",
"command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker set πŸ’¬ || true",
- "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker set πŸ’¬ || exit /b 0"
+ "commandWindows": "cmd /d /c call \"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker set πŸ’¬"
}
]
}
@@ -51,7 +51,7 @@
{
"type": "command",
"command": "bash \"$PLUGIN_ROOT/hooks/wt.sh\" config state marker clear || true",
- "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker clear || exit /b 0",
+ "commandWindows": "cmd /d /c call \"${PLUGIN_ROOT}\\hooks\\wt.cmd\" config state marker clear",
"timeout": 3
}
]
diff --git a/plugins/worktrunk/hooks/wt.cmd b/plugins/worktrunk/hooks/wt.cmd
index 8e286fd1d..eb2e9e3d1 100644
--- a/plugins/worktrunk/hooks/wt.cmd
+++ b/plugins/worktrunk/hooks/wt.cmd
@@ -1,16 +1,18 @@
@echo off
-rem Windows counterpart of the `bash "$PLUGIN_ROOT/hooks/wt.sh"` that the Unix
-rem hook commands lead with: it finds Git Bash by path, then runs wt.sh through
-rem it, so every integration resolves the worktrunk binary through that one
-rem script.
-rem
-rem Codex runs hook commands through `cmd.exe /C` on Windows, where a bare
-rem `bash` resolves through PATH to System32\bash.exe -- the WSL launcher, not
-rem Git Bash -- and in a sandboxed session refuses to start at all (#4007). Only
-rem the bare name is the problem, so this resolves bash.exe the way find_git_bash
-rem does in src/shell_exec.rs and changes nothing else.
+rem Windows hook entrypoint: find Git Bash by installation path, avoiding the
+rem System32\bash.exe WSL launcher (#4007), then run the shared wt.sh.
rem Usage: wt.cmd [args...]
rem
+rem Codex uses the session shell, so commandWindows must parse in cmd and both
+rem PowerShell editions (#4239). `cmd /d /c call "${PLUGIN_ROOT}\hooks\wt.cmd"`
+rem starts with a command rather than a PowerShell string expression. `call`
+rem avoids cmd's initial-quote stripping; /d disables AutoRun for this cmd hop.
+rem The outer cmd, if Codex uses one, still runs its own AutoRun. A cmd-session
+rem lookup of the bare `cmd` can also resolve an executable in the project cwd.
+rem
+rem Always exit 0: markers are best-effort, and cmd's `|| exit /b 0` cannot live
+rem in the cross-shell command string. Diagnostics still go to stderr.
+rem
rem Every branch here is a bare `goto` or `call`: `if <cond> <cmd1> & <cmd2>`
rem runs cmd2 unconditionally, and `if <cond> <cmd1> || <cmd2>` tests the `if`
rem rather than cmd1, so neither connector can carry the control flow.
@@ -40,7 +42,7 @@ if not defined BASH call :accept "%LOCALAPPDATA%\Programs\Git\bin\bash.exe"
if not defined BASH goto :missing
"%BASH%" "%~dp0wt.sh" %*
-exit /b %ERRORLEVEL%
+exit /b 0
rem %1 is a Git install's cmd\, bin\, or mingw64\bin\ directory, with the
rem trailing separator `%~dpI` leaves on; the last sits a level deeper, so the
@@ -61,4 +63,4 @@ goto :eof
:missing
echo worktrunk: Git for Windows is required but bash.exe was not found. Install from https://git-scm.com/download/win 1>&2
-exit /b 1
+exit /b 0
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 302c15c60..f7cf01a51 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -5631,26 +5631,9 @@ fn test_plugin_layout_is_consolidated() {
}
}
-/// Codex resolves a hook `command` through the platform shell β€” `/bin/sh -lc`
-/// on Unix, `cmd.exe /C` on Windows (`default_shell_command` in
-/// `codex-rs/hooks/src/engine/command_runner.rs`). The Unix commands lead with
-/// `bash "$PLUGIN_ROOT/hooks/wt.sh"`, and under `cmd.exe` that bare `bash`
-/// resolves through the Windows PATH to `System32\bash.exe`, the WSL launcher β€”
-/// not Git Bash. In a sandboxed Codex session the launcher refuses to start
-/// (`Bash/Service/CreateInstance/E_ACCESSDENIED`), so every prompt, permission,
-/// stop, and session-end event raises a "Hook failed" banner (#4007).
-///
-/// Codex's fix for this is the per-handler `commandWindows` override, which
-/// *replaces* `command` on Windows (`command_windows.unwrap_or(command)` in
-/// `codex-rs/hooks/src/engine/discovery.rs`). Every Codex command hook must
-/// carry one, and it must name neither `bash` β€” the WSL launcher, under cmd.exe
-/// β€” nor bare `wt`, which belongs to Windows Terminal on Windows. It calls
-/// `hooks/wt.cmd`, which finds Git Bash *by path* and runs the same `wt.sh`.
-///
-/// Codex substitutes only the braced `${PLUGIN_ROOT}` form textually, before
-/// the shell runs; the unbraced `$PLUGIN_ROOT` survives to the shell and is
-/// expanded only by the Unix `/bin/sh`. `cmd.exe` would pass it through
-/// literally, so the Windows commands must brace it.
+/// Keep Windows-specific Codex commands present and shell-neutral on every platform.
+/// The invocation rationale lives in plugins/worktrunk/hooks/wt.cmd; the Windows
+/// shell-integration test below exercises the commands themselves.
#[test]
fn test_codex_hooks_carry_windows_commands() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
@@ -5682,35 +5665,30 @@ fn test_codex_hooks_carry_windows_commands() {
.as_str()
.expect("each Codex hook must define a command");
let windows = hook["commandWindows"].as_str().unwrap_or_else(|| {
- panic!(
- "Codex hook has no `commandWindows`; on Windows its `command` runs under \
- cmd.exe, where bare `bash` resolves to the WSL launcher rather than Git \
- Bash and fails outright in a sandboxed session (#4007). command:\n{command}"
- )
+ panic!("Codex hook must define commandWindows; command:\n{command}")
});
assert!(
!windows.split_whitespace().any(|word| word == "bash"),
- "`commandWindows` must not name bash β€” cmd.exe resolves that name to the WSL \
- launcher (#4007); the shim finds Git Bash by path instead. commandWindows:\n{windows}"
+ "commandWindows must use the Git Bash shim, not bare bash:\n{windows}"
);
assert!(
!windows
.split_whitespace()
.any(|word| word == "wt" || word == "wt.exe" || word.ends_with("\\wt.exe")),
- "`commandWindows` must not invoke bare `wt` β€” that name resolves to Windows \
- Terminal. commandWindows:\n{windows}"
+ "commandWindows must not invoke Windows Terminal as wt:\n{windows}"
);
assert!(
- windows.contains(r"${PLUGIN_ROOT}\hooks\wt.cmd")
+ windows.starts_with(r#"cmd /d /c call "${PLUGIN_ROOT}\hooks\wt.cmd" "#)
&& root.join("plugins/worktrunk/hooks/wt.cmd").is_file(),
- "`commandWindows` must call the cmd.exe shim that ships beside wt.sh. \
- commandWindows:\n{windows}"
+ "commandWindows must invoke the shipped shim through cmd /d /c call:\n{windows}"
+ );
+ assert!(
+ !windows.contains("||") && !windows.contains('&') && !windows.contains("exit /b"),
+ "commandWindows must leave cmd-only failure handling in the shim:\n{windows}"
);
assert!(
windows.contains("${PLUGIN_ROOT}") && !windows.contains("$PLUGIN_ROOT/"),
- "`commandWindows` must reference the plugin root as ${{PLUGIN_ROOT}}: Codex \
- substitutes only the braced form textually, and cmd.exe would pass the \
- unbraced one through literally. commandWindows:\n{windows}"
+ "commandWindows must use Codex's textual ${{PLUGIN_ROOT}} substitution:\n{windows}"
);
// The Unix side keeps the unbraced form the login shell expands.
assert!(
@@ -5771,32 +5749,31 @@ fn msys_path(path: &std::path::Path) -> String {
)
}
-/// The structural guard above pins that a `commandWindows` exists and avoids
-/// `bash`; this one runs the real one the way Codex does and checks it lands the
-/// marker. Codex spawns `cmd.exe /C "<command>"` with the command line wrapped
-/// in quotes as a single raw argument (`build_command` in
-/// `codex-rs/hooks/src/engine/command_runner.rs`) after substituting the braced
-/// `${PLUGIN_ROOT}` textually (`codex-rs/hooks/src/engine/discovery.rs`), so
-/// this reproduces both steps rather than approximating them.
-///
-/// What that covers beyond the manifest text: cmd.exe's quote handling across
-/// the nested quoting around the shim path, the shim's `goto`-based search for
-/// Git Bash, `wt.sh` running under the bash it picks (which is what needs
-/// `Git\bin\bash.exe`, the wrapper that puts `uname` and friends on PATH for a
-/// caller outside Git Bash), the emoji argument surviving both hops intact, and
-/// the `|| exit /b 0` tail keeping a failed marker best-effort β€” a hook that
-/// exits nonzero is what raises the repeated "Hook failed" banner #4007 reports.
-#[cfg(windows)]
+/// Run the shipped hooks through Codex's cmd /C and PowerShell -Command shapes.
+/// Check marker updates, Unicode arguments, and best-effort failures from a plugin
+/// path containing spaces. PowerShell 7 is required by shell-integration-tests.
+#[cfg(all(windows, feature = "shell-integration-tests"))]
#[rstest]
fn test_codex_windows_hook_commands_set_the_marker(repo: TestRepo) {
use std::os::windows::process::CommandExt;
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
- let plugin_root = root.join("plugins/worktrunk");
let codex: serde_json::Value = serde_json::from_str(
- &fs::read_to_string(plugin_root.join(".codex-plugin/plugin.json")).unwrap(),
+ &fs::read_to_string(root.join("plugins/worktrunk/.codex-plugin/plugin.json")).unwrap(),
)
.unwrap();
+
+ // The shipped shim pair, under a plugin root with a space in it.
+ let plugin_root = repo.root_path().join("plug in");
+ fs::create_dir_all(plugin_root.join("hooks")).unwrap();
+ for name in ["wt.cmd", "wt.sh"] {
+ fs::copy(
+ root.join("plugins/worktrunk/hooks").join(name),
+ plugin_root.join("hooks").join(name),
+ )
+ .unwrap();
+ }
+
let command_for = |event: &str| -> String {
codex["hooks"]["hooks"][event][0]["hooks"][0]["commandWindows"]
.as_str()
@@ -5811,20 +5788,26 @@ fn test_codex_windows_hook_commands_set_the_marker(repo: TestRepo) {
let with_worktrunk = pinned_windows_path(&[path_dir]);
let without_worktrunk = pinned_windows_path(&[]);
- let run_hook = |event: &str, path: &std::ffi::OsString| -> std::process::Output {
- let mut cmd = std::process::Command::new("cmd.exe");
- repo.configure_wt_cmd(&mut cmd);
- cmd.arg("/C")
- .raw_arg(format!("\"{}\"", command_for(event)))
- .env("PATH", path)
- .env_remove("WORKTRUNK_BIN")
- .current_dir(repo.root_path())
- .output()
- .unwrap()
- };
- let describe = |output: &std::process::Output| {
+ let run_hook =
+ |shell: &std::path::Path, event: &str, path: &std::ffi::OsString| -> std::process::Output {
+ let line = command_for(event);
+ let mut cmd = std::process::Command::new(shell);
+ repo.configure_wt_cmd(&mut cmd);
+ if shell.file_name() == Some(std::ffi::OsStr::new("cmd.exe")) {
+ cmd.arg("/C").raw_arg(format!("\"{line}\""));
+ } else {
+ cmd.args(["-NoProfile", "-Command"]).arg(line);
+ }
+ cmd.env("PATH", path)
+ .env_remove("WORKTRUNK_BIN")
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap()
+ };
+ let describe = |shell: &std::path::Path, output: &std::process::Output| {
format!(
- "got {}\nstdout:\n{}\nstderr:\n{}",
+ "under {}, got {}\nstdout:\n{}\nstderr:\n{}",
+ shell.display(),
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
@@ -5842,57 +5825,69 @@ fn test_codex_windows_hook_commands_set_the_marker(repo: TestRepo) {
)
};
- let output = run_hook("UserPromptSubmit", &with_worktrunk);
- assert!(
- output.status.success(),
- "UserPromptSubmit hook must succeed; {}",
- describe(&output)
- );
- assert!(
- marker().contains('πŸ€–'),
- "UserPromptSubmit must store the working marker, not a mangled byte sequence; \
- got {:?}",
- marker()
- );
+ for shell in [
+ which::which("cmd.exe").expect("cmd.exe must be installed"),
+ which::which("powershell.exe").expect("Windows PowerShell must be installed"),
+ which::which("pwsh.exe").expect("shell-integration-tests requires PowerShell 7 on PATH"),
+ ] {
+ let shell = shell.as_path();
- let output = run_hook("Stop", &with_worktrunk);
- assert!(
- output.status.success(),
- "Stop hook must succeed; {}",
- describe(&output)
- );
- assert!(
- marker().contains('πŸ’¬'),
- "Stop must replace the marker with the waiting one; got {:?}",
- marker()
- );
+ let output = run_hook(shell, "UserPromptSubmit", &with_worktrunk);
+ assert!(
+ output.status.success(),
+ "UserPromptSubmit hook must succeed; {}",
+ describe(shell, &output)
+ );
+ assert!(
+ marker().contains('πŸ€–'),
+ "UserPromptSubmit must store the working marker, not a mangled byte sequence; \
+ got {:?} {}",
+ marker(),
+ describe(shell, &output)
+ );
- let output = run_hook("SessionEnd", &with_worktrunk);
- assert!(
- output.status.success(),
- "SessionEnd hook must succeed; {}",
- describe(&output)
- );
- assert!(
- marker().is_empty(),
- "SessionEnd must clear the marker; got {:?}",
- marker()
- );
+ let output = run_hook(shell, "Stop", &with_worktrunk);
+ assert!(
+ output.status.success(),
+ "Stop hook must succeed; {}",
+ describe(shell, &output)
+ );
+ assert!(
+ marker().contains('πŸ’¬'),
+ "Stop must replace the marker with the waiting one; got {:?} {}",
+ marker(),
+ describe(shell, &output)
+ );
- // Worktrunk not installed: the marker is optional decoration, so the hook
- // must stay silent rather than fail every prompt (#4007).
- let output = run_hook("UserPromptSubmit", &without_worktrunk);
- assert!(
- output.status.success(),
- "a hook that cannot find worktrunk must still exit 0 β€” a nonzero exit is what \
- raises Codex's repeated \"Hook failed\" banner; {}",
- describe(&output)
- );
- assert!(
- marker().is_empty(),
- "a failed hook must not invent a marker; got {:?}",
- marker()
- );
+ let output = run_hook(shell, "SessionEnd", &with_worktrunk);
+ assert!(
+ output.status.success(),
+ "SessionEnd hook must succeed; {}",
+ describe(shell, &output)
+ );
+ assert!(
+ marker().is_empty(),
+ "SessionEnd must clear the marker; got {:?} {}",
+ marker(),
+ describe(shell, &output)
+ );
+
+ // Worktrunk not installed: the marker is optional decoration, so the
+ // hook must stay silent rather than fail every prompt (#4007).
+ let output = run_hook(shell, "UserPromptSubmit", &without_worktrunk);
+ assert!(
+ output.status.success(),
+ "a hook that cannot find worktrunk must still exit 0 β€” a nonzero exit is what \
+ raises Codex's repeated \"Hook failed\" banner; {}",
+ describe(shell, &output)
+ );
+ assert!(
+ marker().is_empty(),
+ "a failed hook must not invent a marker; got {:?} {}",
+ marker(),
+ describe(shell, &output)
+ );
+ }
}
/// `wt.sh` assigns `WT` in each of its branches, but on Windows every branch can
@@ -5904,6 +5899,10 @@ fn test_codex_windows_hook_commands_set_the_marker(repo: TestRepo) {
/// `command -v "$WT"` check then accepts it and runs it, in place of the
/// worktrunk the script exists to resolve. Windows Terminal is spelled `wt`,
/// which is exactly the binary the branch above rejects by name.
+///
+/// The shim exits 0 either way β€” that is its hook contract (#4239) β€” so what
+/// separates "declined the inherited `WT`" from "ran it" is the output: no
+/// version line, and the resolution failure named on stderr.
#[cfg(windows)]
#[rstest]
fn test_wt_sh_ignores_an_inherited_wt(repo: TestRepo) {
@@ -5929,12 +5928,12 @@ fn test_wt_sh_ignores_an_inherited_wt(repo: TestRepo) {
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
- !output.status.success() && !stdout.contains("wt "),
+ !stdout.contains("wt ") && stderr.contains("could not find 'wt' in PATH"),
"wt.sh must clear WT and resolve worktrunk itself, not run an inherited one; \
- got {}\nstdout:\n{stdout}\nstderr:\n{}",
+ got {}\nstdout:\n{stdout}\nstderr:\n{stderr}",
output.status,
- String::from_utf8_lossy(&output.stderr)
);
}