mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Add Markdown conversation export to the TUI (#37358)
## What changed - Add `/export` with clipboard and file destinations, including a default filename prompt and support for an explicit path argument. - Export the complete conversation history as structured Markdown, preserving user and assistant messages, plans, reasoning, activity, image labels, file changes, and MCP tool details while honoring reasoning visibility. - Fall back to legacy history loading when pagination is unavailable, and use the visible transcript for ephemeral sessions. - Resolve relative and home-relative paths without overwriting an existing file, and report export or copy results in the conversation. ## Testing - Cover Markdown rendering, hidden review prompts, activity details, complete paginated and legacy history loading, destination prompts, status messages, path resolution, and overwrite protection. GitOrigin-RevId: c2815fc2430d7a555da75d7038cc1ac08157b82e
This commit is contained in:
1 parent
4d7e3e90d9
commit
2801d12661
19 files changed
+795
-3
No files matched your search
@@ -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();
|
||||
|
||||
+31
@@ -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
|
||||
@@ -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(())
|
||||
|
||||
@@ -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;
|
||||
@@ -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()));
|
||||
}
|
||||
Reference in new issue
Block a user