Style spoken prompts and link workspace files in voice transcripts (#43676)

## What changed

- Render spoken user prompts with a bold red chevron, preserving its color during live transcript animation. Trim leading whitespace for display while retaining the raw transcript text.
- Underline and link file references such as `src/lib.rs:42` in spoken assistant transcripts using terminal hyperlinks. Preserve existing links and support Windows-style relative separators.
- Restrict generated file links to existing files with allowed extensions inside the workspace, rejecting hidden paths, traversal, and symlink escapes.

## Testing

Add rendering and transcript tests for the spoken marker, raw text preservation, file links, Unicode column offsets, and Windows-style paths, plus validation tests for rejected file destinations.

GitOrigin-RevId: 5fa180aa606acdc579a916441520602cb2bf3655
This commit is contained in:
Benjamin Carlsson authored and copyberry committed 2026-09-08 03:15:37 +00:00
1 parent 4e93cf9b4e
commit 3caf9f9586
21 files changed
+461 -20

No files matched your search

+42 -4
View File
@@ -15,6 +15,7 @@ pub(crate) struct UserHistoryCell {
#[allow(dead_code)]
pub local_image_paths: Vec<PathBuf>,
pub remote_image_urls: Vec<String>,
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<HyperlinkLine> {
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<crate::inline_visualization::InlineVisualizationContext>,
rendered_lines: Option<MarkdownRenderCache>,
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<HyperlinkLine>) -> Vec<HyperlinkLine> {
@@ -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
@@ -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<_>>(),
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{:?} -> <workspace>/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 -> <workspace>/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");
}
+1
View File
@@ -116,6 +116,7 @@ mod request_user_input;
mod search;
mod separators;
mod session;
mod spoken_artifacts;
mod startup_warnings;
pub(crate) use approvals::*;
@@ -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,
]
}
@@ -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::<String>();
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);
}
}
+11
View File
@@ -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<dyn HistoryCell> = 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(),