mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
## 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
441 lines
17 KiB
Rust
441 lines
17 KiB
Rust
//! 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;
|
|
use codex_protocol::ThreadId;
|
|
use codex_protocol::models::local_image_label_text;
|
|
|
|
use super::App;
|
|
use crate::app_event::TranscriptExportDestination;
|
|
use crate::app_server_session::AppServerSession;
|
|
use crate::app_server_session::HistoryHydrationScope;
|
|
use crate::app_server_session::is_history_pagination_unsupported;
|
|
use crate::history_cell::AgentMarkdownCell;
|
|
use crate::history_cell::HistoryCell;
|
|
use crate::history_cell::PlainHistoryCell;
|
|
use crate::history_cell::ProposedPlanCell;
|
|
use crate::history_cell::ReasoningSummaryCell;
|
|
use crate::history_cell::SessionInfoCell;
|
|
use crate::history_cell::UserHistoryCell;
|
|
use crate::history_cell::raw_lines_from_source;
|
|
use crate::legacy_core::config::Config;
|
|
use crate::thread_transcript::RawReasoningVisibility;
|
|
use crate::thread_transcript::thread_items_to_transcript_cells;
|
|
|
|
impl App {
|
|
pub(super) async fn export_transcript(
|
|
&mut self,
|
|
tui: &mut crate::tui::Tui,
|
|
app_server: &mut AppServerSession,
|
|
destination: TranscriptExportDestination,
|
|
) -> Result<(), String> {
|
|
let thread_id = self
|
|
.chat_widget
|
|
.thread_id()
|
|
.ok_or_else(|| "No active conversation to export.".to_string())?;
|
|
let visibility = if self.config.show_raw_agent_reasoning {
|
|
RawReasoningVisibility::Visible
|
|
} else {
|
|
RawReasoningVisibility::Hidden
|
|
};
|
|
let cells = load_export_transcript(
|
|
app_server,
|
|
thread_id,
|
|
visibility,
|
|
Some(&self.config),
|
|
self.transcript_cells.clone(),
|
|
)
|
|
.await?;
|
|
let markdown = render_markdown_transcript(&cells)?;
|
|
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() {
|
|
self.launch_cwd.as_path()
|
|
} else {
|
|
self.chat_widget.config_ref().cwd.as_path()
|
|
};
|
|
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(())
|
|
}
|
|
}
|
|
|
|
pub(super) async fn load_export_transcript(
|
|
app_server: &mut AppServerSession,
|
|
thread_id: ThreadId,
|
|
visibility: RawReasoningVisibility,
|
|
config: Option<&Config>,
|
|
visible_transcript: Vec<Arc<dyn HistoryCell>>,
|
|
) -> Result<Vec<Arc<dyn HistoryCell>>, String> {
|
|
let mut thread = app_server
|
|
.thread_read(thread_id, /*include_turns*/ false)
|
|
.await
|
|
.map_err(|error| format!("could not load conversation: {error}"))?;
|
|
if thread.ephemeral {
|
|
return Ok(visible_transcript);
|
|
}
|
|
if let Err(error) = app_server
|
|
.hydrate_initial_thread_history(
|
|
&mut thread,
|
|
/*turn_cursor*/ None,
|
|
/*item_cursor*/ None,
|
|
/*config*/ None,
|
|
/*local_settings*/ None,
|
|
HistoryHydrationScope::Complete,
|
|
)
|
|
.await
|
|
{
|
|
if matches!(
|
|
error.downcast_ref::<TypedRequestError>(),
|
|
Some(TypedRequestError::Server { source, .. })
|
|
if is_history_pagination_unsupported(source)
|
|
) {
|
|
match app_server
|
|
.thread_read(thread_id, /*include_turns*/ true)
|
|
.await
|
|
{
|
|
Ok(legacy) if !legacy.turns.is_empty() => thread = legacy,
|
|
_ => return Ok(visible_transcript),
|
|
}
|
|
} else {
|
|
return Err(format!("could not load conversation history: {error}"));
|
|
}
|
|
}
|
|
let mut cells: Vec<Arc<dyn HistoryCell>> = Vec::new();
|
|
for item in visible_export_items(thread.turns) {
|
|
if let Some(cell) = export_activity_cell(&item) {
|
|
cells.push(Arc::new(cell));
|
|
} else {
|
|
cells.extend(thread_items_to_transcript_cells(
|
|
Some(thread_id),
|
|
thread.cwd.as_path(),
|
|
[item],
|
|
visibility,
|
|
config,
|
|
));
|
|
}
|
|
}
|
|
Ok(cells)
|
|
}
|
|
|
|
fn export_activity_cell(item: &ThreadItemPayload) -> Option<PlainHistoryCell> {
|
|
let lines = match item {
|
|
ThreadItemPayload::FileChange {
|
|
changes, status, ..
|
|
} => {
|
|
let mut lines =
|
|
vec![format!("file changes: {status:?} · {} changes", changes.len()).into()];
|
|
for change in changes {
|
|
lines.push(format!("{:?}: {}", change.kind, change.path).into());
|
|
lines.extend(change.diff.lines().map(|line| line.to_string().into()));
|
|
}
|
|
lines
|
|
}
|
|
ThreadItemPayload::McpToolCall {
|
|
server,
|
|
tool,
|
|
status,
|
|
arguments,
|
|
result,
|
|
error,
|
|
..
|
|
} => {
|
|
let mut lines =
|
|
vec![format!("mcp tool: {server}/{tool}({arguments}) · {status:?}").into()];
|
|
if let Some(result) = result {
|
|
for content in &result.content {
|
|
match serde_json::from_value::<rmcp::model::ContentBlock>(content.clone()) {
|
|
Ok(rmcp::model::ContentBlock::Text(text)) => {
|
|
lines.extend(raw_lines_from_source(&text.text));
|
|
}
|
|
Ok(rmcp::model::ContentBlock::Image(_)) => {
|
|
lines.push("Returned image".into());
|
|
}
|
|
Ok(rmcp::model::ContentBlock::Audio(_)) => {
|
|
lines.push("<audio content>".into());
|
|
}
|
|
Ok(rmcp::model::ContentBlock::Resource(_)) => {
|
|
let uri = content
|
|
.pointer("/resource/uri")
|
|
.and_then(serde_json::Value::as_str)
|
|
.unwrap_or("<unknown embedded resource>");
|
|
lines.push(format!("embedded resource: {uri}").into());
|
|
}
|
|
Ok(rmcp::model::ContentBlock::ResourceLink(link)) => {
|
|
lines.push(format!("link: {}", link.uri).into());
|
|
}
|
|
_ => lines.push(content.to_string().into()),
|
|
}
|
|
}
|
|
if let Some(content) = &result.structured_content {
|
|
lines.push(format!("structured result: {content}").into());
|
|
}
|
|
}
|
|
if let Some(error) = error {
|
|
lines.extend(raw_lines_from_source(&format!("error: {}", error.message)));
|
|
}
|
|
lines
|
|
}
|
|
_ => return None,
|
|
};
|
|
Some(PlainHistoryCell::new(lines))
|
|
}
|
|
|
|
fn visible_export_items(turns: Vec<Turn>) -> Vec<ThreadItemPayload> {
|
|
let mut visible = Vec::new();
|
|
let mut review_mode = false;
|
|
let mut previous_turn = None;
|
|
|
|
for turn in turns {
|
|
let hidden_nested_review_turn = previous_turn.as_ref().is_some_and(|previous| {
|
|
crate::app_backtrack::is_hidden_nested_review_turn(previous, &turn)
|
|
});
|
|
for item in turn.item_payloads().cloned() {
|
|
match item {
|
|
ThreadItemPayload::EnteredReviewMode { .. }
|
|
| ThreadItemPayload::ExitedReviewMode { .. } => {
|
|
review_mode = matches!(item, ThreadItemPayload::EnteredReviewMode { .. });
|
|
visible.push(item);
|
|
}
|
|
ThreadItemPayload::UserMessage { .. }
|
|
if review_mode || hidden_nested_review_turn => {}
|
|
_ => visible.push(item),
|
|
}
|
|
}
|
|
previous_turn = Some(turn);
|
|
}
|
|
|
|
visible
|
|
}
|
|
|
|
fn render_markdown_transcript(cells: &[Arc<dyn HistoryCell>]) -> Result<String, String> {
|
|
let mut markdown = String::from("# Codex conversation\n");
|
|
for cell in cells {
|
|
let lines = if let Some(user) = cell.as_any().downcast_ref::<UserHistoryCell>() {
|
|
let (message, _) =
|
|
crate::user_prompt::extract_prompt_request_with_offset(&user.message);
|
|
let message = crate::history_cell::sanitize_user_text(message.into());
|
|
let mut lines = raw_lines_from_source(&message);
|
|
let image_count = user.local_image_paths.len() + user.remote_image_urls.len();
|
|
let image_labels = (0..image_count)
|
|
.map(|index| local_image_label_text(index + 1))
|
|
.filter(|label| !message.contains(label))
|
|
.collect::<Vec<_>>();
|
|
if !image_labels.is_empty() && !lines.is_empty() {
|
|
lines.push("".into());
|
|
}
|
|
lines.extend(image_labels.into_iter().map(Into::into));
|
|
lines
|
|
} else if let Some(reasoning) = cell.as_any().downcast_ref::<ReasoningSummaryCell>() {
|
|
raw_lines_from_source(reasoning.markdown_source().trim())
|
|
} else {
|
|
cell.raw_lines()
|
|
};
|
|
if lines.is_empty()
|
|
|| cell.as_any().is::<SessionInfoCell>()
|
|
|| cell.as_any().is::<PlainHistoryCell>()
|
|
&& lines.first().is_some_and(|line| {
|
|
let text = line.to_string();
|
|
[
|
|
"• Saved conversation to ",
|
|
"• Copied conversation to clipboard",
|
|
"■ Export failed: ",
|
|
"■ Copy failed: ",
|
|
]
|
|
.iter()
|
|
.any(|prefix| text.starts_with(prefix))
|
|
|| text.strip_prefix("• ")
|
|
== Some(crate::clipboard_copy::UNCONFIRMED_COPY_MESSAGE)
|
|
})
|
|
{
|
|
continue;
|
|
}
|
|
let (heading, indent) = if cell.as_any().is::<UserHistoryCell>() {
|
|
("User", false)
|
|
} else if cell.as_any().is::<AgentMarkdownCell>() {
|
|
("Assistant", false)
|
|
} else if cell.as_any().is::<ProposedPlanCell>() {
|
|
("Plan", false)
|
|
} else if cell.as_any().is::<ReasoningSummaryCell>() {
|
|
("Reasoning", false)
|
|
} else {
|
|
("Activity", true)
|
|
};
|
|
markdown.push_str(&format!("\n## {heading}\n\n"));
|
|
for line in lines {
|
|
if indent {
|
|
markdown.push_str(" ");
|
|
}
|
|
for span in line.spans {
|
|
markdown.push_str(&crate::history_cell::sanitize_user_text(span.content));
|
|
}
|
|
markdown.push('\n');
|
|
}
|
|
}
|
|
if markdown != "# Codex conversation\n" {
|
|
Ok(markdown)
|
|
} else {
|
|
Err("No conversation content to export.".to_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())?
|
|
.join(relative)
|
|
} else if requested_path.is_absolute() {
|
|
requested_path.to_path_buf()
|
|
} else {
|
|
cwd.join(requested_path)
|
|
};
|
|
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()))?;
|
|
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)]
|
|
#[path = "transcript_export_tests.rs"]
|
|
mod tests;
|