Merge branch 'main' into canvnro/codex-pac-pr1-conf

This commit is contained in:
canvrno-oai
2026-06-11 14:08:44 -07:00
committed by GitHub
410 changed files with 18679 additions and 6510 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
load("//:defs.bzl", "MACOS_WEBRTC_RUSTC_LINK_FLAGS", "codex_rust_crate", "multiplatform_binaries")
load("//:defs.bzl", "MACOS_WEBRTC_RUSTC_LINK_FLAGS", "codex_rust_crate")
load("//bazel/platforms:release_binaries.bzl", "multiplatform_binaries")
codex_rust_crate(
name = "cli",
+1
View File
@@ -33,6 +33,7 @@ codex-utils-cli = { workspace = true }
codex-config = { workspace = true }
codex-core = { workspace = true }
codex-core-plugins = { workspace = true }
codex-home = { workspace = true }
codex-exec = { workspace = true }
codex-exec-server = { workspace = true }
codex-execpolicy = { workspace = true }
+23 -6
View File
@@ -1324,6 +1324,7 @@ fn stored_auth_mode(auth: &codex_login::AuthDotJson) -> &'static str {
codex_app_server_protocol::AuthMode::ChatgptAuthTokens => "chatgpt_auth_tokens",
codex_app_server_protocol::AuthMode::AgentIdentity => "agent_identity",
codex_app_server_protocol::AuthMode::PersonalAccessToken => "personal_access_token",
codex_app_server_protocol::AuthMode::BedrockApiKey => "bedrock_api_key",
}
}
@@ -1331,10 +1332,12 @@ fn stored_auth_mode_value(auth: &AuthDotJson) -> codex_app_server_protocol::Auth
if let Some(mode) = auth.auth_mode {
return mode;
}
if auth.openai_api_key.is_some() {
codex_app_server_protocol::AuthMode::ApiKey
} else if auth.personal_access_token.is_some() {
if auth.personal_access_token.is_some() {
codex_app_server_protocol::AuthMode::PersonalAccessToken
} else if auth.bedrock_api_key.is_some() {
codex_app_server_protocol::AuthMode::BedrockApiKey
} else if auth.openai_api_key.is_some() {
codex_app_server_protocol::AuthMode::ApiKey
} else {
codex_app_server_protocol::AuthMode::Chatgpt
}
@@ -1407,6 +1410,11 @@ fn stored_auth_issues(
issues.push("personal access token auth is missing a personal access token");
}
}
codex_app_server_protocol::AuthMode::BedrockApiKey => {
if auth.bedrock_api_key.is_none() {
issues.push("Bedrock API key auth is missing a Bedrock API key");
}
}
}
issues
}
@@ -2141,8 +2149,9 @@ async fn state_check(config: &Config) -> DoctorCheck {
};
let mut check = DoctorCheck::new("state.paths", "state", status, summary).details(details);
if status == CheckStatus::Fail {
check = check
.remediation("Back up CODEX_HOME, then remove or repair the affected SQLite database.");
check = check.remediation(
"Move the damaged SQLite database aside, then restart the interactive CLI or app server so it can rebuild that runtime database from saved data. Other entry points may not rebuild automatically.",
);
}
check
}
@@ -2436,6 +2445,7 @@ fn auth_mode_name(auth: &CodexAuth) -> &'static str {
codex_app_server_protocol::AuthMode::ChatgptAuthTokens => "chatgpt_auth_tokens",
codex_app_server_protocol::AuthMode::AgentIdentity => "agent_identity",
codex_app_server_protocol::AuthMode::PersonalAccessToken => "personal_access_token",
codex_app_server_protocol::AuthMode::BedrockApiKey => "bedrock_api_key",
}
}
@@ -2565,7 +2575,10 @@ fn provider_auth_reachability_mode_from_auth(
return ProviderAuthReachabilityMode::Chatgpt;
}
match stored_auth.map(stored_auth_mode_value) {
Some(codex_app_server_protocol::AuthMode::ApiKey) => ProviderAuthReachabilityMode::ApiKey,
Some(
codex_app_server_protocol::AuthMode::ApiKey
| codex_app_server_protocol::AuthMode::BedrockApiKey,
) => ProviderAuthReachabilityMode::ApiKey,
Some(
codex_app_server_protocol::AuthMode::Chatgpt
| codex_app_server_protocol::AuthMode::ChatgptAuthTokens
@@ -3470,6 +3483,7 @@ mod tests {
last_refresh: None,
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
};
assert_eq!(
@@ -3488,6 +3502,7 @@ mod tests {
last_refresh: None,
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
};
assert_eq!(
@@ -3508,6 +3523,7 @@ mod tests {
last_refresh: None,
agent_identity: None,
personal_access_token: Some("at-test".to_string()),
bedrock_api_key: None,
};
assert_eq!(stored_auth_mode(&auth), "personal_access_token");
@@ -3530,6 +3546,7 @@ mod tests {
last_refresh: None,
agent_identity: None,
personal_access_token: None,
bedrock_api_key: None,
};
assert_eq!(
+4
View File
@@ -395,6 +395,10 @@ pub async fn run_login_status(cli_config_overrides: CliConfigOverrides) -> ! {
eprintln!("Logged in using personal access token");
std::process::exit(0);
}
AuthMode::BedrockApiKey => {
eprintln!("Logged in using Amazon Bedrock API key");
std::process::exit(0);
}
},
Ok(None) => {
eprintln!("Not logged in");
+135 -22
View File
@@ -36,10 +36,12 @@ use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_cli::CliConfigOverrides;
use codex_utils_cli::ProfileV2Name;
use codex_utils_cli::SharedCliOptions;
use codex_utils_cli::resume_hint;
use owo_colors::OwoColorize;
use std::collections::HashSet;
use std::io::IsTerminal;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use supports_color::Stream;
#[cfg(any(target_os = "macos", target_os = "windows"))]
@@ -75,6 +77,7 @@ use codex_features::FEATURES;
use codex_features::Feature;
use codex_features::Stage;
use codex_features::is_known_feature_key;
use codex_home::CodexHomeUserInstructionsProvider;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_login::read_codex_access_token_from_env;
@@ -180,6 +183,9 @@ enum Subcommand {
/// Archive a saved session by id or session name.
Archive(SessionArchiveCommand),
/// Permanently delete a saved session by id or session name.
Delete(DeleteCommand),
/// Unarchive a saved session by id or session name.
Unarchive(SessionArchiveCommand),
@@ -354,6 +360,16 @@ struct SessionArchiveConfigOverrides {
config_overrides: CliConfigOverrides,
}
#[derive(Debug, Args)]
struct DeleteCommand {
#[clap(flatten)]
session: SessionArchiveCommand,
/// Delete without prompting. SESSION must be a UUID.
#[arg(long, default_value_t = false)]
force: bool,
}
#[derive(Debug, Parser)]
struct ForkCommand {
/// Conversation/session id (UUID). When provided, forks this session.
@@ -685,10 +701,11 @@ fn parse_socket_path(raw: &str) -> Result<AbsolutePathBuf, String> {
}
fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<String> {
let is_fatal = matches!(&exit_info.exit_reason, ExitReason::Fatal(_));
let AppExitInfo {
token_usage,
thread_id: conversation_id,
thread_name,
resume_hint,
..
} = exit_info;
@@ -697,13 +714,15 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<Stri
lines.push(token_usage.to_string());
}
if let Some(resume_cmd) = resume_hint(thread_name.as_deref(), conversation_id) {
if let Some(resume_cmd) = resume_hint {
let command = if color_enabled {
resume_cmd.cyan().to_string()
} else {
resume_cmd
};
lines.push(format!("To continue this session, run {command}"));
} else if is_fatal && let Some(conversation_id) = conversation_id {
lines.push(format!("Session ID: {conversation_id}"));
}
lines
@@ -711,19 +730,23 @@ fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec<Stri
/// Handle the app exit and print the results. Optionally run the update action.
fn handle_app_exit(exit_info: AppExitInfo) -> anyhow::Result<()> {
match exit_info.exit_reason {
let is_fatal = match &exit_info.exit_reason {
ExitReason::Fatal(message) => {
eprintln!("ERROR: {message}");
std::process::exit(1);
true
}
ExitReason::UserRequested => { /* normal exit */ }
}
ExitReason::UserRequested => false,
};
let update_action = exit_info.update_action;
let color_enabled = supports_color::on(Stream::Stdout).is_some();
for line in format_exit_messages(exit_info, color_enabled) {
println!("{line}");
}
if is_fatal {
std::io::stdout().flush()?;
std::process::exit(1);
}
if let Some(action) = update_action {
run_update_action(action)?;
}
@@ -829,6 +852,17 @@ async fn run_session_archive_cli_command(
.map_err(|err| anyhow::anyhow!("{err}"))
}
fn delete_action(target: &str, force: bool) -> anyhow::Result<codex_tui::SessionArchiveAction> {
if force && codex_protocol::ThreadId::from_string(target).is_err() {
anyhow::bail!("--force requires a session UUID; names must be confirmed interactively");
}
let confirmation = match force {
true => codex_tui::DeleteConfirmation::Skip,
false => codex_tui::DeleteConfirmation::Prompt,
};
Ok(codex_tui::SessionArchiveAction::Delete(confirmation))
}
async fn run_debug_app_server_command(cmd: DebugAppServerCommand) -> anyhow::Result<()> {
match cmd.subcommand {
DebugAppServerSubcommand::SendMessageV2(cmd) => {
@@ -1243,6 +1277,20 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
.await?;
println!("{output}");
}
Some(Subcommand::Delete(DeleteCommand { session, force })) => {
let action = delete_action(&session.target, force)?;
let output = run_session_archive_cli_command(
action,
session,
interactive,
root_config_overrides.clone(),
root_remote.clone(),
root_remote_auth_token_env.clone(),
arg0_paths.clone(),
)
.await?;
println!("{output}");
}
Some(Subcommand::Unarchive(cmd)) => {
let output = run_session_archive_cli_command(
codex_tui::SessionArchiveAction::Unarchive,
@@ -1607,6 +1655,7 @@ fn profile_v2_for_subcommand<'a>(
| Subcommand::Review(_)
| Subcommand::Resume(_)
| Subcommand::Archive(_)
| Subcommand::Delete(_)
| Subcommand::Unarchive(_)
| Subcommand::Fork(_)
| Subcommand::Mcp(_)
@@ -1615,7 +1664,7 @@ fn profile_v2_for_subcommand<'a>(
subcommand: DebugSubcommand::PromptInput(_),
}) => Ok(Some(profile_v2)),
_ => anyhow::bail!(
"--profile only applies to runtime commands and `codex mcp`: `codex`, `codex exec`, `codex review`, `codex resume`, `codex archive`, `codex unarchive`, `codex fork`, `codex mcp`, `codex sandbox`, and `codex debug prompt-input`."
"--profile only applies to runtime commands and `codex mcp`: `codex`, `codex exec`, `codex review`, `codex resume`, `codex archive`, `codex delete`, `codex unarchive`, `codex fork`, `codex mcp`, `codex sandbox`, and `codex debug prompt-input`."
),
}
}
@@ -1905,7 +1954,16 @@ async fn run_debug_prompt_input_command(
});
}
let prompt_input = codex_core::build_prompt_input(config, input, /*state_db*/ None).await?;
let user_instructions_provider = Arc::new(CodexHomeUserInstructionsProvider::new(
config.codex_home.clone(),
));
let prompt_input = codex_core::build_prompt_input(
config,
input,
/*state_db*/ None,
user_instructions_provider,
)
.await?;
println!("{}", serde_json::to_string_pretty(&prompt_input)?);
Ok(())
@@ -2036,6 +2094,7 @@ fn unsupported_subcommand_name_for_strict_config(
| Some(Subcommand::ExecServer(_))
| Some(Subcommand::Resume(_))
| Some(Subcommand::Archive(_))
| Some(Subcommand::Delete(_))
| Some(Subcommand::Unarchive(_))
| Some(Subcommand::Fork(_))
| Some(Subcommand::Doctor(_)) => None,
@@ -2199,7 +2258,7 @@ async fn run_interactive_tui(
remote_endpoint.clone(),
)
};
let mut attempted_repair = false;
let mut attempted_backups = HashSet::new();
loop {
let err = match start_tui().await {
Ok(exit_info) => return Ok(exit_info),
@@ -2212,25 +2271,25 @@ async fn run_interactive_tui(
local_state_db::print_locked_guidance(startup_error);
return Ok(AppExitInfo::fatal(startup_error.to_string()));
}
if attempted_repair {
if !local_state_db::is_auto_backup_recoverable(startup_error) {
local_state_db::print_diagnostic_guidance(startup_error);
return Ok(AppExitInfo::fatal(startup_error.to_string()));
}
if !local_state_db::confirm_repair(startup_error)? {
if !attempted_backups.insert(startup_error.database_path().to_path_buf()) {
local_state_db::print_diagnostic_guidance(startup_error);
return Ok(AppExitInfo::fatal(startup_error.to_string()));
}
match local_state_db::repair_files(startup_error).await {
Ok(backups) => local_state_db::print_repair_backups(&backups),
Err(repair_err) => {
local_state_db::print_auto_backup_start(startup_error);
match local_state_db::backup_files_for_fresh_start(startup_error).await {
Ok(backups) => local_state_db::confirm_fresh_start_rebuild(startup_error, &backups)?,
Err(backup_err) => {
local_state_db::print_diagnostic_guidance(startup_error);
return Ok(AppExitInfo::fatal(format!(
"failed to repair Codex local data automatically: {repair_err}"
"failed to move damaged Codex local database files into a backup folder automatically: {backup_err}"
)));
}
}
attempted_repair = true;
}
}
@@ -2610,6 +2669,14 @@ mod tests {
);
}
#[test]
fn import_remains_an_interactive_prompt() {
let cli = MultitoolCli::try_parse_from(["codex", "import"]).expect("parse");
assert!(cli.subcommand.is_none());
assert_eq!(cli.interactive.prompt.as_deref(), Some("import"));
}
#[test]
fn profile_v2_rejects_non_plain_names_at_parse_time() {
assert!(
@@ -2870,6 +2937,17 @@ mod tests {
assert!(interactive.bypass_hook_trust);
}
#[test]
fn delete_force_requires_uuid() {
assert!(delete_action("123e4567-e89b-12d3-a456-426614174000", true).is_ok());
let err = delete_action("my-thread", true).expect_err("name should require prompt");
assert_eq!(
err.to_string(),
"--force requires a session UUID; names must be confirmed interactively"
);
}
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
#[test]
fn sandbox_parses_permissions_profile() {
@@ -2988,12 +3066,13 @@ mod tests {
total_tokens: 2,
..Default::default()
};
let thread_id = conversation_id
.map(ThreadId::from_string)
.map(Result::unwrap);
AppExitInfo {
token_usage,
thread_id: conversation_id
.map(ThreadId::from_string)
.map(Result::unwrap),
thread_name: thread_name.map(str::to_string),
thread_id,
resume_hint: codex_utils_cli::resume_hint(thread_name, thread_id),
update_action: None,
exit_reason: ExitReason::UserRequested,
}
@@ -3004,7 +3083,7 @@ mod tests {
let exit_info = AppExitInfo {
token_usage: TokenUsage::default(),
thread_id: None,
thread_name: None,
resume_hint: None,
update_action: None,
exit_reason: ExitReason::UserRequested,
};
@@ -3012,6 +3091,40 @@ mod tests {
assert!(lines.is_empty());
}
#[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,
update_action: None,
exit_reason: ExitReason::Fatal("boom".to_string()),
};
let lines = format_exit_messages(exit_info, /*color_enabled*/ false);
assert_eq!(
lines,
vec!["Session ID: 123e4567-e89b-12d3-a456-426614174000".to_string()]
);
}
#[test]
fn format_exit_messages_includes_resume_hint_for_fatal_exit() {
let mut exit_info = sample_exit_info(
Some("123e4567-e89b-12d3-a456-426614174000"),
/*thread_name*/ None,
);
exit_info.exit_reason = ExitReason::Fatal("boom".to_string());
let lines = format_exit_messages(exit_info, /*color_enabled*/ false);
assert_eq!(
lines,
vec![
"Token usage: total=2 input=0 output=2".to_string(),
"To continue this session, run codex resume 123e4567-e89b-12d3-a456-426614174000"
.to_string(),
]
);
}
#[test]
fn format_exit_messages_includes_resume_hint_without_color() {
let exit_info = sample_exit_info(
+2 -2
View File
@@ -204,7 +204,7 @@ pub async fn run_plugin_list(
..
} = load_plugin_command_context(overrides).await?;
let outcome = manager
.list_marketplaces_for_config(&plugins_input, &[])
.list_marketplaces_for_config(&plugins_input, &[], /*include_openai_curated*/ true)
.context("failed to list marketplace plugins")?;
ensure_configured_marketplace_snapshots_loaded(
codex_home.as_path(),
@@ -609,7 +609,7 @@ fn find_marketplace_for_plugin(
plugin_name: &str,
) -> Result<ConfiguredMarketplace> {
let outcome = manager
.list_marketplaces_for_config(plugins_input, &[])
.list_marketplaces_for_config(plugins_input, &[], /*include_openai_curated*/ true)
.context("failed to list marketplace plugins")?;
ensure_configured_marketplace_snapshots_loaded(
codex_home,
+84 -110
View File
@@ -1,10 +1,12 @@
//! CLI recovery for local state database startup failures.
//! CLI handling for local state database startup failures.
//!
//! This keeps user-facing repair and lock-contention handling out of the main
//! This keeps user-facing backup and lock-contention handling out of the main
//! CLI dispatch path while preserving the TUI startup error as the boundary type.
use codex_state::RuntimeDbBackup;
use codex_tui::LocalStateDbStartupError;
use std::path::PathBuf;
use std::io::IsTerminal;
use std::path::Path;
pub(crate) fn startup_error(err: &std::io::Error) -> Option<&LocalStateDbStartupError> {
err.get_ref()
@@ -12,66 +14,60 @@ pub(crate) fn startup_error(err: &std::io::Error) -> Option<&LocalStateDbStartup
}
pub(crate) fn is_locked(detail: &str) -> bool {
let detail = detail.to_ascii_lowercase();
detail.contains("database is locked") || detail.contains("database is busy")
codex_state::sqlite_error_detail_is_lock(detail)
}
pub(crate) fn confirm_repair(startup_error: &LocalStateDbStartupError) -> std::io::Result<bool> {
pub(crate) fn is_corruption(detail: &str) -> bool {
codex_state::sqlite_error_detail_is_corruption(detail)
}
pub(crate) fn is_auto_backup_recoverable(startup_error: &LocalStateDbStartupError) -> bool {
is_corruption(startup_error.detail()) || sqlite_home_is_blocking_file(startup_error)
}
fn sqlite_home_is_blocking_file(startup_error: &LocalStateDbStartupError) -> bool {
startup_error
.database_path()
.parent()
.and_then(|path| std::fs::metadata(path).ok())
.is_some_and(|metadata| metadata.is_file())
}
pub(crate) fn print_auto_backup_start(startup_error: &LocalStateDbStartupError) {
eprintln!("Codex couldn't start because its local database appears to be damaged.");
eprintln!("Codex can try a safe repair by backing up those files and rebuilding them.");
eprintln!("Moving the damaged local database aside so Codex can rebuild it from saved data.");
print_technical_details(startup_error);
crate::confirm("Repair Codex local data now? [y/N]: ")
}
pub(crate) async fn repair_files(
pub(crate) async fn backup_files_for_fresh_start(
startup_error: &LocalStateDbStartupError,
) -> std::io::Result<Vec<PathBuf>> {
let state_db_path = startup_error.state_db_path();
let sqlite_home = state_db_path.parent().ok_or_else(|| {
std::io::Error::other("state database path does not have a parent directory")
})?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |duration| duration.as_secs());
let repair_suffix = format!("codex-repair-{timestamp}");
let mut backups = Vec::new();
match tokio::fs::metadata(sqlite_home).await {
Ok(metadata) if metadata.is_dir() => {}
Ok(_) => {
backups.push(backup_path(sqlite_home, &repair_suffix).await?);
tokio::fs::create_dir_all(sqlite_home).await?;
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
tokio::fs::create_dir_all(sqlite_home).await?;
}
Err(err) => return Err(err),
}
for path in codex_state::runtime_db_paths(sqlite_home)
.into_iter()
.flat_map(|db| sqlite_paths(db.path.as_path()))
{
if tokio::fs::try_exists(path.as_path()).await? {
backups.push(backup_path(path.as_path(), &repair_suffix).await?);
}
}
if backups.is_empty() {
return Err(std::io::Error::other(
"no repairable Codex local data files were found",
));
}
Ok(backups)
) -> std::io::Result<Vec<RuntimeDbBackup>> {
codex_state::backup_runtime_db_for_fresh_start(startup_error.database_path()).await
}
pub(crate) fn print_repair_backups(backups: &[PathBuf]) {
eprintln!("Backed up Codex local data before repair:");
for backup in backups {
eprintln!(" {}", backup.display());
pub(crate) fn confirm_fresh_start_rebuild(
startup_error: &LocalStateDbStartupError,
backups: &[RuntimeDbBackup],
) -> std::io::Result<()> {
eprintln!("Codex rebuilt its local database.");
eprintln!(
"Codex detected a damaged local database, moved it into a backup folder, and will continue startup with a fresh database."
);
eprintln!("Database path: {}", startup_error.database_path().display());
if let Some(backup_folder) = backup_folder(backups) {
eprintln!("Backup folder: {}", backup_folder.display());
} else {
eprintln!("Backup folder: unavailable");
}
eprintln!("Retrying startup with rebuilt local data...");
if std::io::stdin().is_terminal() && std::io::stderr().is_terminal() {
eprintln!("Press Enter to continue.");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
} else {
eprintln!("Continuing startup with a fresh local database...");
}
Ok(())
}
pub(crate) fn print_diagnostic_guidance(startup_error: &LocalStateDbStartupError) {
@@ -87,79 +83,50 @@ pub(crate) fn print_locked_guidance(startup_error: &LocalStateDbStartupError) {
print_technical_details(startup_error);
}
fn sqlite_paths(db_path: &std::path::Path) -> Vec<PathBuf> {
let mut wal_path = db_path.as_os_str().to_os_string();
wal_path.push("-wal");
let mut shm_path = db_path.as_os_str().to_os_string();
shm_path.push("-shm");
vec![
db_path.to_path_buf(),
PathBuf::from(wal_path),
PathBuf::from(shm_path),
]
}
async fn backup_path(path: &std::path::Path, repair_suffix: &str) -> std::io::Result<PathBuf> {
let file_name = path.file_name().ok_or_else(|| {
std::io::Error::other(format!(
"cannot create a repair backup name for {}",
path.display()
))
})?;
let mut sequence = 0;
loop {
let mut backup_name = file_name.to_os_string();
backup_name.push(format!(".{repair_suffix}.{sequence}.bak"));
let backup_path = path.with_file_name(backup_name);
if !tokio::fs::try_exists(backup_path.as_path()).await? {
tokio::fs::rename(path, backup_path.as_path()).await?;
return Ok(backup_path);
}
sequence += 1;
}
}
fn print_technical_details(startup_error: &LocalStateDbStartupError) {
eprintln!("Technical details:");
eprintln!(" Location: {}", startup_error.state_db_path().display());
eprintln!(" Location: {}", startup_error.database_path().display());
eprintln!(" Cause: {}", startup_error.detail());
}
fn backup_folder(backups: &[RuntimeDbBackup]) -> Option<&Path> {
backups.first()?.backup_path.parent()
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
use tempfile::TempDir;
#[tokio::test]
async fn repair_backs_up_owned_database_files() -> std::io::Result<()> {
async fn backup_backs_up_only_failed_database_file() -> std::io::Result<()> {
let temp_dir = TempDir::new()?;
let state_path = codex_state::state_db_path(temp_dir.path());
let logs_path = codex_state::logs_db_path(temp_dir.path());
let goals_path = codex_state::goals_db_path(temp_dir.path());
let state_sidecars = sqlite_paths(state_path.as_path());
let failed_db_path = codex_state::logs_db_path(temp_dir.path());
tokio::fs::write(state_path.as_path(), b"state").await?;
tokio::fs::write(state_sidecars[1].as_path(), b"state-wal").await?;
tokio::fs::write(logs_path.as_path(), b"logs").await?;
tokio::fs::write(goals_path.as_path(), b"goals").await?;
tokio::fs::write(failed_db_path.as_path(), b"logs").await?;
let startup_error =
LocalStateDbStartupError::new(state_path.clone(), "corrupt".to_string());
let backups = repair_files(&startup_error).await?;
LocalStateDbStartupError::new(failed_db_path.clone(), "corrupt".to_string());
let backups = backup_files_for_fresh_start(&startup_error).await?;
assert_eq!(backups.len(), 4);
assert!(!tokio::fs::try_exists(state_path.as_path()).await?);
assert!(!tokio::fs::try_exists(state_sidecars[1].as_path()).await?);
assert!(!tokio::fs::try_exists(logs_path.as_path()).await?);
assert!(!tokio::fs::try_exists(goals_path.as_path()).await?);
for backup in backups {
assert!(tokio::fs::try_exists(backup.as_path()).await?);
}
assert_eq!(
backups
.iter()
.map(|backup| &backup.original_path)
.collect::<Vec<_>>(),
vec![&failed_db_path]
);
assert!(!tokio::fs::try_exists(failed_db_path.as_path()).await?);
assert!(tokio::fs::try_exists(state_path.as_path()).await?);
assert!(tokio::fs::try_exists(backups[0].backup_path.as_path()).await?);
Ok(())
}
#[tokio::test]
async fn repair_replaces_blocking_sqlite_home_file() -> std::io::Result<()> {
async fn backup_replaces_blocking_sqlite_home_file() -> std::io::Result<()> {
let temp_dir = TempDir::new()?;
let sqlite_home = temp_dir.path().join("sqlite-home");
tokio::fs::write(sqlite_home.as_path(), b"not-a-directory").await?;
@@ -168,18 +135,25 @@ mod tests {
"File exists".to_string(),
);
let backups = repair_files(&startup_error).await?;
assert!(is_auto_backup_recoverable(&startup_error));
let backups = backup_files_for_fresh_start(&startup_error).await?;
assert_eq!(backups.len(), 1);
assert!(tokio::fs::metadata(sqlite_home.as_path()).await?.is_dir());
assert!(tokio::fs::try_exists(backups[0].as_path()).await?);
assert!(tokio::fs::try_exists(backups[0].backup_path.as_path()).await?);
Ok(())
}
#[test]
fn lock_failures_skip_repair() {
assert!(is_locked("database is locked"));
assert!(is_locked("database is busy"));
assert!(!is_locked("database disk image is malformed"));
fn backup_folder_uses_parent_of_first_backup_path() {
let backups = vec![RuntimeDbBackup {
original_path: PathBuf::from("/tmp/state_5.sqlite"),
backup_path: PathBuf::from("/tmp/db-backups/sqlite-1-0/state_5.sqlite"),
}];
assert_eq!(
backup_folder(&backups),
Some(Path::new("/tmp/db-backups/sqlite-1-0"))
);
}
}
+17
View File
@@ -0,0 +1,17 @@
use predicates::prelude::*;
#[test]
fn missing_session_fails_before_delete_confirmation() -> anyhow::Result<()> {
let codex_home = tempfile::tempdir()?;
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
cmd.env("CODEX_HOME", codex_home.path())
.args(["delete", "123e4567-e89b-12d3-a456-426614174000"]);
cmd.assert()
.failure()
.stderr(predicate::str::contains(
"No active or archived session found matching",
))
.stderr(predicate::str::contains("cannot confirm").not());
Ok(())
}