Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Add Markdown conversation export to the TUI (#37358)

Eric Traut2801d12661be
diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs
index 1b3e6f2305..8f4de9a945 100644
--- a/codex-rs/tui/src/app.rs
+++ b/codex-rs/tui/src/app.rs
@@ -230,6 +230,7 @@ mod thread_goal_actions;
mod thread_routing;
mod thread_session_state;
mod thread_settings;
+mod transcript_export;
use self::agent_navigation::AgentNavigationDirection;
use self::agent_navigation::AgentNavigationState;
diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs
index 2d55735451..02f1ba13b2 100644
--- a/codex-rs/tui/src/app/event_dispatch.rs
+++ b/codex-rs/tui/src/app/event_dispatch.rs
@@ -61,6 +61,20 @@ impl App {
tracing::warn!(%thread_id, error = %err, "failed to load older transcript history");
}
}
+ AppEvent::OpenTranscriptExportFilePrompt => {
+ self.chat_widget.show_transcript_export_file_prompt();
+ }
+ AppEvent::ExportTranscript { destination } => {
+ if let Err(error) = self.export_transcript(app_server, destination).await {
+ self.chat_widget
+ .add_error_message(format!("Export failed: {error}"));
+ }
+ if self.chat_widget.no_modal_or_popup_active() {
+ self.chat_widget
+ .set_queue_autosend_suppressed(/*suppressed*/ false);
+ self.chat_widget.maybe_send_next_queued_input();
+ }
+ }
AppEvent::ClearUi { name } => {
self.clear_terminal_ui(tui, /*redraw_header*/ false)?;
self.reset_app_ui_state_after_clear();
diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__transcript_export__tests__markdown_transcript.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__transcript_export__tests__markdown_transcript.snap
new file mode 100644
index 0000000000..d06cd9f173
--- /dev/null
+++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__transcript_export__tests__markdown_transcript.snap
@@ -0,0 +1,31 @@
+---
+source: tui/src/app/transcript_export_tests.rs
+expression: "render_markdown_transcript(&cells).expect(\"exported transcript\")"
+---
+# Codex conversation
+
+## User
+
+Explain **the change**
+
+## Assistant
+
+```rust
+let answer = 42;
+```
+
+## Plan
+
+completed plan
+
+## Activity
+
+ $ cargo test
+
+## User
+
+[Image #1]
+
+## User
+
+[Image #1] describe this
diff --git a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs
index c560f72f86..2c36f0d809 100644
--- a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs
+++ b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::app_event::TranscriptExportDestination;
use app_test_support::create_fake_paginated_rollout;
use app_test_support::create_fake_parented_rollout_with_source;
use app_test_support::create_fake_rollout;
@@ -579,11 +580,47 @@ async fn transcript_home_loads_every_older_history_page() -> Result<()> {
app.enqueue_primary_thread_session(started.session, started.turns)
.await?;
app.transcript_cells = initial_cells;
+ while app_event_rx.try_recv().is_ok() {}
+ let initial_turn_requests = recorded_params(&requests, "thread/turns/list").len();
+ let initial_item_requests = recorded_params(&requests, "thread/items/list").len();
+ let export_path = codex_home.path().join("complete-export.md");
+ app.chat_widget
+ .set_queue_autosend_suppressed(/*suppressed*/ true);
+ app.chat_widget.insert_str("queued after export");
+ app.chat_widget
+ .handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ let mut tui = crate::tui::test_support::make_test_tui()?;
+ app.handle_event(
+ &mut tui,
+ &mut app_server,
+ AppEvent::ExportTranscript {
+ destination: TranscriptExportDestination::File(export_path.clone()),
+ },
+ )
+ .await?;
+ assert!(app.chat_widget.queued_user_message_texts().is_empty());
+ let markdown = std::fs::read_to_string(export_path)?;
+ assert!(
+ (0..305)
+ .map(|index| format!("history output {index}"))
+ .eq(markdown.lines().filter(|line| line.starts_with("history")))
+ );
+ assert!(
+ recorded_params(&requests, "thread/turns/list")[initial_turn_requests..]
+ .iter()
+ .all(|params| params["itemsView"] == "notLoaded")
+ );
+ assert!(
+ recorded_params(&requests, "thread/items/list")[initial_item_requests..]
+ .iter()
+ .all(|params| {
+ params["limit"] == crate::app_server_session::HISTORY_ITEM_PAGE_LIMIT
+ })
+ );
app.scrollback_has_older_history = app_server.has_older_history(thread_id);
assert!(app.scrollback_has_older_history);
while app_event_rx.try_recv().is_ok() {}
let initial_page_requests = recorded_params(&requests, "thread/items/list").len();
- let mut tui = crate::tui::test_support::make_test_tui()?;
app.open_transcript_overlay(&mut tui);
app.handle_backtrack_overlay_event(
@@ -635,6 +672,11 @@ async fn remote_legacy_history_start_negotiates_once_for_resume_and_fork() -> Re
let (app, _codex_home) = make_history_test_app().await?;
let legacy_thread_id =
create_history_rollout(&app.config, ThreadHistoryMode::Legacy, "legacy history")?;
+ let paginated_thread_id = create_history_rollout(
+ &app.config,
+ ThreadHistoryMode::Paginated,
+ "paginated history",
+ )?;
let (mut app_server, requests, proxy) = start_recording_app_server_with_history(
&app.config,
HistoryCapabilities::LegacyOnly,
@@ -671,6 +713,24 @@ async fn remote_legacy_history_start_negotiates_once_for_resume_and_fork() -> Re
assert!(recorded_params(&requests, "thread/turns/list").is_empty());
assert!(recorded_params(&requests, "thread/items/list").is_empty());
+ let initial_read_count = recorded_params(&requests, "thread/read").len();
+ let exported = crate::app::transcript_export::load_export_transcript(
+ &mut app_server,
+ paginated_thread_id,
+ crate::thread_transcript::RawReasoningVisibility::Hidden,
+ Some(app.config.codex_home.as_path()),
+ vec![Arc::new(PlainHistoryCell::new(vec!["visible".into()]))],
+ )
+ .await
+ .map_err(|error| color_eyre::eyre::eyre!(error))?;
+ assert_eq!(exported[0].raw_lines()[0].to_string(), "visible");
+ assert!(
+ recorded_params(&requests, "thread/read")[initial_read_count..]
+ .iter()
+ .any(|params| params["includeTurns"] == true)
+ );
+ assert_eq!(recorded_params(&requests, "thread/turns/list").len(), 1);
+
app_server.shutdown().await?;
proxy.await??;
Ok(())
diff --git a/codex-rs/tui/src/app/transcript_export.rs b/codex-rs/tui/src/app/transcript_export.rs
new file mode 100644
index 0000000000..81cf6e73bd
--- /dev/null
+++ b/codex-rs/tui/src/app/transcript_export.rs
@@ -0,0 +1,311 @@
+//! Complete, Markdown-preserving conversation exports.
+
+use std::io::Write;
+use std::path::Path;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use codex_app_server_client::TypedRequestError;
+use codex_app_server_protocol::ThreadItem;
+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::thread_transcript::RawReasoningVisibility;
+use crate::thread_transcript::thread_items_to_transcript_cells;
+
+impl App {
+ pub(super) async fn export_transcript(
+ &mut self,
+ 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 codex_home = self.config.codex_home.to_path_buf();
+ let cells = load_export_transcript(
+ app_server,
+ thread_id,
+ visibility,
+ Some(codex_home.as_path()),
+ self.transcript_cells.clone(),
+ )
+ .await?;
+ let markdown = render_markdown_transcript(&cells)?;
+ match destination {
+ TranscriptExportDestination::Clipboard => {
+ self.chat_widget.copy_transcript_to_clipboard(&markdown);
+ }
+ 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()
+ };
+ let path = write_transcript(cwd, &path, &markdown)?;
+ 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,
+ codex_home: Option<&Path>,
+ 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,
+ 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,
+ [item],
+ visibility,
+ codex_home,
+ ));
+ }
+ }
+ Ok(cells)
+}
+
+fn export_activity_cell(item: &ThreadItem) -> Option<PlainHistoryCell> {
+ let lines = match item {
+ ThreadItem::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
+ }
+ ThreadItem::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("<image content>".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<ThreadItem> {
+ 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.items.iter().cloned() {
+ match item {
+ ThreadItem::EnteredReviewMode { .. } | ThreadItem::ExitedReviewMode { .. } => {
+ review_mode = matches!(item, ThreadItem::EnteredReviewMode { .. });
+ visible.push(item);
+ }
+ ThreadItem::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::ide_context::extract_prompt_request_with_offset(&user.message);
+ let message = crate::history_cell::sanitize_user_text(message);
+ 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 {
+ 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))
+ })
+ {
+ 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.as_ref(),
+ ));
+ }
+ markdown.push('\n');
+ }
+ }
+ if markdown != "# Codex conversation\n" {
+ Ok(markdown)
+ } else {
+ Err("No conversation content to export.".to_string())
+ }
+}
+
+fn write_transcript(cwd: &Path, requested_path: &Path, markdown: &str) -> Result<PathBuf, 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 mut file = tempfile::NamedTempFile::new_in(path.parent().unwrap_or(cwd))
+ .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)
+}
+
+#[cfg(test)]
+#[path = "transcript_export_tests.rs"]
+mod tests;
diff --git a/codex-rs/tui/src/app/transcript_export_tests.rs b/codex-rs/tui/src/app/transcript_export_tests.rs
new file mode 100644
index 0000000000..f7212ad9d5
--- /dev/null
+++ b/codex-rs/tui/src/app/transcript_export_tests.rs
@@ -0,0 +1,198 @@
+use std::sync::Arc;
+
+use pretty_assertions::assert_eq;
+
+use super::render_markdown_transcript;
+use super::visible_export_items;
+use super::write_transcript;
+use crate::history_cell::AgentMarkdownCell;
+use crate::history_cell::HistoryCell;
+use crate::history_cell::PlainHistoryCell;
+use crate::history_cell::UserHistoryCell;
+use crate::history_cell::new_proposed_plan;
+use codex_app_server_protocol::ThreadItem;
+use codex_app_server_protocol::Turn;
+use codex_app_server_protocol::TurnItemsView;
+use codex_app_server_protocol::TurnStatus;
+use codex_app_server_protocol::UserInput;
+
+#[test]
+fn markdown_transcript_preserves_messages_and_formats_activity() {
+ assert!(render_markdown_transcript(&[]).is_err());
+ let user = |message: &str, local_image_paths| {
+ Arc::new(UserHistoryCell {
+ message: message.to_string(),
+ text_elements: Vec::new(),
+ local_image_paths,
+ remote_image_urls: Vec::new(),
+ }) as Arc<dyn HistoryCell>
+ };
+ let cells = vec![
+ user(
+ concat!(
+ "# Context from my IDE setup:\n\n## Active file: src/lib.rs\n\n",
+ "## My request for Codex:\nExplain \u{1b}[31m**the change**\u{1b}[0m"
+ ),
+ Vec::new(),
+ ),
+ Arc::new(AgentMarkdownCell::new(
+ "```rust\nlet answer = 42;\n```".to_string(),
+ std::path::Path::new("."),
+ )),
+ Arc::new(new_proposed_plan(
+ "completed plan".to_string(),
+ std::path::Path::new("."),
+ )),
+ Arc::new(PlainHistoryCell::new(vec!["$ cargo test".into()])),
+ Arc::new(PlainHistoryCell::new(vec![
+ "■ Export failed: missing parent".into(),
+ ])),
+ user("", vec!["image.png".into()]),
+ user("[Image #1] describe this", vec!["image.png".into()]),
+ ];
+
+ insta::assert_snapshot!(
+ "markdown_transcript",
+ render_markdown_transcript(&cells).expect("exported transcript")
+ );
+}
+
+#[test]
+fn transcript_export_excludes_hidden_review_prompts_and_nested_duplicates() {
+ let user = |id: &str, text: &str| ThreadItem::UserMessage {
+ id: id.to_string(),
+ client_id: None,
+ content: vec![UserInput::Text {
+ text: text.to_string(),
+ text_elements: Vec::new(),
+ }],
+ };
+ let entered_review = ThreadItem::EnteredReviewMode {
+ id: "review-enter".to_string(),
+ review: "review".to_string(),
+ };
+ let exited_review = ThreadItem::ExitedReviewMode {
+ id: "review-exit".to_string(),
+ review: "review".to_string(),
+ };
+ let duplicate_one = user("duplicate-one", "duplicate review prompt");
+ let duplicate_two = user("duplicate-two", "duplicate review prompt");
+ let turn = |id: &str, items: Vec<ThreadItem>, status| Turn {
+ id: id.to_string(),
+ items,
+ items_view: TurnItemsView::Full,
+ status,
+ error: None,
+ started_at: None,
+ completed_at: None,
+ duration_ms: None,
+ };
+ let review = turn(
+ "review-turn",
+ vec![
+ entered_review.clone(),
+ user("review-prompt", "hidden review prompt"),
+ exited_review.clone(),
+ ],
+ TurnStatus::Completed,
+ );
+ let nested = turn(
+ "nested-turn",
+ vec![duplicate_one.clone(), duplicate_two.clone()],
+ TurnStatus::Interrupted,
+ );
+ assert_eq!(
+ visible_export_items(vec![review.clone(), nested]),
+ vec![entered_review.clone(), exited_review.clone()],
+ );
+ let completed = turn(
+ "completed-turn",
+ vec![duplicate_one.clone(), duplicate_two.clone()],
+ TurnStatus::Completed,
+ );
+ assert_eq!(
+ visible_export_items(vec![review, completed]),
+ vec![entered_review, exited_review, duplicate_one, duplicate_two],
+ );
+}
+
+#[test]
+fn persisted_transcript_includes_file_and_mcp_details() {
+ let cells = [
+ serde_json::json!({
+ "type": "fileChange", "id": "patch", "status": "completed",
+ "changes": [{"path": "src/lib.rs", "kind": {"type": "add"},
+ "diff": "+fn answer() -> u8 { 42 }"}]
+ }),
+ serde_json::json!({
+ "type": "mcpToolCall", "id": "tool", "server": "docs", "tool": "search",
+ "status": "completed", "arguments": {"query": "export"},
+ "result": {"content": [
+ {"type": "text", "text": "\u{1b}[31mmatching docs\u{1b}[0m\nnext line"},
+ {"type": "image", "data": "c2VjcmV0", "mimeType": "image/png"},
+ {"type": "audio", "data": "c2VjcmV0", "mimeType": "audio/wav"},
+ {"type": "resource", "resource": {
+ "uri": "file:///report.md", "text": "hidden resource body"}},
+ {"type": "resource_link", "uri": "file:///linked.md", "name": "linked"}
+ ],
+ "structuredContent": {"count": 1}, "_meta": null}
+ }),
+ serde_json::json!({
+ "type": "mcpToolCall", "id": "failed", "server": "docs", "tool": "fetch",
+ "status": "failed", "arguments": {"id": 7},
+ "error": {"message": "document unavailable\n# injected heading"}
+ }),
+ ]
+ .into_iter()
+ .map(|item| serde_json::from_value::<ThreadItem>(item).expect("valid thread item"))
+ .filter_map(|item| {
+ super::export_activity_cell(&item).map(|cell| Arc::new(cell) as Arc<dyn HistoryCell>)
+ })
+ .collect::<Vec<_>>();
+ let markdown = render_markdown_transcript(&cells).expect("exported transcript");
+
+ for detail in [
+ "src/lib.rs",
+ "+fn answer() -> u8 { 42 }",
+ r#"{"query":"export"}"#,
+ "matching docs",
+ "next line",
+ "<image content>",
+ "<audio content>",
+ "embedded resource: file:///report.md",
+ "link: file:///linked.md",
+ r#"structured result: {"count":1}"#,
+ "document unavailable",
+ " # injected heading",
+ ] {
+ assert!(markdown.contains(detail), "missing {detail}: {markdown}");
+ }
+ assert!(!markdown.contains("c2VjcmV0"));
+ assert!(!markdown.contains('\u{1b}'));
+}
+
+#[test]
+fn transcript_file_resolves_relative_paths_and_refuses_to_overwrite() {
+ let directory = tempfile::tempdir().expect("temporary directory");
+ let path = 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());
+ assert_eq!(
+ std::fs::read_to_string(&path).expect("read"),
+ "# First export\n"
+ );
+
+ let directory_name = directory.path().file_name().expect("directory name");
+ let requested = std::path::Path::new("~")
+ .join(directory_name)
+ .join("conversation.md");
+ let error = write_transcript(directory.path(), &requested, "# Export\n")
+ .expect_err("missing home-relative parent directory");
+ assert!(error.contains(&dirs::home_dir().expect("home").display().to_string()));
+}
diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs
index 4e55cca72c..0d07498516 100644
--- a/codex-rs/tui/src/app_event.rs
+++ b/codex-rs/tui/src/app_event.rs
@@ -184,6 +184,12 @@ pub(crate) enum KeymapCaptureMode {
Chord,
}
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) enum TranscriptExportDestination {
+ Clipboard,
+ File(PathBuf),
+}
+
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub(crate) enum AppEvent {
@@ -237,6 +243,14 @@ pub(crate) enum AppEvent {
result: Result<ThreadItemsListResponse, String>,
},
+ /// Open the filename prompt for an on-demand Markdown transcript export.
+ OpenTranscriptExportFilePrompt,
+
+ /// Export all current-thread history to the selected destination.
+ ExportTranscript {
+ destination: TranscriptExportDestination,
+ },
+
/// Persist a submitted prompt in the cross-session message history.
AppendMessageHistoryEntry {
thread_id: ThreadId,
diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs
index 06166e5969..fb007c653a 100644
--- a/codex-rs/tui/src/app_server_session.rs
+++ b/codex-rs/tui/src/app_server_session.rs
@@ -169,7 +169,7 @@ fn bootstrap_request_error(context: &'static str, err: TypedRequestError) -> col
color_eyre::eyre::eyre!("{context}: {err}")
}
-fn is_history_pagination_unsupported(source: &JSONRPCErrorError) -> bool {
+pub(crate) fn is_history_pagination_unsupported(source: &JSONRPCErrorError) -> bool {
if source.code == JSONRPC_METHOD_NOT_FOUND {
return true;
}
diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs
index 9574b615ed..9dc2cd92a2 100644
--- a/codex-rs/tui/src/bottom_pane/chat_composer.rs
+++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs
@@ -85,7 +85,8 @@
//! Parent-owned subagent threads keep the draft editable while blocking agent-directed submission.
//! On the `Enter` and `Tab` submission paths, normal prompts, disallowed slash commands, and `!`
//! shell commands return `ParentOwnedInputBlocked` without clearing the draft. Bare local and
-//! navigation slash commands remain available so users can leave or manage the view.
+//! navigation slash commands remain available so users can leave or manage the view. Transcript
+//! exports also remain available, including an explicit destination filename.
//!
//! # Reasoning Effort Animations
//!
@@ -357,6 +358,10 @@ pub enum InputResult {
}
fn parent_owned_command_is_allowed(command: SlashCommand, args: &str) -> bool {
+ if command == SlashCommand::Export {
+ return true;
+ }
+
args.is_empty()
&& matches!(
command,
diff --git a/codex-rs/tui/src/bottom_pane/slash_commands.rs b/codex-rs/tui/src/bottom_pane/slash_commands.rs
index 6ca1ba93d1..139990e40f 100644
--- a/codex-rs/tui/src/bottom_pane/slash_commands.rs
+++ b/codex-rs/tui/src/bottom_pane/slash_commands.rs
@@ -304,6 +304,7 @@ mod tests {
vec![
SlashCommand::Ide,
SlashCommand::Copy,
+ SlashCommand::Export,
SlashCommand::Raw,
SlashCommand::Diff,
SlashCommand::Mention,
diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__command_popup__tests__command_popup_default_items.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__command_popup__tests__command_popup_default_items.snap
index 93b3d93a8f..f7c45aec63 100644
--- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__command_popup__tests__command_popup_default_items.snap
+++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__command_popup__tests__command_popup_default_items.snap
@@ -26,6 +26,7 @@ expression: commands
/agent - switch the active agent thread
/side - start a side conversation in an ephemeral fork
/copy - copy last response as markdown
+/export - export the conversation as markdown
/raw - toggle raw scrollback mode for copy-friendly terminal selection
/diff - show git diff (including untracked files)
/mention - mention a file
diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs
index bb1d3aac47..4948cce1e3 100644
--- a/codex-rs/tui/src/chatwidget.rs
+++ b/codex-rs/tui/src/chatwidget.rs
@@ -429,6 +429,7 @@ pub(crate) use self::tokens::TokenActivityView;
mod tool_lifecycle;
mod tool_requests;
mod transcript;
+mod transcript_export;
use self::transcript::TranscriptState;
mod turn_lifecycle;
mod turn_runtime;
diff --git a/codex-rs/tui/src/chatwidget/slash_dispatch.rs b/codex-rs/tui/src/chatwidget/slash_dispatch.rs
index e0d19d8b89..fafe2e079b 100644
--- a/codex-rs/tui/src/chatwidget/slash_dispatch.rs
+++ b/codex-rs/tui/src/chatwidget/slash_dispatch.rs
@@ -141,6 +141,7 @@ impl ChatWidget {
|| (cmd == SlashCommand::Resume
&& (self.input_queue.user_turn_pending_start
|| self.turn_lifecycle.agent_turn_running))
+ || (cmd == SlashCommand::Export && self.input_queue.suppress_queue_autosend)
}
pub(super) fn dispatch_command(&mut self, cmd: SlashCommand) {
@@ -399,6 +400,9 @@ impl ChatWidget {
SlashCommand::Copy => {
self.copy_last_agent_markdown();
}
+ SlashCommand::Export => {
+ self.show_transcript_export_popup();
+ }
SlashCommand::Raw => {
let enabled = self.toggle_raw_output_mode_and_notify();
self.emit_raw_output_mode_changed(enabled);
@@ -681,6 +685,15 @@ impl ChatWidget {
} = prepared;
let trimmed = args.trim();
match cmd {
+ SlashCommand::Export if trimmed.is_empty() => self.show_transcript_export_popup(),
+ SlashCommand::Export => {
+ self.set_queue_autosend_suppressed(/*suppressed*/ true);
+ self.app_event_tx.send(AppEvent::ExportTranscript {
+ destination: crate::app_event::TranscriptExportDestination::File(
+ PathBuf::from(trimmed),
+ ),
+ });
+ }
SlashCommand::Usage => {
if self.ensure_usage_command_available() {
match tokens::TokenActivityView::parse(trimmed) {
@@ -1090,6 +1103,7 @@ impl ChatWidget {
| SlashCommand::Rename
| SlashCommand::TestApproval => QueueDrain::Continue,
SlashCommand::Feedback
+ | SlashCommand::Export
| SlashCommand::New
| SlashCommand::Archive
| SlashCommand::Delete
diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_export_completion_message.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_export_completion_message.snap
new file mode 100644
index 0000000000..48d4adb50e
--- /dev/null
+++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_export_completion_message.snap
@@ -0,0 +1,8 @@
+---
+source: tui/src/chatwidget/tests/slash_commands.rs
+expression: "cells.iter().map(|cell|\nlines_to_single_string(cell).trim().to_string()).collect::<Vec<_>>().join(\"\\n\")"
+---
+• Saved conversation to conversation.md
+• Copied conversation to clipboard
+■ Copy failed: clipboard unavailable
+■ Export failed: missing parent
diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_export_destination_picker.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_export_destination_picker.snap
new file mode 100644
index 0000000000..122c1f8d54
--- /dev/null
+++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_export_destination_picker.snap
@@ -0,0 +1,11 @@
+---
+source: tui/src/chatwidget/tests/slash_commands.rs
+expression: popup
+---
+ Export conversation
+ Save the complete conversation as Markdown
+
+› 1. Copy to clipboard Copy the complete Markdown transcript
+ 2. Save to file Choose a Markdown filename
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_export_filename_prompt.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_export_filename_prompt.snap
new file mode 100644
index 0000000000..aab1da242c
--- /dev/null
+++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__slash_export_filename_prompt.snap
@@ -0,0 +1,9 @@
+---
+source: tui/src/chatwidget/tests/slash_commands.rs
+expression: popup
+---
+▌ Save conversation
+▌
+▌ codex-session-00000000-0000-0000-0000-000000000123.md
+
+Press enter to confirm or esc to go back
diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs
index ff3b3fb5df..bb62505808 100644
--- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs
+++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs
@@ -1757,6 +1757,40 @@ async fn slash_copy_reports_when_no_agent_response_exists() {
);
}
+#[tokio::test]
+async fn slash_export_opens_destination_picker() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
+
+ chat.thread_id = Some(
+ ThreadId::from_string("00000000-0000-0000-0000-000000000123").expect("valid thread ID"),
+ );
+ handle_turn_started(&mut chat, "turn-1");
+ queue_composer_text_with_tab(&mut chat, "/export");
+ complete_turn_with_message(&mut chat, "turn-1", /*message*/ None);
+
+ let popup = render_bottom_popup(&chat, /*width*/ 80);
+ assert_chatwidget_snapshot!("slash_export_destination_picker", popup);
+ chat.show_transcript_export_file_prompt();
+ let popup = render_bottom_popup(&chat, /*width*/ 100);
+ assert_chatwidget_snapshot!("slash_export_filename_prompt", popup);
+
+ let statuses = "Saved conversation to conversation.md\nCopied conversation to clipboard";
+ for message in statuses.lines() {
+ chat.add_info_message(message.into(), /*hint*/ None);
+ }
+ chat.add_error_message("Copy failed: clipboard unavailable".to_string());
+ chat.add_error_message("Export failed: missing parent".to_string());
+ let cells = drain_insert_history(&mut rx);
+ assert_chatwidget_snapshot!(
+ "slash_export_completion_message",
+ cells
+ .iter()
+ .map(|cell| lines_to_single_string(cell).trim().to_string())
+ .collect::<Vec<_>>()
+ .join("\n"),
+ );
+}
+
#[tokio::test]
async fn ctrl_o_copy_reports_when_no_agent_response_exists() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
diff --git a/codex-rs/tui/src/chatwidget/transcript_export.rs b/codex-rs/tui/src/chatwidget/transcript_export.rs
new file mode 100644
index 0000000000..a12686b487
--- /dev/null
+++ b/codex-rs/tui/src/chatwidget/transcript_export.rs
@@ -0,0 +1,74 @@
+//! Destination and filename prompts for on-demand transcript exports.
+
+use super::*;
+use crate::app_event::TranscriptExportDestination;
+
+impl ChatWidget {
+ pub(crate) fn copy_transcript_to_clipboard(&mut self, markdown: &str) {
+ match crate::clipboard_copy::copy_to_clipboard(markdown) {
+ Ok(lease) => {
+ self.clipboard_lease = lease;
+ self.add_info_message(
+ "Copied conversation to clipboard".to_string(),
+ /*hint*/ None,
+ );
+ }
+ Err(error) => self.add_error_message(format!("Copy failed: {error}")),
+ }
+ }
+
+ pub(super) fn show_transcript_export_popup(&mut self) {
+ self.show_selection_view(SelectionViewParams {
+ title: Some("Export conversation".to_string()),
+ subtitle: Some("Save the complete conversation as Markdown".to_string()),
+ footer_hint: Some(standard_popup_hint_line()),
+ items: vec![
+ SelectionItem {
+ name: "Copy to clipboard".to_string(),
+ description: Some("Copy the complete Markdown transcript".to_string()),
+ is_disabled: cfg!(target_os = "android"),
+ actions: vec![Box::new(|tx| {
+ tx.send(AppEvent::ExportTranscript {
+ destination: TranscriptExportDestination::Clipboard,
+ });
+ })],
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "Save to file".to_string(),
+ description: Some("Choose a Markdown filename".to_string()),
+ actions: vec![Box::new(|tx| {
+ tx.send(AppEvent::OpenTranscriptExportFilePrompt);
+ })],
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ],
+ ..Default::default()
+ });
+ self.defer_input_until_settings_applied();
+ 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"),
+ );
+ let view = CustomPromptView::new(
+ "Save conversation".to_string(),
+ "Type a filename and press Enter".to_string(),
+ filename,
+ /*context_label*/ None,
+ Box::new(move |filename| {
+ tx.send(AppEvent::ExportTranscript {
+ destination: TranscriptExportDestination::File(PathBuf::from(filename)),
+ });
+ }),
+ );
+ self.bottom_pane.show_view(Box::new(view));
+ self.request_redraw();
+ }
+}
diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs
index 07cb2c14da..b369870346 100644
--- a/codex-rs/tui/src/slash_command.rs
+++ b/codex-rs/tui/src/slash_command.rs
@@ -44,6 +44,7 @@ pub enum SlashCommand {
Side,
Btw,
Copy,
+ Export,
Raw,
Diff,
Mention,
@@ -96,6 +97,7 @@ impl SlashCommand {
SlashCommand::App => "continue this session in the Desktop app",
SlashCommand::Quit | SlashCommand::Exit => "exit Codex",
SlashCommand::Copy => "copy last response as markdown",
+ SlashCommand::Export => "export the conversation as markdown",
SlashCommand::Raw => "toggle raw scrollback mode for copy-friendly terminal selection",
SlashCommand::Diff => "show git diff (including untracked files)",
SlashCommand::Mention => "mention a file",
@@ -163,6 +165,7 @@ impl SlashCommand {
| SlashCommand::Ide
| SlashCommand::Keymap
| SlashCommand::Mcp
+ | SlashCommand::Export
| SlashCommand::Raw
| SlashCommand::Usage
| SlashCommand::Pets
@@ -178,6 +181,7 @@ impl SlashCommand {
matches!(
self,
SlashCommand::Copy
+ | SlashCommand::Export
| SlashCommand::Raw
| SlashCommand::Diff
| SlashCommand::Mention
@@ -196,6 +200,7 @@ impl SlashCommand {
| SlashCommand::Fork
| SlashCommand::Init
| SlashCommand::Compact
+ | SlashCommand::Export
| SlashCommand::Keymap
| SlashCommand::Vim
| SlashCommand::ElevateSandbox