diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index ddddc61d49..53c82be9c7 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -656,7 +656,13 @@ pub(crate) struct App { realtime_replay_order: VecDeque, background_voice: Option>, background_voice_error: Option<(ThreadId, String)>, - temporary_structured_requests: HashMap>, + temporary_structured_requests: HashMap< + ThreadId, + ( + crate::temporary_structured_request::TemporaryThreadKind, + mpsc::UnboundedSender, + ), + >, /// Track title generation across thread switches and deduplicate automatic requests. pending_thread_titles: HashMap<(ThreadId, ThreadTitleDestination), CancellationToken>, thread_event_listener_tasks: HashMap>, diff --git a/codex-rs/tui/src/app/app_server_events.rs b/codex-rs/tui/src/app/app_server_events.rs index 8f179f3f66..5f3680248f 100644 --- a/codex-rs/tui/src/app/app_server_events.rs +++ b/codex-rs/tui/src/app/app_server_events.rs @@ -228,7 +228,7 @@ impl App { // Hidden helper threads must not enter visible thread routing or overview refreshes. let target = server_notification_thread_target(¬ification); if let ServerNotificationThreadTarget::Thread(thread_id) = target - && let Some(sender) = self.temporary_structured_requests.get(&thread_id) + && let Some((_, sender)) = self.temporary_structured_requests.get(&thread_id) { if matches!( ¬ification, @@ -597,9 +597,16 @@ impl App { ) { let request = &buffered_request.request; let thread_id = server_request_thread_id(request); - if thread_id - .is_some_and(|thread_id| self.temporary_structured_requests.contains_key(&thread_id)) + if let Some((kind, _)) = + thread_id.and_then(|id| self.temporary_structured_requests.get(&id)) { + // Managed policy can allow a title turn to ask a question. Keep it on + // the hidden thread until the structured turn times out, as on desktop. + if *kind == crate::temporary_structured_request::TemporaryThreadKind::Title + && matches!(request, ServerRequest::ToolRequestUserInput { params, .. } if params.is_blocking) + { + return; + } self.reject_unsupported_app_server_request( super::app_server_requests::UnsupportedAppServerRequest { request_id: request.id().clone(), diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 881d272ed1..9b695c3adb 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -3278,7 +3278,7 @@ impl App { AppEvent::RenameAgentsOverviewThread { thread_id, name } => { match app_server.thread_set_name(thread_id, name.clone()).await { Ok(()) => { - self.chat_widget.expect_manual_thread_name(thread_id, name); + self.chat_widget.display_thread_name(thread_id, name); self.cancel_thread_title_generation(thread_id); } Err(error) => { @@ -3316,6 +3316,7 @@ impl App { thread_id, destination, prompt, + fallback_title, effort, result, } => { @@ -3324,6 +3325,7 @@ impl App { thread_id, destination, prompt, + fallback_title, effort, result, cancellation, diff --git a/codex-rs/tui/src/app/recap.rs b/codex-rs/tui/src/app/recap.rs index 84b8f00355..d6059eec1d 100644 --- a/codex-rs/tui/src/app/recap.rs +++ b/codex-rs/tui/src/app/recap.rs @@ -15,10 +15,10 @@ use crate::history_cell::ThreadRecapHistoryCell; use crate::history_cell::ThreadRecapLoadingCell; use crate::pager_overlay::Overlay; use crate::temporary_structured_request::TemporaryStructuredThreadOptions; +use crate::temporary_structured_request::TemporaryThreadKind; use crate::temporary_structured_request::run_temporary_structured_turn; use crate::temporary_structured_request::start_temporary_thread; use crate::temporary_structured_request::unsubscribe_temporary_thread; -use codex_app_server_protocol::ThreadSource; use codex_app_server_protocol::Turn; use codex_app_server_protocol::TurnStatus; use codex_context_fragments::ContextualUserFragment; @@ -237,7 +237,7 @@ impl App { config.cwd.display().to_string() }; let options = TemporaryStructuredThreadOptions { - thread_source: ThreadSource::Feature("system".to_string()), + kind: TemporaryThreadKind::Recap, model, model_provider: config.model_provider_id.clone(), cwd, @@ -337,17 +337,19 @@ impl App { let (sender, receiver) = mpsc::unbounded_channel(); self.temporary_structured_requests - .insert(temporary_thread_id, sender); + .insert(temporary_thread_id, (TemporaryThreadKind::Recap, sender)); let request_handle = app_server.request_handle(); let event_sender = self.app_event_tx.clone(); let task = tokio::spawn(async move { let result = run_temporary_structured_turn( request_handle, - temporary_thread_id_text, - recap_prompt(&history), - recap_output_schema(), - /*effort*/ None, + TemporaryThreadKind::Recap.turn_params( + temporary_thread_id_text, + recap_prompt(&history), + recap_output_schema(), + /*effort*/ None, + ), receiver, CancellationToken::new(), ) diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__thread_title__tests__automatic_thread_title_pending.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__thread_title__tests__automatic_thread_title_pending.snap index 81b1335186..82d49a4f69 100644 --- a/codex-rs/tui/src/app/snapshots/codex_tui__app__thread_title__tests__automatic_thread_title_pending.snap +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__thread_title__tests__automatic_thread_title_pending.snap @@ -1,11 +1,10 @@ --- source: tui/src/app/thread_title_tests.rs -assertion_line: 302 expression: "normalize_snapshot_paths(format!(\"terminal title: {}\\nfooter:\\n{}\",\napp.chat_widget.last_terminal_title.as_deref().unwrap_or_default(),\nrender_bottom_popup(&app.chat_widget, 120)))" --- -terminal title: project +terminal title: Fix the login timeout | project footer: › Ask Codex to do anything - gpt-5.2 default · /tmp/project + gpt-5.2 default · /tmp/project · Fix the login timeout ← for agents · ? for shortcuts diff --git a/codex-rs/tui/src/app/tests/recap_generation_tests.rs b/codex-rs/tui/src/app/tests/recap_generation_tests.rs index 049b473937..c1f60346b0 100644 --- a/codex-rs/tui/src/app/tests/recap_generation_tests.rs +++ b/codex-rs/tui/src/app/tests/recap_generation_tests.rs @@ -3,6 +3,7 @@ use crate::app::session_lifecycle::ThreadAttachPresentation; use crate::app::tests::session_lifecycle_requests::recorded_params; use crate::app::tests::session_lifecycle_requests::start_recording_remote_app_server; use crate::app_event::RecapTrigger; +use crate::temporary_structured_request::TemporaryThreadKind; use codex_app_server_client::AppServerClient; use codex_model_provider_info::ModelProviderInfo; use core_test_support::responses; @@ -493,7 +494,7 @@ async fn temporary_recap_threads_disable_memories_and_remote_mcp_servers() -> Re let config = app.chat_widget.config_ref(); let options = crate::temporary_structured_request::TemporaryStructuredThreadOptions { - thread_source: codex_app_server_protocol::ThreadSource::Feature("system".to_string()), + kind: TemporaryThreadKind::Recap, model: app.chat_widget.current_model().to_string(), model_provider: config.model_provider_id.clone(), cwd: config.cwd.display().to_string(), @@ -509,7 +510,8 @@ async fn temporary_recap_threads_disable_memories_and_remote_mcp_servers() -> Re .await?; let thread_id = ThreadId::from_string(&response.thread.id)?; let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); - app.temporary_structured_requests.insert(thread_id, sender); + app.temporary_structured_requests + .insert(thread_id, (TemporaryThreadKind::Recap, sender)); // Even if a hidden thread reaches visible routing, it must not prompt. app.primary_thread_id = Some(thread_id); app.active_thread_id = Some(thread_id); @@ -528,6 +530,23 @@ async fn temporary_recap_threads_disable_memories_and_remote_mcp_servers() -> Re ); } + // A managed policy can also cause an ephemeral title to ask for input. + // Its request stays unanswered and never enters the visible chat. + let title_id = ThreadId::new(); + let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); + app.temporary_structured_requests + .insert(title_id, (TemporaryThreadKind::Title, sender)); + let question = request_user_input_request(title_id, "title-turn", "question"); + app.handle_app_server_event( + &app_server, + codex_app_server_client::AppServerEvent::ServerRequest(Box::new(question.clone())), + ) + .await; + assert!( + !app.pending_app_server_requests + .contains_server_request(&question) + ); + let starts = recorded_params(&requests, "thread/start"); assert_eq!(starts.len(), 1); assert_eq!(starts[0]["sandbox"], "read-only"); diff --git a/codex-rs/tui/src/app/thread_routing.rs b/codex-rs/tui/src/app/thread_routing.rs index 57145d6c9c..f333f98752 100644 --- a/codex-rs/tui/src/app/thread_routing.rs +++ b/codex-rs/tui/src/app/thread_routing.rs @@ -857,7 +857,7 @@ impl App { AppCommand::SetThreadName { name } => { 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); + self.chat_widget.display_thread_name(thread_id, name); self.cancel_thread_title_generation(thread_id); Ok(true) } @@ -2206,7 +2206,7 @@ impl App { app_server, thread_id, ThreadTitleDestination::Automatic, - super::thread_title::thread_title_prompt(&user_message), + &user_message, ); } if !had_active_modal diff --git a/codex-rs/tui/src/app/thread_title.rs b/codex-rs/tui/src/app/thread_title.rs index 93b8d13c56..d33362705c 100644 --- a/codex-rs/tui/src/app/thread_title.rs +++ b/codex-rs/tui/src/app/thread_title.rs @@ -1,6 +1,6 @@ //! Structured-output schema and normalization for generated TUI thread titles. //! -//! Automatic titles are persisted only after generation, including for inactive threads; +//! Automatic titles use the first message until generation completes and as a fallback; //! the originating thread's saved name takes precedence over an automatic result. Manual //! renames cancel pending requests; canceled events cannot affect newer requests. @@ -11,17 +11,20 @@ use crate::app_event::ThreadTitleDestination; use crate::app_server_session::AppServerSession; use crate::app_server_session::ThreadSettingsOwner; use crate::temporary_structured_request::TemporaryStructuredThreadOptions; +use crate::temporary_structured_request::TemporaryThreadKind; use crate::temporary_structured_request::run_temporary_structured_turn; use crate::temporary_structured_request::start_temporary_thread; use crate::temporary_structured_request::unsubscribe_temporary_thread; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ThreadItemPayload; -use codex_app_server_protocol::ThreadSource; use codex_app_server_protocol::Turn; use codex_app_server_protocol::UserInput; use codex_protocol::ThreadId; use codex_protocol::models::MessagePhase; use codex_protocol::openai_models::ReasoningEffort; +use pulldown_cmark::Event; +use pulldown_cmark::Parser; +use pulldown_cmark::TagEnd; use serde::Deserialize; use serde_json::Value; use serde_json::json; @@ -66,7 +69,7 @@ impl App { app_server: &AppServerSession, thread_id: ThreadId, destination: ThreadTitleDestination, - prompt: String, + source_text: &str, ) { if app_server.thread_params_mode().settings_owner() == ThreadSettingsOwner::Server { if let ThreadTitleDestination::RenameSuggestion { request_id } = destination { @@ -81,6 +84,19 @@ impl App { return; }; let cancellation = entry.insert(CancellationToken::new()).clone(); + let (prompt, fallback_title) = match destination { + ThreadTitleDestination::Automatic => { + let fallback = fallback_thread_title(source_text); + if let Some(title) = &fallback { + self.chat_widget + .display_thread_name(thread_id, title.clone()); + } + (thread_title_prompt(source_text), fallback) + } + ThreadTitleDestination::RenameSuggestion { .. } => { + (recent_conversation_thread_title_prompt(source_text), None) + } + }; 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() @@ -97,7 +113,7 @@ impl App { let effort = (model == THREAD_TITLE_MODEL).then_some(ReasoningEffort::Low); let config = self.chat_widget.config_ref(); let options = TemporaryStructuredThreadOptions { - thread_source: ThreadSource::Feature("thread_title".to_string()), + kind: TemporaryThreadKind::Title, model, model_provider: config.model_provider_id.clone(), cwd: config.cwd.display().to_string(), @@ -119,6 +135,7 @@ impl App { thread_id, destination, prompt, + fallback_title, effort, result, }); @@ -133,6 +150,7 @@ impl App { thread_id: ThreadId, destination: ThreadTitleDestination, prompt: String, + fallback_title: Option, effort: Option, result: Result, cancellation: CancellationToken, @@ -146,11 +164,18 @@ impl App { } return; } - let temporary_thread_id_text = match result { - Ok(thread_id) => thread_id, + let save_name = (destination == ThreadTitleDestination::Automatic) + .then(|| app_server.automatic_thread_name_writer(thread_id)); + let temporary_thread_id = match result + .and_then(|id| ThreadId::from_string(&id).map_err(|error| error.to_string())) + { + Ok(id) => id, Err(error) => { tracing::debug!(%error, "failed to start title-generation thread"); self.finish_thread_title_generation(thread_id, destination); + if let (Some(writer), Some(title)) = (save_name, fallback_title) { + tokio::spawn(async move { writer.save(title, &cancellation).await }); + } if let ThreadTitleDestination::RenameSuggestion { request_id } = destination { self.chat_widget.apply_thread_name_suggestion( thread_id, request_id, /*suggestion*/ None, @@ -160,30 +185,21 @@ impl App { } }; - let Ok(temporary_thread_id) = ThreadId::from_string(&temporary_thread_id_text) else { - self.finish_thread_title_generation(thread_id, destination); - if let ThreadTitleDestination::RenameSuggestion { request_id } = destination { - self.chat_widget - .apply_thread_name_suggestion(thread_id, request_id, /*suggestion*/ None); - } - return; - }; - let (sender, receiver) = mpsc::unbounded_channel(); self.temporary_structured_requests - .insert(temporary_thread_id, sender); + .insert(temporary_thread_id, (TemporaryThreadKind::Title, sender)); - let save_name = (destination == ThreadTitleDestination::Automatic) - .then(|| app_server.automatic_thread_name_writer(thread_id)); 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, + TemporaryThreadKind::Title.turn_params( + temporary_thread_id.to_string(), + prompt, + thread_title_output_schema(), + effort, + ), receiver, cancellation.clone(), ) @@ -191,8 +207,11 @@ impl App { .map_err(|error| error.to_string()); if let Some(save_name) = save_name - && let Ok(response) = &result - && let Some(title) = parse_thread_title(response) + && let Some(title) = result + .as_deref() + .ok() + .and_then(parse_thread_title) + .or(fallback_title) { save_name.save(title, &cancellation).await; } @@ -258,7 +277,7 @@ impl App { app_server, thread_id, ThreadTitleDestination::RenameSuggestion { request_id }, - recent_conversation_thread_title_prompt(&conversation), + &conversation, ); } } @@ -291,6 +310,35 @@ fn thread_title_instructions() -> String { ) } +/// Desktop shows a single line from the first message until a generated title is available. +fn fallback_thread_title(message: &str) -> Option { + const MAX_CHARS: usize = 60; + const INPUT_CHAR_LIMIT: usize = 2_000; + let excerpt: String = message.trim().chars().take(INPUT_CHAR_LIMIT).collect(); + let mut text = String::new(); + for event in Parser::new(&excerpt) { + match event { + Event::Text(value) | Event::Code(value) => text.push_str(&value), + Event::SoftBreak + | Event::HardBreak + | Event::Rule + | Event::End( + TagEnd::Paragraph | TagEnd::Heading(_) | TagEnd::Item | TagEnd::CodeBlock, + ) => text.push(' '), + _ => {} + } + } + let mut title = text.split_whitespace().collect::>().join(" "); + let mut chars = title.char_indices().skip(MAX_CHARS - 1); + if let Some((end, _)) = chars.next() + && chars.next().is_some() + { + title.truncate(title[..end].trim_end().len()); + title.push('…'); + } + (!title.is_empty()).then_some(title) +} + /// 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(); diff --git a/codex-rs/tui/src/app/thread_title_tests.rs b/codex-rs/tui/src/app/thread_title_tests.rs index 3d51f75f7b..f1788ca4c4 100644 --- a/codex-rs/tui/src/app/thread_title_tests.rs +++ b/codex-rs/tui/src/app/thread_title_tests.rs @@ -108,7 +108,7 @@ async fn cloud_conversations_skip_tui_generated_titles() { &app_server, thread_id, ThreadTitleDestination::Automatic, - thread_title_prompt("Fix the login timeout"), + "Fix the login timeout", ); assert!(app.pending_thread_titles.is_empty()); @@ -210,10 +210,16 @@ async fn slash_rename_generates_editable_title_through_embedded_app_server() } #[tokio::test] -async fn automatic_thread_title_generates_without_a_provisional_name() -> color_eyre::Result<()> { +async fn automatic_thread_title_replaces_the_provisional_name() -> color_eyre::Result<()> { check_thread_title_generation(TitleScenario::Automatic).await } +#[tokio::test] +async fn automatic_thread_title_saves_the_first_message_if_generation_fails() +-> color_eyre::Result<()> { + check_thread_title_generation(TitleScenario::Fallback).await +} + #[tokio::test] async fn manual_rename_cancels_running_thread_title() -> color_eyre::Result<()> { check_thread_title_generation(TitleScenario::ManualRename).await @@ -227,6 +233,7 @@ async fn overview_rename_cancels_running_thread_title() -> color_eyre::Result<() #[derive(Clone, Copy)] enum TitleScenario { Automatic, + Fallback, Suggestion, ManualRename, OverviewRename, @@ -239,9 +246,19 @@ async fn check_thread_title_generation(scenario: TitleScenario) -> color_eyre::R TitleScenario::ManualRename | TitleScenario::OverviewRename ); let server = wiremock::MockServer::start().await; + let user_message = if matches!(scenario, TitleScenario::Fallback) { + "Fix the **login**\n[timeout](https://example.test/issue)" + } else { + "Fix the login timeout" + }; + let title_message = if matches!(scenario, TitleScenario::Fallback) { + "{}" + } else { + r#"{"title":"Fix login timeout"}"# + }; let mut template = responses::sse_response(responses::sse(vec![ responses::ev_response_created("title-response"), - responses::ev_assistant_message("title-message", r#"{"title":"Fix login timeout"}"#), + responses::ev_assistant_message("title-message", title_message), responses::ev_completed("title-response"), ])); if cancel { @@ -303,7 +320,7 @@ async fn check_thread_title_generation(scenario: TitleScenario) -> color_eyre::R root_turn_id: None, items: vec![ThreadItem::untimed(title_user_message( "user-message", - "Fix the login timeout", + user_message, ))], items_view: Default::default(), status: TurnStatus::Completed, @@ -323,7 +340,7 @@ async fn check_thread_title_generation(scenario: TitleScenario) -> color_eyre::R ItemCompletedNotification::new( thread_id.to_string(), "existing-turn".to_string(), - title_user_message("user-message", "Fix the login timeout"), + title_user_message("user-message", user_message), /*started_at_ms*/ None, /*completed_at_ms*/ 0, ), @@ -331,7 +348,10 @@ async fn check_thread_title_generation(scenario: TitleScenario) -> color_eyre::R ) .await?; } - assert_eq!(app.chat_widget.thread_name(), None); + assert_eq!( + app.chat_widget.thread_name().as_deref(), + Some("Fix the login timeout") + ); if matches!(scenario, TitleScenario::Automatic) { app.chat_widget.refresh_status_surfaces(); insta::assert_snapshot!( @@ -421,7 +441,9 @@ async fn check_thread_title_generation(scenario: TitleScenario) -> color_eyre::R TitleScenario::OverviewRename => { AppEvent::RenameAgentsOverviewThread { thread_id, name } } - TitleScenario::Automatic | TitleScenario::Suggestion => unreachable!(), + TitleScenario::Automatic + | TitleScenario::Fallback + | TitleScenario::Suggestion => unreachable!(), }; app.handle_event(&mut tui, &mut app_server, event).await?; assert!(app.pending_thread_titles.is_empty()); @@ -441,7 +463,8 @@ async fn check_thread_title_generation(scenario: TitleScenario) -> color_eyre::R } if generated && (!cancel || interrupted) - && (!automatic || app.chat_widget.thread_name().is_some()) + && (!matches!(scenario, TitleScenario::Automatic) + || app.chat_widget.thread_name().as_deref() == Some("Fix login timeout")) { break; } @@ -450,6 +473,8 @@ async fn check_thread_title_generation(scenario: TitleScenario) -> color_eyre::R if automatic { let expected_name = if cancel { "Keep this title" + } else if matches!(scenario, TitleScenario::Fallback) { + "Fix the login timeout" } else { "Fix login timeout" }; @@ -483,9 +508,9 @@ async fn check_thread_title_generation(scenario: TitleScenario) -> color_eyre::R let request = response.single_request(); assert!( request - .body_json() - .to_string() - .contains("Fix the login timeout") + .message_input_texts("user") + .iter() + .any(|prompt| prompt.contains(user_message)) ); app_server.shutdown().await?; @@ -533,6 +558,7 @@ async fn canceled_thread_title_ignores_late_start_and_completion() -> color_eyre thread_id, destination, "prompt".to_string(), + /*fallback_title*/ None, /*effort*/ None, Ok(temporary_thread_id.to_string()), cancellation.clone(), @@ -889,6 +915,7 @@ async fn failed_thread_title_requests_are_removed() -> color_eyre::Result<()> { thread_id, ThreadTitleDestination::Automatic, "prompt".to_string(), + /*fallback_title*/ None, /*effort*/ None, Err("startup failed".to_string()), CancellationToken::new(), @@ -898,6 +925,7 @@ async fn failed_thread_title_requests_are_removed() -> color_eyre::Result<()> { thread_id, suggestion, "prompt".to_string(), + /*fallback_title*/ None, /*effort*/ None, Ok("invalid-thread-id".to_string()), CancellationToken::new(), diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index c858e8196f..b1dd1bae17 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -439,6 +439,7 @@ pub(crate) enum AppEvent { thread_id: ThreadId, destination: ThreadTitleDestination, prompt: String, + fallback_title: Option, effort: Option, result: Result, }, diff --git a/codex-rs/tui/src/chatwidget/session_flow.rs b/codex-rs/tui/src/chatwidget/session_flow.rs index 398fa0013a..f9d4ca9827 100644 --- a/codex-rs/tui/src/chatwidget/session_flow.rs +++ b/codex-rs/tui/src/chatwidget/session_flow.rs @@ -412,8 +412,8 @@ impl ChatWidget { ))); } - /// Update status surfaces before a confirmed manual rename's server notification arrives. - pub(crate) fn expect_manual_thread_name(&mut self, thread_id: ThreadId, name: String) { + /// Show a provisional or manually chosen name before its server notification arrives. + pub(crate) fn display_thread_name(&mut self, thread_id: ThreadId, name: String) { if self.thread_id == Some(thread_id) { self.thread_name = Some(name); self.refresh_status_surfaces(); diff --git a/codex-rs/tui/src/chatwidget/tests/app_server.rs b/codex-rs/tui/src/chatwidget/tests/app_server.rs index f617e1032d..f10acfc397 100644 --- a/codex-rs/tui/src/chatwidget/tests/app_server.rs +++ b/codex-rs/tui/src/chatwidget/tests/app_server.rs @@ -2176,7 +2176,7 @@ async fn live_app_server_manual_thread_name_updates_status_surfaces() { ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").expect("thread id"); chat.thread_id = Some(thread_id); - chat.expect_manual_thread_name(thread_id, "review-fix".to_string()); + chat.display_thread_name(thread_id, "review-fix".to_string()); chat.handle_server_notification( ServerNotification::ThreadNameUpdated( @@ -2245,7 +2245,7 @@ async fn live_app_server_manual_thread_name_is_visible_before_notification() { let thread_id = ThreadId::new(); chat.thread_id = Some(thread_id); - chat.expect_manual_thread_name(thread_id, "Manual title".to_string()); + chat.display_thread_name(thread_id, "Manual title".to_string()); assert_eq!(chat.thread_name(), Some("Manual title".to_string())); assert!(drain_insert_history(&mut rx).is_empty()); diff --git a/codex-rs/tui/src/temporary_structured_request.rs b/codex-rs/tui/src/temporary_structured_request.rs index 44df87574c..b19590422c 100644 --- a/codex-rs/tui/src/temporary_structured_request.rs +++ b/codex-rs/tui/src/temporary_structured_request.rs @@ -1,7 +1,7 @@ //! Run isolated structured requests through existing app-server methods. use codex_app_server_client::AppServerRequestHandle; -use codex_app_server_client::TypedRequestError; +use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SandboxMode; @@ -31,9 +31,15 @@ use uuid::Uuid; const STRUCTURED_TURN_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30); const STRUCTURED_RESPONSE_MAX_BYTES: usize = 8 * 1024; -/// Preserve the visible thread's provider, permissions, and external-tool isolation. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum TemporaryThreadKind { + Title, + Recap, +} + +/// Settings for an isolated structured request using the visible thread's provider. pub(crate) struct TemporaryStructuredThreadOptions { - pub(crate) thread_source: ThreadSource, + pub(crate) kind: TemporaryThreadKind, pub(crate) model: String, pub(crate) model_provider: String, pub(crate) cwd: String, @@ -44,20 +50,30 @@ pub(crate) struct TemporaryStructuredThreadOptions { /// /// Structured prompts can contain untrusted transcript text, so the effective app-server config is /// read first and every MCP server is explicitly disabled alongside built-in and extension tools. -/// Approval policy is inherited from the server; the TUI rejects unexpected interaction requests. +/// As on desktop, title threads request read-only permissions and the `never` approval policy. pub(crate) async fn start_temporary_thread( request_handle: &AppServerRequestHandle, options: TemporaryStructuredThreadOptions, ) -> color_eyre::Result { let TemporaryStructuredThreadOptions { - thread_source, + kind, model, model_provider, cwd, active_permission_profile, } = options; - let custom_permission_profile = - active_permission_profile.filter(|profile| !profile.starts_with(':')); + let (source, permissions, approval_policy) = match kind { + TemporaryThreadKind::Title => ( + "thread_title", + Some(BUILT_IN_PERMISSION_PROFILE_READ_ONLY.to_string()), + Some(AskForApproval::Never), + ), + TemporaryThreadKind::Recap => ( + "system", + active_permission_profile.filter(|profile| !profile.starts_with(':')), + None, + ), + }; let mut config = std::collections::HashMap::from([ ("features.apps".to_string(), false.into()), ("features.code_mode".to_string(), false.into()), @@ -93,7 +109,7 @@ pub(crate) async fn start_temporary_thread( ("tools.update_plan.enabled".to_string(), false.into()), ("web_search".to_string(), "disabled".into()), ]); - if custom_permission_profile.is_none() { + if permissions.is_none() { // Managed profiles take precedence over the legacy sandbox override below. config.insert( "default_permissions".to_string(), @@ -116,13 +132,12 @@ pub(crate) async fn start_temporary_thread( model: Some(model), model_provider: Some(model_provider), cwd: Some(cwd), - sandbox: custom_permission_profile - .is_none() - .then_some(SandboxMode::ReadOnly), - permissions: custom_permission_profile.clone(), + approval_policy, + sandbox: permissions.is_none().then_some(SandboxMode::ReadOnly), + permissions: permissions.clone(), runtime_workspace_roots: Some(Vec::new()), ephemeral: Some(true), - thread_source: Some(thread_source), + thread_source: Some(ThreadSource::Feature(source.to_string())), environments: Some(Vec::new()), dynamic_tools: Some(Vec::new()), selected_capability_roots: Some(Vec::new()), @@ -136,7 +151,9 @@ pub(crate) async fn start_temporary_thread( .await .map_err(|_| eyre!("temporary structured thread start timed out"))??; - if let Some(expected_profile) = custom_permission_profile { + if kind == TemporaryThreadKind::Recap + && let Some(expected_profile) = permissions + { if response .active_permission_profile .as_ref() @@ -147,6 +164,7 @@ pub(crate) async fn start_temporary_thread( )); } } else if !matches!(response.sandbox, SandboxPolicy::ReadOnly { .. }) { + unsubscribe_temporary_thread(request_handle, response.thread.id).await; return Err(eyre!( "temporary structured thread did not start with read-only permissions" )); @@ -155,29 +173,28 @@ pub(crate) async fn start_temporary_thread( Ok(response) } -/// Submit a structured turn using the temporary thread's existing settings. -pub(crate) async fn start_structured_turn( - request_handle: &AppServerRequestHandle, - thread_id: String, - prompt: String, - output_schema: Value, - effort: Option, -) -> Result { - request_handle - .request_typed(ClientRequest::TurnStart { - request_id: RequestId::String(format!("temporary-structured-turn-{}", Uuid::new_v4())), - params: TurnStartParams { - thread_id, - input: vec![UserInput::Text { - text: prompt, - text_elements: Vec::new(), - }], - output_schema: Some(output_schema), - effort, - ..TurnStartParams::default() - }, - }) - .await +impl TemporaryThreadKind { + pub(crate) fn turn_params( + self, + thread_id: String, + prompt: String, + output_schema: Value, + effort: Option, + ) -> TurnStartParams { + let is_title = self == Self::Title; + TurnStartParams { + thread_id, + input: vec![UserInput::Text { + text: prompt, + text_elements: Vec::new(), + }], + permissions: is_title.then(|| BUILT_IN_PERMISSION_PROFILE_READ_ONLY.to_string()), + runtime_workspace_roots: is_title.then(Vec::new), + output_schema: Some(output_schema), + effort, + ..Default::default() + } + } } /// Return the latest assistant message when the requested turn completes. @@ -252,13 +269,11 @@ pub(crate) async fn unsubscribe_temporary_thread( /// Run a bounded structured turn, interrupt it on cancellation, and detach the temporary thread. pub(crate) async fn run_temporary_structured_turn( request_handle: AppServerRequestHandle, - thread_id: String, - prompt: String, - output_schema: Value, - effort: Option, + params: TurnStartParams, notifications: UnboundedReceiver, cancellation: CancellationToken, ) -> color_eyre::Result { + let thread_id = params.thread_id.clone(); let mut turn_id = None; let result = tokio::time::timeout(STRUCTURED_TURN_TIMEOUT, async { if cancellation.is_cancelled() { @@ -266,14 +281,15 @@ pub(crate) async fn run_temporary_structured_turn( } // Wait for turn/start to return its ID before interrupting, even if cancellation // arrives during startup. Dropping that request could leave an orphaned turn. - let turn = start_structured_turn( - &request_handle, - thread_id.clone(), - prompt, - output_schema, - effort, - ) - .await?; + let turn: TurnStartResponse = request_handle + .request_typed(ClientRequest::TurnStart { + request_id: RequestId::String(format!( + "temporary-structured-turn-{}", + Uuid::new_v4() + )), + params, + }) + .await?; turn_id = Some(turn.turn.id.clone()); tokio::select! { @@ -282,12 +298,13 @@ pub(crate) async fn run_temporary_structured_turn( result = collect_structured_response(notifications, &turn.turn.id) => result, } }) - .await - .unwrap_or_else(|_| Err(eyre!("temporary structured turn timed out"))); + .await; + let timed_out = result.is_err(); + let result = result.unwrap_or_else(|_| Err(eyre!("temporary structured turn timed out"))); // Give interruption its own deadline so cancellation near the response timeout // still gets a chance to stop the hidden turn. - if cancellation.is_cancelled() + if (timed_out || cancellation.is_cancelled()) && let Some(turn_id) = turn_id { let interrupt = diff --git a/codex-rs/tui/src/temporary_structured_request_tests.rs b/codex-rs/tui/src/temporary_structured_request_tests.rs index 1fe86cd5a5..1a71bd472a 100644 --- a/codex-rs/tui/src/temporary_structured_request_tests.rs +++ b/codex-rs/tui/src/temporary_structured_request_tests.rs @@ -1,5 +1,6 @@ use super::STRUCTURED_RESPONSE_MAX_BYTES; use super::TemporaryStructuredThreadOptions; +use super::TemporaryThreadKind; use super::collect_structured_response; use super::start_temporary_thread; use crate::legacy_core::config::ConfigBuilder; @@ -59,14 +60,40 @@ fn turn_completed_notification(turn_id: &str, status: TurnStatus) -> ServerNotif #[tokio::test] async fn managed_workspace_default_respects_read_only_availability() -> color_eyre::Result<()> { - for read_only_allowed in [true, false] { + for (kind, read_only_allowed, policies, expected_approval) in [ + ( + TemporaryThreadKind::Recap, + true, + r#""on-request""#, + AskForApproval::OnRequest, + ), + ( + TemporaryThreadKind::Recap, + false, + r#""on-request""#, + AskForApproval::OnRequest, + ), + ( + TemporaryThreadKind::Title, + true, + r#""on-request", "never""#, + AskForApproval::Never, + ), + ( + TemporaryThreadKind::Title, + true, + r#""on-request""#, + AskForApproval::OnRequest, + ), + ] { let codex_home = tempdir()?; let requirements_path = codex_home.path().join("requirements.toml"); std::fs::write( &requirements_path, format!( - "allowed_approval_policies = [\"on-request\"]\n\ + "allowed_approval_policies = [{policies}]\n\ default_permissions = \":workspace\"\n\n\ + [features]\nskill_mcp_dependency_install = true\n\n\ [allowed_permission_profiles]\n\ \":read-only\" = {read_only_allowed}\n\ \":workspace\" = true\n" @@ -84,7 +111,7 @@ async fn managed_workspace_default_respects_read_only_availability() -> color_ey .build() .await?; let options = TemporaryStructuredThreadOptions { - thread_source: ThreadSource::Feature("thread_title".to_string()), + kind, model: "gpt-5.2".to_string(), model_provider: config.model_provider_id.clone(), cwd: config.cwd.to_string_lossy().into_owned(), @@ -118,7 +145,9 @@ async fn managed_workspace_default_respects_read_only_availability() -> color_ey continue; }; match *notification { - ServerNotification::ConfigWarning(warning) => { + ServerNotification::ConfigWarning(warning) + if kind == TemporaryThreadKind::Recap => + { assert!( !warning.summary.contains("`approval_policy`"), "{warning:?}" @@ -142,7 +171,7 @@ async fn managed_workspace_default_respects_read_only_availability() -> color_ey ), ( Some(":read-only".to_string()), - AskForApproval::OnRequest, + expected_approval, SandboxPolicy::ReadOnly { network_access: false, }, @@ -187,7 +216,7 @@ async fn preserves_custom_permissions_and_disables_required_mcp_servers() -> col let response = start_temporary_thread( &app_server.request_handle(), TemporaryStructuredThreadOptions { - thread_source: ThreadSource::Feature("thread_title".to_string()), + kind: TemporaryThreadKind::Recap, model: "gpt-5.2".to_string(), model_provider: config.model_provider_id.clone(), cwd: config.cwd.display().to_string(), @@ -207,7 +236,7 @@ async fn preserves_custom_permissions_and_disables_required_mcp_servers() -> col Some("title-restricted".to_string()), config.model_provider_id, true, - Some(ThreadSource::Feature("thread_title".to_string())), + Some(ThreadSource::Feature("system".to_string())), ) ); diff --git a/codex-rs/tui/tests/suite/mod.rs b/codex-rs/tui/tests/suite/mod.rs index 5d88a0be9b..b2992f4a2e 100644 --- a/codex-rs/tui/tests/suite/mod.rs +++ b/codex-rs/tui/tests/suite/mod.rs @@ -13,6 +13,8 @@ mod resize_reflow; #[cfg(unix)] mod screen_reader; mod status_indicator; +#[cfg(unix)] +mod thread_title; mod vt100_history; mod vt100_live_commit; #[cfg(unix)] diff --git a/codex-rs/tui/tests/suite/thread_title.rs b/codex-rs/tui/tests/suite/thread_title.rs new file mode 100644 index 0000000000..d5c49be23e --- /dev/null +++ b/codex-rs/tui/tests/suite/thread_title.rs @@ -0,0 +1,91 @@ +//! Exercises automatic title generation alongside a foreground skill installation prompt. + +use super::focus_palette::PtyCodex; +use super::focus_palette::write_test_config; +use anyhow::Result; +use core_test_support::responses; +use std::io::Write; +use std::time::Duration; +use std::time::Instant; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn automatic_title_after_continue_anyway() -> Result<()> { + core_test_support::skip_if_no_network!(Ok(())); + let workspace = tempfile::tempdir()?; + let cwd = workspace.path().canonicalize()?; + let home = tempfile::tempdir()?; + write_test_config(home.path(), &cwd)?; + let skill = home.path().join("skills/ping"); + std::fs::create_dir_all(skill.join("agents"))?; + std::fs::write( + skill.join("SKILL.md"), + "---\nname: ping\ndescription: Ping a service.\n---\nCheck the service.\n", + )?; + std::fs::write( + skill.join("agents/openai.yaml"), + "dependencies: + tools: + - type: mcp + value: ping + transport: streamable_http + url: http://127.0.0.1:1/mcp +", + )?; + + let server = responses::start_mock_server().await; + responses::mount_response_handler(&server, |request| { + let (id, message) = if request.body_json()["text"]["format"]["type"] == "json_schema" { + ("title", r#"{"title":"Check service health"}"#) + } else { + ("foreground", "Foreground turn completed") + }; + responses::sse_response(responses::sse(vec![ + responses::ev_assistant_message(id, message), + responses::ev_completed(id), + ])) + }) + .await; + let mut config = std::fs::OpenOptions::new() + .append(true) + .open(home.path().join("config.toml"))?; + writeln!( + config, + "[model_providers.test] +name = 'Mock' +base_url = '{}/v1' +wire_api = 'responses' + +[tui] +status_line = ['thread-title']", + server.uri(), + )?; + let mut terminal = PtyCodex::start( + &cwd, + home, + &[ + "--no-daemon", + "-c", + "model_provider='test'", + "-c", + "approval_policy='on-request'", + "$ping the service", + ], + )?; + terminal.wait_for_screen("Continue anyway")?; + // Startup can drain pending input after it first draws the installation prompt. + let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30); + while terminal.screen_contains("1 unanswered") { + anyhow::ensure!(Instant::now() < deadline, "installation prompt stayed open"); + terminal.write_input(b"2")?; + terminal.read_output(Duration::from_millis(/*millis*/ 50))?; + } + terminal.wait_for_screen("answer: Continue anyway")?; + terminal.wait_for_screen("Foreground turn completed")?; + terminal.wait_for_screen("Check service health")?; + assert!( + !terminal.screen_contains("temporary structured threads cannot request"), + "{}", + terminal.screen_contents() + ); + Ok(()) +}