Suggest conversation-based thread titles in /rename (#40495)

## What changed

- Generate a title suggestion from the latest substantive user and assistant messages when the TUI `/rename` prompt opens.
- Prefill the prompt with the result while keeping it editable and preserving any text the user enters before generation finishes.
- Bound and escape the conversation context, omit commentary and IDE context, and correlate responses with the active thread and prompt so stale suggestions are ignored.

## Testing

- Cover conversation selection and prompt construction, generated-title delivery through the embedded app server, loading and prefilled prompt states, stale responses, and preservation of manual edits.

GitOrigin-RevId: 1e7f1d5d4f6503ff9da0548388f610c446c130ca
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-08-24 23:15:04 +00:00
1 parent 0c992c305d
commit 5a51caf04d
13 files changed
+877 -2

No files matched your search

+177
View File
@@ -1,13 +1,18 @@
//! Structured-output schema and normalization for generated TUI thread titles.
use super::App;
use super::thread_events::ThreadBufferedEvent;
use crate::app_event::AppEvent;
use crate::app_event::ThreadTitleDestination;
use crate::app_server_session::AppServerSession;
use crate::temporary_structured_request::TemporaryStructuredThreadOptions;
use crate::temporary_structured_request::run_temporary_structured_turn;
use crate::temporary_structured_request::start_temporary_thread;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::UserInput;
use codex_protocol::ThreadId;
use codex_protocol::models::MessagePhase;
use codex_protocol::openai_models::ReasoningEffort;
use serde::Deserialize;
use serde_json::Value;
@@ -17,6 +22,7 @@ use tokio::sync::mpsc;
pub(super) const THREAD_TITLE_MAX_CHARS: usize = 36;
const THREAD_TITLE_MODEL: &str = "gpt-5.6-luna";
pub(super) const THREAD_TITLE_PROMPT_MAX_BYTES: usize = 960;
const THREAD_TITLE_RECENT_MESSAGES: usize = 8;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
@@ -90,11 +96,20 @@ impl App {
Ok(thread_id) => thread_id,
Err(error) => {
tracing::debug!(%error, "failed to start title-generation thread");
if let ThreadTitleDestination::RenameSuggestion { request_id } = destination {
self.chat_widget.apply_thread_name_suggestion(
thread_id, request_id, /*suggestion*/ None,
);
}
return;
}
};
let Ok(temporary_thread_id) = ThreadId::from_string(&temporary_thread_id_text) else {
if let ThreadTitleDestination::RenameSuggestion { request_id } = destination {
self.chat_widget
.apply_thread_name_suggestion(thread_id, request_id, /*suggestion*/ None);
}
return;
};
@@ -124,6 +139,62 @@ impl App {
});
});
}
/// Suggest a title from stored and live conversation items without persisting it.
pub(super) async fn suggest_thread_name(
&mut self,
app_server: &AppServerSession,
thread_id: ThreadId,
request_id: uuid::Uuid,
) {
if self.chat_widget.thread_id() != Some(thread_id) {
return;
}
let Some(channel) = self.thread_event_channels.get(&thread_id) else {
self.chat_widget
.apply_thread_name_suggestion(thread_id, request_id, /*suggestion*/ None);
return;
};
let conversation = {
let store = channel.store.lock().await;
let mut seen = std::collections::HashSet::new();
recent_conversation_messages(
store
.turns
.iter()
.flat_map(|turn| turn.items.iter())
.chain(store.buffer.iter().filter_map(|event| {
let ThreadBufferedEvent::Notification(notification) = event else {
return None;
};
let ServerNotification::ItemCompleted(notification) = notification.as_ref()
else {
return None;
};
Some(&notification.item)
}))
.filter(|item| seen.insert(item.id().to_string())),
)
};
let Some(conversation) = conversation else {
self.chat_widget
.apply_thread_name_suggestion(thread_id, request_id, /*suggestion*/ None);
return;
};
self.generate_thread_title(
app_server,
thread_id,
ThreadTitleDestination::RenameSuggestion { request_id },
recent_conversation_thread_title_prompt(&conversation),
);
}
}
/// Constrain generated metadata to one nonempty title within the display limit.
@@ -169,6 +240,112 @@ pub(super) fn thread_title_prompt(user_message: &str) -> String {
format!("{prefix}{user_message}")
}
/// Format recent substantive messages chronologically without trusting their markup.
pub(super) fn recent_conversation_messages<'a, I>(items: I) -> Option<String>
where
I: IntoIterator<Item = &'a ThreadItem>,
I::IntoIter: DoubleEndedIterator,
{
let mut messages = items
.into_iter()
.rev()
.filter_map(|item| match item {
ThreadItem::UserMessage { content, .. } => {
let text = content
.iter()
.filter_map(|input| match input {
UserInput::Text { text, .. } => {
Some(crate::ide_context::extract_prompt_request_with_offset(text).0)
}
_ => None,
})
.collect::<Vec<_>>()
.join("\n");
(!text.trim().is_empty()).then_some(("user", text))
}
ThreadItem::AgentMessage { text, phase, .. }
if !matches!(phase, Some(MessagePhase::Commentary)) && !text.trim().is_empty() =>
{
Some(("assistant", text.clone()))
}
_ => None,
})
.take(THREAD_TITLE_RECENT_MESSAGES)
.map(|(role, text)| {
let escaped = text
.trim()
.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;");
(role, escaped)
})
.collect::<Vec<_>>();
if messages.is_empty() {
return None;
}
messages.reverse();
let conversation_bytes = THREAD_TITLE_PROMPT_MAX_BYTES
.saturating_sub(recent_conversation_thread_title_prompt("").len());
let markup_bytes = "<conversation>\n".len()
+ "\n</conversation>".len()
+ messages.len().saturating_sub(/*rhs*/ 1)
+ messages
.iter()
.map(|(role, _)| "<message role=\"\"></message>".len() + role.len())
.sum::<usize>();
let message_bytes = conversation_bytes.saturating_sub(markup_bytes) / messages.len();
let content_bytes = messages.iter().map(|(_, text)| text.len()).sum::<usize>();
let should_truncate = content_bytes > conversation_bytes.saturating_sub(markup_bytes);
let messages = messages
.into_iter()
.map(|(role, mut text)| {
if should_truncate && text.len() > message_bytes {
let mut end = message_bytes;
while !text.is_char_boundary(end) {
end -= 1;
}
if let Some(entity_start) = text[..end].rfind('&')
&& !text[entity_start..end].contains(';')
{
end = entity_start;
}
text.truncate(end);
}
format!("<message role=\"{role}\">{text}</message>")
})
.collect::<Vec<_>>();
Some(format!(
"<conversation>\n{}\n</conversation>",
messages.join("\n")
))
}
/// Bound the entire suggestion prompt while preserving complete Unicode characters.
pub(super) fn recent_conversation_thread_title_prompt(conversation: &str) -> String {
let instructions = thread_title_instructions();
let prefix = format!(
"{instructions}\n\
Prioritize the current task and latest substantive user request.\n\n\
Recent conversation messages:\n"
);
let conversation = conversation.trim();
let remaining_bytes = THREAD_TITLE_PROMPT_MAX_BYTES.saturating_sub(prefix.len());
let mut start = conversation.len().saturating_sub(remaining_bytes);
while !conversation.is_char_boundary(start) {
start += 1;
}
let conversation = &conversation[start..];
format!("{prefix}{conversation}")
}
/// Normalize a generated title and truncate it without splitting Unicode characters.
pub(super) fn parse_thread_title(response: &str) -> Option<String> {
if !response.trim_start().starts_with('{') {