Prompt before replacing an existing transcript export (#64822)

## Why

When a filename is already taken, saving a conversation with `/export` ends
with an error. Users have to restart the export to choose a different name.

## What changed

Show a conflict picker with options to choose another name, replace the
existing file, or cancel. Choosing another name pre-fills an editable
numbered filename, such as `notes-3.md` when `notes.md` and `notes-2.md`
already exist.

Offer replacement only for regular files. After confirmation, check the
directory and file identities and use an atomic rename to install the new
transcript.

## Testing

Cover the picker actions and numbered filename suggestion, verify that
replacement requires confirmation, and check that replacement rejects a
changed file or redirected directory.

GitOrigin-RevId: edcb2fad858bab15a7228c69bd27a8ffd18e8d05
This commit is contained in:
Eric Traut
2026-11-30 22:40:58 +00:00
committed by copyberry
parent debcc79621
commit 3496c2f99c
11 changed files with 431 additions and 25 deletions
+10
View File
File diff suppressed because one or more lines are too long
+103
View File
@@ -199,6 +199,12 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "ambient-authority"
version = "0.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
[[package]]
name = "android_system_properties"
version = "0.1.5"
@@ -1591,6 +1597,48 @@ dependencies = [
"displaydoc",
]
[[package]]
name = "cap-fs-ext"
version = "3.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "476f0d0003a760918ed4b1e039a59e11769030416f79c8222551d22785f7f70d"
dependencies = [
"cap-primitives",
"cap-std",
"io-lifetimes",
"windows-sys 0.59.0",
]
[[package]]
name = "cap-primitives"
version = "3.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e0bf07d379916947be6c4a07f43684153d710a2896c31f9e97781362895596c"
dependencies = [
"ambient-authority",
"fs-set-times",
"io-extras",
"io-lifetimes",
"ipnet",
"maybe-owned",
"rustix 1.1.4",
"rustix-linux-procfs",
"windows-sys 0.59.0",
"winx",
]
[[package]]
name = "cap-std"
version = "3.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a59e59fa26472d29680ece6a9f8ee8b0551a719a33df2f5240bde065ecbddfd7"
dependencies = [
"cap-primitives",
"io-extras",
"io-lifetimes",
"rustix 1.1.4",
]
[[package]]
name = "caseless"
version = "0.2.2"
@@ -5390,6 +5438,8 @@ dependencies = [
"assert_matches",
"axum",
"base64 0.22.1",
"cap-fs-ext",
"cap-std",
"chrono",
"clap",
"clipboard-win",
@@ -8029,6 +8079,17 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "fs-set-times"
version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
dependencies = [
"io-lifetimes",
"rustix 1.1.4",
"windows-sys 0.59.0",
]
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -10152,6 +10213,22 @@ dependencies = [
"rustversion",
]
[[package]]
name = "io-extras"
version = "0.18.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2285ddfe3054097ef4b2fe909ef8c3bcd1ea52a8f0d274416caebeef39f04a65"
dependencies = [
"io-lifetimes",
"windows-sys 0.59.0",
]
[[package]]
name = "io-lifetimes"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
[[package]]
name = "io_tee"
version = "0.1.1"
@@ -10803,6 +10880,12 @@ version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3eede3bdf92f3b4f9dc04072a9ce5ab557d5ec9038773bf9ffcd5588b3cc05b"
[[package]]
name = "maybe-owned"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
[[package]]
name = "md-5"
version = "0.10.6"
@@ -14207,6 +14290,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rustix-linux-procfs"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
dependencies = [
"once_cell",
"rustix 1.1.4",
]
[[package]]
name = "rustls"
version = "0.23.46"
@@ -18307,6 +18400,16 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ab703352da6a72f35c39a533526393725640575bb211f61987a2748323ad956"
[[package]]
name = "winx"
version = "0.36.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
dependencies = [
"bitflags 2.13.1",
"windows-sys 0.59.0",
]
[[package]]
name = "wiremock"
version = "0.6.5"
+2
View File
@@ -26,6 +26,8 @@ codex-build-info = { workspace = true }
anyhow = { workspace = true }
axum = { workspace = true, default-features = false, features = ["http1", "tokio"] }
base64 = { workspace = true }
cap-fs-ext = "3.4.6"
cap-std = "3.4.6"
chrono = { workspace = true, features = ["serde"] }
clap = { workspace = true, features = ["derive"] }
codex-ansi-escape = { workspace = true }
+1
View File
@@ -312,6 +312,7 @@ mod thread_session_state;
mod thread_settings;
mod thread_title;
mod transcript_export;
pub(crate) use transcript_export::ExportConflict;
mod tui_mode_picker;
mod user_turn_submission;
mod user_verification;
+5 -2
View File
@@ -647,8 +647,11 @@ impl App {
let result = tui.copy_transcript_selection(&text, crate::clipboard_copy::CopyFormat::PlainText);
self.chat_widget.show_selection_copy_result(result);
}
AppEvent::OpenTranscriptExportFilePrompt => {
self.chat_widget.show_transcript_export_file_prompt();
AppEvent::OpenTranscriptExportFilePrompt { alternative_to } => {
match alternative_to {
Some(path) => self.chat_widget.show_transcript_checkpoint_prompt(&path),
None => self.chat_widget.show_transcript_export_file_prompt(),
}
}
AppEvent::ExportTranscript { destination } => {
if let Err(error) = self.export_transcript(tui, app_server, destination).await {
+131 -12
View File
@@ -1,10 +1,14 @@
//! Complete, Markdown-preserving conversation exports.
use std::io;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use cap_fs_ext::DirExt;
use cap_fs_ext::MetadataExt;
use cap_std::fs::Dir;
use codex_app_server_client::TypedRequestError;
use codex_app_server_protocol::ThreadItemPayload;
use codex_app_server_protocol::Turn;
@@ -53,13 +57,14 @@ impl App {
)
.await?;
let markdown = render_markdown_transcript(&cells)?;
match destination {
let path = match destination {
TranscriptExportDestination::Clipboard => {
let result = tui.copy_transcript_selection(
&markdown,
crate::clipboard_copy::CopyFormat::PlainText,
);
self.chat_widget.show_copy_result("conversation", result);
return Ok(());
}
TranscriptExportDestination::File(path) => {
let cwd = if self.app_server_target.uses_remote_workspace() {
@@ -67,13 +72,25 @@ impl App {
} else {
self.chat_widget.config_ref().cwd.as_path()
};
let path = write_transcript(cwd, &path, &markdown)?;
self.chat_widget.add_info_message(
format!("Saved conversation to {}", path.display()),
/*hint*/ None,
);
match write_transcript(cwd, &path, &markdown)? {
SaveOutcome::Saved(path) => path,
SaveOutcome::AlreadyExists(conflict) => {
self.chat_widget.show_transcript_export_conflict(conflict);
return Ok(());
}
}
}
}
TranscriptExportDestination::ReplaceFile(conflict) => {
conflict.replace(&markdown).map_err(|error| {
format!("could not replace {}: {error}", conflict.path.display())
})?;
conflict.path
}
};
self.chat_widget.add_info_message(
format!("Saved conversation to {}", path.display()),
/*hint*/ None,
);
Ok(())
}
}
@@ -297,7 +314,102 @@ fn render_markdown_transcript(cells: &[Arc<dyn HistoryCell>]) -> Result<String,
}
}
fn write_transcript(cwd: &Path, requested_path: &Path, markdown: &str) -> Result<PathBuf, String> {
/// The resolved path and filesystem identities presented for overwrite confirmation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ExportConflict {
pub(crate) path: PathBuf,
directory: (u64, u64),
file: Option<(u64, u64)>,
}
// Open each component of an already resolved path without following new symlinks.
fn open_export_directory(path: &Path) -> io::Result<Dir> {
let mut components = path.ancestors().collect::<Vec<_>>();
let root = components.pop().ok_or(io::ErrorKind::InvalidInput)?;
let mut dir = Dir::open_ambient_dir(root, cap_std::ambient_authority())?;
for component in components.into_iter().rev() {
dir = dir.open_dir_nofollow(component.file_name().ok_or(io::ErrorKind::InvalidInput)?)?;
}
Ok(dir)
}
impl ExportConflict {
pub(crate) fn new(path: &Path) -> io::Result<Self> {
let parent = dunce::canonicalize(path.parent().ok_or(io::ErrorKind::InvalidInput)?)?;
let name = path.file_name().ok_or(io::ErrorKind::InvalidInput)?;
let dir = open_export_directory(&parent)?;
let directory = dir.dir_metadata()?;
let file = dir.symlink_metadata(name)?;
Ok(Self {
path: parent.join(name),
directory: (directory.dev(), directory.ino()),
file: file.is_file().then(|| (file.dev(), file.ino())),
})
}
pub(crate) fn can_replace(&self) -> bool {
self.file.is_some()
}
fn replace(&self, markdown: &str) -> io::Result<()> {
let parent = self.path.parent().ok_or(io::ErrorKind::InvalidInput)?;
let name = self.path.file_name().ok_or(io::ErrorKind::InvalidInput)?;
// cap-std's Windows rename and cleanup strip the verbatim prefix, which
// would turn a UNC share into a relative path.
#[cfg(windows)]
if !matches!(parent.components().next(), Some(std::path::Component::Prefix(prefix))
if matches!(prefix.kind(), std::path::Prefix::Disk(_) | std::path::Prefix::VerbatimDisk(_)))
{
return Err(io::Error::other(
"cannot replace exports on network shares. Choose another name",
));
}
let dir = open_export_directory(parent)?;
let directory = dir.dir_metadata()?;
if self.directory != (directory.dev(), directory.ino()) {
return Err(io::Error::other(
"export directory changed. Run /export again",
));
}
// Keep staging, cleanup and the atomic rename relative to the same directory handle.
let temp = format!(".codex-export-{}", uuid::Uuid::new_v4());
let mut options = cap_std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use cap_std::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = dir.open_with(&temp, &options)?;
let result = (|| {
file.write_all(markdown.as_bytes())?;
let target = dir.symlink_metadata(name)?;
if !target.is_file() || self.file != Some((target.dev(), target.ino())) {
return Err(io::Error::other(
"export destination changed. Run /export again",
));
}
dir.rename(&temp, &dir, name)
})();
if result.is_err() {
let _ = dir.remove_file(&temp);
}
result
}
}
#[derive(Debug, PartialEq)]
enum SaveOutcome {
Saved(PathBuf),
AlreadyExists(ExportConflict),
}
fn write_transcript(
cwd: &Path,
requested_path: &Path,
markdown: &str,
) -> Result<SaveOutcome, String> {
let path = if let Ok(relative) = requested_path.strip_prefix("~") {
dirs::home_dir()
.ok_or_else(|| "could not determine the home directory".to_string())?
@@ -307,13 +419,20 @@ fn write_transcript(cwd: &Path, requested_path: &Path, markdown: &str) -> Result
} else {
cwd.join(requested_path)
};
let mut file = tempfile::NamedTempFile::new_in(path.parent().unwrap_or(cwd))
let parent = path.parent().unwrap_or(cwd);
let mut file = tempfile::NamedTempFile::new_in(parent)
.map_err(|error| format!("could not create {}: {error}", path.display()))?;
file.write_all(markdown.as_bytes())
.map_err(|error| format!("could not write {}: {error}", path.display()))?;
file.persist_noclobber(&path)
.map_err(|error| format!("could not create {}: {error}", path.display()))?;
Ok(path)
match file.persist_noclobber(&path) {
Ok(_) => Ok(SaveOutcome::Saved(path)),
Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {
ExportConflict::new(&path)
.map(SaveOutcome::AlreadyExists)
.map_err(|error| format!("could not inspect {}: {error}", path.display()))
}
Err(error) => Err(format!("could not create {}: {error}", path.display())),
}
}
#[cfg(test)]
@@ -178,22 +178,34 @@ fn persisted_transcript_includes_file_and_mcp_details() {
}
#[test]
fn transcript_file_resolves_relative_paths_and_refuses_to_overwrite() {
fn transcript_file_requires_explicit_replacement_of_the_resolved_path() {
let directory = tempfile::tempdir().expect("temporary directory");
let path = write_transcript(
let result = write_transcript(
directory.path(),
"conversation.md".as_ref(),
"# First export\n",
)
.expect("write first export");
assert_eq!(path, directory.path().join("conversation.md"));
assert!(write_transcript(directory.path(), &path, "# Second export\n").is_err());
let path = directory.path().join("conversation.md");
assert_eq!(result, super::SaveOutcome::Saved(path.clone()));
let conflict = super::ExportConflict::new(&path).unwrap();
assert_eq!(
write_transcript(
directory.path(),
"conversation.md".as_ref(),
"# Second export\n",
),
Ok(super::SaveOutcome::AlreadyExists(conflict.clone())),
);
assert_eq!(
std::fs::read_to_string(&path).expect("read"),
"# First export\n"
);
conflict.replace("# Second export\n").unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), "# Second export\n");
let directory_name = directory.path().file_name().expect("directory name");
let requested = std::path::Path::new("~")
.join(directory_name)
@@ -203,6 +215,28 @@ fn transcript_file_resolves_relative_paths_and_refuses_to_overwrite() {
assert!(error.contains(&dirs::home_dir().expect("home").display().to_string()));
}
#[cfg(unix)]
#[test]
fn replacement_rejects_a_redirected_directory_or_changed_file() {
let root = tempfile::tempdir().unwrap();
let parent = root.path().join("exports");
std::fs::create_dir(&parent).unwrap();
let path = parent.join("notes.md");
std::fs::write(&path, "original").unwrap();
let conflict = super::ExportConflict::new(&path).unwrap();
std::fs::rename(&path, parent.join("original.md")).unwrap();
std::fs::write(&path, "different file").unwrap();
assert!(conflict.replace("refresh").is_err());
assert_eq!(std::fs::read_to_string(&path).unwrap(), "different file");
let conflict = super::ExportConflict::new(&path).unwrap();
std::fs::rename(&parent, root.path().join("moved")).unwrap();
std::fs::write(root.path().join("notes.md"), "outside").unwrap();
std::os::unix::fs::symlink(root.path(), &parent).unwrap();
assert!(conflict.replace("refresh").is_err());
assert_eq!(std::fs::read_to_string(&path).unwrap(), "outside");
}
#[test]
fn persisted_web_and_image_activity_preserves_full_details() {
let items = [
+4 -1
View File
@@ -261,6 +261,7 @@ pub(crate) enum KeymapCaptureMode {
pub(crate) enum TranscriptExportDestination {
Clipboard,
File(PathBuf),
ReplaceFile(crate::app::ExportConflict),
}
/// Deliver a generated title to its originating automatic rename or editable prompt.
@@ -659,7 +660,9 @@ pub(crate) enum AppEvent {
},
/// Open the filename prompt for an on-demand Markdown transcript export.
OpenTranscriptExportFilePrompt,
OpenTranscriptExportFilePrompt {
alternative_to: Option<PathBuf>,
},
/// Open retained warnings without changing the draft or transcript position.
OpenWarnings,
/// Copy a diagnostic and acknowledge in the footer, without appending history.
@@ -0,0 +1,19 @@
---
source: tui/src/chatwidget/tests/copy_export_picker_tests.rs
expression: prompts
---
File already exists
exports/notes.md
› 1. Choose another name
2. Replace
3. Cancel
f3 select · f2 back
Save conversation
› exports/notes-3.md
enter submit · esc back
@@ -96,15 +96,19 @@ async fn copy_export_picker_custom_keys_preserve_payloads_and_composer_draft() {
assert!(
std::iter::from_fn(|| rx.try_recv().ok()).all(|event| !matches!(
event,
AppEvent::ExportTranscript { .. } | AppEvent::OpenTranscriptExportFilePrompt
AppEvent::ExportTranscript { .. } | AppEvent::OpenTranscriptExportFilePrompt { .. }
))
);
chat.show_transcript_export_popup();
chat.handle_key_event(KeyEvent::from(KeyCode::Down));
chat.handle_key_event(KeyEvent::from(KeyCode::F(/*n*/ 3)));
assert!(
std::iter::from_fn(|| rx.try_recv().ok())
.any(|event| matches!(event, AppEvent::OpenTranscriptExportFilePrompt))
std::iter::from_fn(|| rx.try_recv().ok()).any(|event| matches!(
event,
AppEvent::OpenTranscriptExportFilePrompt {
alternative_to: None
}
))
);
chat.show_transcript_export_file_prompt();
chat.handle_key_event(KeyEvent::from(KeyCode::Esc));
@@ -115,7 +119,51 @@ async fn copy_export_picker_custom_keys_preserve_payloads_and_composer_draft() {
.all(|event| !matches!(event, AppEvent::ExportTranscript { .. }))
);
chat.show_transcript_export_file_prompt();
let dir = tempfile::tempdir().unwrap();
let parent = dunce::canonicalize(dir.path()).unwrap();
let path = parent.join("notes.md");
std::fs::write(&path, "original").unwrap();
std::fs::write(dir.path().join("notes-2.md"), "checkpoint").unwrap();
let target = crate::app::ExportConflict::new(&path).unwrap();
chat.show_transcript_export_conflict(target.clone());
chat.handle_key_event(KeyEvent::from(KeyCode::Down));
chat.handle_key_event(KeyEvent::from(KeyCode::F(/*n*/ 3)));
let destination = std::iter::from_fn(|| rx.try_recv().ok()).find_map(|event| match event {
AppEvent::ExportTranscript { destination } => Some(destination),
_ => None,
});
assert_eq!(
destination,
Some(TranscriptExportDestination::ReplaceFile(target.clone()))
);
chat.show_transcript_export_conflict(target.clone());
chat.handle_key_event(KeyEvent::from(KeyCode::Down));
chat.handle_key_event(KeyEvent::from(KeyCode::Down));
chat.handle_key_event(KeyEvent::from(KeyCode::F(/*n*/ 3)));
assert!(chat.no_modal_or_popup_active());
assert!(
std::iter::from_fn(|| rx.try_recv().ok()).all(|event| !matches!(
event,
AppEvent::ExportTranscript { .. } | AppEvent::OpenTranscriptExportFilePrompt { .. }
))
);
chat.show_transcript_export_conflict(target);
let conflict = render_bottom_popup(&chat, /*width*/ 300);
chat.handle_key_event(KeyEvent::from(KeyCode::F(/*n*/ 3)));
let alternative = std::iter::from_fn(|| rx.try_recv().ok()).find_map(|event| match event {
AppEvent::OpenTranscriptExportFilePrompt { alternative_to } => alternative_to,
_ => None,
});
assert_eq!(alternative.as_ref(), Some(&path));
chat.show_transcript_checkpoint_prompt(&alternative.unwrap());
let popup = render_bottom_popup(&chat, /*width*/ 300);
let prompts = format!("{conflict}\n\n{popup}").replace(
&format!("{}{}", parent.display(), std::path::MAIN_SEPARATOR),
"exports/",
);
assert_chatwidget_snapshot!("slash_export_filename_taken", prompts);
chat.handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::CONTROL));
chat.handle_key_event(KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL));
let filename = "reviews/日本語 - result.md";
@@ -32,7 +32,9 @@ impl ChatWidget {
name: "Save to file".to_string(),
description: Some("Choose a Markdown filename".to_string()),
actions: vec![Box::new(|tx| {
tx.send(AppEvent::OpenTranscriptExportFilePrompt);
tx.send(AppEvent::OpenTranscriptExportFilePrompt {
alternative_to: None,
});
})],
dismiss_on_select: true,
..Default::default()
@@ -44,12 +46,74 @@ impl ChatWidget {
self.request_redraw();
}
pub(crate) fn show_transcript_export_conflict(&mut self, conflict: crate::app::ExportConflict) {
let alternative_to = conflict.path.clone();
self.show_selection_view(SelectionViewParams {
title: Some("File already exists".to_string()),
subtitle: Some(conflict.path.display().to_string()),
footer_hint: Some(picker_hint_line_for_keymap(&self.bottom_pane.list_keymap())),
items: vec![
SelectionItem {
name: "Choose another name".to_string(),
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::OpenTranscriptExportFilePrompt {
alternative_to: Some(alternative_to.clone()),
});
})],
dismiss_on_select: true,
..Default::default()
},
SelectionItem {
name: "Replace".to_string(),
is_disabled: !conflict.can_replace(),
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::ExportTranscript {
destination: TranscriptExportDestination::ReplaceFile(conflict.clone()),
});
})],
dismiss_on_select: true,
..Default::default()
},
SelectionItem {
name: "Cancel".to_string(),
dismiss_on_select: true,
..Default::default()
},
],
..SelectionViewParams::picker()
});
self.request_redraw();
}
pub(crate) fn show_transcript_export_file_prompt(&mut self) {
let tx = self.app_event_tx.clone();
let filename = self.thread_id().map_or_else(
|| "codex-session.md".to_string(),
|thread_id| format!("codex-session-{thread_id}.md"),
);
self.prompt_for_export_filename(filename);
}
pub(crate) fn show_transcript_checkpoint_prompt(&mut self, path: &Path) {
let stem = path.file_stem().unwrap_or_default();
let mut suffix = 2;
let filename = loop {
let mut name = stem.to_os_string();
name.push(format!("-{suffix}"));
if let Some(extension) = path.extension() {
name.push(".");
name.push(extension);
}
let candidate = path.with_file_name(name);
if candidate.symlink_metadata().is_err() {
break candidate.to_string_lossy().into_owned();
}
suffix += 1;
};
self.prompt_for_export_filename(filename);
}
fn prompt_for_export_filename(&mut self, filename: String) {
let tx = self.app_event_tx.clone();
let view = CustomPromptView::new(
"Save conversation".to_string(),
"Type a filename and press Enter".to_string(),