mirror of
https://github.com/openai/codex.git
synced 2026-12-04 00:51:02 +00:00
Preserve the exit summary when Ctrl+C is pressed again on Windows (#65038)
## Why Once the TUI restores the terminal, another Ctrl+C becomes a Windows console event and can terminate Codex before it prints the exit summary, including the resume hint when available. The npm launcher can also force-terminate the child by forwarding a Ctrl+C that Windows already delivered to it. ## What changed Register a Windows Ctrl+C listener before restoring the terminal and keep it alive until the CLI or standalone TUI finishes printing the exit summary. Skip forwarding `SIGINT` from the npm launcher on Windows. ## Testing Add a Windows regression test that simulates `SIGINT` in the npm launcher and checks that the child can finish and report its own exit code. GitOrigin-RevId: cd73a4a2ecc22812bc301787e67c349f7720a93b
This commit is contained in:
@@ -261,6 +261,11 @@ child.on("error", (err) => {
|
||||
// Keep forwarding signals until the child exits so a second signal can
|
||||
// interrupt a graceful shutdown.
|
||||
const forwardSignal = (signal) => {
|
||||
// Windows sends console Ctrl+C to the child too. child.kill("SIGINT")
|
||||
// would force-terminate it even if it handles the console event.
|
||||
if (process.platform === "win32" && signal === "SIGINT") {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
child.kill(signal);
|
||||
} catch {
|
||||
|
||||
@@ -17,10 +17,15 @@ import test from "node:test";
|
||||
|
||||
async function installWrapper(directory, executable) {
|
||||
const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
|
||||
const target = `${arch}-${process.platform === "darwin" ? "apple-darwin" : "unknown-linux-musl"}`;
|
||||
const platform = { darwin: "apple-darwin", win32: "pc-windows-msvc" };
|
||||
const target = `${arch}-${platform[process.platform] ?? "unknown-linux-musl"}`;
|
||||
const bin = path.join(directory, "vendor", target, "bin");
|
||||
await mkdir(bin, { recursive: true });
|
||||
await symlink(executable, path.join(bin, "codex"));
|
||||
if (process.platform === "win32") {
|
||||
await copyFile(executable, path.join(bin, "codex.exe"));
|
||||
} else {
|
||||
await symlink(executable, path.join(bin, "codex"));
|
||||
}
|
||||
await mkdir(path.join(directory, "bin"));
|
||||
await writeFile(path.join(directory, "package.json"), '{"type":"module"}');
|
||||
const wrapper = path.join(directory, "bin", "codex.js");
|
||||
@@ -28,6 +33,39 @@ async function installWrapper(directory, executable) {
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
test(
|
||||
"Windows console SIGINT lets the child finish and report its exit code",
|
||||
{ skip: process.platform !== "win32" },
|
||||
async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "codex-npm-signal-"));
|
||||
try {
|
||||
const wrapper = await installWrapper(directory, process.execPath);
|
||||
// Deliver SIGINT to the launcher without signaling the test runner's console.
|
||||
const preload = path.join(directory, "interrupt.cjs");
|
||||
await writeFile(
|
||||
preload,
|
||||
'process.once("message", () => { process.emit("SIGINT"); process.send("done"); });',
|
||||
);
|
||||
const launcher = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
"--require",
|
||||
preload,
|
||||
wrapper,
|
||||
"-e",
|
||||
'process.stdin.once("data", () => process.exit(17)); console.log("ready");',
|
||||
],
|
||||
{ stdio: ["pipe", "pipe", "inherit", "ipc"], timeout: 10_000 },
|
||||
);
|
||||
launcher.stdout.once("data", () => launcher.send("interrupt"));
|
||||
launcher.once("message", () => launcher.stdin.end("finish"));
|
||||
assert.deepEqual(await once(launcher, "exit"), [17, null]);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
"the npm spawn fallback forwards a second SIGTERM to a running child",
|
||||
{ skip: process.platform === "win32" },
|
||||
|
||||
@@ -782,10 +782,7 @@ fn handle_app_exit(
|
||||
eprintln!("{warning}");
|
||||
}
|
||||
} else {
|
||||
let color_enabled = codex_tui::stdout_supports_color();
|
||||
for line in exit_info.format_exit_messages(color_enabled) {
|
||||
println!("{line}");
|
||||
}
|
||||
exit_info.print_exit_messages();
|
||||
}
|
||||
if is_fatal {
|
||||
std::io::stdout().flush()?;
|
||||
@@ -3842,24 +3839,13 @@ enabled = true
|
||||
thread_id,
|
||||
thread_name: thread_name.map(str::to_string),
|
||||
}),
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_exit_messages_skips_zero_usage() {
|
||||
let exit_info = AppExitInfo {
|
||||
token_usage: TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
};
|
||||
let exit_info = AppExitInfo::default();
|
||||
let lines = exit_info.format_exit_messages(/*color_enabled*/ false);
|
||||
assert!(lines.is_empty());
|
||||
}
|
||||
@@ -3913,13 +3899,9 @@ enabled = true
|
||||
#[test]
|
||||
fn format_exit_messages_includes_session_id_for_fatal_exit_without_resume_hint() {
|
||||
let exit_info = AppExitInfo {
|
||||
token_usage: TokenUsage::default(),
|
||||
thread_id: Some(ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap()),
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::Fatal("boom".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
let lines = exit_info.format_exit_messages(/*color_enabled*/ false);
|
||||
assert_eq!(
|
||||
|
||||
@@ -496,8 +496,11 @@ impl AutoReviewMode {
|
||||
/// perceived typing speed for non-backlogged output.
|
||||
const COMMIT_ANIMATION_TICK: Duration = tui::TARGET_FRAME_INTERVAL;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct AppExitInfo {
|
||||
/// Keep Windows console Ctrl+C handled until the exit summary is printed.
|
||||
#[cfg(windows)]
|
||||
pub shutdown_ctrl_c: Option<Arc<tokio::signal::windows::CtrlC>>,
|
||||
pub token_usage: TokenUsage,
|
||||
pub thread_id: Option<ThreadId>,
|
||||
pub resume_hint: Option<ResumableThread>,
|
||||
@@ -510,13 +513,8 @@ pub struct AppExitInfo {
|
||||
impl AppExitInfo {
|
||||
pub fn fatal(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
token_usage: TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::Fatal(message.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -536,8 +534,9 @@ pub(crate) enum AppRunControl {
|
||||
Exit(ExitReason),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub enum ExitReason {
|
||||
#[default]
|
||||
UserRequested,
|
||||
TurnInterrupted,
|
||||
Fatal(String),
|
||||
|
||||
@@ -86,14 +86,27 @@ impl App {
|
||||
self.chat_widget.rollout_path().as_deref(),
|
||||
),
|
||||
disconnect_info,
|
||||
archive_warnings: Vec::new(),
|
||||
update_action: self.pending_update_action,
|
||||
exit_reason,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AppExitInfo {
|
||||
#[expect(
|
||||
clippy::print_stdout,
|
||||
reason = "The terminal is restored before the CLI prints the exit summary."
|
||||
)]
|
||||
pub fn print_exit_messages(self) {
|
||||
// Formatting consumes self. Keep the listener alive through the last write.
|
||||
#[cfg(windows)]
|
||||
let _shutdown_ctrl_c = self.shutdown_ctrl_c.clone();
|
||||
for line in self.format_exit_messages(crate::stdout_supports_color()) {
|
||||
println!("{line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Format the terminal summary for both the CLI and standalone TUI binaries.
|
||||
pub fn format_exit_messages(self, color_enabled: bool) -> Vec<String> {
|
||||
let color_command = |command: String| {
|
||||
|
||||
@@ -2096,6 +2096,15 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
};
|
||||
let mut info = app.exit_info(exit_reason);
|
||||
info.archive_warnings = archive_warnings;
|
||||
// Once raw mode is disabled, a second Ctrl+C becomes a console event.
|
||||
// Subscribe before that handoff and keep the listener through the final write.
|
||||
#[cfg(windows)]
|
||||
if info.update_action.is_none() {
|
||||
info.shutdown_ctrl_c = tokio::signal::windows::ctrl_c()
|
||||
.inspect_err(|err| tracing::warn!("failed to handle Ctrl+C during exit: {err}"))
|
||||
.ok()
|
||||
.map(Arc::new);
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,15 +387,7 @@ pub(super) async fn handle_model_migration_prompt_if_needed(
|
||||
});
|
||||
}
|
||||
ModelMigrationOutcome::Exit => {
|
||||
return Ok(Some(AppExitInfo {
|
||||
token_usage: TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
}));
|
||||
return Ok(Some(AppExitInfo::default()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-62
@@ -1139,15 +1139,9 @@ pub async fn run_main(
|
||||
))
|
||||
.await
|
||||
{
|
||||
Err(err) if startup_draft::StartupCancelled::matches(&err) => Ok(AppExitInfo {
|
||||
token_usage: TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
}),
|
||||
Err(err) if startup_draft::StartupCancelled::matches(&err) => {
|
||||
Ok(AppExitInfo::default())
|
||||
}
|
||||
Err(err) => {
|
||||
restore_terminal_before_fatal_exit();
|
||||
Err(err)
|
||||
@@ -1232,13 +1226,8 @@ async fn run_ratatui_app(
|
||||
terminal_restore_guard.restore()?;
|
||||
launch_telemetry.record("update_requested");
|
||||
return Ok(AppExitInfo {
|
||||
token_usage: crate::token_usage::TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: Some(action),
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1436,15 +1425,7 @@ async fn run_ratatui_app(
|
||||
if onboarding_result.should_exit {
|
||||
shutdown_startup_session(app_server.take(), &mut terminal_restore_guard).await;
|
||||
let _ = tui.terminal.clear();
|
||||
return Ok(AppExitInfo {
|
||||
token_usage: crate::token_usage::TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
});
|
||||
return Ok(AppExitInfo::default());
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
@@ -1576,17 +1557,9 @@ async fn run_ratatui_app(
|
||||
terminal_restore_guard.restore_silently();
|
||||
session_log::log_session_end();
|
||||
let _ = tui.terminal.clear();
|
||||
Ok(AppExitInfo {
|
||||
token_usage: crate::token_usage::TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::Fatal(format!(
|
||||
"No saved session found with ID {id_str}. Run `codex {action}` without an ID to choose from existing sessions."
|
||||
)),
|
||||
})
|
||||
Ok(AppExitInfo::fatal(format!(
|
||||
"No saved session found with ID {id_str}. Run `codex {action}` without an ID to choose from existing sessions."
|
||||
)))
|
||||
};
|
||||
|
||||
crate::markdown_render::preferences::init(local_settings.tui.rendering);
|
||||
@@ -1693,15 +1666,7 @@ async fn run_ratatui_app(
|
||||
resume_picker::SessionSelection::Exit => {
|
||||
terminal_restore_guard.restore_silently();
|
||||
session_log::log_session_end();
|
||||
return Ok(AppExitInfo {
|
||||
token_usage: crate::token_usage::TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
});
|
||||
return Ok(AppExitInfo::default());
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
@@ -1798,15 +1763,7 @@ async fn run_ratatui_app(
|
||||
resume_picker::SessionSelection::Exit => {
|
||||
terminal_restore_guard.restore_silently();
|
||||
session_log::log_session_end();
|
||||
return Ok(AppExitInfo {
|
||||
token_usage: crate::token_usage::TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
});
|
||||
return Ok(AppExitInfo::default());
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
@@ -1851,15 +1808,7 @@ async fn run_ratatui_app(
|
||||
Ok(ResolveCwdOutcome::Exit) => {
|
||||
terminal_restore_guard.restore_silently();
|
||||
session_log::log_session_end();
|
||||
return Ok(AppExitInfo {
|
||||
token_usage: crate::token_usage::TokenUsage::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
});
|
||||
return Ok(AppExitInfo::default());
|
||||
}
|
||||
Err(err) => {
|
||||
terminal_restore_guard.restore_silently();
|
||||
|
||||
@@ -45,10 +45,7 @@ fn main() -> anyhow::Result<()> {
|
||||
ExitReason::UserRequested | ExitReason::TurnInterrupted => false,
|
||||
};
|
||||
|
||||
let color_enabled = codex_tui::stdout_supports_color();
|
||||
for line in exit_info.format_exit_messages(color_enabled) {
|
||||
println!("{line}");
|
||||
}
|
||||
exit_info.print_exit_messages();
|
||||
if is_fatal {
|
||||
std::io::stdout().flush()?;
|
||||
std::process::exit(1);
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
//! Retries preserve the launch-resolved local presentation settings from the first attempt.
|
||||
|
||||
use crate::app::AppExitInfo;
|
||||
use crate::app::ExitReason;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::app_server_session::AppServerStartedThread;
|
||||
use crate::app_server_session::ForkPermissionMode;
|
||||
@@ -122,15 +121,7 @@ pub(crate) async fn cancel_session_start(app_server: AppServerSession) -> AppExi
|
||||
if let Err(err) = app_server.shutdown().await {
|
||||
tracing::warn!("app-server shutdown failed: {err}");
|
||||
}
|
||||
AppExitInfo {
|
||||
token_usage: Default::default(),
|
||||
thread_id: None,
|
||||
resume_hint: None,
|
||||
archive_warnings: Vec::new(),
|
||||
disconnect_info: None,
|
||||
update_action: None,
|
||||
exit_reason: ExitReason::UserRequested,
|
||||
}
|
||||
AppExitInfo::default()
|
||||
}
|
||||
|
||||
fn session_start_error(
|
||||
|
||||
Reference in New Issue
Block a user