diff --git a/codex-rs/tui/src/app/recap_tests.rs b/codex-rs/tui/src/app/recap_tests.rs index 4fecb1fc47..8f03cabe41 100644 --- a/codex-rs/tui/src/app/recap_tests.rs +++ b/codex-rs/tui/src/app/recap_tests.rs @@ -48,6 +48,7 @@ fn turn(status: TurnStatus) -> Turn { fn user_history_cell(message: &str) -> Arc { Arc::new(UserHistoryCell { message: message.to_string(), + spoken: false, text_elements: Vec::new(), local_image_paths: Vec::new(), remote_image_urls: Vec::new(), diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 16a583e918..a3d6f456dd 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -5665,6 +5665,7 @@ async fn render_clear_ui_header_after_long_transcript_for_snapshot() -> String { let user_cell = |text: &str| -> Arc { Arc::new(UserHistoryCell { + spoken: false, message: text.to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), @@ -7096,6 +7097,7 @@ async fn backtrack_selection_preserves_selected_prompt_and_requests_branch() { remote_image_urls: Vec| -> Arc { Arc::new(UserHistoryCell { + spoken: false, message: text.to_string(), text_elements, local_image_paths, @@ -9107,6 +9109,7 @@ async fn clear_only_ui_reset_preserves_chat_session_state() { app.chat_widget .apply_external_edit("draft prompt".to_string()); app.transcript_cells = vec![Arc::new(UserHistoryCell { + spoken: false, message: "old message".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), diff --git a/codex-rs/tui/src/app/tests/recap_generation_tests.rs b/codex-rs/tui/src/app/tests/recap_generation_tests.rs index 60ef4b4fb0..b194702f1f 100644 --- a/codex-rs/tui/src/app/tests/recap_generation_tests.rs +++ b/codex-rs/tui/src/app/tests/recap_generation_tests.rs @@ -39,6 +39,7 @@ fn prepare_eligible_recap(app: &mut App, thread_id: ThreadId) { app.transcript_cells .push(Arc::new(crate::history_cell::UserHistoryCell { message: "Finish the recap implementation".to_string(), + spoken: false, text_elements: Vec::new(), local_image_paths: Vec::new(), remote_image_urls: Vec::new(), @@ -200,6 +201,7 @@ async fn manual_recap_works_when_auto_recap_disabled() -> Result<()> { app.transcript_cells .push(Arc::new(crate::history_cell::UserHistoryCell { message: "Summarize this conversation".to_string(), + spoken: false, text_elements: Vec::new(), local_image_paths: Vec::new(), remote_image_urls: Vec::new(), @@ -379,6 +381,7 @@ async fn recap_generation_uses_remote_workspace_cwd() -> Result<()> { app.transcript_cells .push(Arc::new(crate::history_cell::UserHistoryCell { message: "Finish the recap implementation".to_string(), + spoken: false, text_elements: Vec::new(), local_image_paths: Vec::new(), remote_image_urls: Vec::new(), diff --git a/codex-rs/tui/src/app/tests/startup_warnings_tests.rs b/codex-rs/tui/src/app/tests/startup_warnings_tests.rs index ab2bcaa976..e079c86ffb 100644 --- a/codex-rs/tui/src/app/tests/startup_warnings_tests.rs +++ b/codex-rs/tui/src/app/tests/startup_warnings_tests.rs @@ -53,6 +53,7 @@ async fn startup_warnings_preserve_stream_repair_and_backtrack_selection() -> Re text_elements: Vec::new(), local_image_paths: Vec::new(), remote_image_urls: Vec::new(), + spoken: false, })]; app.transcript_reflow.mark_resize_requested_during_stream(); insert_warnings(&mut app, &mut tui, &["First warning"]); diff --git a/codex-rs/tui/src/app/tests/transcript_composer.rs b/codex-rs/tui/src/app/tests/transcript_composer.rs index 358e05d031..7d0fce5446 100644 --- a/codex-rs/tui/src/app/tests/transcript_composer.rs +++ b/codex-rs/tui/src/app/tests/transcript_composer.rs @@ -42,6 +42,7 @@ async fn transcript_flag_off_preserves_viewer_and_backtracking() -> Result<()> { text_elements: Vec::new(), local_image_paths: Vec::new(), remote_image_urls: Vec::new(), + spoken: false, }) as Arc }) .to_vec(); diff --git a/codex-rs/tui/src/app/transcript_export_tests.rs b/codex-rs/tui/src/app/transcript_export_tests.rs index f7212ad9d5..1acf971073 100644 --- a/codex-rs/tui/src/app/transcript_export_tests.rs +++ b/codex-rs/tui/src/app/transcript_export_tests.rs @@ -21,6 +21,7 @@ fn markdown_transcript_preserves_messages_and_formats_activity() { assert!(render_markdown_transcript(&[]).is_err()); let user = |message: &str, local_image_paths| { Arc::new(UserHistoryCell { + spoken: false, message: message.to_string(), text_elements: Vec::new(), local_image_paths, diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index 242b0215c6..bb6189bdd3 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -960,6 +960,7 @@ mod tests { assert!(!has_backtrack_target(&cells)); cells.push(Arc::new(UserHistoryCell { + spoken: false, message: "hello".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), diff --git a/codex-rs/tui/src/chatwidget/realtime.rs b/codex-rs/tui/src/chatwidget/realtime.rs index 0c0950ed32..c3dc17683c 100644 --- a/codex-rs/tui/src/chatwidget/realtime.rs +++ b/codex-rs/tui/src/chatwidget/realtime.rs @@ -1500,20 +1500,12 @@ impl ChatWidget { fn realtime_transcript_history_cell(&self, role: &str, text: &str) -> Box { if role == "user" { - Box::new(history_cell::new_user_prompt( - text.to_string(), - Vec::new(), - Vec::new(), - Vec::new(), - )) + Box::new(history_cell::new_spoken_user_prompt(text.to_string())) } else { - Box::new( - history_cell::AgentMarkdownCell::new_with_inline_visualizations( - text.to_string(), - &self.config.cwd, - /*inline_visualization_context*/ None, - ), - ) + Box::new(history_cell::AgentMarkdownCell::new_spoken( + text.to_string(), + &self.config.cwd, + )) } } diff --git a/codex-rs/tui/src/chatwidget/realtime_split_flap.rs b/codex-rs/tui/src/chatwidget/realtime_split_flap.rs index 2adf54120c..85a68e3b92 100644 --- a/codex-rs/tui/src/chatwidget/realtime_split_flap.rs +++ b/codex-rs/tui/src/chatwidget/realtime_split_flap.rs @@ -196,7 +196,7 @@ impl SplitFlapTranscriptCell { text } else { if grapheme == "›" { - style = style.fg(Color::Cyan); + style = style.fg(span.style.fg.unwrap_or(Color::Cyan)); } else if grapheme == "•" { style = style.fg(Color::Magenta); } diff --git a/codex-rs/tui/src/chatwidget/realtime_tests/transcripts.rs b/codex-rs/tui/src/chatwidget/realtime_tests/transcripts.rs index 39096aef9f..99768e31a0 100644 --- a/codex-rs/tui/src/chatwidget/realtime_tests/transcripts.rs +++ b/codex-rs/tui/src/chatwidget/realtime_tests/transcripts.rs @@ -726,3 +726,33 @@ async fn live_voice_split_flap_animates_without_changing_final_history() { .any(|line| { line.to_string().contains("gate 73") }) ); } + +#[tokio::test] +async fn spoken_user_transcript_preserves_red_chevron_and_canonical_history() { + let (mut chat, _sender, mut events, _ops) = make_chatwidget_manual_with_sender().await; + activate_voice(&mut chat); + chat.on_realtime_transcript_delta("user".to_string(), "hello".to_string()); + let marker = chat + .realtime_conversation + .live_transcript_cell + .as_ref() + .unwrap() + .display_lines(/*width*/ 32) + .into_iter() + .flat_map(|line| line.spans) + .find(|span| span.content == "›") + .expect("genuine spoken user marker"); + assert_eq!(marker.style.fg, Some(ratatui::style::Color::Red)); + assert!( + marker + .style + .add_modifier + .contains(ratatui::style::Modifier::BOLD) + ); + chat.on_realtime_transcript_done("user".to_string(), "hello".to_string()); + let Ok(AppEvent::InsertHistoryCell(cell)) = events.try_recv() else { + panic!("completed voice transcript should retain its ordinary history cell"); + }; + assert!(cell.as_any().is::()); + assert_eq!(cell.raw_lines()[0].to_string(), "hello"); +} diff --git a/codex-rs/tui/src/history_cell/messages.rs b/codex-rs/tui/src/history_cell/messages.rs index c026b5dcae..ea74889d03 100644 --- a/codex-rs/tui/src/history_cell/messages.rs +++ b/codex-rs/tui/src/history_cell/messages.rs @@ -15,6 +15,7 @@ pub(crate) struct UserHistoryCell { #[allow(dead_code)] pub local_image_paths: Vec, pub remote_image_urls: Vec, + pub(crate) spoken: bool, } /// Remove CSI sequences and control characters, preserving tabs and newlines. @@ -157,8 +158,14 @@ impl HistoryCell for UserHistoryCell { } fn display_hyperlink_lines(&self, width: u16) -> Vec { - let message = sanitize_user_text((&self.message).into()); - let text_elements = if message.as_ref() == self.message { + let sanitized_message = sanitize_user_text((&self.message).into()); + // Speech transcripts can begin with whitespace; the marker already supplies its separator. + let message = if self.spoken { + sanitized_message.trim_start() + } else { + sanitized_message.as_ref() + }; + let text_elements = if message == self.message { self.text_elements.as_slice() } else { &[] @@ -203,7 +210,7 @@ impl HistoryCell for UserHistoryCell { } else { adaptive_wrap_lines( build_user_message_lines_with_elements( - message.as_ref(), + message, text_elements, style, element_style, @@ -262,7 +269,11 @@ impl HistoryCell for UserHistoryCell { if let Some(wrapped_message) = wrapped_message { lines.extend(prefix_hyperlink_lines( wrapped_message, - "› ".bold().dim(), + if self.spoken { + "› ".red().bold() + } else { + "› ".bold().dim() + }, " ".into(), )); } @@ -449,6 +460,7 @@ pub(crate) struct AgentMarkdownCell { cwd: PathBuf, inline_visualization_context: Option, rendered_lines: Option, + spoken_artifacts: bool, } impl AgentMarkdownCell { @@ -481,8 +493,19 @@ impl AgentMarkdownCell { cwd: cwd.to_path_buf(), inline_visualization_context, rendered_lines, + spoken_artifacts: false, } } + + pub(crate) fn new_spoken(markdown_source: String, cwd: &Path) -> Self { + let mut cell = Self::new_with_inline_visualizations( + markdown_source, + cwd, + /*inline_visualization_context*/ None, + ); + cell.spoken_artifacts = true; + cell + } } fn normalize_whitespace_only_hyperlink_lines(mut lines: Vec) -> Vec { @@ -525,6 +548,13 @@ impl HistoryCell for AgentMarkdownCell { Some(self.cwd.as_path()), self.inline_visualization_context.as_ref(), ); + let lines = if self.spoken_artifacts { + let mut lines = lines; + super::spoken_artifacts::annotate_spoken_artifacts(&mut lines, &self.cwd); + lines + } else { + lines + }; normalize_whitespace_only_hyperlink_lines(prefix_hyperlink_lines( lines, "• ".dim(), @@ -618,8 +648,16 @@ pub(crate) fn new_user_prompt( text_elements, local_image_paths, remote_image_urls, + spoken: false, } } + +pub(crate) fn new_spoken_user_prompt(message: String) -> UserHistoryCell { + let mut cell = new_user_prompt(message, Vec::new(), Vec::new(), Vec::new()); + cell.spoken = true; + cell +} + /// Create the reasoning history cell emitted at the end of a reasoning block. /// /// The helper snapshots `cwd` into the returned cell so local file links render the same way they diff --git a/codex-rs/tui/src/history_cell/messages_tests.rs b/codex-rs/tui/src/history_cell/messages_tests.rs index 0288915899..deabffe9ad 100644 --- a/codex-rs/tui/src/history_cell/messages_tests.rs +++ b/codex-rs/tui/src/history_cell/messages_tests.rs @@ -62,6 +62,51 @@ fn sanitizer_preallocates_owned_multi_fragment_text() { }) } +#[test] +fn spoken_user_messages_have_a_red_chevron_without_changing_raw_text() { + let message = " hello from voice"; + let spoken = new_spoken_user_prompt(message.to_string()); + let typed = new_user_prompt(message.to_string(), Vec::new(), Vec::new(), Vec::new()); + let marker = spoken + .display_hyperlink_lines(/*width*/ 40) + .into_iter() + .flat_map(|line| line.line.spans) + .find(|span| span.content == "› ") + .expect("spoken user marker"); + + assert!( + spoken + .display_lines(/*width*/ 40) + .iter() + .any(|line| line.to_string() == "› hello from voice") + ); + assert!( + typed + .display_lines(/*width*/ 40) + .iter() + .any(|line| { line.to_string() == "› hello from voice" }) + ); + assert_eq!(marker.style.fg, Some(Color::Red)); + assert!(marker.style.add_modifier.contains(Modifier::BOLD)); + assert_eq!(spoken.raw_lines(), vec![Line::from(message)]); + assert_eq!( + spoken.display_lines_for_mode(/*width*/ 40, HistoryRenderMode::Raw), + vec![Line::from(message)] + ); + assert!(typed.display_lines(/*width*/ 40).iter().any(|line| { + line.spans + .iter() + .any(|span| span.content == "› " && span.style.fg != Some(Color::Red)) + })); + + let area = Rect::new( + /*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 3, + ); + let mut buf = Buffer::empty(area); + Paragraph::new(spoken.display_lines(area.width)).render(area, &mut buf); + insta::assert_snapshot!("spoken_user_prompt", format!("{buf:?}")); +} + fn replace_cached_lines( cell: &AgentMarkdownCell, update_key: impl FnOnce(&mut MarkdownRenderCacheKey), @@ -158,3 +203,86 @@ fn visualization_directives_are_not_cached() { assert!(cell.rendered_lines.is_none()); } } + +#[test] +fn spoken_artifacts_link_only_real_workspace_files_and_preserve_existing_urls() { + let workspace = tempfile::tempdir().expect("workspace"); + let source_directory = workspace.path().join("src"); + std::fs::create_dir(&source_directory).expect("source directory"); + let source_file = source_directory.join("lib.rs"); + std::fs::write(&source_file, "fn example() {}\n").expect("source file"); + let markdown = "中 src/lib.rs:42 and https://example.com"; + let spoken = AgentMarkdownCell::new_spoken(markdown.to_string(), workspace.path()); + let lines = spoken.display_hyperlink_lines(/*width*/ 90); + let line = &lines[0]; + + let expected_destination = + url::Url::from_file_path(source_file.canonicalize().expect("canonical source file")) + .expect("workspace file URL") + .to_string(); + assert_eq!( + line.hyperlinks + .iter() + .map(|link| (link.columns.clone(), link.destination.as_str())) + .collect::>(), + vec![ + (5..18, expected_destination.as_str()), + (23..42, "https://example.com"), + ] + ); + assert!(line.line.spans.iter().any(|span| { + span.content == "src/lib.rs:42" && span.style.add_modifier.contains(Modifier::UNDERLINED) + })); + assert_eq!(spoken.raw_lines(), vec![Line::from(markdown)]); + insta::assert_snapshot!( + format!( + "{}\n{:?} -> /src/lib.rs\n{:?} -> https://example.com", + line.line, line.hyperlinks[0].columns, line.hyperlinks[1].columns + ), + @r" + • 中 src/lib.rs:42 and https://example.com + 5..18 -> /src/lib.rs + 23..42 -> https://example.com + " + ); + + let ordinary = AgentMarkdownCell::new(markdown.to_string(), workspace.path()); + assert_eq!( + ordinary.display_hyperlink_lines(/*width*/ 90)[0].hyperlinks[0].destination, + "https://example.com" + ); + let bare = AgentMarkdownCell::new_spoken("src/lib.rs".to_string(), workspace.path()); + assert_eq!( + bare.display_hyperlink_lines(/*width*/ 40)[0] + .hyperlinks + .len(), + 1 + ); +} + +#[test] +fn spoken_windows_relative_paths_keep_original_text_and_link_the_workspace_file() { + let workspace = tempfile::tempdir().expect("workspace"); + let source_directory = workspace.path().join("src"); + std::fs::create_dir(&source_directory).expect("source directory"); + let source_file = source_directory.join("lib.rs"); + std::fs::write(&source_file, "fn example() {}\n").expect("source file"); + let markdown = "Updated src\\lib.rs:42"; + let spoken = AgentMarkdownCell::new_spoken(markdown.to_string(), workspace.path()); + let lines = spoken.display_hyperlink_lines(/*width*/ 80); + let line = &lines[0]; + + assert_eq!(spoken.raw_lines(), vec![Line::from(markdown)]); + assert_eq!(line.hyperlinks.len(), 1); + assert_eq!(line.hyperlinks[0].columns, 10..23); + assert_eq!( + line.hyperlinks[0].destination, + url::Url::from_file_path(source_file.canonicalize().expect("canonical source file")) + .expect("workspace file URL") + .to_string() + ); + assert!(line.line.spans.iter().any(|span| { + span.content == "src\\lib.rs:42" && span.style.add_modifier.contains(Modifier::UNDERLINED) + })); + insta::assert_snapshot!(line.line.to_string(), @"• Updated src\\lib.rs:42"); +} diff --git a/codex-rs/tui/src/history_cell/mod.rs b/codex-rs/tui/src/history_cell/mod.rs index 5caf68623c..bcbcd8dc1c 100644 --- a/codex-rs/tui/src/history_cell/mod.rs +++ b/codex-rs/tui/src/history_cell/mod.rs @@ -116,6 +116,7 @@ mod request_user_input; mod search; mod separators; mod session; +mod spoken_artifacts; mod startup_warnings; pub(crate) use approvals::*; diff --git a/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__messages__tests__spoken_user_prompt.snap b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__messages__tests__spoken_user_prompt.snap new file mode 100644 index 0000000000..5e4c5f320f --- /dev/null +++ b/codex-rs/tui/src/history_cell/snapshots/codex_tui__history_cell__messages__tests__spoken_user_prompt.snap @@ -0,0 +1,18 @@ +--- +source: tui/src/history_cell/messages_tests.rs +assertion_line: 107 +expression: "format!(\"{buf:?}\")" +--- +Buffer { + area: Rect { x: 0, y: 0, width: 40, height: 3 }, + content: [ + " ", + "› hello from voice ", + " ", + ], + styles: [ + x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + x: 0, y: 1, fg: Red, bg: Reset, underline: Reset, modifier: BOLD, + x: 2, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE, + ] +} diff --git a/codex-rs/tui/src/history_cell/spoken_artifacts.rs b/codex-rs/tui/src/history_cell/spoken_artifacts.rs new file mode 100644 index 0000000000..ae13971b9d --- /dev/null +++ b/codex-rs/tui/src/history_cell/spoken_artifacts.rs @@ -0,0 +1,94 @@ +//! Workspace-confined OSC 8 file links for spoken assistant transcript cells. + +use crate::terminal_hyperlinks::HyperlinkLine; +use crate::terminal_hyperlinks::TerminalHyperlink; +use crate::terminal_hyperlinks::TrustedWorkspaceFile; +use crate::width::display_width; +use ratatui::style::Modifier; +use ratatui::text::Span; +use std::path::Path; + +const MAX_ARTIFACT_CANDIDATES: usize = 16; + +pub(super) fn annotate_spoken_artifacts(lines: &mut [HyperlinkLine], cwd: &Path) { + let mut inspected = 0; + for line in lines { + let text = line + .line + .spans + .iter() + .map(|span| span.content.as_ref()) + .collect::(); + let mut search_from = 0; + for token in text.split_ascii_whitespace() { + let Some(relative_start) = text[search_from..].find(token) else { + continue; + }; + let token_start = search_from + relative_start; + search_from = token_start + token.len(); + let leading = token.trim_start_matches(['(', '[', '{', '<', '\'', '"', '`']); + let candidate = + leading.trim_end_matches([')', ']', '}', '>', '\'', '"', '`', ',', ';', '.', '!']); + let Some(filename) = candidate.rsplit('/').next() else { + continue; + }; + if !filename.contains('.') { + continue; + } + let mut path = candidate; + for _ in 0..2 { + if let Some((without_suffix, suffix)) = path.rsplit_once(':') + && !suffix.is_empty() + && suffix.bytes().all(|byte| byte.is_ascii_digit()) + { + path = without_suffix; + } + } + inspected += 1; + if inspected > MAX_ARTIFACT_CANDIDATES { + return; + } + let Some(file) = TrustedWorkspaceFile::validate(cwd, path) else { + continue; + }; + let byte_start = token_start + token.len() - leading.len(); + let byte_end = byte_start + candidate.len(); + let columns = display_width(&text[..byte_start])..display_width(&text[..byte_end]); + if line.hyperlinks.iter().any(|existing| { + existing.columns.start < columns.end && columns.start < existing.columns.end + }) { + continue; + } + line.hyperlinks + .push(TerminalHyperlink::trusted_workspace_file(columns, file)); + + let mut offset = 0; + for span in std::mem::take(&mut line.line.spans) { + let style = span.style; + let content = span.content.into_owned(); + let start = byte_start.saturating_sub(offset).min(content.len()); + let end = byte_end.saturating_sub(offset).min(content.len()); + offset += content.len(); + if start >= end { + line.line.spans.push(Span::styled(content, style)); + continue; + } + if start > 0 { + line.line + .spans + .push(Span::styled(content[..start].to_string(), style)); + } + line.line.spans.push(Span::styled( + content[start..end].to_string(), + style.add_modifier(Modifier::UNDERLINED), + )); + if end < content.len() { + line.line + .spans + .push(Span::styled(content[end..].to_string(), style)); + } + } + } + line.hyperlinks.sort_by_key(|link| link.columns.start); + } +} diff --git a/codex-rs/tui/src/history_cell/tests.rs b/codex-rs/tui/src/history_cell/tests.rs index a3c911aaf1..a2e321cf2b 100644 --- a/codex-rs/tui/src/history_cell/tests.rs +++ b/codex-rs/tui/src/history_cell/tests.rs @@ -2310,6 +2310,7 @@ fn ran_cell_multiline_with_stderr_snapshot() { fn user_history_cell_wraps_and_prefixes_each_line_snapshot() { let msg = "_count_r\x1b[13;2:3uows"; let cell = UserHistoryCell { + spoken: false, message: msg.to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), @@ -2333,6 +2334,7 @@ fn user_history_cell_wraps_long_urls_inside_the_message_gutter() { ); let image_start = message.find("[Image #1]").unwrap(); let cell = UserHistoryCell { + spoken: false, message, text_elements: vec![TextElement::new( (image_start..image_start + "[Image #1]".len()).into(), @@ -2383,6 +2385,7 @@ fn user_history_cell_wraps_long_urls_inside_the_message_gutter() { #[test] fn user_history_cell_renders_remote_image_urls() { let cell = UserHistoryCell { + spoken: false, message: "describe these".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), @@ -2399,6 +2402,7 @@ fn user_history_cell_renders_remote_image_urls() { #[test] fn user_history_cell_summarizes_inline_data_urls() { let cell = UserHistoryCell { + spoken: false, message: "describe inline image".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), @@ -2414,6 +2418,7 @@ fn user_history_cell_summarizes_inline_data_urls() { #[test] fn user_history_cell_numbers_multiple_remote_images() { let cell = UserHistoryCell { + spoken: false, message: "describe both".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), @@ -2433,6 +2438,7 @@ fn user_history_cell_numbers_multiple_remote_images() { #[test] fn user_history_cell_height_matches_rendered_lines_with_remote_images() { let cell = UserHistoryCell { + spoken: false, message: "line one\nline two".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), @@ -2455,6 +2461,7 @@ fn user_history_cell_height_matches_rendered_lines_with_remote_images() { #[test] fn user_history_cell_trims_trailing_blank_message_lines() { let cell = UserHistoryCell { + spoken: false, message: "line one\n\n \n\t \n".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), @@ -2475,6 +2482,7 @@ fn user_history_cell_trims_trailing_blank_message_lines() { fn user_history_cell_trims_trailing_blank_message_lines_with_text_elements() { let message = "tokenized\n\n\n".to_string(); let cell = UserHistoryCell { + spoken: false, message, text_elements: vec![TextElement::new( (0..8).into(), @@ -2498,6 +2506,7 @@ fn user_history_cell_trims_trailing_blank_message_lines_with_text_elements() { fn render_uses_wrapping_for_long_url_like_line() { let url = "https://example.test/api/v1/projects/alpha-team/releases/2026-02-17/builds/1234567890/artifacts/reports/performance/summary/detail/with/a/very/long/path/that/keeps/going/for/testing/purposes-only-and-does/not/need/to/resolve/index.html?session_id=abc123def456ghi789jkl012mno345pqr678stu901vwx234yz"; let cell: Box = Box::new(UserHistoryCell { + spoken: false, message: url.to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), @@ -2973,6 +2982,7 @@ fn agent_markdown_cell_narrow_width_shows_prefix_only() { #[test] fn wrapped_and_prefixed_cells_handle_tiny_widths() { let user_cell = UserHistoryCell { + spoken: false, message: "tiny width coverage for wrapped user history".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), @@ -3079,6 +3089,7 @@ fn consolidation_walker_replaces_agent_message_cells() { // Build a transcript with: [UserCell, AgentMsg(head), AgentMsg(cont), AgentMsg(cont)] let user = Arc::new(UserHistoryCell { + spoken: false, message: "hello".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), diff --git a/codex-rs/tui/src/insert_history.rs b/codex-rs/tui/src/insert_history.rs index 165bc56c77..9952230823 100644 --- a/codex-rs/tui/src/insert_history.rs +++ b/codex-rs/tui/src/insert_history.rs @@ -870,6 +870,7 @@ mod tests { let url = "https://example.test/forwarded/threads/10930?page=1&queue=customer_support_unprocessed&forwardedScope=all"; let cell = UserHistoryCell { + spoken: false, message: url.to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), diff --git a/codex-rs/tui/src/pager_overlay/highlight_tests.rs b/codex-rs/tui/src/pager_overlay/highlight_tests.rs index a3661013f5..15663f686f 100644 --- a/codex-rs/tui/src/pager_overlay/highlight_tests.rs +++ b/codex-rs/tui/src/pager_overlay/highlight_tests.rs @@ -83,6 +83,7 @@ fn moving_highlight_matches_full_rebuild_with_live_tail() { text_elements: Vec::new(), local_image_paths: Vec::new(), remote_image_urls: Vec::new(), + spoken: false, }) as Arc }) .collect(); diff --git a/codex-rs/tui/src/pager_overlay/scrolling_tests.rs b/codex-rs/tui/src/pager_overlay/scrolling_tests.rs index ddec5e7059..2e15be86e1 100644 --- a/codex-rs/tui/src/pager_overlay/scrolling_tests.rs +++ b/codex-rs/tui/src/pager_overlay/scrolling_tests.rs @@ -89,6 +89,7 @@ fn scrolled_test_renderables(lines: &[HyperlinkLine]) -> Vec<(&'static str, Box< lines: lines.to_vec(), }); let user: Arc = Arc::new(UserHistoryCell { + spoken: false, message: "highlighted 漢字 user message that wraps\nsecond user line".to_string(), text_elements: Vec::new(), local_image_paths: Vec::new(), diff --git a/codex-rs/tui/src/terminal_hyperlinks.rs b/codex-rs/tui/src/terminal_hyperlinks.rs index c154ef6480..390d50d309 100644 --- a/codex-rs/tui/src/terminal_hyperlinks.rs +++ b/codex-rs/tui/src/terminal_hyperlinks.rs @@ -9,6 +9,7 @@ pub(crate) use paragraph::HyperlinkParagraph; use std::num::NonZeroU16; use std::ops::Range; +use std::path::Path; use ratatui::buffer::Buffer; use ratatui::buffer::CellDiffOption; @@ -45,9 +46,52 @@ pub(crate) struct TerminalHyperlink { #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum DestinationKind { Web, + /// A generated visualization or a capability-validated spoken workspace artifact. TrustedFile, } +/// An existing, inert source file proven to remain inside its session workspace. +pub(crate) struct TrustedWorkspaceFile(Url); + +const SAFE_WORKSPACE_EXTENSIONS: &[&str] = &[ + "rs", "go", "c", "cc", "cpp", "h", "hpp", "java", "kt", "swift", "toml", "json", "yaml", "yml", + "md", "txt", "css", +]; + +impl TrustedWorkspaceFile { + pub(crate) fn validate(workspace: &Path, candidate: &str) -> Option { + if candidate.is_empty() + || candidate.len() > 512 + || candidate.contains(':') + || candidate.chars().any(char::is_control) + { + return None; + } + let normalized = candidate.replace('\\', "/"); + let path = Path::new(&normalized); + if path.is_absolute() + || normalized + .split('/') + .any(|part| part.is_empty() || part.starts_with('.')) + || !SAFE_WORKSPACE_EXTENSIONS.contains(&path.extension()?.to_str()?) + { + return None; + } + let workspace = workspace.canonicalize().ok()?; + let target = workspace.join(path).canonicalize().ok()?; + let relative = target.strip_prefix(&workspace).ok()?; + if !target.metadata().ok()?.is_file() + || target.extension() != path.extension() + || relative + .iter() + .any(|part| part.to_string_lossy().starts_with('.')) + { + return None; + } + Url::from_file_path(target).ok().map(Self) + } +} + impl TerminalHyperlink { pub(crate) fn web(columns: Range, destination: String) -> Self { Self { @@ -58,13 +102,24 @@ impl TerminalHyperlink { } pub(crate) fn retarget_to_trusted_file(&mut self, destination: &Url) { - // Keep file URLs out of the general Markdown link path. Only generated visualization links - // are promoted to this destination kind. + // General Markdown never promotes file URLs. Only generated visualization links use this + // path; spoken workspace artifacts require a separately validated capability. debug_assert_eq!(destination.scheme(), "file"); self.destination = destination.to_string(); self.destination_kind = DestinationKind::TrustedFile; } + pub(crate) fn trusted_workspace_file( + columns: Range, + file: TrustedWorkspaceFile, + ) -> Self { + Self { + columns, + destination: file.0.to_string(), + destination_kind: DestinationKind::TrustedFile, + } + } + fn with_columns(&self, columns: Range) -> Self { Self { columns, @@ -1048,4 +1103,63 @@ mod tests { ); assert_eq!(osc8_hyperlink(file_url.as_str(), "view"), "view"); } + + #[test] + fn trusted_workspace_files_require_confined_regular_inert_sources() { + let workspace = tempfile::tempdir().expect("workspace"); + let source_directory = workspace.path().join("src"); + std::fs::create_dir(&source_directory).expect("source directory"); + std::fs::write(source_directory.join("safe.rs"), "fn safe() {}").expect("source"); + std::fs::write(source_directory.join("run.py"), "print('no')").expect("script"); + std::fs::write(source_directory.join(".hidden.rs"), "hidden").expect("hidden"); + std::fs::create_dir(source_directory.join("directory.rs")).expect("directory"); + + let file = TrustedWorkspaceFile::validate(workspace.path(), "src/safe.rs") + .expect("workspace source should be trusted"); + let windows_file = TrustedWorkspaceFile::validate(workspace.path(), "src\\safe.rs") + .expect("relative Windows separators should be trusted"); + assert_eq!(file.0, windows_file.0); + let link = TerminalHyperlink::trusted_workspace_file(/*columns*/ 0..11, file); + assert!(link.destination.starts_with("file://")); + assert_eq!(osc8_hyperlink(&link.destination, "safe.rs"), "safe.rs"); + + for candidate in [ + "../safe.rs", + "src/../src/safe.rs", + "/src/safe.rs", + "src\\\\safe.rs", + "src\\..\\safe.rs", + "\\src\\safe.rs", + "\\\\server\\share\\safe.rs", + "C:\\src\\safe.rs", + "file://src/safe.rs", + "src/safe.rs\u{7}", + "src/.hidden.rs", + "src/missing.rs", + "src/directory.rs", + "src/run.py", + ] { + assert!( + TrustedWorkspaceFile::validate(workspace.path(), candidate).is_none(), + "unsafe artifact was accepted: {candidate}" + ); + } + + #[cfg(unix)] + { + let outside = tempfile::tempdir().expect("outside directory"); + let outside_file = outside.path().join("outside.rs"); + std::fs::write(&outside_file, "outside").expect("outside source"); + std::os::unix::fs::symlink(&outside_file, source_directory.join("escape.rs")) + .expect("escape symlink"); + std::os::unix::fs::symlink( + source_directory.join("run.py"), + source_directory.join("disguised.rs"), + ) + .expect("disguised script symlink"); + for candidate in ["src/escape.rs", "src/disguised.rs"] { + assert!(TrustedWorkspaceFile::validate(workspace.path(), candidate).is_none()); + } + } + } } diff --git a/codex-rs/tui/src/thread_transcript.rs b/codex-rs/tui/src/thread_transcript.rs index d47f9fa3e4..38e4aaf5f7 100644 --- a/codex-rs/tui/src/thread_transcript.rs +++ b/codex-rs/tui/src/thread_transcript.rs @@ -120,6 +120,7 @@ pub(crate) fn thread_items_to_transcript_cells( .collect(), }; cells.push(Arc::new(UserHistoryCell { + spoken: false, message: item.message(), text_elements: item.text_elements(), local_image_paths: item.local_image_paths(),