From b135af68f0331a7da0be36f3f92b37c739929f66 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 29 May 2026 13:35:55 +0100 Subject: [PATCH] make it better --- codex-rs/core/src/codex_thread.rs | 19 +---- codex-rs/core/src/goals.rs | 111 ++++++++++++++++++++-------- codex-rs/core/src/session/inject.rs | 64 ++++++++++++++++ codex-rs/core/src/tasks/mod.rs | 75 ------------------- codex-rs/ext/goal/src/runtime.rs | 26 +------ 5 files changed, 150 insertions(+), 145 deletions(-) diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index b87ec60928..75bb15828d 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -43,7 +43,6 @@ use codex_utils_absolute_path::AbsolutePathBuf; use rmcp::model::ReadResourceRequestParams; use std::collections::BTreeMap; use std::collections::HashMap; -use std::future::Future; use std::path::PathBuf; use std::sync::Arc; use tokio::sync::Mutex; @@ -277,20 +276,10 @@ impl CodexThread { self.codex.session.inject_if_running(items).await } - /// Starts a regular turn with model-visible initial input if the thread is - /// still idle after caller-owned validation. - /// - /// Core owns the idle scheduling invariants; the caller owns deciding - /// whether the synthetic work is still current. - pub async fn start_idle_turn_if_current(&self, items: Vec, validate: F) - where - F: FnOnce() -> Fut + Send, - Fut: Future + Send, - { - self.codex - .session - .start_idle_turn_if_current(items, validate) - .await + /// Injects model-visible items into active work, or starts a regular turn + /// with them if the thread is idle. + pub async fn inject_or_start_turn(&self, items: Vec) { + self.codex.session.inject_or_start_turn(items).await } pub async fn set_app_server_client_info( diff --git a/codex-rs/core/src/goals.rs b/codex-rs/core/src/goals.rs index 765be97108..00b6854342 100644 --- a/codex-rs/core/src/goals.rs +++ b/codex-rs/core/src/goals.rs @@ -8,8 +8,12 @@ use crate::StateDbHandle; use crate::context::ContextualUserFragment; use crate::context::InternalContextSource; use crate::context::InternalModelContextFragment; +use crate::session::TurnInput; use crate::session::session::Session; use crate::session::turn_context::TurnContext; +use crate::state::ActiveTurn; +use crate::state::TurnState; +use crate::tasks::RegularTask; use crate::tools::handlers::goal_spec::UPDATE_GOAL_TOOL_NAME; use anyhow::Context; use codex_features::Feature; @@ -895,6 +899,16 @@ impl Session { } } + async fn clear_reserved_goal_continuation_turn(&self, turn_state: &Arc>) { + let mut active_turn_guard = self.active_turn.lock().await; + if let Some(active_turn) = active_turn_guard.as_ref() + && active_turn.task.is_none() + && Arc::ptr_eq(&active_turn.turn_state, turn_state) + { + *active_turn_guard = None; + } + } + async fn finish_thread_goal_turn( self: &Arc, turn_context: &TurnContext, @@ -1268,43 +1282,80 @@ impl Session { return; }; - let session = Arc::clone(self); - let goal_id = candidate.goal_id; - self.start_idle_turn_if_current(candidate.items, move || async move { - match session.state_db_for_thread_goals().await { - Ok(Some(state_db)) => match state_db - .thread_goals() - .get_thread_goal(session.conversation_id) - .await + let turn_state = { + let mut active_turn = self.active_turn.lock().await; + if active_turn.is_some() { + return; + } + let active_turn = active_turn.get_or_insert_with(ActiveTurn::default); + Arc::clone(&active_turn.turn_state) + }; + let goal_is_current = match self.state_db_for_thread_goals().await { + Ok(Some(state_db)) => match state_db + .thread_goals() + .get_thread_goal(self.conversation_id) + .await + { + Ok(Some(goal)) + if goal.goal_id == candidate.goal_id + && goal.status == codex_state::ThreadGoalStatus::Active => { - Ok(Some(goal)) - if goal.goal_id == goal_id - && goal.status == codex_state::ThreadGoalStatus::Active => - { - true - } - Ok(Some(_)) | Ok(None) => { - tracing::debug!( - "skipping active goal continuation because the goal changed before launch" - ); - false - } - Err(err) => { - tracing::warn!("failed to re-read thread goal before continuation: {err}"); - false - } - }, - Ok(None) => { - tracing::debug!("skipping active goal continuation for ephemeral thread"); + true + } + Ok(Some(_)) | Ok(None) => { + tracing::debug!( + "skipping active goal continuation because the goal changed before launch" + ); false } Err(err) => { - tracing::warn!("failed to open state db before goal continuation: {err}"); + tracing::warn!("failed to re-read thread goal before continuation: {err}"); false } + }, + Ok(None) => { + tracing::debug!("skipping active goal continuation for ephemeral thread"); + false } - }) - .await; + Err(err) => { + tracing::warn!("failed to open state db before goal continuation: {err}"); + false + } + }; + if !goal_is_current { + self.clear_reserved_goal_continuation_turn(&turn_state) + .await; + return; + } + self.input_queue + .extend_pending_input_for_turn_state( + turn_state.as_ref(), + candidate + .items + .into_iter() + .map(TurnInput::ResponseItem) + .collect(), + ) + .await; + + let turn_context = self + .new_default_turn_with_sub_id(uuid::Uuid::new_v4().to_string()) + .await; + self.maybe_emit_unknown_model_warning_for_turn(turn_context.as_ref()) + .await; + let still_reserved = { + let active_turn = self.active_turn.lock().await; + active_turn.as_ref().is_some_and(|active_turn| { + active_turn.task.is_none() && Arc::ptr_eq(&active_turn.turn_state, &turn_state) + }) + }; + if !still_reserved { + self.clear_reserved_goal_continuation_turn(&turn_state) + .await; + return; + } + self.start_task(turn_context, Vec::new(), RegularTask::new()) + .await; } async fn goal_continuation_candidate_if_active( diff --git a/codex-rs/core/src/session/inject.rs b/codex-rs/core/src/session/inject.rs index 4a7189bbd6..3b495742b1 100644 --- a/codex-rs/core/src/session/inject.rs +++ b/codex-rs/core/src/session/inject.rs @@ -1,7 +1,11 @@ use super::input_queue::TurnInput; use super::session::Session; use super::turn_context::TurnContext; +use crate::state::ActiveTurn; +use crate::tasks::RegularTask; +use codex_protocol::config_types::ModeKind; use codex_protocol::models::ResponseItem; +use std::sync::Arc; impl Session { /// Returns the input if there is no active turn to inject into. @@ -28,6 +32,66 @@ impl Session { } } + /// Injects items into active work, or starts a regular turn with them. + pub(crate) async fn inject_or_start_turn(self: &Arc, input: Vec) { + if input.is_empty() { + return; + } + let input = match self.inject_if_running(input).await { + Ok(()) => return, + Err(input) => input, + }; + if self.collaboration_mode().await.mode == ModeKind::Plan { + let _ = self.inject_if_running(input).await; + return; + } + + let (turn_state, should_start_turn) = { + let mut active_turn = self.active_turn.lock().await; + if let Some(active_turn) = active_turn.as_ref() { + (Arc::clone(&active_turn.turn_state), false) + } else { + let active_turn = active_turn.get_or_insert_with(ActiveTurn::default); + (Arc::clone(&active_turn.turn_state), true) + } + }; + + self.input_queue + .extend_pending_input_for_turn_state( + turn_state.as_ref(), + input.into_iter().map(TurnInput::ResponseItem).collect(), + ) + .await; + if !should_start_turn { + return; + } + + let turn_context = self + .new_default_turn_with_sub_id(uuid::Uuid::new_v4().to_string()) + .await; + self.maybe_emit_unknown_model_warning_for_turn(turn_context.as_ref()) + .await; + let still_reserved = { + let active_turn = self.active_turn.lock().await; + active_turn.as_ref().is_some_and(|active_turn| { + active_turn.task.is_none() && Arc::ptr_eq(&active_turn.turn_state, &turn_state) + }) + }; + if !still_reserved { + let mut active_turn_guard = self.active_turn.lock().await; + if let Some(active_turn) = active_turn_guard.as_ref() + && active_turn.task.is_none() + && Arc::ptr_eq(&active_turn.turn_state, &turn_state) + { + *active_turn_guard = None; + } + return; + } + + self.start_task(turn_context, Vec::new(), RegularTask::new()) + .await; + } + /// Injects items into active work, or records them without starting a turn. pub(crate) async fn inject_no_new_turn( &self, diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 7b31d49bd5..38a8a96276 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -4,7 +4,6 @@ mod regular; mod review; mod user_shell; -use std::future::Future; use std::sync::Arc; use std::time::Duration; use std::time::Instant; @@ -34,7 +33,6 @@ use crate::session::turn_context::TurnContext; use crate::state::ActiveTurn; use crate::state::RunningTask; use crate::state::TaskKind; -use crate::state::TurnState; use codex_analytics::TurnTokenUsageFact; use codex_login::AuthManager; use codex_models_manager::manager::SharedModelsManager; @@ -53,7 +51,6 @@ use codex_protocol::protocol::TurnCompleteEvent; use codex_protocol::protocol::WarningEvent; use codex_features::Feature; -use codex_protocol::config_types::ModeKind; use codex_protocol::models::ContentItem; pub(crate) use compact::CompactTask; pub(crate) use regular::RegularTask; @@ -482,78 +479,6 @@ impl Session { .await; } - pub(crate) async fn start_idle_turn_if_current( - self: &Arc, - items: Vec, - validate: F, - ) where - F: FnOnce() -> Fut + Send, - Fut: Future + Send, - { - if self.input_queue.has_trigger_turn_mailbox_items().await { - self.maybe_start_turn_for_pending_work().await; - return; - } - if self.collaboration_mode().await.mode == ModeKind::Plan { - return; - } - - let turn_state = { - let mut active_turn = self.active_turn.lock().await; - if active_turn.is_some() { - return; - } - let active_turn = active_turn.get_or_insert_with(ActiveTurn::default); - Arc::clone(&active_turn.turn_state) - }; - - if !validate().await { - self.clear_reserved_idle_turn(&turn_state).await; - return; - } - if self.input_queue.has_trigger_turn_mailbox_items().await { - self.clear_reserved_idle_turn(&turn_state).await; - self.maybe_start_turn_for_pending_work().await; - return; - } - - self.input_queue - .extend_pending_input_for_turn_state( - turn_state.as_ref(), - items.into_iter().map(TurnInput::ResponseItem).collect(), - ) - .await; - - let turn_context = self - .new_default_turn_with_sub_id(uuid::Uuid::new_v4().to_string()) - .await; - self.maybe_emit_unknown_model_warning_for_turn(turn_context.as_ref()) - .await; - let still_reserved = { - let active_turn = self.active_turn.lock().await; - active_turn.as_ref().is_some_and(|active_turn| { - active_turn.task.is_none() && Arc::ptr_eq(&active_turn.turn_state, &turn_state) - }) - }; - if !still_reserved { - self.clear_reserved_idle_turn(&turn_state).await; - return; - } - - self.start_task(turn_context, Vec::new(), RegularTask::new()) - .await; - } - - async fn clear_reserved_idle_turn(&self, turn_state: &Arc>) { - let mut active_turn_guard = self.active_turn.lock().await; - if let Some(active_turn) = active_turn_guard.as_ref() - && active_turn.task.is_none() - && Arc::ptr_eq(&active_turn.turn_state, turn_state) - { - *active_turn_guard = None; - } - } - pub async fn abort_all_tasks(self: &Arc, reason: TurnAbortReason) { let mut aborted_turn = false; let mut active_turn_to_clear = None; diff --git a/codex-rs/ext/goal/src/runtime.rs b/codex-rs/ext/goal/src/runtime.rs index e59977cdaa..dd18d5d6cc 100644 --- a/codex-rs/ext/goal/src/runtime.rs +++ b/codex-rs/ext/goal/src/runtime.rs @@ -298,7 +298,6 @@ impl GoalRuntimeHandle { return Ok(()); } - let expected_goal_id = goal.goal_id.clone(); let item = continuation_steering_item(&protocol_goal_from_state(goal)); let Some(thread_manager) = self.inner.thread_manager.upgrade() else { tracing::debug!("skipping goal continuation because thread manager is unavailable"); @@ -309,30 +308,7 @@ impl GoalRuntimeHandle { return Ok(()); }; - let state_dbs = Arc::clone(&self.inner.state_dbs); - let thread_id = self.inner.thread_id; - thread - .start_idle_turn_if_current(vec![item], move || async move { - match state_dbs.thread_goals().get_thread_goal(thread_id).await { - Ok(Some(goal)) - if goal.goal_id == expected_goal_id - && goal.status == codex_state::ThreadGoalStatus::Active => - { - true - } - Ok(Some(_)) | Ok(None) => { - tracing::debug!( - "skipping active goal continuation because the goal changed before launch" - ); - false - } - Err(err) => { - tracing::warn!("failed to re-read thread goal before continuation: {err}"); - false - } - } - }) - .await; + thread.inject_or_start_turn(vec![item]).await; let current_turn_is_goal_active = self .inner