Search inline link labels in user messages (#63758)

## Why

Searching raw user messages can return hits from Markdown link destinations
that readers never see in the link label.

## What changed

Use inline Markdown link labels for user-message matches and snippets while
preserving surrounding whitespace and code blocks. Keep literal text for
messages with byte-ranged inline elements.

Reject cursors that counted raw-text matches because hidden URL hits could
shift the index and cause pagination to skip a visible match.

## Testing

Extend the thread search integration test to check match offsets, snippet
formatting, pagination, and rejection of a raw-text cursor.

GitOrigin-RevId: 19af5ab4aa16933e83b4eb2cb15e57cc92597b6b
This commit is contained in:
Brent Traut
2026-11-24 22:46:22 +00:00
committed by copyberry
parent 110f065202
commit 9202c7916b
2 changed files with 83 additions and 13 deletions
@@ -691,7 +691,8 @@ async fn thread_search_occurrences_reads_paginated_projection() -> Result<()> {
text_elements: Vec::new(),
},
codex_protocol::user_input::UserInput::Text {
text: "dle needle needle needle".to_string(),
text: "dle needle needle [needle](https://example.com/needle) end\n\n```\na b\n```"
.to_string(),
text_elements: Vec::new(),
},
],
@@ -704,8 +705,8 @@ async fn thread_search_occurrences_reads_paginated_projection() -> Result<()> {
id: "steer-1".to_string(),
client_id: None,
content: vec![codex_protocol::user_input::UserInput::Text {
text: "steer toward needle".to_string(),
text_elements: Vec::new(),
text: "steer [label](https://example.com/needle)".to_string(),
text_elements: vec![TextElement::new(ByteRange { start: 0, end: 5 }, /*placeholder*/ None)],
}],
}),
),
@@ -798,8 +799,32 @@ async fn thread_search_occurrences_reads_paginated_projection() -> Result<()> {
.collect::<Vec<_>>(),
vec![0, 7, 14]
);
assert_eq!(
data[0].snippet,
"Needle needle needle needle end\n\n```\na b\n```"
);
let next_cursor = next_cursor.expect("first page should have another occurrence");
// A raw-text index may count a URL before a visible hit. Reject it rather than skipping that hit.
let old_cursor = serde_json::json!({
"threadId": thread_id.to_string(), "searchTerm": "needle",
"nextRolloutOrdinal": 2, "nextOccurrenceIndex": 1
});
let request_id = mcp
.send_thread_search_occurrences_request(ThreadSearchOccurrencesParams {
thread_id: thread_id.to_string(),
search_term: "needle".to_string(),
cursor: Some(old_cursor.to_string()),
limit: Some(3),
})
.await?;
let error = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert!(error.error.message.contains("invalid cursor"));
let request_id = mcp
.send_thread_search_occurrences_request(ThreadSearchOccurrencesParams {
thread_id: thread_id.to_string(),
@@ -8,7 +8,9 @@ use codex_protocol::ThreadId;
use codex_protocol::protocol::strip_user_message_prefix;
use futures::TryStreamExt;
use pulldown_cmark::Event;
use pulldown_cmark::LinkType;
use pulldown_cmark::Parser;
use pulldown_cmark::Tag;
use pulldown_cmark::TagEnd;
use serde::Deserialize;
use serde::Serialize;
@@ -37,7 +39,8 @@ struct SearchCursor {
thread_id: ThreadId,
search_term: String,
next_rollout_ordinal: i64,
next_occurrence_index: usize,
// Raw-text cursors counted hidden destinations. Reject them instead of skipping visible hits.
next_visible_occurrence_index: usize,
}
struct CandidateRow {
@@ -188,7 +191,7 @@ ORDER BY rollout_ordinal ASC
let first_occurrence_index = cursor
.as_ref()
.filter(|cursor| cursor.next_rollout_ordinal == row.rollout_ordinal)
.map_or(0, |cursor| cursor.next_occurrence_index);
.map_or(0, |cursor| cursor.next_visible_occurrence_index);
let remaining = params
.page_size
.saturating_add(1)
@@ -242,7 +245,7 @@ ORDER BY rollout_ordinal ASC
thread_id: params.thread_id,
search_term: params.search_term,
next_rollout_ordinal: row.rollout_ordinal,
next_occurrence_index: occurrence_index,
next_visible_occurrence_index: occurrence_index,
})?),
});
}
@@ -326,14 +329,15 @@ fn searchable_text(item: &ThreadItemPayload) -> Option<Cow<'_, str>> {
.filter(|text| !text.is_empty())
.peekable();
let first = text_parts.next()?;
match text_parts.next() {
None => Some(Cow::Borrowed(first)),
Some(second) => {
let mut parts = vec![first, second];
parts.extend(text_parts);
Some(Cow::Owned(parts.concat()))
}
let text = match text_parts.peek() {
None => Cow::Borrowed(first),
Some(_) => Cow::Owned(std::iter::once(first).chain(text_parts).collect()),
};
// Inline elements address byte ranges in the literal prompt.
if content.iter().any(|part| matches!(part, UserInput::Text { text_elements, .. } if !text_elements.is_empty())) {
return Some(text);
}
Some(user_link_labels(text))
}
ThreadItemPayload::AgentMessage { text, .. } => {
let text = markdown_to_search_text(text);
@@ -359,6 +363,47 @@ fn searchable_text(item: &ThreadItemPayload) -> Option<Cow<'_, str>> {
}
}
// Leave literal prompt text (including code and whitespace) alone outside inline links.
fn user_link_labels(source: Cow<'_, str>) -> Cow<'_, str> {
if !source.contains("](") {
return source;
}
let mut text = String::new();
let mut copied = 0;
let mut events = Parser::new(&source).into_offset_iter();
while let Some((event, span)) = events.next() {
if !matches!(
event,
Event::Start(Tag::Link {
link_type: LinkType::Inline,
..
})
) {
continue;
}
text.push_str(&source[copied..span.start]);
for (event, _) in events.by_ref() {
match event {
Event::End(TagEnd::Link) => break,
Event::Text(value) | Event::Code(value) | Event::InlineHtml(value) => {
text.push_str(&value)
}
Event::SoftBreak | Event::HardBreak => text.push('\n'),
_ => {}
}
}
copied = span.end;
}
if copied == 0 {
return source;
}
text.push_str(&source[copied..]);
if text.trim().is_empty() {
return source;
}
Cow::Owned(text)
}
fn markdown_to_search_text(markdown: &str) -> String {
let mut text = String::new();
for event in Parser::new(markdown.trim()) {