mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
Render follow-up directive labels in the TUI and copied responses (#49089)
## Why
Follow-up directives contain display labels and prompt attributes. Show the labels without exposing directive syntax or prompt text in rendered responses and streaming previews.
## What changed
- Render `:codex-followup[label]{prompt="..."}` as its label, preserving inline Markdown styling and source offsets.
- Replace recognized follow-up directives with their labels when copying whole responses, while retaining the original source.
- Withhold unfinished directives in rich streaming previews and avoid cropping into prompt attributes when the preview window advances.
- Preserve literal code, escaped directives, and malformed source when rendering completed messages or copying responses.
## Testing
Add regression coverage for label formatting, nested brackets and backticks, literal and malformed directives, whole-response copying, and streaming holdback across long prompts and preview window boundaries.
GitOrigin-RevId: dce61d1164de0a576fe95fb2c67b177a1ed414e8
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
//! Follow-up labels keep Markdown styling and stream offsets without exposing prompts.
|
||||
|
||||
use super::super::ListSpacing;
|
||||
use super::super::render_streaming_markdown_lines_with_width_and_cwd;
|
||||
use crate::markdown::render_markdown_agent_with_links_and_cwd;
|
||||
use crate::terminal_hyperlinks::visible_lines;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::text::Text;
|
||||
|
||||
#[test]
|
||||
fn followup_labels_render_like_ordinary_markdown_snapshot() {
|
||||
let source = concat!(
|
||||
"Next actions:\n\n",
|
||||
"- :codex-followup[Add **revenue charts**]{prompt=\"Add a \\\"Q3\\\" chart with } labels\"}\n",
|
||||
"- :codex-followup[Format `Sheet1`]{prompt=\"Format the spreadsheet\"}\n\n",
|
||||
"Or :codex-followup[explain café totals]{prompt=\"Explain $x$ and *all* totals\"}.\n",
|
||||
);
|
||||
let plain =
|
||||
"Next actions:\n\n- Add **revenue charts**\n- Format `Sheet1`\n\nOr explain café totals.\n";
|
||||
let streamed = render_streaming_markdown_lines_with_width_and_cwd(
|
||||
source,
|
||||
Some(32),
|
||||
/*cwd*/ None,
|
||||
&|_| false,
|
||||
ListSpacing::AfterMultiline,
|
||||
);
|
||||
let rendered = Text::from(visible_lines(streamed.lines));
|
||||
assert_eq!(
|
||||
rendered,
|
||||
Text::from(visible_lines(render_markdown_agent_with_links_and_cwd(
|
||||
plain,
|
||||
Some(32),
|
||||
/*cwd*/ None
|
||||
)))
|
||||
);
|
||||
assert_eq!(streamed.last_top_level_block_start, source.find("Or "));
|
||||
insta::assert_snapshot!(rendered.to_string(), @"
|
||||
Next actions:
|
||||
|
||||
• Add revenue charts
|
||||
• Format Sheet1
|
||||
|
||||
Or explain café totals.
|
||||
");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn followups_preserve_literal_and_malformed_source() {
|
||||
let directive = r#":codex-followup[Add charts]{prompt="Add charts"}"#;
|
||||
for source in [
|
||||
format!("`{directive}`"),
|
||||
format!("```text\n{directive}\n```"),
|
||||
format!(r"\{directive}"),
|
||||
format!("<!-- {directive} -->"),
|
||||
format!("[{directive}](https://example.com)"),
|
||||
":codex-followup[Add charts]{prompt=\"unfinished".to_string(),
|
||||
":codex-followup[Add charts".to_string(),
|
||||
":codex-followup[Add charts]{prompt=one prompt=two}".to_string(),
|
||||
] {
|
||||
assert_eq!(
|
||||
super::InlineDirectives::new(&source, pulldown_cmark::Options::empty()).markdown,
|
||||
source
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn followups_do_not_consume_neighbors_or_nested_directives() {
|
||||
let source = concat!(
|
||||
"& :codex-followup[**First**]{prompt=\"Use :codex-file-citation{path=\\\"/tmp/private\\\"}\"} ",
|
||||
":codex-followup[*Second*]{prompt=\"Then continue\"} ©\n",
|
||||
);
|
||||
assert_eq!(
|
||||
render_markdown_agent_with_links_and_cwd(source, /*width*/ None, /*cwd*/ None),
|
||||
render_markdown_agent_with_links_and_cwd(
|
||||
"& **First** *Second* ©\n",
|
||||
/*width*/ None,
|
||||
/*cwd*/ None
|
||||
),
|
||||
);
|
||||
let source = format!("{source}\n:codex-file-citation{{path=\"/tmp/report.pdf\"}}\n");
|
||||
let rendered = crate::markdown::render_markdown_agent_with_links_and_cwd(
|
||||
&source, /*width*/ None, /*cwd*/ None,
|
||||
);
|
||||
assert_eq!(
|
||||
Text::from(visible_lines(rendered)).to_string(),
|
||||
"& First Second ©\n\n/tmp/report.pdf"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn followup_labels_cannot_introduce_blocks() {
|
||||
for label in [
|
||||
"# Heading",
|
||||
"- List item",
|
||||
"---",
|
||||
" Indented",
|
||||
"~~Old~~ new",
|
||||
"Inspect `items[0]`",
|
||||
"Inspect ``items[`key`]``",
|
||||
"Type a ` character",
|
||||
"Type a ` character and ``items]``",
|
||||
r"Type a \` character",
|
||||
"Inspect [nested [labels]]",
|
||||
r"Inspect \] and \[ brackets",
|
||||
] {
|
||||
let source = format!("Before :codex-followup[{label}]{{prompt=action}} after.");
|
||||
let plain = format!("Before {label} after.");
|
||||
assert_eq!(
|
||||
render_markdown_agent_with_links_and_cwd(
|
||||
&source, /*width*/ None, /*cwd*/ None
|
||||
),
|
||||
render_markdown_agent_with_links_and_cwd(
|
||||
&plain, /*width*/ None, /*cwd*/ None
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmatched_label_backticks_render_and_copy_as_literal_text() {
|
||||
let source = ":codex-followup[Type a ` character]{prompt=action}\n";
|
||||
insta::assert_snapshot!(
|
||||
Text::from(visible_lines(render_markdown_agent_with_links_and_cwd(
|
||||
source, /*width*/ None, /*cwd*/ None
|
||||
))).to_string(),
|
||||
@"Type a ` character"
|
||||
);
|
||||
assert_eq!(super::followup_labels(source), "Type a ` character\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_directives_leave_budget_for_followups() {
|
||||
for prefix in [":x0[:x1[", ":codex-followup[` "] {
|
||||
let source = format!("{prefix}:codex-followup[Open]{{prompt=secret}}");
|
||||
let expected = format!("{prefix}Open");
|
||||
assert_eq!(super::followup_labels(&source), expected);
|
||||
assert_eq!(
|
||||
render_markdown_agent_with_links_and_cwd(
|
||||
&source, /*width*/ None, /*cwd*/ None
|
||||
),
|
||||
render_markdown_agent_with_links_and_cwd(
|
||||
&expected, /*width*/ None, /*cwd*/ None
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+97
-27
@@ -1,4 +1,6 @@
|
||||
//! Prepare file citations once, then feed them to the ordinary Markdown link renderer.
|
||||
//! Render file citations as links and follow-up directives as labels.
|
||||
//!
|
||||
//! Preserve source offsets and literal Markdown boundaries for streaming and completed messages.
|
||||
|
||||
use super::local_links::extract_colon_location_suffix;
|
||||
use super::local_links::is_local_path_like_link;
|
||||
@@ -16,21 +18,48 @@ use std::borrow::Cow;
|
||||
use std::ops::Range;
|
||||
use std::path::Path;
|
||||
|
||||
/// Offset-preserving Markdown plus the original, fully parsed citation metadata.
|
||||
pub(super) struct FileCitations<'a> {
|
||||
input: &'a str,
|
||||
pub(super) markdown: Cow<'a, str>,
|
||||
citations: Vec<(Range<usize>, AssistantDirective<'a>)>,
|
||||
/// Preserve source Markdown when copying, replacing only recognized follow-up directives.
|
||||
pub(crate) fn followup_labels(input: &str) -> Cow<'_, str> {
|
||||
if !input.contains(":codex-followup[") {
|
||||
return Cow::Borrowed(input);
|
||||
}
|
||||
let prepared = InlineDirectives::new(
|
||||
input,
|
||||
Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES | Options::ENABLE_TASKLISTS,
|
||||
);
|
||||
let mut copied = String::new();
|
||||
let mut offset = 0;
|
||||
for (range, directive) in prepared.directives {
|
||||
if directive.name == "codex-followup"
|
||||
&& let Some(label) = directive.label
|
||||
{
|
||||
copied.push_str(&input[offset..range.start]);
|
||||
copied.push_str(label);
|
||||
offset = range.end;
|
||||
}
|
||||
}
|
||||
if offset == 0 {
|
||||
return Cow::Borrowed(input);
|
||||
}
|
||||
copied.push_str(&input[offset..]);
|
||||
Cow::Owned(copied)
|
||||
}
|
||||
|
||||
impl<'a> FileCitations<'a> {
|
||||
/// Offset-preserving Markdown plus the original, fully parsed directive metadata.
|
||||
pub(super) struct InlineDirectives<'a> {
|
||||
input: &'a str,
|
||||
pub(super) markdown: Cow<'a, str>,
|
||||
directives: Vec<(Range<usize>, AssistantDirective<'a>)>,
|
||||
}
|
||||
|
||||
impl<'a> InlineDirectives<'a> {
|
||||
pub(super) fn new(input: &'a str, options: Options) -> Self {
|
||||
let mut prepared = Self {
|
||||
input,
|
||||
markdown: Cow::Borrowed(input),
|
||||
citations: Vec::new(),
|
||||
directives: Vec::new(),
|
||||
};
|
||||
if !input.contains("codex-file-citation") {
|
||||
if !input.contains("codex-file-citation") && !input.contains(":codex-followup[") {
|
||||
return prepared;
|
||||
}
|
||||
|
||||
@@ -55,8 +84,9 @@ impl<'a> FileCitations<'a> {
|
||||
let mut literal_ranges = literal_ranges.into_iter().peekable();
|
||||
|
||||
let mut directive_end = 0;
|
||||
// Share the allowance across offsets and quote modes: malformed retries must stay linear.
|
||||
let mut scan_budget = input.len().saturating_mul(/*rhs*/ 4);
|
||||
// Share separate preferred/fallback allowances across offsets, so fallback retries
|
||||
// cannot starve later preferred parses. Both allowances stay proportional to input size.
|
||||
let mut scan_budget = [input.len().saturating_mul(/*rhs*/ 4); 2];
|
||||
for (start, _) in input.match_indices(':') {
|
||||
while literal_ranges.next_if(|range| range.end <= start).is_some() {}
|
||||
if start < directive_end
|
||||
@@ -77,9 +107,14 @@ impl<'a> FileCitations<'a> {
|
||||
} else {
|
||||
[QuoteEscaping::Backslash, QuoteEscaping::Literal]
|
||||
};
|
||||
let Some(directive) = escaping.into_iter().find_map(|escaping| {
|
||||
parse_assistant_directive_with_budget(source, escaping, &mut scan_budget)
|
||||
}) else {
|
||||
let Some(directive) =
|
||||
escaping
|
||||
.into_iter()
|
||||
.zip(&mut scan_budget)
|
||||
.find_map(|(escaping, remaining)| {
|
||||
parse_assistant_directive_with_budget(source, escaping, remaining)
|
||||
})
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let end = start + directive.raw.len();
|
||||
@@ -91,18 +126,24 @@ impl<'a> FileCitations<'a> {
|
||||
.count()
|
||||
% 2
|
||||
!= 0
|
||||
|| directive.name != "codex-file-citation"
|
||||
|| directive
|
||||
.attributes
|
||||
.get("path")
|
||||
.is_none_or(|path| path.is_empty())
|
||||
|| match directive.name {
|
||||
"codex-file-citation" => directive
|
||||
.attributes
|
||||
.get("path")
|
||||
.is_none_or(|path| path.is_empty()),
|
||||
"codex-followup" => {
|
||||
!directive.raw.starts_with(":codex-followup[")
|
||||
|| directive.label.is_none_or(|label| label.trim().is_empty())
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Mask the interior without moving offsets or changing Markdown delimiter flanking.
|
||||
let markdown = prepared.markdown.to_mut();
|
||||
markdown.replace_range(start + 1..end - 1, &"x".repeat(end - start - 2));
|
||||
prepared.citations.push((start..end, directive));
|
||||
prepared.directives.push((start..end, directive));
|
||||
}
|
||||
prepared
|
||||
}
|
||||
@@ -113,24 +154,24 @@ impl<'a> FileCitations<'a> {
|
||||
events: impl Iterator<Item = (Event<'s>, Range<usize>)>,
|
||||
cwd: Option<&'s Path>,
|
||||
) -> impl Iterator<Item = (Event<'s>, Range<usize>)> {
|
||||
let mut citations = self.citations.iter().peekable();
|
||||
let mut directives = self.directives.iter().peekable();
|
||||
events.flat_map(move |(event, range)| {
|
||||
while citations
|
||||
while directives
|
||||
.next_if(|(span, _)| span.end <= range.start)
|
||||
.is_some()
|
||||
{}
|
||||
let Event::Text(text) = event else {
|
||||
return Either::Left(std::iter::once((event, range)));
|
||||
};
|
||||
if citations
|
||||
if directives
|
||||
.peek()
|
||||
.is_none_or(|(span, _)| span.start >= range.end)
|
||||
{
|
||||
return Either::Left(std::iter::once((Event::Text(text), range)));
|
||||
}
|
||||
// Never apply source offsets to entity-decoded text or a partial citation.
|
||||
// Never apply source offsets to entity-decoded text or a partial directive.
|
||||
if text.as_ref() != &self.markdown[range.clone()]
|
||||
|| citations
|
||||
|| directives
|
||||
.peek()
|
||||
.is_some_and(|(span, _)| span.start < range.start || span.end > range.end)
|
||||
{
|
||||
@@ -140,7 +181,8 @@ impl<'a> FileCitations<'a> {
|
||||
|
||||
let mut events = Vec::new();
|
||||
let mut offset = range.start;
|
||||
while let Some((span, directive)) = citations.next_if(|(span, _)| span.end <= range.end)
|
||||
while let Some((span, directive)) =
|
||||
directives.next_if(|(span, _)| span.end <= range.end)
|
||||
{
|
||||
if offset < span.start {
|
||||
events.push((
|
||||
@@ -148,6 +190,31 @@ impl<'a> FileCitations<'a> {
|
||||
offset..span.start,
|
||||
));
|
||||
}
|
||||
offset = span.end;
|
||||
if let Some(label) = directive
|
||||
.label
|
||||
.filter(|_| directive.name == "codex-followup")
|
||||
{
|
||||
// Keep the unmatched `[` as a sentinel so labels cannot introduce blocks.
|
||||
let inline = &directive.raw
|
||||
[":codex-followup".len()..":codex-followup[".len() + label.len()];
|
||||
events.extend(
|
||||
Parser::new_ext(inline, Options::ENABLE_STRIKETHROUGH)
|
||||
.into_offset_iter()
|
||||
.filter_map(|(event, range)| {
|
||||
let event = match event {
|
||||
Event::Start(Tag::Paragraph)
|
||||
| Event::End(TagEnd::Paragraph) => return None,
|
||||
Event::Text(text) if range.start == 0 => {
|
||||
Event::Text(text[1..].to_owned().into())
|
||||
}
|
||||
event => event,
|
||||
};
|
||||
Some((event, span.clone()))
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let path = directive.attributes["path"].as_ref();
|
||||
let destination = if is_local_path_like_link(path) {
|
||||
path.to_string()
|
||||
@@ -180,7 +247,6 @@ impl<'a> FileCitations<'a> {
|
||||
(Event::Text(destination.into()), span.clone()),
|
||||
(Event::End(TagEnd::Link), span.clone()),
|
||||
]);
|
||||
offset = span.end;
|
||||
}
|
||||
if offset < range.end {
|
||||
events.push((
|
||||
@@ -196,3 +262,7 @@ impl<'a> FileCitations<'a> {
|
||||
#[cfg(test)]
|
||||
#[path = "file_citations_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "followups_tests.rs"]
|
||||
mod followups_tests;
|
||||
@@ -5,8 +5,8 @@
|
||||
|
||||
use super::DecodedTextMerge;
|
||||
use super::Event;
|
||||
use super::FileCitations;
|
||||
use super::HyperlinkLine;
|
||||
use super::InlineDirectives;
|
||||
use super::ListSpacing;
|
||||
use super::Options;
|
||||
use super::Parser;
|
||||
@@ -50,14 +50,14 @@ pub(crate) fn render_streaming_markdown_lines_with_width_and_cwd(
|
||||
Options::ENABLE_TASKLISTS,
|
||||
super::preferences::current().lists,
|
||||
);
|
||||
let citations = FileCitations::new(input, options);
|
||||
let math = MathMarkdown::new(&citations.markdown, options, width);
|
||||
let directives = InlineDirectives::new(input, options);
|
||||
let math = MathMarkdown::new(&directives.markdown, options, width);
|
||||
let parser = Parser::new_ext(&math.markdown, options);
|
||||
let has_reference_link_definition = parser.reference_definitions().iter().next().is_some();
|
||||
let parser = TopLevelBlockTracker {
|
||||
iter: DecodedTextMerge::new(super::source_tables::preserve(
|
||||
input,
|
||||
citations.events(math.events(parser.into_offset_iter()), cwd),
|
||||
directives.events(math.events(parser.into_offset_iter()), cwd),
|
||||
)),
|
||||
depth: 0,
|
||||
block_count: 0,
|
||||
|
||||
Reference in New Issue
Block a user