Match TUI task mentions by displayed title (#62691)

## What changed

Use state database-backed `thread/list` requests for task mentions without
searching conversation contents. Merge title-filtered results with recent
threads by thread ID so a full filtered page cannot crowd out recent
candidates. Native Cloud uses the recent list because it lacks a title filter.

Fuzzy-match the displayed title in the picker. Keep the working directory
visible as a description and exclude it from matching.

## Testing

Cover remote listing, retention of recent candidates when the filtered page
is full, and fallback when the filtered request times out. Check that a
directory-only match stays out of the picker.

GitOrigin-RevId: ec2a5ae9f046e533104251fd82f6683343854ee0
This commit is contained in:
Eric Traut
2026-11-20 07:15:35 +00:00
committed by copyberry
parent 0f3a4756f9
commit 0e8c7683c4
4 changed files with 126 additions and 195 deletions
@@ -7907,14 +7907,18 @@ mod tests {
title: "Review database migration".to_string(),
label_style: crate::thread_label::ThreadLabelStyle::Cloud,
cwd: "/workspace/project".to_string(),
snippet: "database migration".to_string(),
},
crate::task_mentions::TaskMention {
thread_id: "task-456".to_string(),
title: "migration".to_string(),
label_style: crate::thread_label::ThreadLabelStyle::Plain,
cwd: "/another/project".to_string(),
snippet: "migration".to_string(),
},
crate::task_mentions::TaskMention {
thread_id: "task-789".to_string(),
title: "Unrelated task".to_string(),
label_style: crate::thread_label::ThreadLabelStyle::Plain,
cwd: "/workspace/migration".to_string(),
},
],
);
@@ -7947,7 +7951,6 @@ mod tests {
title: format!("task\n\t{}é{}", "a".repeat(154), "é".repeat(200)),
label_style: crate::thread_label::ThreadLabelStyle::Plain,
cwd: "/workspace/project".to_string(),
snippet: String::new(),
};
composer.on_task_search_result("task", vec![task.clone()]);
composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
@@ -49,11 +49,7 @@ pub(crate) fn build_search_catalog(
Candidate {
display_name: title.clone(),
description: (!task.cwd.is_empty()).then(|| task.cwd.clone()),
search_terms: vec![
title.clone(),
task.cwd.chars().take(MAX_TASK_TITLE_CHARS).collect(),
task.snippet.chars().take(MAX_TASK_TITLE_CHARS).collect(),
],
search_terms: Vec::new(),
mention_type: MentionType::Task,
label_style: task.label_style,
selection: Selection::Tool {
+59 -126
View File
@@ -10,12 +10,6 @@ use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::SortDirection;
use codex_app_server_protocol::ThreadListParams;
use codex_app_server_protocol::ThreadListResponse;
use codex_app_server_protocol::ThreadSearchCancelParams;
use codex_app_server_protocol::ThreadSearchCancelResponse;
use codex_app_server_protocol::ThreadSearchParams;
use codex_app_server_protocol::ThreadSearchResponse;
use codex_app_server_protocol::ThreadSearchResult;
use codex_app_server_protocol::ThreadSearchSortKey;
use codex_app_server_protocol::ThreadSortKey;
use codex_app_server_protocol::ThreadSource;
use codex_app_server_protocol::UserInput;
@@ -32,7 +26,6 @@ use crate::thread_label::ThreadLabelStyle;
const MAX_SEARCH_RESULTS: u32 = 50;
const SEARCH_DEBOUNCE: Duration = Duration::from_millis(/*millis*/ 100);
const SEARCH_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
const CANCEL_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 1);
pub(crate) const MAX_REFERENCED_TASKS: usize = 16;
pub(crate) const MAX_TASK_TITLE_CHARS: usize = 160;
const MAX_REFERENCED_THREAD_ID_BYTES: usize = 768;
@@ -44,7 +37,6 @@ pub(crate) struct TaskMention {
pub(crate) title: String,
pub(crate) label_style: ThreadLabelStyle,
pub(crate) cwd: String,
pub(crate) snippet: String,
}
/// Owns the pending task search for a session and cancels it when replaced or dropped.
@@ -95,83 +87,70 @@ impl TaskSearch {
() = tokio::time::sleep(SEARCH_DEBOUNCE) => {}
}
let request_id = RequestId::String(format!("task-search-{}", Uuid::new_v4()));
let (response, titled_threads) = tokio::join!(
search_with_cancellation(
&handle,
&cancellation,
ClientRequest::ThreadSearch {
request_id: request_id.clone(),
params: ThreadSearchParams {
include_attached_threads: false,
current_account_only: true,
cursor: None,
limit: Some(MAX_SEARCH_RESULTS),
sort_key: Some(ThreadSearchSortKey::RecencyAt),
sort_direction: Some(SortDirection::Desc),
source_kinds: Some(Vec::new()),
archived: Some(false),
search_term: query.trim().to_string(),
let params = ThreadListParams {
include_attached_threads: false,
current_account_only: true,
included_thread_ids: None,
excluded_thread_ids: None,
attached_to_thread_id: None,
originators: None,
cursor: None,
limit: Some(MAX_SEARCH_RESULTS),
sort_key: Some(ThreadSortKey::UpdatedAt),
sort_direction: Some(SortDirection::Desc),
model_providers: Some(Vec::new()),
source_kinds: Some(Vec::new()),
archived: Some(false),
section_id: None,
project_id: None,
cwd: None,
use_state_db_only: true,
search_term: None,
parent_thread_id: None,
ancestor_thread_id: None,
};
let (recent, filtered) = tokio::select! {
biased;
() = cancellation.cancelled() => return,
result = async {
tokio::join!(
tokio::time::timeout(
SEARCH_TIMEOUT,
handle.request_typed::<ThreadListResponse>(ClientRequest::ThreadList {
request_id: RequestId::String(format!("task-recent-{}", Uuid::new_v4())),
params: params.clone(),
}),
),
async {
// Native Cloud does not support a title filter.
if matches!(handle, AppServerRequestHandle::Cloud(_)) {
return None;
}
tokio::time::timeout(
SEARCH_TIMEOUT,
handle.request_typed::<ThreadListResponse>(ClientRequest::ThreadList {
request_id: RequestId::String(format!("task-title-search-{}", Uuid::new_v4())),
params: ThreadListParams {
search_term: Some(query.trim().to_string()),
..params
},
}),
).await.ok().and_then(Result::ok)
},
},
request_id,
),
async {
tokio::select! {
biased;
() = cancellation.cancelled() => None,
result = tokio::time::timeout(SEARCH_TIMEOUT,
handle.request_typed::<ThreadListResponse>(ClientRequest::ThreadList {
request_id: RequestId::String(format!("task-title-search-{}", Uuid::new_v4())),
params: ThreadListParams {
include_attached_threads: false,
current_account_only: true,
included_thread_ids: None,
excluded_thread_ids: None,
attached_to_thread_id: None,
originators: None,
cursor: None,
limit: Some(MAX_SEARCH_RESULTS),
sort_key: Some(ThreadSortKey::UpdatedAt),
sort_direction: Some(SortDirection::Desc),
model_providers: Some(Vec::new()),
source_kinds: Some(Vec::new()),
archived: Some(false),
section_id: None,
project_id: None,
cwd: None,
use_state_db_only: true,
search_term: None,
parent_thread_id: None,
ancestor_thread_id: None,
},
})) => result.ok().and_then(Result::ok),
}
}
);
if cancellation.is_cancelled() {
return;
}
if response.is_none() && titled_threads.is_none() {
return;
}
let mut results = response.map(|response| response.data).unwrap_or_default();
if let Some(response) = titled_threads {
for thread in response.data {
if results.iter().all(|result| result.thread.id != thread.id) {
results.push(ThreadSearchResult {
thread,
snippet: String::new(),
});
)
} => result,
};
let mut threads = filtered.map(|page| page.data).unwrap_or_default();
if let Ok(Ok(recent)) = recent {
for thread in recent.data {
if threads.iter().all(|existing| existing.id != thread.id) {
threads.push(thread);
}
}
}
let mut matches = results
let mut matches = threads
.into_iter()
.filter_map(|result| {
let thread = result.thread;
.filter_map(|thread| {
if thread.id == current_thread_id.to_string()
|| thread.ephemeral
|| matches!(
@@ -196,10 +175,8 @@ impl TaskSearch {
title,
label_style,
cwd: thread.cwd.into_string(),
snippet: result.snippet,
})
})
.take(MAX_SEARCH_RESULTS as usize)
.collect::<Vec<_>>();
let cwd = cwd.to_string_lossy();
let windows_cwd = cwd.as_bytes().get(1) == Some(&b':') || cwd.starts_with(r"\\");
@@ -225,50 +202,6 @@ impl TaskSearch {
}
}
async fn search_with_cancellation(
handle: &AppServerRequestHandle,
cancellation: &CancellationToken,
request: ClientRequest,
request_id: RequestId,
) -> Option<ThreadSearchResponse> {
// Native Cloud supports title listing, but does not implement thread/search or its
// cancellation method. Avoid queuing an unsupported detached Cloud command.
if matches!(handle, AppServerRequestHandle::Cloud(_)) {
return None;
}
tokio::select! {
biased;
() = cancellation.cancelled() => {},
result = tokio::time::timeout(SEARCH_TIMEOUT, handle.request_typed::<ThreadSearchResponse>(request)) => {
if let Ok(result) = result {
return result.ok();
}
}
}
// Dropping the request future cancels an in-process search through the facade. Remote
// requests need an explicit connection-scoped cancellation message. Send it in the
// background so a slow cancellation reply cannot delay already available title results.
if matches!(handle, AppServerRequestHandle::Remote(_)) {
let handle = handle.clone();
tokio::spawn(async move {
let _ = tokio::time::timeout(
CANCEL_TIMEOUT,
handle.request_typed::<ThreadSearchCancelResponse>(
ClientRequest::ThreadSearchCancel {
request_id: RequestId::String(format!(
"task-search-cancel-{}",
Uuid::new_v4()
)),
params: ThreadSearchCancelParams { request_id },
},
),
)
.await;
});
}
None
}
pub(crate) fn valid_thread_path(path: &str) -> Option<&str> {
let thread_id = path.strip_prefix("thread://")?;
(!thread_id.is_empty()
+60 -61
View File
@@ -9,53 +9,56 @@ use pretty_assertions::assert_eq;
use tokio_tungstenite::tungstenite::Message;
#[tokio::test]
async fn remote_task_search_cancels_without_delaying_results() {
for timeout in [false, true] {
check_remote_task_search_cancellation(timeout).await;
}
}
async fn check_remote_task_search_cancellation(timeout: bool) {
async fn remote_task_search_uses_indexed_title_listing() {
use codex_app_server_client::RemoteAppServerClient;
use codex_app_server_client::RemoteAppServerConnectArgs;
use codex_app_server_client::RemoteAppServerEndpoint;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let websocket_url = format!("ws://{}", listener.local_addr().unwrap());
let (search_started, started) = tokio::sync::oneshot::channel();
let (cancel_sent, cancelled) = tokio::sync::oneshot::channel();
let (stalled_tx, stalled_rx) = tokio::sync::oneshot::channel();
let rpc = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
let mut search_started = Some(search_started);
let mut search_id = None;
let mut filtered_count = 0;
let mut stalled_tx = Some(stalled_tx);
while let Some(Ok(Message::Text(text))) = socket.next().await {
let request: serde_json::Value = serde_json::from_str(&text).unwrap();
let result = match request["method"].as_str() {
Some("initialize") => {
json!({"userAgent":"task-search-test", "codexHome":"/unused"})
}
Some("thread/list") => json!({
"data": [{
Some("thread/list") => {
assert_eq!(request["params"]["useStateDbOnly"], true);
let thread = json!({
"id": "task-123", "sessionId": "task-123", "preview": "needle",
"name": "needle title", "ephemeral": false, "modelProvider": "openai",
"createdAt": 0, "updatedAt": 0, "status": {"type": "notLoaded"},
"cwd": std::env::temp_dir(), "cliVersion": "test", "source": "cli",
"turns": []
}],
"nextCursor": null
}),
Some("thread/search") => {
search_id = Some(request["id"].clone());
search_started.take().unwrap().send(()).unwrap();
continue;
});
if request["params"]["searchTerm"].is_null() {
json!({"data": [thread], "nextCursor": null})
} else {
assert_eq!(request["params"]["searchTerm"], "needle");
filtered_count += 1;
if filtered_count == 2 {
stalled_tx.take().unwrap().send(()).unwrap();
continue;
}
let data = (0..MAX_SEARCH_RESULTS)
.map(|index| {
let mut row = thread.clone();
row["id"] = json!(format!("preview-{index}"));
row["name"] = json!("unrelated title");
row
})
.collect::<Vec<_>>();
json!({"data": data, "nextCursor": null})
}
}
Some("thread/search/cancel") => {
assert_eq!(Some(&request["params"]["requestId"]), search_id.as_ref());
cancel_sent.send(()).unwrap();
// Leave cancellation unanswered to verify it cannot delay title results.
std::future::pending::<()>().await;
return;
Some("thread/search" | "thread/search/cancel") => {
panic!("task mentions must not search conversation contents");
}
_ => continue,
};
@@ -68,7 +71,6 @@ async fn check_remote_task_search_cancellation(timeout: bool) {
.await
.unwrap();
}
panic!("remote disconnected before cancelling the search");
});
let remote = RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
required_human_approval: false,
@@ -85,49 +87,46 @@ async fn check_remote_task_search_cancellation(timeout: bool) {
})
.await
.unwrap();
let handle = AppServerRequestHandle::Remote(remote.request_handle());
let (tx, mut events) = tokio::sync::mpsc::unbounded_channel();
let current = ThreadId::from_u128(/*value*/ 1);
let mut search = TaskSearch::default();
let handle = AppServerRequestHandle::Remote(remote.request_handle());
search.spawn(
handle.clone(),
"needle".into(),
current,
PathBuf::from("/tmp"),
std::env::temp_dir(),
AppEventSender::new(tx.clone()),
);
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), started)
.await
.unwrap()
.unwrap();
if timeout {
tokio::time::pause();
let deadline = tokio::time::Instant::now() + SEARCH_TIMEOUT;
tokio::time::advance(SEARCH_TIMEOUT).await;
let event = events.recv().await.unwrap();
assert!(
matches!(event, AppEvent::TaskSearchResult { query, matches, .. }
if query == "needle" && matches.len() == 1 && matches[0].title == "needle title")
);
assert!(tokio::time::Instant::now() < deadline + CANCEL_TIMEOUT / 2);
tokio::time::resume();
} else {
search.spawn(
handle,
String::new(),
current,
PathBuf::from("/tmp"),
AppEventSender::new(tx),
);
let event = events.recv().await.unwrap();
assert!(
matches!(event, AppEvent::TaskSearchResult { query, matches, .. } if query.is_empty() && matches.is_empty())
);
}
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), cancelled)
.await
.unwrap()
.unwrap();
let event = events.recv().await.unwrap();
let AppEvent::TaskSearchResult { query, matches, .. } = event else {
panic!("expected task search results");
};
assert_eq!(query, "needle");
assert_eq!(matches.len(), MAX_SEARCH_RESULTS as usize + 1);
let expected = TaskMention {
thread_id: "task-123".into(),
title: "needle title".into(),
label_style: ThreadLabelStyle::Plain,
cwd: std::env::temp_dir().to_string_lossy().into_owned(),
};
assert_eq!(matches.last(), Some(&expected));
search.spawn(
handle,
"needle".into(),
current,
std::env::temp_dir(),
AppEventSender::new(tx),
);
stalled_rx.await.unwrap();
tokio::time::pause();
tokio::time::advance(SEARCH_TIMEOUT).await;
let event = events.recv().await.unwrap();
tokio::time::resume();
assert!(
matches!(event, AppEvent::TaskSearchResult { matches, .. } if matches == vec![expected])
);
rpc.abort();
let _ = remote.shutdown().await;
}