codex: address PR review feedback (#28120)

This commit is contained in:
Adam Perry
2026-06-13 23:57:54 +00:00
parent 86d138c3fd
commit a8c3e18db3
2 changed files with 212 additions and 152 deletions
+172 -125
View File
@@ -6,9 +6,11 @@ use std::collections::HashMap;
use std::fs;
use std::future::Future;
use std::io::Write;
use std::os::unix::process::ExitStatusExt;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command as StdCommand;
use std::process::Output;
use std::process::Stdio;
use std::time::Duration;
@@ -26,10 +28,10 @@ use tokio::time::timeout;
const ASYNC_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
const BLOCKING_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
const POWERSHELL_COMMAND_TIMEOUT: Duration = Duration::from_secs(30);
const COMMAND_OUTPUT_TIMEOUT: Duration = Duration::from_secs(30);
const POWERSHELL_EXE: &str = r"C:\Program Files\PowerShell\7\pwsh.exe";
enum PowerShellIo {
enum CommandOutputIo {
Pipes,
Pty,
}
@@ -39,6 +41,7 @@ pub struct WineTestCommand {
executable: PathBuf,
args: Vec<OsString>,
env: Vec<(OsString, OsString)>,
output_io: CommandOutputIo,
}
/// Owns a Wine process and its isolated wineserver.
@@ -64,6 +67,12 @@ struct WineRuntimePaths {
wineserver: PathBuf,
}
struct WineOutputEnvironment {
cleanup_complete: bool,
prefix: TempDir,
runtime: WineRuntimePaths,
}
impl WineTestCommand {
/// Creates a Wine command for `executable`.
pub fn new(executable: impl Into<PathBuf>) -> Self {
@@ -71,9 +80,20 @@ impl WineTestCommand {
executable: executable.into(),
args: Vec::new(),
env: Vec::new(),
output_io: CommandOutputIo::Pipes,
}
}
/// Creates a command for the pinned Windows PowerShell runtime.
pub fn powershell(script: impl Into<OsString>) -> Self {
Self::new(POWERSHELL_EXE)
.arg("-NoLogo")
.arg("-NoProfile")
.arg("-NonInteractive")
.arg("-Command")
.arg(script)
}
/// Adds an argument passed to the Windows executable.
#[must_use]
pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
@@ -88,6 +108,116 @@ impl WineTestCommand {
self
}
/// Attaches a PTY when [`Self::output`] runs the command.
#[must_use]
pub fn with_pty(mut self) -> Self {
self.output_io = CommandOutputIo::Pty;
self
}
/// Runs the command to completion and returns its exit status and output.
///
/// Like [`std::process::Command::output`], a non-zero exit is represented
/// by [`Output::status`] rather than returned as an error. The default
/// transport uses ordinary pipes; call [`Self::with_pty`] for console-aware
/// programs. The isolated Wine prefix and wineserver are always torn down
/// before this method returns.
pub async fn output(self) -> Result<Output> {
let runtime = WineRuntimePaths::from_runfiles()?;
let prefix = TempDir::new().context("create isolated Wine prefix")?;
install_powershell_runtime(prefix.path(), &runtime.powershell_runtime)?;
let mut environment = WineOutputEnvironment {
cleanup_complete: false,
prefix,
runtime,
};
let mut env = wine_environment(&environment.runtime, environment.prefix.path());
for (key, value) in self.env {
let key = key
.into_string()
.map_err(|key| anyhow::anyhow!("Wine environment key is not UTF-8: {key:?}"))?;
let value = value.into_string().map_err(|value| {
anyhow::anyhow!("Wine environment value for {key} is not UTF-8: {value:?}")
})?;
env.insert(key, value);
}
let wine = environment.runtime.wine.to_string_lossy().into_owned();
let args = std::iter::once(self.executable.into_os_string())
.chain(self.args)
.map(|argument| {
argument
.into_string()
.map_err(|argument| anyhow::anyhow!("Wine argument is not UTF-8: {argument:?}"))
})
.collect::<Result<Vec<_>>>()?;
let spawned = match self.output_io {
CommandOutputIo::Pipes => {
spawn_pipe_process_no_stdin(
&wine,
&args,
environment.prefix.path(),
&env,
/*arg0*/ &None,
)
.await?
}
CommandOutputIo::Pty => {
spawn_pty_process(
&wine,
&args,
environment.prefix.path(),
&env,
/*arg0*/ &None,
TerminalSize::default(),
)
.await?
}
};
let SpawnedProcess {
session,
mut stdout_rx,
mut stderr_rx,
exit_rx,
} = spawned;
let command_result = timeout(COMMAND_OUTPUT_TIMEOUT, async {
let stdout = async {
let mut output = Vec::new();
while let Some(chunk) = stdout_rx.recv().await {
output.extend(chunk);
}
output
};
let stderr = async {
let mut output = Vec::new();
while let Some(chunk) = stderr_rx.recv().await {
output.extend(chunk);
}
output
};
let (stdout, stderr, exit_code) = tokio::join!(stdout, stderr, exit_rx);
let exit_code = exit_code.context("wait for Wine command")?;
Ok(Output {
status: std::process::ExitStatus::from_raw(exit_code << 8),
stdout,
stderr,
})
})
.await
.context("Wine command timed out")
.and_then(std::convert::identity);
drop(session);
let shutdown_result = environment.shutdown().await;
match (command_result, shutdown_result) {
(Ok(output), Ok(())) => Ok(output),
(Err(error), Ok(())) => Err(error),
(Ok(_), Err(error)) => Err(error),
(Err(error), Err(shutdown_error)) => {
Err(error.context(format!("Wine teardown also failed: {shutdown_error:#}")))
}
}
}
/// Starts the Windows executable with a fresh `WINEPREFIX`.
pub fn spawn(self) -> Result<WineTestProcess> {
let runtime = WineRuntimePaths::from_runfiles()?;
@@ -120,116 +250,6 @@ impl WineTestCommand {
}
}
/// Runs `script` with the pinned Windows PowerShell runtime under Wine.
///
/// This is the simpler non-terminal path. Use [`run_powershell_with_pty`] when
/// the code under test changes behavior after detecting a console or needs its
/// output. Wine does not relay PowerShell's console output through ordinary
/// Unix pipes, so this helper reports command success without returning output.
pub async fn run_powershell(script: &str) -> Result<()> {
run_powershell_with_io(script, PowerShellIo::Pipes)
.await
.map(drop)
}
/// Runs `script` with the pinned Windows PowerShell runtime attached to a PTY.
///
/// Wine console programs can select different I/O paths when their standard
/// handles are terminal handles, so this helper exercises that behavior while
/// retaining the same isolated prefix and runtime as [`run_powershell`].
pub async fn run_powershell_with_pty(script: &str) -> Result<String> {
run_powershell_with_io(script, PowerShellIo::Pty).await
}
async fn run_powershell_with_io(script: &str, io: PowerShellIo) -> Result<String> {
let runtime = WineRuntimePaths::from_runfiles()?;
let prefix = TempDir::new().context("create isolated Wine prefix")?;
install_powershell_runtime(prefix.path(), &runtime.powershell_runtime)?;
let env = wine_environment(&runtime, prefix.path());
let wine = runtime.wine.to_string_lossy().into_owned();
let args = std::iter::once(POWERSHELL_EXE.to_string())
.chain(
powershell_arguments(script)
.into_iter()
.map(|argument| argument.to_string_lossy().into_owned()),
)
.collect::<Vec<_>>();
let spawned = match io {
PowerShellIo::Pipes => {
spawn_pipe_process_no_stdin(
&wine,
&args,
prefix.path(),
&env,
/*arg0*/ &None,
)
.await?
}
PowerShellIo::Pty => {
spawn_pty_process(
&wine,
&args,
prefix.path(),
&env,
/*arg0*/ &None,
TerminalSize::default(),
)
.await?
}
};
let SpawnedProcess {
session,
mut stdout_rx,
mut stderr_rx,
exit_rx,
} = spawned;
let stderr_task = tokio::spawn(async move { while stderr_rx.recv().await.is_some() {} });
let command_result = timeout(POWERSHELL_COMMAND_TIMEOUT, async {
let mut output = Vec::new();
while let Some(chunk) = stdout_rx.recv().await {
output.extend(chunk);
}
let exit_code = exit_rx.await.context("wait for PowerShell")?;
anyhow::ensure!(exit_code == 0, "PowerShell exited with {exit_code}");
String::from_utf8(output).context("decode PowerShell output as UTF-8")
})
.await
.context("PowerShell command timed out")
.and_then(std::convert::identity);
drop(session);
stderr_task.abort();
let shutdown_result = timeout(ASYNC_SHUTDOWN_TIMEOUT, async {
let mut stop_wineserver = StdCommand::new(&runtime.wineserver);
configure_wine_environment(&mut stop_wineserver, &runtime, prefix.path());
stop_wineserver.args(["-k", "-w"]);
let mut stop_wineserver = TokioCommand::from(stop_wineserver);
stop_wineserver.kill_on_drop(true);
let status = stop_wineserver
.status()
.await
.context("stop isolated wineserver")?;
// PTY session teardown may already have stopped the server. Wine uses
// status 1 for that harmless no-server case.
anyhow::ensure!(
status.success() || status.code() == Some(1),
"wineserver exited with {status}"
);
Ok::<_, anyhow::Error>(())
})
.await
.context("stop isolated wineserver timed out")
.and_then(std::convert::identity);
match (command_result, shutdown_result) {
(Ok(output), Ok(())) => Ok(output),
(Err(error), Ok(())) => Err(error),
(Ok(_), Err(error)) => Err(error),
(Err(error), Err(shutdown_error)) => {
Err(error.context(format!("Wine teardown also failed: {shutdown_error:#}")))
}
}
}
impl WineTestProcess {
/// Takes the piped standard output of the Wine process.
///
@@ -306,6 +326,46 @@ impl WineRuntimePaths {
}
}
impl WineOutputEnvironment {
async fn shutdown(&mut self) -> Result<()> {
let mut command = self.wineserver_command();
command.args(["-k", "-w"]);
let mut command = TokioCommand::from(command);
command.kill_on_drop(true);
let status = timeout(ASYNC_SHUTDOWN_TIMEOUT, command.status())
.await
.context("stop isolated wineserver timed out")?
.context("stop isolated wineserver")?;
// The process adapter may already have stopped the server. Wine uses
// status 1 for that harmless no-server case.
anyhow::ensure!(
status.success() || status.code() == Some(1),
"wineserver exited with {status}"
);
self.cleanup_complete = true;
Ok(())
}
fn wineserver_command(&self) -> StdCommand {
let mut command = StdCommand::new(&self.runtime.wineserver);
configure_wine_environment(&mut command, &self.runtime, self.prefix.path());
command
.stdout(Stdio::null())
.stderr(Stdio::null());
command
}
}
impl Drop for WineOutputEnvironment {
fn drop(&mut self) {
if !self.cleanup_complete {
let mut command = self.wineserver_command();
command.arg("-k");
let _ = command.status();
}
}
}
impl WineProcesses {
async fn shutdown(&mut self) -> Result<()> {
let (kill_result, check_exit_status) = match self.child.try_wait() {
@@ -497,19 +557,6 @@ fn wine_environment(runtime: &WineRuntimePaths, prefix: &Path) -> HashMap<String
env
}
fn powershell_arguments(script: &str) -> Vec<OsString> {
[
"-NoLogo",
"-NoProfile",
"-NonInteractive",
"-Command",
script,
]
.into_iter()
.map(OsString::from)
.collect()
}
/// Installs the complete pinned PowerShell distribution where Windows tooling
/// expects to discover PowerShell 7.
///
+40 -27
View File
@@ -18,8 +18,6 @@ use tokio::process::Command as TokioCommand;
use super::WineTestCommand;
use super::WineTestProcess;
use super::install_powershell_runtime;
use super::run_powershell;
use super::run_powershell_with_pty;
// The marker makes the assertion resilient to Wine or PTY startup chatter.
const POWERSHELL_SMOKE_MARKER: &str = "WINE_PWSH_SMOKE";
@@ -40,28 +38,6 @@ const POWERSHELL_SMOKE_SCRIPT: &str = concat!(
"$IsWindows.ToString().ToLowerInvariant() + '|' + $separatorCode)",
);
fn assert_powershell_smoke_output(output: &str) -> Result<()> {
let marker_start = output
.find(POWERSHELL_SMOKE_MARKER)
.with_context(|| format!("PowerShell smoke marker was missing from {output:?}"))?;
let smoke = output[marker_start..]
.lines()
.next()
.context("PowerShell smoke marker line was incomplete")?
.trim_end_matches('\r');
let fields = smoke.split('|').collect::<Vec<_>>();
assert_eq!(fields.len(), 5, "unexpected PowerShell smoke output: {smoke}");
assert_eq!(fields[0], POWERSHELL_SMOKE_MARKER);
assert_eq!(
fields[1].split('.').next(),
Some("7"),
"expected PowerShell 7.x, got {}",
fields[1],
);
assert_eq!(&fields[2..], &["Core", "true", "92"]);
Ok(())
}
async fn waiting_smoke_process() -> Result<WineTestProcess> {
let executable = codex_utils_cargo_bin::cargo_bin("wine-smoke")?;
let mut process = WineTestCommand::new(executable).arg("--wait").spawn()?;
@@ -303,11 +279,48 @@ fn powershell_runtime_is_materialized_at_the_windows_fallback_path() -> Result<(
#[tokio::test]
async fn pinned_powershell_runs_without_a_pty_under_wine() -> Result<()> {
run_powershell(POWERSHELL_SMOKE_SCRIPT).await
let output = WineTestCommand::powershell(POWERSHELL_SMOKE_SCRIPT)
.output()
.await?;
assert!(
output.status.success(),
"PowerShell failed; stdout: {}; stderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
Ok(())
}
#[tokio::test]
async fn pinned_powershell_runs_with_a_pty_under_wine() -> Result<()> {
let output = run_powershell_with_pty(POWERSHELL_SMOKE_SCRIPT).await?;
assert_powershell_smoke_output(&output)
let output = WineTestCommand::powershell(POWERSHELL_SMOKE_SCRIPT)
.with_pty()
.output()
.await?;
assert!(
output.status.success(),
"PowerShell failed; stdout: {}; stderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
let output = String::from_utf8(output.stdout)?;
let marker_start = output
.find(POWERSHELL_SMOKE_MARKER)
.with_context(|| format!("PowerShell smoke marker was missing from {output:?}"))?;
let smoke = output[marker_start..]
.lines()
.next()
.context("PowerShell smoke marker line was incomplete")?
.trim_end_matches('\r');
let fields = smoke.split('|').collect::<Vec<_>>();
assert_eq!(fields.len(), 5, "unexpected PowerShell smoke output: {smoke}");
assert_eq!(fields[0], POWERSHELL_SMOKE_MARKER);
assert_eq!(
fields[1].split('.').next(),
Some("7"),
"expected PowerShell 7.x, got {}",
fields[1],
);
assert_eq!(&fields[2..], &["Core", "true", "92"]);
Ok(())
}