diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index d29f0cb59a..1cee518b5a 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -241,6 +241,7 @@ mod permission_shortcuts; mod pets; mod platform_actions; mod plugin_mentions; +mod prompt_suggestions; mod rate_limit_refresh; mod realtime_delivery; mod realtime_settings; @@ -645,6 +646,7 @@ pub(crate) struct App { background_voice: Option>, background_voice_error: Option<(ThreadId, String)>, temporary_structured_requests: HashMap>, + hidden_prompt_threads: VecDeque, /// 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 cf6e42e3d4..35f9ae5d79 100644 --- a/codex-rs/tui/src/app/app_server_events.rs +++ b/codex-rs/tui/src/app/app_server_events.rs @@ -119,6 +119,31 @@ impl App { app_server_client: &AppServerSession, notification: ServerNotification, ) { + if let ServerNotification::ThreadStarted(started) = ¬ification + && started.thread.ephemeral + && matches!(started.thread.thread_source.as_ref(), Some(ThreadSource::Feature(source)) if source == "prompt_suggestion") + && let Ok(id) = ThreadId::from_string(&started.thread.id) + { + self.hidden_prompt_threads.push_back(id); + if self.hidden_prompt_threads.len() > 32 { + self.hidden_prompt_threads.pop_front(); + } + return; + } + if let ServerNotificationThreadTarget::Thread(id) = + server_notification_thread_target(¬ification) + && self.hidden_prompt_threads.contains(&id) + { + if let Some(sender) = self.temporary_structured_requests.get(&id) + && matches!( + ¬ification, + ServerNotification::ItemCompleted(_) | ServerNotification::TurnCompleted(_) + ) + { + let _ = sender.send(notification); + } + return; + } // A picker can leave an old runtime's close notification queued while the same thread // is resumed. Thread IDs survive reloads, so confirm that the displayed thread is still // unloaded before routing a close that would exit the TUI or switch away from it. @@ -517,6 +542,18 @@ impl App { app_server_client: &AppServerSession, request: ServerRequest, ) { + if server_request_thread_id(&request) + .is_some_and(|id| self.hidden_prompt_threads.contains(&id)) + { + let _ = self + .reject_app_server_request( + app_server_client, + request.id().clone(), + "Prompt suggestions cannot request user interaction".to_string(), + ) + .await; + return; + } if let ServerRequest::DynamicToolCall { request_id, params } = &request { if self.dynamic_tool_tasks.contains_key(request_id) || (params.namespace.as_deref() != Some(crate::dynamic_tools::NAMESPACE) diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs index d04b74576d..ad7675361d 100644 --- a/codex-rs/tui/src/app/config_persistence.rs +++ b/codex-rs/tui/src/app/config_persistence.rs @@ -418,6 +418,11 @@ impl App { .tui .terminal_resize_reflow_max_rows = self.local_settings.tui.terminal_resize_reflow_max_rows; + self.chat_widget.local_settings.tui.prompt_suggestions = + self.local_settings.tui.prompt_suggestions; + if !self.local_settings.tui.prompt_suggestions { + self.chat_widget.clear_prompt_suggestion(); + } self.config = config; self.chat_widget.sync_plugin_mentions_config(&self.config); Ok(()) diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 3fa573ca10..fe693a6ab8 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -48,6 +48,8 @@ impl App { | AppEvent::CommitRealtimeTranscriptHistory | AppEvent::ResetTranscriptForThreadSwitch | AppEvent::FinishPromptRevert { .. } + | AppEvent::PromptSuggestionStarted { .. } + | AppEvent::PromptSuggestionFinished { .. } | AppEvent::ManagedWorktreeCreated(_) | AppEvent::AgentsOverviewWorktreeCreated(_) | AppEvent::AppendMessageHistoryEntry { .. } @@ -2633,6 +2635,19 @@ impl App { self.suggest_thread_name(app_server, thread_id, request_id) .await; } + AppEvent::GeneratePromptSuggestion(request) => { + self.generate_prompt_suggestion(app_server, request); + } + AppEvent::PromptSuggestionStarted { request, result } => { + self.on_prompt_suggestion_started(app_server, request, result); + } + AppEvent::PromptSuggestionFinished { request, temporary_thread_id, text } => { + self.temporary_structured_requests.remove(&temporary_thread_id); + if text.is_none() { + request.cancellation.cancel(); + } + self.chat_widget.apply_prompt_suggestion(&request, text); + } AppEvent::ThreadTitleStarted { cancellation, thread_id, diff --git a/codex-rs/tui/src/app/input.rs b/codex-rs/tui/src/app/input.rs index 3bf3754f23..a440ef07b0 100644 --- a/codex-rs/tui/src/app/input.rs +++ b/codex-rs/tui/src/app/input.rs @@ -719,6 +719,7 @@ impl App { pub(crate) fn should_handle_backtrack_esc(&self, key_event: KeyEvent) -> bool { !self.chat_widget.is_external_writer_view() + && !self.chat_widget.has_prompt_suggestion() && !self.chat_widget.side_conversation_active() && !self.chat_widget.shortcut_overlay_visible() && self.chat_widget.is_normal_backtrack_mode() diff --git a/codex-rs/tui/src/app/prompt_suggestions.rs b/codex-rs/tui/src/app/prompt_suggestions.rs new file mode 100644 index 0000000000..40f6d4883f --- /dev/null +++ b/codex-rs/tui/src/app/prompt_suggestions.rs @@ -0,0 +1,195 @@ +//! Hidden fork requests. The composer owns request identity and cancellation, including +//! Escape during startup. A deadline cancels the result without dropping an in-flight fork. +use super::*; +use crate::prompt_suggestions::SuggestionRequest; +use crate::temporary_structured_request::collect_structured_response; +use crate::temporary_structured_request::unsubscribe_temporary_thread; +use codex_app_server_protocol::ClientRequest; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ThreadForkParams; +use codex_app_server_protocol::ThreadForkResponse; +use codex_app_server_protocol::ThreadResumeParams; +use codex_app_server_protocol::ThreadResumeResponse; +use codex_app_server_protocol::ThreadSource; +use codex_app_server_protocol::TurnInterruptParams; +use codex_app_server_protocol::TurnInterruptResponse; +use codex_app_server_protocol::TurnStartParams; +use codex_app_server_protocol::TurnStartResponse; +use codex_app_server_protocol::UserInput; +use codex_context_fragments::AdditionalContextUserFragment; +use codex_context_fragments::ContextualUserFragment; +use codex_protocol::config_types::CollaborationMode; +use color_eyre::eyre::eyre; + +const SUGGESTION_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30); + +impl App { + pub(super) fn generate_prompt_suggestion( + &mut self, + app_server: &AppServerSession, + request: SuggestionRequest, + ) { + if !self.local_settings.tui.prompt_suggestions + || request.cancellation.is_cancelled() + || self.chat_widget.thread_id() != Some(request.thread_id) + { + request.cancellation.cancel(); + return; + } + let cancellation = request.cancellation.clone(); + let finished = request.generation_finished.clone(); + tokio::spawn(async move { + tokio::select! { + _ = cancellation.cancelled() => {}, + _ = finished.cancelled() => {}, + _ = tokio::time::sleep(SUGGESTION_TIMEOUT) => cancellation.cancel(), + } + }); + let handle = app_server.request_handle(); + let events = self.app_event_tx.clone(); + tokio::spawn(async move { + // Await startup even after cancellation so the returned fork can be detached. + // Fork reloads config files; only exposed live settings can be preserved here. + let mut result = async { + let parent: ThreadResumeResponse = handle + .request_typed(ClientRequest::ThreadResume { + request_id: RequestId::String(format!("suggestion-resume-{}", request.id)), + params: ThreadResumeParams { + thread_id: request.thread_id.to_string(), + exclude_turns: true, + ..Default::default() + }, + }) + .await?; + if request.cancellation.is_cancelled() { + return Err(eyre!("suggestion cancelled")); + } + let mut config = std::collections::HashMap::from([( + "model_reasoning_summary".to_string(), + serde_json::to_value(request.summary)?, + )]); + if let Some(effort) = parent.reasoning_effort { + config.insert( + "model_reasoning_effort".to_string(), + serde_json::to_value(effort)?, + ); + } + let fork: ThreadForkResponse = handle + .request_typed(ClientRequest::ThreadFork { + request_id: RequestId::String(format!("suggestion-fork-{}", request.id)), + params: ThreadForkParams { + thread_id: request.thread_id.to_string(), + last_turn_id: Some(request.turn_id.clone()), + model: Some(parent.model), + model_provider: Some(parent.model_provider), + service_tier: Some(parent.service_tier), + runtime_workspace_roots: Some(parent.runtime_workspace_roots), + config: Some(config), + ephemeral: true, + exclude_turns: true, + thread_source: Some(ThreadSource::Feature( + "prompt_suggestion".to_string(), + )), + ..Default::default() + }, + }) + .await?; + color_eyre::eyre::Ok((fork.thread.id, parent.collaboration_mode)) + } + .await + .map_err(|error| error.to_string()); + if request.cancellation.is_cancelled() { + if let Ok((thread_id, _)) = result { + unsubscribe_temporary_thread(&handle, thread_id).await; + } + result = Err("suggestion cancelled".to_string()); + } + events.send(AppEvent::PromptSuggestionStarted { request, result }); + }); + } + + pub(super) fn on_prompt_suggestion_started( + &mut self, + app_server: &AppServerSession, + request: SuggestionRequest, + result: Result<(String, Option), String>, + ) { + let Ok((thread_id, collaboration_mode)) = result else { + request.generation_finished.cancel(); + request.cancellation.cancel(); + return; + }; + let handle = app_server.request_handle(); + let Ok(temporary_thread_id) = ThreadId::from_string(&thread_id) else { + request.generation_finished.cancel(); + request.cancellation.cancel(); + tokio::spawn(async move { + unsubscribe_temporary_thread(&handle, thread_id).await; + }); + return; + }; + let (sender, receiver) = mpsc::unbounded_channel(); + self.temporary_structured_requests + .insert(temporary_thread_id, sender); + let events = self.app_event_tx.clone(); + tokio::spawn(async move { + // Retain the inherited tools and settings. Await the turn ID before interrupting. + let mut turn_id = None; + let result = async { + if request.cancellation.is_cancelled() { + return Err(eyre!("suggestion cancelled")); + } + let response: TurnStartResponse = handle.request_typed(ClientRequest::TurnStart { + request_id: RequestId::String(format!("suggestion-turn-{}", Uuid::new_v4())), + params: TurnStartParams { + thread_id: thread_id.clone(), + collaboration_mode, + input: vec![UserInput::Text { + text: AdditionalContextUserFragment::new("prompt_suggestion".to_string(), format!("{}\n\nReturn only JSON matching this schema: {{\"type\":\"object\",\"properties\":{{\"suggestion\":{{\"type\":[\"string\",\"null\"]}}}},\"required\":[\"suggestion\"],\"additionalProperties\":false}}.", crate::prompt_suggestions::PROMPT)).render(), + text_elements: Vec::new(), + }], + ..Default::default() + }, + }).await?; + turn_id = Some(response.turn.id.clone()); + tokio::select! { + biased; + _ = request.cancellation.cancelled() => Err(eyre!("suggestion cancelled or timed out")), + result = collect_structured_response(receiver, &response.turn.id) => result, + } + }.await; + if result.is_err() + && let Some(turn_id) = turn_id + { + let _ = tokio::time::timeout( + SUGGESTION_TIMEOUT, + handle.request_typed::(ClientRequest::TurnInterrupt { + request_id: RequestId::String(format!( + "suggestion-interrupt-{}", + Uuid::new_v4() + )), + params: TurnInterruptParams { + thread_id: thread_id.clone(), + turn_id, + }, + }), + ) + .await; + } + unsubscribe_temporary_thread(&handle, thread_id).await; + let text = result + .ok() + .and_then(|text| crate::prompt_suggestions::parse_suggestion(&text)); + request.generation_finished.cancel(); + events.send(AppEvent::PromptSuggestionFinished { + request, + temporary_thread_id, + text, + }); + }); + } +} + +#[cfg(test)] +#[path = "prompt_suggestions_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/app/prompt_suggestions_tests.rs b/codex-rs/tui/src/app/prompt_suggestions_tests.rs new file mode 100644 index 0000000000..194f9c15c5 --- /dev/null +++ b/codex-rs/tui/src/app/prompt_suggestions_tests.rs @@ -0,0 +1,241 @@ +//! Tests hidden suggestion forks through the app-server API. + +use super::*; +use crate::app::session_lifecycle::ThreadAttachPresentation; +use crate::app::test_support::make_test_app; +use crate::app_event_sender::AppEventSender; +use codex_app_server_client::AppServerEvent; +use codex_app_server_protocol::ClientRequest; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ServerNotification; +use codex_app_server_protocol::TurnStartParams; +use codex_app_server_protocol::TurnStartResponse; +use codex_app_server_protocol::UserInput; +use core_test_support::context_snapshot; +use core_test_support::context_snapshot::ContextSnapshotOptions; +use core_test_support::responses; +use pretty_assertions::assert_eq; +use tempfile::tempdir; +use tokio::sync::mpsc::unbounded_channel; + +#[derive(Clone, Copy, PartialEq)] +enum Scenario { + Success, + UnchangedSettings, + CancelStartup, + Timeout, +} + +#[tokio::test] +async fn prompt_suggestion_fork_preserves_request_prefix_and_stays_hidden() -> color_eyre::Result<()> +{ + check_suggestion(Scenario::UnchangedSettings).await?; + check_suggestion(Scenario::Success).await +} + +#[tokio::test] +async fn prompt_suggestion_cancelled_startup_cleans_up_without_a_turn() -> color_eyre::Result<()> { + check_suggestion(Scenario::CancelStartup).await +} + +#[tokio::test] +async fn prompt_suggestion_timeout_interrupts_and_cleans_up() -> color_eyre::Result<()> { + check_suggestion(Scenario::Timeout).await +} + +async fn check_suggestion(scenario: Scenario) -> color_eyre::Result<()> { + let server = wiremock::MockServer::start().await; + let parent_response = responses::mount_sse_once( + &server, + responses::sse(vec![ + responses::ev_response_created("parent"), + responses::ev_assistant_message("answer", "Fixed the timeout."), + responses::ev_completed("parent"), + ]), + ) + .await; + let codex_home = tempdir()?; + let provider_id = "suggestion-test"; + std::fs::write( + codex_home.path().join("config.toml"), + format!( + "model = \"gpt-5.2\"\n\ + model_provider = \"{provider_id}\"\n\n\ + [model_providers.{provider_id}]\n\ + name = \"Suggestion test\"\n\ + base_url = \"{}/v1\"\n\ + wire_api = \"responses\"\n\ + request_max_retries = 0\n\ + stream_max_retries = 0\n", + server.uri() + ), + )?; + + let mut app = make_test_app().await; + let (event_tx, mut event_rx) = unbounded_channel(); + app.local_settings.tui.animations = false; + app.local_settings.tui.prompt_suggestions = true; + app.app_event_tx = AppEventSender::new(event_tx); + app.config = ConfigBuilder::default() + .loader_overrides(LoaderOverrides::without_managed_config_for_tests()) + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(dunce::canonicalize(codex_home.path())?)) + .build() + .await?; + + let mut tui = crate::tui::test_support::make_test_tui()?; + 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.replace_chat_widget_with_app_server_thread( + &mut tui, + started, + ThreadAttachPresentation::SessionLineage, + /*initial_user_message*/ None, + ) + .await?; + + app_server + .thread_set_name(thread_id, "Timeout fix".into()) + .await?; + app.chat_widget + .on_thread_name_updated(thread_id, Some("Timeout fix".into())); + while event_rx.try_recv().is_ok() {} + let _: TurnStartResponse = app_server + .request_handle() + .request_typed(ClientRequest::TurnStart { + request_id: RequestId::String("parent-turn".into()), + params: TurnStartParams { + thread_id: thread_id.to_string(), + service_tier: (scenario == Scenario::Success).then(|| Some("priority".into())), + collaboration_mode: (scenario == Scenario::Success).then(|| { + codex_protocol::config_types::CollaborationMode { + mode: codex_protocol::config_types::ModeKind::Default, + settings: codex_protocol::config_types::Settings { + model: "gpt-5.2".into(), + reasoning_effort: Some( + codex_protocol::openai_models::ReasoningEffort::High, + ), + developer_instructions: Some("Keep requests concise.".into()), + }, + } + }), + input: vec![UserInput::Text { + text: "Fix the timeout".into(), + text_elements: vec![], + }], + ..Default::default() + }, + }) + .await?; + let mut fork_response = None; + let mut hidden_id = None; + let mut interrupted = false; + tokio::time::timeout(Duration::from_secs(/*secs*/ 45), async { + loop { + tokio::select! { + Some(event) = event_rx.recv() => { + if matches!(&event, AppEvent::GeneratePromptSuggestion(_)) { + let mut response = responses::sse_response(responses::sse(vec![ + responses::ev_response_created("prediction"), + responses::ev_assistant_message("suggestion", r#"{"suggestion":"Add a regression test"}"#), + responses::ev_completed("prediction"), + ])); + if scenario == Scenario::Timeout { response = response.set_delay(Duration::from_secs(/*secs*/ 60)); } + fork_response = Some(responses::mount_response_once(&server, response).await); + } + if let AppEvent::PromptSuggestionStarted { result, request } = &event { + result.as_ref().expect("fork startup"); + if scenario == Scenario::CancelStartup { request.cancellation.cancel(); } + } + if let AppEvent::PromptSuggestionFinished { temporary_thread_id, .. } = &event { + hidden_id = Some(*temporary_thread_id); + } + app.handle_event(&mut tui, &mut app_server, event).await?; + + } + Some(event) = app_server.next_event() => { + if let AppServerEvent::ServerNotification(notification) = &event { + if let ServerNotification::TurnCompleted(completed) = notification.as_ref() + && completed.thread_id != thread_id.to_string() + { interrupted = completed.turn.status == codex_app_server_protocol::TurnStatus::Interrupted; } + if let ServerNotification::TurnStarted(started) = notification.as_ref() + && started.thread_id != thread_id.to_string() && scenario == Scenario::Timeout + { + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(/*secs*/ 31)).await; + tokio::time::resume(); + } + } + app.handle_app_server_event(&app_server, event).await; + app.drain_active_thread_events_until(&mut tui, Instant::now() + Duration::from_secs(/*secs*/ 1)).await?; + } + } + if hidden_id.is_some() && (scenario != Scenario::Timeout || interrupted) { break; } + } + color_eyre::eyre::Ok(()) + }).await??; + let hidden_id = hidden_id.expect("hidden fork"); + assert!(!app.thread_event_channels.contains_key(&hidden_id)); + assert!(app.temporary_structured_requests.is_empty()); + let detached: codex_app_server_protocol::ThreadUnsubscribeResponse = app_server + .request_handle() + .request_typed(ClientRequest::ThreadUnsubscribe { + request_id: RequestId::String("verify-cleanup".into()), + params: codex_app_server_protocol::ThreadUnsubscribeParams { + thread_id: hidden_id.to_string(), + }, + }) + .await?; + assert!(matches!( + detached.status, + codex_app_server_protocol::ThreadUnsubscribeStatus::NotSubscribed + | codex_app_server_protocol::ThreadUnsubscribeStatus::NotLoaded + )); + if matches!(scenario, Scenario::CancelStartup | Scenario::Timeout) { + if scenario == Scenario::CancelStartup { + assert!(fork_response.as_ref().unwrap().requests().is_empty()); + } + assert!(!app.chat_widget.has_prompt_suggestion()); + return Ok(()); + } + let requests = [ + parent_response.single_request(), + fork_response + .expect("generation requested") + .single_request(), + ]; + if scenario == Scenario::Success { + insta::assert_snapshot!( + "prompt_suggestion_request_history", + context_snapshot::format_request_history_snapshot( + "A completed turn is forked for a hidden follow-up suggestion with the parent's request prefix intact.", + &requests, + &ContextSnapshotOptions::default().rewrite_known_segments(), + ) + ); + } + let parent = requests[0].body_json(); + let fork = requests[1].body_json(); + for field in [ + "model", + "instructions", + "tools", + "reasoning", + "service_tier", + "text", + "prompt_cache_key", + "stream_options", + ] { + assert_eq!(&fork[field], &parent[field], "{field}"); + } + let parent_input = parent["input"].as_array().expect("parent input"); + let fork_input = fork["input"].as_array().expect("fork input"); + assert_eq!(&fork_input[..parent_input.len()], parent_input.as_slice()); + assert!(app.chat_widget.composer_is_empty()); + assert!( + crate::chatwidget::tests::helpers::render_bottom_popup(&app.chat_widget, /*width*/ 80) + .contains("Add a regression test") + ); + Ok(()) +} diff --git a/codex-rs/tui/src/app/reconnect.rs b/codex-rs/tui/src/app/reconnect.rs index 01cc928474..ab6c32aff0 100644 --- a/codex-rs/tui/src/app/reconnect.rs +++ b/codex-rs/tui/src/app/reconnect.rs @@ -175,6 +175,7 @@ impl App { } pub(super) fn begin_reconnect(&mut self) -> bool { + self.chat_widget.clear_prompt_suggestion(); if matches!(self.app_server_target, AppServerTarget::Embedded) { return false; } diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 44017d43ac..fad3e284f1 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -490,6 +490,7 @@ impl App { /// This helper copies every known nickname/role from `AgentNavigationState` into the /// replacement widget so that replayed collab items render agent names immediately. pub(super) fn replace_chat_widget(&mut self, mut chat_widget: ChatWidget) { + self.chat_widget.clear_prompt_suggestion(); if !self.chat_widget.realtime_conversation_is_running() { self.retain_realtime_replay_state_before_replace(); } @@ -869,6 +870,7 @@ impl App { .set_queue_submissions_until_session_configured(/*queue*/ false); match result { Ok(started) => { + self.chat_widget.prompt_suggestion_summary = started.reasoning_summary; self.chat_widget.mark_fresh_task_for_sparkle(&started); let thread_id = started.session.thread_id; if started.task_tools_available { @@ -1100,6 +1102,7 @@ impl App { initial_user_message, ); self.replace_chat_widget(ChatWidget::new_with_app_event(init)); + self.chat_widget.prompt_suggestion_summary = started.reasoning_summary; if matches!(presentation, ThreadAttachPresentation::Fresh) { self.chat_widget.mark_fresh_task_for_sparkle(&started); self.chat_widget diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__prompt_suggestions__tests__prompt_suggestion_request_history.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__prompt_suggestions__tests__prompt_suggestion_request_history.snap new file mode 100644 index 0000000000..56079d5be7 --- /dev/null +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__prompt_suggestions__tests__prompt_suggestion_request_history.snap @@ -0,0 +1,27 @@ +--- +source: tui/src/app/prompt_suggestions_tests.rs +expression: "context_snapshot::format_request_history_snapshot(\"A completed turn is forked for a hidden follow-up suggestion with the parent's request prefix intact.\",\n&requests, &ContextSnapshotOptions::default().rewrite_known_segments(),)" +--- +Scenario: A completed turn is forked for a hidden follow-up suggestion with the parent's request prefix intact. + +## Window 1 +-- request 1 (turn) -- +00:message/developer[3]: + [01] + [02] + [03] +01:message/user: + +02:message/user: + Fix the timeout +-- request 2 (turn) -- +03:message/assistant: + Fixed the timeout. +04:message/user: + This is an app-generated request for a suggested next user message. The user did not write this message. + + Your suggestion will appear in the user's empty message composer. They can accept it, edit it, or ignore it; it will not be sent automatically. + + Predict this user's next message from the whole conversation. Before choosing a new content question, co...e null only if every concrete next move is arbitrary. [hash=08478ce37447c028] + + Return only JSON matching this schema: {"type":"object","properties":{"suggestion":{"type":["string","nu...ionalProperties":false}. [hash=18d5da5f1ee1d605] diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index d17ace0869..9ff5f6ad62 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -808,6 +808,7 @@ See the Codex keymap documentation for supported actions and examples." background_voice: None, background_voice_error: None, temporary_structured_requests: HashMap::new(), + hidden_prompt_threads: VecDeque::new(), pending_thread_titles: HashMap::new(), thread_event_listener_tasks: HashMap::new(), agent_navigation: AgentNavigationState::default(), @@ -870,6 +871,7 @@ See the Codex keymap documentation for supported actions and examples." app.update_visible_history_rows(tui.terminal.last_known_screen_size); let initial_session_started_at = Instant::now(); if let Some(started) = initial_started_thread { + app.chat_widget.prompt_suggestion_summary = started.reasoning_summary; let thread_id = started.session.thread_id; app.chat_widget .set_task_mentions_enabled(started.task_tools_available); diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index 5bab28c833..c5c714e369 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -90,6 +90,7 @@ pub(crate) async fn make_test_app() -> App { background_voice: None, background_voice_error: None, temporary_structured_requests: HashMap::new(), + hidden_prompt_threads: VecDeque::new(), pending_thread_titles: HashMap::new(), thread_event_listener_tasks: HashMap::new(), agent_navigation: AgentNavigationState::default(), diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 0c0587001b..3fd815daeb 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -630,6 +630,7 @@ async fn enqueue_primary_thread_session_replays_buffered_approval_after_attach() turns: Vec::new(), blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }, session_lifecycle::ThreadAttachPresentation::SessionLineage, /*initial_user_message*/ None, @@ -5312,6 +5313,7 @@ async fn primary_thread_ignores_child_mcp_startup_notifications() { turns: Vec::new(), blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }, &mut child_snapshot, ) @@ -6048,6 +6050,7 @@ async fn make_test_app() -> Box { background_voice: None, background_voice_error: None, temporary_structured_requests: HashMap::new(), + hidden_prompt_threads: VecDeque::new(), pending_thread_titles: HashMap::new(), thread_event_listener_tasks: HashMap::new(), agent_navigation: AgentNavigationState::default(), @@ -6156,6 +6159,7 @@ pub(super) async fn make_test_app_with_channels() -> ( background_voice: None, background_voice_error: None, temporary_structured_requests: HashMap::new(), + hidden_prompt_threads: VecDeque::new(), pending_thread_titles: HashMap::new(), thread_event_listener_tasks: HashMap::new(), agent_navigation: AgentNavigationState::default(), @@ -6484,6 +6488,7 @@ async fn app_server_thread_replacement_clears_previous_transcript_before_replay( )], blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }, session_lifecycle::ThreadAttachPresentation::SessionLineage, /*initial_user_message*/ None, @@ -8850,6 +8855,7 @@ async fn refreshed_snapshot_session_persists_resumed_turns() { turns: resumed_turns.clone(), blocks_direct_input: true, task_tools_available: false, + reasoning_summary: None, }, &mut snapshot, ) diff --git a/codex-rs/tui/src/app/tests/buffered_replay.rs b/codex-rs/tui/src/app/tests/buffered_replay.rs index 708efcacb6..a9aeed4df2 100644 --- a/codex-rs/tui/src/app/tests/buffered_replay.rs +++ b/codex-rs/tui/src/app/tests/buffered_replay.rs @@ -103,6 +103,7 @@ async fn refreshed_active_reasoning_accepts_later_deltas_and_complete_summary() turns: vec![turn], blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }, &mut snapshot, ) diff --git a/codex-rs/tui/src/app/tests/fresh_sparkle_tests.rs b/codex-rs/tui/src/app/tests/fresh_sparkle_tests.rs index 714e9bd22b..745d538412 100644 --- a/codex-rs/tui/src/app/tests/fresh_sparkle_tests.rs +++ b/codex-rs/tui/src/app/tests/fresh_sparkle_tests.rs @@ -16,6 +16,7 @@ fn started(model: &str) -> AppServerStartedThread { turns: Vec::new(), blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, } } diff --git a/codex-rs/tui/src/app/tests/startup.rs b/codex-rs/tui/src/app/tests/startup.rs index c5f43238be..33c1204e93 100644 --- a/codex-rs/tui/src/app/tests/startup.rs +++ b/codex-rs/tui/src/app/tests/startup.rs @@ -921,6 +921,7 @@ async fn fresh_startup_thread_drains_buffered_approval_before_draft_handoff() -> turns: Vec::new(), blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }), }, )) @@ -1136,6 +1137,7 @@ async fn startup_thread_started_submits_queued_startup_input() { turns: Vec::new(), blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }), ) .await @@ -1174,6 +1176,7 @@ async fn fresh_startup_notice_follows_session_attachment() { turns: Vec::new(), blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }), ) .await @@ -1333,6 +1336,7 @@ async fn startup_thread_started_discards_another_threads_buffered_events() { turns: Vec::new(), blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }), ) .await @@ -1382,6 +1386,7 @@ async fn startup_thread_started_does_not_replay_resolved_approval() -> Result<() turns: Vec::new(), blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }), ) .await?; @@ -1524,6 +1529,7 @@ fn stale_startup_thread_started_removes_local_routing_state() -> Result<()> { turns: Vec::new(), blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }), ) .await?; diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index 4e63f0caef..cc2c5513eb 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -122,6 +122,7 @@ impl App { /// Revert the current thread before the selected prompt. pub(crate) fn apply_backtrack_selection(&mut self, selection: BacktrackSelection) { + self.chat_widget.clear_prompt_suggestion(); if self.chat_widget.side_conversation_active() { self.reset_backtrack_state(); self.chat_widget diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index f6661a8a62..a7e383bdae 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -61,6 +61,7 @@ use codex_app_server_protocol::AskForApproval; use codex_config::types::ApprovalsReviewer; use codex_features::Feature; use codex_plugin::PluginCapabilitySummary; +use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::models::ActivePermissionProfile; use codex_realtime_webrtc::StartedRealtimeWebrtcSession; @@ -313,6 +314,17 @@ pub(crate) enum AppEvent { thread_id: ThreadId, request_id: Uuid, }, + /// Generate a next-message suggestion for one live completed turn. + GeneratePromptSuggestion(crate::prompt_suggestions::SuggestionRequest), + PromptSuggestionStarted { + request: crate::prompt_suggestions::SuggestionRequest, + result: Result<(String, Option), String>, + }, + PromptSuggestionFinished { + request: crate::prompt_suggestions::SuggestionRequest, + temporary_thread_id: ThreadId, + text: Option, + }, /// Register a hidden title-generation thread started in the background. ThreadTitleStarted { cancellation: CancellationToken, diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 322cdb2445..13b4ed0a11 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -364,6 +364,7 @@ impl ThreadParamsMode { #[derive(Debug, Clone)] pub(crate) struct AppServerStartedThread { + pub(crate) reasoning_summary: Option, pub(crate) session: ThreadSessionState, pub(crate) turns: Vec, pub(crate) blocks_direct_input: bool, @@ -2201,6 +2202,14 @@ async fn started_thread_from_start_response( turns: response.thread.turns, blocks_direct_input, task_tools_available: false, + reasoning_summary: match thread_params_mode { + ThreadParamsMode::Embedded => Some( + config + .model_reasoning_summary + .unwrap_or(codex_protocol::config_types::ReasoningSummary::None), + ), + ThreadParamsMode::Remote => config.model_reasoning_summary, + }, }) } @@ -2224,6 +2233,7 @@ async fn started_thread_from_resume_response( turns: response.thread.turns, blocks_direct_input, task_tools_available: false, + reasoning_summary: None, }) } @@ -2247,6 +2257,7 @@ async fn started_thread_from_fork_response( turns: response.thread.turns, blocks_direct_input, task_tools_available: false, + reasoning_summary: None, }) } diff --git a/codex-rs/tui/src/app_server_session/rollout_history.rs b/codex-rs/tui/src/app_server_session/rollout_history.rs index 5a86ee0260..ff984cb219 100644 --- a/codex-rs/tui/src/app_server_session/rollout_history.rs +++ b/codex-rs/tui/src/app_server_session/rollout_history.rs @@ -103,6 +103,7 @@ impl AppServerSession { turns: thread.turns, blocks_direct_input: false, task_tools_available: false, + reasoning_summary: None, }, history_notice, )) diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/prompt_suggestions.rs b/codex-rs/tui/src/bottom_pane/chat_composer/prompt_suggestions.rs index d07cfbe084..034f4e3c90 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/prompt_suggestions.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/prompt_suggestions.rs @@ -7,10 +7,6 @@ use crate::prompt_suggestions::PromptSuggestion; use crate::prompt_suggestions::SuggestionRequest; impl ChatComposer { - #[cfg_attr( - not(test), - expect(dead_code, reason = "Connected by the next PR in this stack.") - )] pub(crate) fn set_prompt_suggestion(&mut self, request: SuggestionRequest) { self.prompt_suggestion = Some(PromptSuggestion { request, @@ -28,10 +24,6 @@ impl ChatComposer { self.prompt_suggestion = None; } - #[cfg_attr( - not(test), - expect(dead_code, reason = "Connected by the next PR in this stack.") - )] pub(crate) fn apply_prompt_suggestion( &mut self, request: &SuggestionRequest, diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 0e6b006f4f..883e2f559f 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -1273,6 +1273,30 @@ impl BottomPane { // esc_backtrack_hint_visible removed; hints are controlled internally. + pub(crate) fn set_prompt_suggestion( + &mut self, + request: crate::prompt_suggestions::SuggestionRequest, + ) { + self.composer.set_prompt_suggestion(request); + } + + pub(crate) fn has_prompt_suggestion(&self) -> bool { + self.composer.has_prompt_suggestion() + } + + pub(crate) fn clear_prompt_suggestion(&mut self) { + self.composer.clear_prompt_suggestion(); + } + + pub(crate) fn apply_prompt_suggestion( + &mut self, + request: &crate::prompt_suggestions::SuggestionRequest, + text: Option, + ) { + self.composer.apply_prompt_suggestion(request, text); + self.request_redraw(); + } + pub fn set_task_running(&mut self, running: bool) { let was_running = self.is_task_running; self.is_task_running = running; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 5ca4182939..79db6b69bf 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -288,6 +288,7 @@ mod input_flow; mod input_restore; mod input_submission; mod interrupts; +mod prompt_suggestions; mod questions; mod startup_submission; use self::interrupts::InterruptManager; @@ -657,6 +658,8 @@ pub(crate) struct ChatWidget { pet_image_support_override: Option, thread_id: Option, thread_name: Option, + // Unknown until the server supplies live settings; resume responses omit summary. + pub(crate) prompt_suggestion_summary: Option, thread_rename_block_message: Option, active_side_conversation: bool, blocks_direct_input: bool, @@ -1775,6 +1778,7 @@ impl ChatWidget { } pub(crate) fn show_external_writer_thread(&mut self) { + self.clear_prompt_suggestion(); self.cancel_image_submission(); self.blocks_direct_input = true; self.external_writer_view = true; diff --git a/codex-rs/tui/src/chatwidget/constructor.rs b/codex-rs/tui/src/chatwidget/constructor.rs index f769908be2..aee46661dc 100644 --- a/codex-rs/tui/src/chatwidget/constructor.rs +++ b/codex-rs/tui/src/chatwidget/constructor.rs @@ -220,6 +220,7 @@ impl ChatWidget { pet_image_support_override: None, thread_id: None, thread_name: None, + prompt_suggestion_summary: None, thread_rename_block_message: None, active_side_conversation: false, blocks_direct_input: false, diff --git a/codex-rs/tui/src/chatwidget/input_flow.rs b/codex-rs/tui/src/chatwidget/input_flow.rs index a6b5cdd9a5..b22d4088fa 100644 --- a/codex-rs/tui/src/chatwidget/input_flow.rs +++ b/codex-rs/tui/src/chatwidget/input_flow.rs @@ -23,6 +23,9 @@ impl ChatWidget { input_result: InputResult, had_modal_or_popup: bool, ) { + if !matches!(input_result, InputResult::None) { + self.clear_prompt_suggestion(); + } let follow_transcript = match &input_result { // Opening settings is not a request to leave the current reading anchor. // Inline commands still follow so their output (including usage errors) is visible. diff --git a/codex-rs/tui/src/chatwidget/input_submission.rs b/codex-rs/tui/src/chatwidget/input_submission.rs index a37e938cdd..6a8dfe92e4 100644 --- a/codex-rs/tui/src/chatwidget/input_submission.rs +++ b/codex-rs/tui/src/chatwidget/input_submission.rs @@ -76,6 +76,7 @@ impl ChatWidget { } pub(super) fn submit_user_message(&mut self, user_message: UserMessage) { + self.clear_prompt_suggestion(); let _accepted = self.submit_user_message_with_history_record( user_message, UserMessageHistoryRecord::UserMessageText, diff --git a/codex-rs/tui/src/chatwidget/prompt_suggestions.rs b/codex-rs/tui/src/chatwidget/prompt_suggestions.rs new file mode 100644 index 0000000000..ed1e2c3c12 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/prompt_suggestions.rs @@ -0,0 +1,60 @@ +//! Suggests after successful live turns with known settings. The composer owns cancellation; +//! request identity prevents late results from replacing a newer suggestion. + +use super::*; +use crate::prompt_suggestions::SuggestionRequest; +use tokio_util::sync::CancellationToken; + +impl ChatWidget { + pub(crate) fn has_prompt_suggestion(&self) -> bool { + self.bottom_pane.has_prompt_suggestion() + } + + pub(crate) fn clear_prompt_suggestion(&mut self) { + self.bottom_pane.clear_prompt_suggestion(); + } + + pub(super) fn suggest_next_prompt(&mut self, turn_id: String) { + if !self.local_settings.tui.prompt_suggestions + || self.is_user_turn_pending_or_running() + || self.external_writer_view + || self.blocks_direct_input + || self.side_conversation_active() + || self.has_queued_follow_up_messages() + { + return; + } + let Some(thread_id) = self.thread_id() else { + return; + }; + let Some(summary) = self.prompt_suggestion_summary else { + return; + }; + let request = SuggestionRequest { + thread_id, + turn_id, + summary, + id: uuid::Uuid::new_v4(), + cancellation: CancellationToken::new(), + generation_finished: CancellationToken::new(), + }; + self.bottom_pane.set_prompt_suggestion(request.clone()); + self.app_event_tx + .send(AppEvent::GeneratePromptSuggestion(request)); + } + + pub(crate) fn apply_prompt_suggestion( + &mut self, + request: &SuggestionRequest, + text: Option, + ) { + if self.thread_id() == Some(request.thread_id) && self.local_settings.tui.prompt_suggestions + { + self.bottom_pane.apply_prompt_suggestion(request, text); + } + } +} + +#[cfg(test)] +#[path = "prompt_suggestions_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/chatwidget/prompt_suggestions_tests.rs b/codex-rs/tui/src/chatwidget/prompt_suggestions_tests.rs new file mode 100644 index 0000000000..e1686d308a --- /dev/null +++ b/codex-rs/tui/src/chatwidget/prompt_suggestions_tests.rs @@ -0,0 +1,59 @@ +//! Tests follow-up suggestion eligibility and deduplication. + +use super::*; +use codex_app_server_protocol::Turn; +use codex_app_server_protocol::TurnStartedNotification; +use pretty_assertions::assert_eq; + +#[tokio::test] +async fn prompt_suggestion_only_follows_enabled_successful_live_turns() { + for (enabled, status, replay, expected) in [ + (false, TurnStatus::Completed, None, 0), + (true, TurnStatus::Failed, None, 0), + (true, TurnStatus::Interrupted, None, 0), + ( + true, + TurnStatus::Completed, + Some(ReplayKind::ResumeInitialMessages), + 0, + ), + (true, TurnStatus::Completed, None, 1), + ] { + let (mut chat, _, mut events, _) = + super::super::tests::helpers::make_chatwidget_manual_with_sender().await; + let thread_id = ThreadId::new(); + chat.thread_id = Some(thread_id); + chat.local_settings.tui.prompt_suggestions = enabled; + chat.prompt_suggestion_summary = Some(codex_protocol::config_types::ReasoningSummary::None); + let turn = Turn { + id: "turn".into(), + items: vec![], + items_view: Default::default(), + status: TurnStatus::InProgress, + error: None, + started_at: None, + completed_at: None, + duration_ms: None, + }; + chat.handle_server_notification( + ServerNotification::TurnStarted(TurnStartedNotification { + thread_id: thread_id.to_string(), + turn: turn.clone(), + }), + replay, + ); + let completed = ServerNotification::TurnCompleted(TurnCompletedNotification { + thread_id: thread_id.to_string(), + turn: Turn { status, ..turn }, + }); + chat.handle_server_notification(completed.clone(), replay); + chat.handle_server_notification(completed, replay); + let mut requests = 0; + while let Ok(event) = events.try_recv() { + if matches!(event, AppEvent::GeneratePromptSuggestion(_)) { + requests += 1; + } + } + assert_eq!(requests, expected); + } +} diff --git a/codex-rs/tui/src/chatwidget/protocol.rs b/codex-rs/tui/src/chatwidget/protocol.rs index ba0d2e4061..f5fe7c0a50 100644 --- a/codex-rs/tui/src/chatwidget/protocol.rs +++ b/codex-rs/tui/src/chatwidget/protocol.rs @@ -73,6 +73,7 @@ impl ChatWidget { self.on_thread_settings_updated(notification); } ServerNotification::TurnStarted(notification) => { + self.clear_prompt_suggestion(); if from_replay { self.restore_realtime_transcripts_before_turn(¬ification.turn.id); } else { @@ -407,6 +408,10 @@ impl ChatWidget { // User-message dedupe only suppresses the app-server echo of a prompt // this TUI already rendered locally. Once that turn ends, another // client can submit the same text and it still needs its own user cell. + let suggest = replay_kind.is_none() + && notification.turn.status == TurnStatus::Completed + && self.turn_lifecycle.agent_turn_running + && self.turn_lifecycle.last_turn_id.as_deref() == Some(notification.turn.id.as_str()); self.last_rendered_user_message_display = None; let mut question_drafts = None; let was_replaying_turn_completion = self.thread_usage.replaying_turn_completion; @@ -522,6 +527,9 @@ impl ChatWidget { self.finish_realtime_turn(¬ification.turn.id); } self.thread_usage.replaying_turn_completion = was_replaying_turn_completion; + if suggest { + self.suggest_next_prompt(notification.turn.id); + } } fn handle_item_started_notification( diff --git a/codex-rs/tui/src/chatwidget/settings.rs b/codex-rs/tui/src/chatwidget/settings.rs index a9c2d1932d..7cd1531017 100644 --- a/codex-rs/tui/src/chatwidget/settings.rs +++ b/codex-rs/tui/src/chatwidget/settings.rs @@ -444,6 +444,7 @@ impl ChatWidget { } fn apply_thread_settings(&mut self, mut settings: ThreadSettings) { + self.prompt_suggestion_summary = settings.summary; self.invalidate_permission_discovery(); let cwd_changed = self.config.cwd != settings.cwd; self.apply_thread_settings_cwd(settings.cwd.clone()); diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index d933f1931c..a32dee4e0e 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -183,10 +183,6 @@ mod npm_registry; pub(crate) mod onboarding; mod oss_selection; mod pager_overlay; -#[expect( - dead_code, - reason = "The next PR in this stack connects suggestion generation." -)] mod prompt_suggestions; pub(crate) mod public_widgets; mod render;