Clean up temporary Codex homes after TUI tests (#47894)

## Why

TUI test helpers used `TempDir::keep()`, leaving temporary Codex homes on disk after fixtures were dropped.

## What changed

Retain `TempDir` ownership in widget and app fixtures so their homes are removed on drop. Transfer ownership to app fixtures to keep the home alive across widget replacement, and retain directory guards in tests that use configs directly.

## Testing

Add regression tests for recursive cleanup, isolation between widget homes, and app home survival across widget replacement followed by cleanup on app drop.

GitOrigin-RevId: fe80f982cc467ede4c3e1edbac8012ec3066dfb3
This commit is contained in:
Felipe Coury
2026-09-24 17:43:15 +00:00
committed by copyberry
parent 83b56bc5ad
commit f6fd7f17ed
12 changed files with 107 additions and 29 deletions
+3
View File
@@ -692,6 +692,9 @@ pub(crate) struct App {
// persist an older toggle after a newer one.
pending_hook_enabled_writes: HashMap<String, Option<bool>>,
recap: recap::RecapState,
// App fixtures keep their home alive across widget replacement; drop it last.
#[cfg(test)]
_test_codex_home: Option<tempfile::TempDir>,
}
#[derive(Debug, Clone, PartialEq)]
+2
View File
@@ -845,6 +845,8 @@ See the Codex keymap documentation for supported actions and examples."
pending_plugin_enabled_writes: HashMap::new(),
pending_hook_enabled_writes: HashMap::new(),
recap: recap::RecapState::default(),
#[cfg(test)]
_test_codex_home: None,
};
if !tui.is_terminal_focused() {
app.recap.note_focus_lost(Instant::now());
+3 -1
View File
@@ -23,7 +23,8 @@ pub(super) fn select_catalog_tip(app: &mut App, width: u16, expected: &str) {
}
pub(crate) async fn make_test_app() -> App {
let (chat_widget, app_event_tx, _rx, _op_rx) = make_chatwidget_manual_with_sender().await;
let (mut chat_widget, app_event_tx, _rx, _op_rx) = make_chatwidget_manual_with_sender().await;
let test_codex_home = chat_widget.test_codex_home.take();
let config = chat_widget.config_ref().clone();
let file_search = FileSearchManager::new(config.cwd.to_path_buf(), app_event_tx.clone());
let model = get_model_offline_for_tests(config.model.as_deref());
@@ -120,6 +121,7 @@ pub(crate) async fn make_test_app() -> App {
pending_plugin_enabled_writes: HashMap::new(),
pending_hook_enabled_writes: HashMap::new(),
recap: recap::RecapState::default(),
_test_codex_home: test_codex_home,
}
}
+10 -6
View File
@@ -35,6 +35,8 @@ mod external_writer_fork_tests;
mod fork_workspace_roots_tests;
#[path = "tests/fresh_sparkle_tests.rs"]
mod fresh_sparkle_tests;
#[path = "tests/home_cleanup_tests.rs"]
mod home_cleanup_tests;
#[path = "tests/key_chords.rs"]
mod key_chords;
#[path = "tests/local_command_scroll_tests.rs"]
@@ -2671,10 +2673,8 @@ fn attach_live_thread_for_selection_rejects_empty_non_ephemeral_fallback_threads
.build()?;
runtime.block_on(async {
let config = {
let app = make_test_app().await;
app.chat_widget.config_ref().clone()
};
let config_owner = make_test_app().await;
let config = config_owner.chat_widget.config_ref().clone();
let mut app_server = crate::start_embedded_app_server_for_picker(&config)
.await
.expect("embedded app server");
@@ -5982,7 +5982,8 @@ async fn clear_ui_header_shows_fast_status_for_fast_capable_models() {
}
async fn make_test_app() -> Box<App> {
let (chat_widget, app_event_tx, _rx, _op_rx) = make_chatwidget_manual_with_sender().await;
let (mut chat_widget, app_event_tx, _rx, _op_rx) = make_chatwidget_manual_with_sender().await;
let test_codex_home = chat_widget.test_codex_home.take();
let config = chat_widget.config_ref().clone();
let file_search = FileSearchManager::new(config.cwd.to_path_buf(), app_event_tx.clone());
let model = get_model_offline_for_tests(config.model.as_deref());
@@ -6079,6 +6080,7 @@ async fn make_test_app() -> Box<App> {
pending_plugin_enabled_writes: HashMap::new(),
pending_hook_enabled_writes: HashMap::new(),
recap: recap::RecapState::default(),
_test_codex_home: test_codex_home,
})
}
@@ -6087,7 +6089,8 @@ pub(super) async fn make_test_app_with_channels() -> (
tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
tokio::sync::mpsc::UnboundedReceiver<Op>,
) {
let (chat_widget, app_event_tx, rx, op_rx) = make_chatwidget_manual_with_sender().await;
let (mut chat_widget, app_event_tx, rx, op_rx) = make_chatwidget_manual_with_sender().await;
let test_codex_home = chat_widget.test_codex_home.take();
let config = chat_widget.config_ref().clone();
let file_search = FileSearchManager::new(config.cwd.to_path_buf(), app_event_tx.clone());
let model = get_model_offline_for_tests(config.model.as_deref());
@@ -6185,6 +6188,7 @@ pub(super) async fn make_test_app_with_channels() -> (
pending_plugin_enabled_writes: HashMap::new(),
pending_hook_enabled_writes: HashMap::new(),
recap: recap::RecapState::default(),
_test_codex_home: test_codex_home,
}),
rx,
op_rx,
@@ -0,0 +1,26 @@
//! Verifies that app fixtures own their Codex homes across widget replacement.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn app_home_survives_widget_replacement_until_app_drop() {
let (mut app, _events, _ops) = make_test_app_with_channels().await;
let home = app.config.codex_home.clone();
std::fs::write(home.join("test.log"), "app fixture").expect("app fixture file");
let mut tui = crate::tui::test_support::make_test_tui().expect("test tui");
let init = app.chatwidget_init_for_forked_or_resumed_thread(
&mut tui,
app.config.clone(),
/*initial_user_message*/ None,
);
app.replace_chat_widget(ChatWidget::new_with_app_event(init));
assert_eq!(
std::fs::read_to_string(home.join("test.log")).expect("app fixture remains"),
"app fixture"
);
drop(app);
assert!(!home.exists(), "app fixture should be removed");
}
+3
View File
@@ -768,6 +768,9 @@ pub(crate) struct ChatWidget {
last_rendered_user_message_display: Option<UserMessageDisplay>,
last_rendered_user_message_client_id: Option<String>,
last_non_retry_error: Option<(String, String)>,
// Keep fixture storage alive until all other widget fields have been dropped.
#[cfg(test)]
pub(crate) test_codex_home: Option<tempfile::TempDir>,
}
#[cfg_attr(not(test), allow(dead_code))]
@@ -278,6 +278,8 @@ impl ChatWidget {
last_rendered_user_message_display: None,
last_rendered_user_message_client_id: None,
last_non_retry_error: None,
#[cfg(test)]
test_codex_home: None,
};
widget.prefetch_rate_limits();
+2
View File
@@ -256,6 +256,8 @@ pub(crate) mod helpers;
#[path = "tests/history_projection.rs"]
mod history_projection;
mod history_replay;
#[path = "tests/home_cleanup_tests.rs"]
mod home_cleanup_tests;
#[path = "tests/luna_reserve_usage_tests.rs"]
mod luna_reserve_usage_tests;
mod mcp_startup;
+14 -12
View File
@@ -3,26 +3,27 @@ use codex_app_server_protocol::ImageGenerationItem;
use codex_app_server_protocol::PluginAvailability;
use codex_utils_absolute_path::test_support::PathExt;
pub(super) async fn test_config() -> Config {
pub(super) async fn test_config() -> (tempfile::TempDir, Config) {
// Start from the built-in defaults so tests do not inherit host/system config.
let codex_home = tempfile::Builder::new()
.prefix("chatwidget-tests-")
.tempdir()
.expect("tempdir")
.keep();
let mut config =
Config::load_default_with_cli_overrides_for_codex_home(codex_home.clone(), Vec::new())
.await
.expect("config");
.expect("tempdir");
let mut config = Config::load_default_with_cli_overrides_for_codex_home(
codex_home.path().to_path_buf(),
Vec::new(),
)
.await
.expect("config");
// Keep generic UI snapshots stable when the bundled catalog default changes.
config.model = Some("gpt-5.6-sol".to_string());
config.codex_home = codex_home.abs();
config.sqlite = codex_state::SqliteConfig::new_for_testing(codex_home.as_path().abs());
config.log_dir = codex_home.join("log");
config.codex_home = codex_home.path().abs();
config.sqlite = codex_state::SqliteConfig::new_for_testing(codex_home.path().abs());
config.log_dir = codex_home.path().join("log");
config.cwd = PathBuf::from(test_path_display("/tmp/project")).abs();
config.config_layer_stack = ConfigLayerStack::default();
config.startup_warnings.clear();
config
(codex_home, config)
}
pub(super) fn test_project_path() -> PathBuf {
@@ -217,7 +218,7 @@ pub(super) async fn make_chatwidget_manual_with_auth(
let (tx_raw, rx) = unbounded_channel::<AppEvent>();
let app_event_tx = AppEventSender::new(tx_raw);
let (op_tx, op_rx) = unbounded_channel::<Op>();
let mut cfg = test_config().await;
let (codex_home, mut cfg) = test_config().await;
let resolved_model = model_override
.map(str::to_owned)
.unwrap_or_else(|| get_model_offline_for_tests(cfg.model.as_deref()));
@@ -249,6 +250,7 @@ pub(super) async fn make_chatwidget_manual_with_auth(
session_telemetry,
};
let mut widget = ChatWidget::new_with_op_target(common, super::CodexOpTarget::Direct(op_tx));
widget.test_codex_home = Some(codex_home);
widget.clock_format = crate::clock_format::ClockFormat::TwentyFourHour;
widget.windows_sandbox_host = crate::app::WindowsSandboxHost::Local;
widget.windows_sandbox_config.requirements = Some(None);
@@ -0,0 +1,31 @@
//! Verifies that widget fixtures own and clean up their isolated Codex homes.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn widget_homes_remain_isolated_until_their_owners_drop() {
let (first, _first_events, _first_ops) = make_chatwidget_manual(/*model_override*/ None).await;
let (second, _second_events, _second_ops) =
make_chatwidget_manual(/*model_override*/ None).await;
let first_home = first.config.codex_home.clone();
let second_home = second.config.codex_home.clone();
assert_ne!(first_home, second_home);
std::fs::create_dir_all(first_home.join("log")).expect("first fixture directory");
std::fs::write(first_home.join("log/test.log"), "first").expect("first fixture file");
std::fs::write(second_home.join("test.log"), "second").expect("second fixture file");
drop(first);
assert!(
!first_home.exists(),
"first fixture should be removed recursively"
);
assert_eq!(
std::fs::read_to_string(second_home.join("test.log")).expect("second fixture remains"),
"second"
);
drop(second);
assert!(!second_home.exists(), "second fixture should be removed");
}
@@ -500,7 +500,7 @@ async fn completed_plan_table_tail_skips_provisional_history_insert() {
async fn configured_pet_load_is_deferred_until_after_construction() {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let tx = AppEventSender::new(tx_raw);
let mut cfg = test_config().await;
let (_codex_home, mut cfg) = test_config().await;
cfg.tui_pet = Some(crate::pets::DEFAULT_PET_ID.to_string());
crate::pets::write_test_pack(&cfg.codex_home);
let resolved_model = get_model_offline_for_tests(cfg.model.as_deref());
@@ -7,13 +7,14 @@ use codex_protocol::openai_models::ReasoningEffort;
use codex_utils_absolute_path::test_support::PathBufExt;
use pretty_assertions::assert_eq;
async fn test_config() -> Config {
let codex_home = tempfile::tempdir().expect("tempdir").keep();
ConfigBuilder::default()
.codex_home(codex_home)
async fn test_config() -> (tempfile::TempDir, Config) {
let codex_home = tempfile::tempdir().expect("tempdir");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("config")
.expect("config");
(codex_home, config)
}
fn defaults() -> NewThreadModelDefaults {
@@ -26,7 +27,7 @@ fn defaults() -> NewThreadModelDefaults {
#[tokio::test]
async fn applies_managed_defaults_to_a_new_thread_config() {
let mut actual = test_config().await;
let (_codex_home, mut actual) = test_config().await;
actual.model = Some("configured-model".to_string());
actual.model_reasoning_effort = Some(ReasoningEffort::Low);
actual.service_tier = Some("flex".to_string());
@@ -47,7 +48,7 @@ async fn applies_managed_defaults_to_a_new_thread_config() {
#[tokio::test]
async fn explicit_model_skips_managed_model_and_reasoning_effort() {
let mut actual = test_config().await;
let (_codex_home, mut actual) = test_config().await;
actual.model = Some("explicit-model".to_string());
actual.model_reasoning_effort = None;
actual.service_tier = Some("flex".to_string());
@@ -65,7 +66,7 @@ async fn explicit_model_skips_managed_model_and_reasoning_effort() {
#[tokio::test]
async fn explicit_reasoning_effort_skips_managed_model_and_reasoning_effort() {
let mut actual = test_config().await;
let (_codex_home, mut actual) = test_config().await;
actual.model = Some("configured-model".to_string());
actual.model_reasoning_effort = Some(ReasoningEffort::Low);
actual.service_tier = Some("flex".to_string());
@@ -88,7 +89,7 @@ async fn explicit_reasoning_effort_skips_managed_model_and_reasoning_effort() {
#[tokio::test]
async fn explicit_launch_overrides_take_precedence() {
let mut actual = test_config().await;
let (_codex_home, mut actual) = test_config().await;
actual.model = Some("explicit-model".to_string());
actual.model_reasoning_effort = Some(ReasoningEffort::Low);
actual.service_tier = Some("flex".to_string());