Generate descriptive TUI thread titles (#40492)

## What changed

- Give unnamed TUI threads an immediate provisional title from the first user message, then replace it asynchronously with a normalized generated title.
- Preserve manual renames by applying a generated title only while the provisional title is still current, and keep automatic rename notifications out of the transcript.
- Run title generation in a bounded ephemeral structured request that preserves custom permission profiles, otherwise uses read-only access, and disables tools and MCP servers.

## Testing

- Cover prompt and response bounds, Unicode-safe truncation, title normalization, manual-rename races, silent automatic updates, permission preservation, and structured-response failures.

GitOrigin-RevId: 7ed73522f4f6c65a005f65f3a903974d8419e312
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-08-24 23:06:06 +00:00
1 parent c941572917
commit b3c7e1a47f
18 files changed
+1032 -12

No files matched your search

+16
View File
@@ -92,6 +92,22 @@ impl App {
let _ = self.dynamic_tool_status_updates.send(status.clone());
}
// Hidden helper threads must not enter visible thread routing or overview refreshes.
if let ServerNotificationThreadTarget::Thread(thread_id) =
server_notification_thread_target(&notification)
&& let Some(sender) = self.temporary_structured_requests.get(&thread_id)
{
if matches!(
&notification,
ServerNotification::ItemCompleted(_) | ServerNotification::TurnCompleted(_)
) && sender.send(notification).is_err()
{
self.temporary_structured_requests.remove(&thread_id);
}
return;
}
if let ServerNotification::ThreadStarted(started) = &notification
&& let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id, ..
+53 -6
View File
@@ -6,6 +6,7 @@
use super::resize_reflow::trailing_run_start;
use super::session_lifecycle::ThreadAttachPresentation;
use super::*;
use crate::app_event::ThreadTitleDestination;
use crate::app_server_session::ForkGoalContinuation;
use crate::app_server_session::UnsupportedLegacyPermissionProfile;
use crate::app_server_session::turn_permissions_overrides;
@@ -2459,13 +2460,59 @@ impl App {
.await;
}
AppEvent::RenameAgentsOverviewThread { thread_id, name } => {
if let Err(error) = app_server.thread_set_name(thread_id, name.clone()).await {
if let Ok(mut state) = self.agents_overview.view_state.lock() {
state.input = name;
state.renaming = true;
match app_server.thread_set_name(thread_id, name.clone()).await {
Ok(()) => self.chat_widget.expect_manual_thread_name(thread_id, name),
Err(error) => {
if let Ok(mut state) = self.agents_overview.view_state.lock() {
state.input = name;
state.renaming = true;
}
self.chat_widget
.add_error_message(format!("Failed to rename task: {error}"));
}
}
}
AppEvent::ThreadTitleStarted {
thread_id,
destination,
prompt,
effort,
result,
} => {
self.on_thread_title_started(
app_server,
thread_id,
destination,
prompt,
effort,
result,
);
}
AppEvent::GeneratedThreadTitle {
thread_id,
temporary_thread_id,
destination,
result,
} => {
self.temporary_structured_requests
.remove(&temporary_thread_id);
match destination {
ThreadTitleDestination::Automatic { expected_title } => {
if let Ok(response) = result
&& let Some(title) = super::thread_title::parse_thread_title(&response)
&& self.chat_widget.thread_id() == Some(thread_id)
&& self.chat_widget.thread_name().as_deref()
== Some(expected_title.as_str())
{
match app_server.thread_set_name(thread_id, title.clone()).await {
Ok(()) => self.chat_widget.expect_automatic_thread_name(title),
Err(error) => {
tracing::debug!(%error, "failed to apply generated thread title");
}
}
}
}
self.chat_widget
.add_error_message(format!("Failed to rename task: {error}"));
}
}
AppEvent::StopAgentsOverviewThread { thread_id } => {
+1
View File
@@ -507,6 +507,7 @@ See the Codex keymap documentation for supported actions and examples."
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
thread_event_channels: HashMap::new(),
temporary_structured_requests: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
agents_overview: Default::default(),
+1
View File
@@ -60,6 +60,7 @@ pub(super) async fn make_test_app() -> App {
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
thread_event_channels: HashMap::new(),
temporary_structured_requests: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
agents_overview: Default::default(),
+2
View File
@@ -5447,6 +5447,7 @@ async fn make_test_app() -> App {
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
thread_event_channels: HashMap::new(),
temporary_structured_requests: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
agents_overview: Default::default(),
@@ -5526,6 +5527,7 @@ async fn make_test_app_with_channels() -> (
pending_shutdown_exit_thread_id: None,
windows_sandbox: WindowsSandboxState::default(),
thread_event_channels: HashMap::new(),
temporary_structured_requests: HashMap::new(),
thread_event_listener_tasks: HashMap::new(),
agent_navigation: AgentNavigationState::default(),
agents_overview: Default::default(),
@@ -31,6 +31,7 @@ const RETRY_PROMPT: &str = "Handle the safety-buffered request";
const COMMITTED_STEER: &str = "Keep the accepted steer";
const UNSENT_DRAFT: &str = "Keep this unsent draft";
const RETRY_GOAL: &str = "Preserve this goal across the retry";
const SAFETY_RETRY_THREAD_NAME: &str = "Safety retry source";
#[derive(Clone, Copy, PartialEq, Eq)]
enum SafetyRetryScenario {
@@ -420,8 +421,13 @@ goals = true
let mut tui = crate::tui::test_support::make_test_tui()?;
let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
let started = app_server.start_thread(&app.config).await?;
let mut started = app_server.start_thread(&app.config).await?;
let source_thread_id = started.session.thread_id;
// Keep ordered response fixtures focused on safety retries, not background naming.
app_server
.thread_set_name(source_thread_id, SAFETY_RETRY_THREAD_NAME.to_string())
.await?;
started.session.thread_name = Some(SAFETY_RETRY_THREAD_NAME.to_string());
app.replace_chat_widget_with_app_server_thread(
&mut tui,
started,
+56 -3
View File
@@ -6,6 +6,7 @@
use super::session_lifecycle::ThreadAttachPresentation;
use super::*;
use crate::app_event::ThreadTitleDestination;
use crate::chatwidget::ThreadInputStateRestoreMode;
use crate::session_resume::read_session_model;
use codex_app_server_protocol::ThreadStartedNotification;
@@ -781,9 +782,9 @@ impl App {
Ok(true)
}
AppCommand::SetThreadName { name } => {
app_server
.thread_set_name(thread_id, name.to_string())
.await?;
let name = name.to_string();
app_server.thread_set_name(thread_id, name.clone()).await?;
self.chat_widget.expect_manual_thread_name(thread_id, name);
Ok(true)
}
AppCommand::Review { target } => {
@@ -1796,9 +1797,61 @@ impl App {
// thread, so unrelated shutdowns cannot consume this marker.
self.pending_shutdown_exit_thread_id = None;
}
let automatic_title_user_message = if self.chat_widget.thread_name().is_none()
&& let ThreadBufferedEvent::Notification(notification) = &event
&& let ServerNotification::ItemCompleted(notification) = notification.as_ref()
&& let ThreadItem::UserMessage { content, .. } = &notification.item
{
Some(
content
.iter()
.filter_map(|item| match item {
codex_app_server_protocol::UserInput::Text { text, .. } => {
Some(crate::ide_context::extract_prompt_request_with_offset(text).0)
}
_ => None,
})
.collect::<Vec<_>>()
.join(" "),
)
} else {
None
};
let had_active_view = self.chat_widget.has_active_view();
self.handle_thread_event_now_recovering_file_changes(event)
.await;
if let Some(user_message) = automatic_title_user_message {
let expected_title = user_message
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.chars()
.take(super::thread_title::THREAD_TITLE_MAX_CHARS)
.collect::<String>();
if !expected_title.is_empty()
&& let Some(thread_id) = self.active_thread_id
{
match app_server
.thread_set_name(thread_id, expected_title.clone())
.await
{
Ok(()) => {
self.chat_widget
.expect_automatic_thread_name(expected_title.clone());
self.generate_thread_title(
app_server,
thread_id,
ThreadTitleDestination::Automatic { expected_title },
super::thread_title::thread_title_prompt(&user_message),
);
}
Err(error) => {
tracing::debug!(%error, "failed to set provisional thread title");
}
}
}
}
if !had_active_view
&& self.chat_widget.has_active_view()
&& self.startup_protected_input_boundary
+201
View File
@@ -0,0 +1,201 @@
//! Structured-output schema and normalization for generated TUI thread titles.
use super::App;
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_protocol::ThreadId;
use codex_protocol::openai_models::ReasoningEffort;
use serde::Deserialize;
use serde_json::Value;
use serde_json::json;
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;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GeneratedThreadTitle {
title: String,
}
impl App {
/// Start a hidden title-generation thread without blocking the UI loop.
pub(super) fn generate_thread_title(
&mut self,
app_server: &AppServerSession,
thread_id: ThreadId,
destination: ThreadTitleDestination,
prompt: String,
) {
let request_handle = app_server.request_handle();
let model = if self.chat_widget.config_ref().model_provider_id == "openai"
&& self.chat_widget.has_chatgpt_account()
&& self
.chat_widget
.model_catalog()
.try_list_models()
.is_ok_and(|models| models.iter().any(|model| model.model == THREAD_TITLE_MODEL))
{
THREAD_TITLE_MODEL.to_string()
} else {
self.chat_widget.current_model().to_string()
};
let effort = (model == THREAD_TITLE_MODEL).then_some(ReasoningEffort::Low);
let config = self.chat_widget.config_ref();
let options = TemporaryStructuredThreadOptions {
model,
model_provider: config.model_provider_id.clone(),
cwd: config.cwd.display().to_string(),
active_permission_profile: config
.permissions
.active_permission_profile()
.map(|profile| profile.id),
mcp_server_names: config.mcp_servers.get().keys().cloned().collect(),
};
let event_sender = self.app_event_tx.clone();
tokio::spawn(async move {
let result = start_temporary_thread(&request_handle, options)
.await
.map(|thread| thread.thread.id)
.map_err(|error| error.to_string());
event_sender.send(AppEvent::ThreadTitleStarted {
thread_id,
destination,
prompt,
effort,
result,
});
});
}
/// Register a started hidden thread and generate its structured title.
pub(super) fn on_thread_title_started(
&mut self,
app_server: &AppServerSession,
thread_id: ThreadId,
destination: ThreadTitleDestination,
prompt: String,
effort: Option<ReasoningEffort>,
result: Result<String, String>,
) {
let temporary_thread_id_text = match result {
Ok(thread_id) => thread_id,
Err(error) => {
tracing::debug!(%error, "failed to start title-generation thread");
return;
}
};
let Ok(temporary_thread_id) = ThreadId::from_string(&temporary_thread_id_text) else {
return;
};
let (sender, receiver) = mpsc::unbounded_channel();
self.temporary_structured_requests
.insert(temporary_thread_id, sender);
let request_handle = app_server.request_handle();
let event_sender = self.app_event_tx.clone();
tokio::spawn(async move {
let result = run_temporary_structured_turn(
request_handle,
temporary_thread_id_text,
prompt,
thread_title_output_schema(),
effort,
receiver,
)
.await
.map_err(|error| error.to_string());
event_sender.send(AppEvent::GeneratedThreadTitle {
thread_id,
temporary_thread_id,
destination,
result,
});
});
}
}
/// Constrain generated metadata to one nonempty title within the display limit.
pub(super) fn thread_title_output_schema() -> Value {
json!({
"type": "object",
"properties": {
"title": {
"type": "string",
"minLength": 1,
"maxLength": THREAD_TITLE_MAX_CHARS,
},
},
"required": ["title"],
"additionalProperties": false,
})
}
fn thread_title_instructions() -> String {
format!(
"Generate a concise, single-line task title of at most \
{THREAD_TITLE_MAX_CHARS} characters and under five words where possible. \
Start with an imperative verb. Capitalize only the first word unless the \
user's language, proper nouns, acronyms, or code terms require otherwise. \
Preserve ticket references exactly. Write in the user's language. \
Do not use quotes, markdown, or trailing punctuation. \
Do not answer the request."
)
}
/// Build a bounded title request without truncating a Unicode character.
pub(super) fn thread_title_prompt(user_message: &str) -> String {
let instructions = thread_title_instructions();
let prefix = format!("{instructions}\n\nUser prompt:\n");
let remaining_bytes = THREAD_TITLE_PROMPT_MAX_BYTES.saturating_sub(prefix.len());
let user_message = user_message
.trim()
.char_indices()
.take_while(|(index, character)| index + character.len_utf8() <= remaining_bytes)
.map(|(_, character)| character)
.collect::<String>();
format!("{prefix}{user_message}")
}
/// 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('{') {
return None;
}
let title = serde_json::from_str::<GeneratedThreadTitle>(response)
.ok()?
.title;
let normalized = title
.trim()
.trim_matches(|character| matches!(character, '"' | '\'' | '`' | '“' | '”' | '‘' | '’'))
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.trim_end_matches(['.', '?', '!'])
.trim_end()
.to_string();
if normalized.is_empty() {
return None;
}
Some(normalized.chars().take(THREAD_TITLE_MAX_CHARS).collect())
}
#[cfg(test)]
#[path = "thread_title_tests.rs"]
mod tests;
+129
View File
@@ -0,0 +1,129 @@
use super::THREAD_TITLE_MAX_CHARS;
use super::THREAD_TITLE_PROMPT_MAX_BYTES;
use super::parse_thread_title;
use super::thread_title_prompt;
use crate::app::test_support::make_test_app;
use crate::app_command::AppCommand;
use pretty_assertions::assert_eq;
const EXPECTED_THREAD_TITLE_INSTRUCTIONS: &str = concat!(
"Generate a concise, single-line task title of at most 36 characters ",
"and under five words where possible. Start with an imperative verb. ",
"Capitalize only the first word unless the user's language, proper nouns, ",
"acronyms, or code terms require otherwise. Preserve ticket references ",
"exactly. Write in the user's language. Do not use quotes, markdown, ",
"or trailing punctuation. Do not answer the request."
);
#[test]
fn trims_user_message_in_title_prompt() {
let prompt = thread_title_prompt(" Fix the login form \n");
assert_eq!(
prompt,
format!("{EXPECTED_THREAD_TITLE_INSTRUCTIONS}\n\nUser prompt:\nFix the login form")
);
}
#[test]
fn truncates_title_prompt_without_splitting_unicode() {
let user_message = "🚀".repeat(THREAD_TITLE_PROMPT_MAX_BYTES);
let prompt = thread_title_prompt(&user_message);
let expected_instructions = format!("{EXPECTED_THREAD_TITLE_INSTRUCTIONS}\n\n");
let prefix = format!("{expected_instructions}User prompt:\n");
let available_bytes = THREAD_TITLE_PROMPT_MAX_BYTES - prefix.len();
let expected = "🚀".repeat(available_bytes / '🚀'.len_utf8());
assert_eq!(
prompt.rsplit_once("User prompt:\n"),
Some((expected_instructions.as_str(), expected.as_str()))
);
assert!(prompt.len() <= THREAD_TITLE_PROMPT_MAX_BYTES);
}
#[test]
fn bounds_the_entire_title_prompt_for_dense_unicode() {
let repeated_characters = THREAD_TITLE_PROMPT_MAX_BYTES * 3;
for message in [
"🚀".repeat(repeated_characters),
"漢".repeat(repeated_characters),
"x".repeat(repeated_characters),
] {
let prompt = thread_title_prompt(&message);
assert!(
prompt.len() <= THREAD_TITLE_PROMPT_MAX_BYTES,
"{} bytes for {:?}",
prompt.len(),
message.chars().next()
);
}
}
#[tokio::test]
async fn manual_rename_invalidates_pending_automatic_title_before_notification()
-> color_eyre::Result<()> {
let mut app = make_test_app().await;
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
let started = app_server.start_thread(&app.config).await?;
let thread_id = started.session.thread_id;
app.enqueue_primary_thread_session(started.session, started.turns)
.await?;
app_server
.thread_set_name(thread_id, "Provisional title".to_string())
.await?;
app.chat_widget
.expect_automatic_thread_name("Provisional title".to_string());
app.submit_thread_op(
&mut app_server,
thread_id,
AppCommand::set_thread_name("Manual title".to_string()),
)
.await?;
assert_eq!(
app.chat_widget.thread_name(),
Some("Manual title".to_string())
);
app_server.shutdown().await?;
Ok(())
}
#[test]
fn normalizes_generated_title_whitespace() {
assert_eq!(
parse_thread_title(r#"{"title":" Fix \n\t login errors "}"#),
Some("Fix login errors".to_string())
);
}
#[test]
fn rejects_invalid_or_empty_generated_titles() {
for response in [
"",
"not json",
"null",
"true",
"42",
"[]",
r#"["title"]"#,
r#""plain title""#,
"{}",
r#"{"title":7}"#,
r#"{"title":"valid","extra":true}"#,
r#"{"title":""}"#,
r#"{"title":" \t "}"#,
] {
assert_eq!(parse_thread_title(response), None, "response: {response}");
}
}
#[test]
fn truncates_generated_titles_without_splitting_unicode() {
let expected = "🚀".repeat(THREAD_TITLE_MAX_CHARS);
let response = serde_json::json!({ "title": format!("{expected}x") }).to_string();
assert_eq!(parse_thread_title(&response), Some(expected));
}