From 986a6b3b115df58ac8fe51dba222fc06ca10048a Mon Sep 17 00:00:00 2001 From: jamy-OAI <332197178+jamy-OAI@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:06:19 +0000 Subject: [PATCH] Preserve the saved Daybreak choice across live goal continuations (#63809) ## Why Automatic goal continuations could lose the thread's saved Daybreak choice, even when the thread was enrolled in Daybreak propagation. ## What changed Capture the saved choice when an externally created live goal first becomes active. For goals created by a tool, carry forward the originating turn's choice and preserve explicit access program overrides. Keep the captured choice in memory for the life of the goal and check it against the current account and model on continuation. Changing the thread's Daybreak setting takes effect for new goals. ## Testing Add coverage for enrolled and opted-out threads, including blocking a goal when the model lacks Daybreak support and starting a new goal after turning Daybreak off. Also cover account changes and isolation from foreground turns. GitOrigin-RevId: 0baf08f06baf267595cb5a2b3b1fe033db52ad06 --- .../tests/suite/v2/thread_resume.rs | 157 ++++++++++++++++++ codex-rs/core/src/agent/control/spawn.rs | 1 + codex-rs/core/src/agent/helper_daybreak.rs | 3 +- .../core/src/agent/helper_daybreak/goal.rs | 97 +++++++++++ .../core/src/agent/helper_daybreak/turn.rs | 40 +++-- codex-rs/core/src/codex_thread.rs | 42 +++++ codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/session/turn_context.rs | 4 + codex-rs/core/src/session/turn_input.rs | 22 ++- codex-rs/core/src/tasks/mod.rs | 1 + .../thread_manager/helper_daybreak_tests.rs | 103 ++++++++++++ codex-rs/ext/goal/src/api.rs | 40 ++++- codex-rs/ext/goal/src/extension.rs | 1 - codex-rs/ext/goal/src/runtime.rs | 143 ++++++++++++---- codex-rs/ext/goal/src/tool.rs | 50 ++---- 15 files changed, 617 insertions(+), 88 deletions(-) create mode 100644 codex-rs/core/src/agent/helper_daybreak/goal.rs diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index 2b71027351..d5097b2366 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -54,6 +54,7 @@ use codex_app_server_protocol::ThreadGoalGetParams; use codex_app_server_protocol::ThreadGoalGetResponse; use codex_app_server_protocol::ThreadGoalSetResponse; use codex_app_server_protocol::ThreadGoalStatus; +use codex_app_server_protocol::ThreadGoalUpdatedNotification; use codex_app_server_protocol::ThreadHistoryMode; use codex_app_server_protocol::ThreadItemPayload; use codex_app_server_protocol::ThreadListResponse; @@ -61,6 +62,7 @@ use codex_app_server_protocol::ThreadLoadedListParams; use codex_app_server_protocol::ThreadLoadedListResponse; use codex_app_server_protocol::ThreadMetadataGitInfoUpdateParams; use codex_app_server_protocol::ThreadMetadataUpdateParams; +use codex_app_server_protocol::ThreadMetadataUpdateResponse; use codex_app_server_protocol::ThreadReadParams; use codex_app_server_protocol::ThreadReadResponse; use codex_app_server_protocol::ThreadResumeInitialTurnsPageParams; @@ -76,6 +78,7 @@ use codex_app_server_protocol::ThreadStatusChangedNotification; use codex_app_server_protocol::ThreadTurnsListParams; use codex_app_server_protocol::ThreadTurnsListResponse; use codex_app_server_protocol::ThreadUnsubscribeParams; +use codex_app_server_protocol::TurnCompletedNotification; use codex_app_server_protocol::TurnEnvironmentParams; use codex_app_server_protocol::TurnItemsView; use codex_app_server_protocol::TurnStartParams; @@ -100,6 +103,7 @@ use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE; use codex_protocol::models::ContentItem; use codex_protocol::models::PermissionProfile; use codex_protocol::models::ResponseItem; +use codex_protocol::openai_models::ModelAccessPrograms; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::AgentMessageEvent; use codex_protocol::protocol::EventMsg; @@ -118,6 +122,7 @@ use codex_protocol::protocol::TokenUsageInfo; use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::TurnAbortedEvent; use codex_protocol::protocol::TurnStartedEvent; +use codex_protocol::turn_input::CyberAccessProgram as ProtocolCyberAccessProgram; use codex_protocol::user_input::ByteRange; use codex_protocol::user_input::TextElement; use codex_rollout::CompactedItem; @@ -173,6 +178,158 @@ const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs #[cfg(not(windows))] const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); +#[test_case(true; "enrolled")] +#[test_case(false; "opted out")] +#[tokio::test] +async fn external_goal_daybreak_respects_thread_enrollment(enrolled: bool) -> Result<()> { + let server = responses::start_sse_server().await; + let response = responses::mount_sse_once( + &server, + responses::sse(vec![ + responses::ev_response_created("new-goal"), + responses::ev_completed_with_tokens("new-goal", /*total_tokens*/ 100), + ]), + ) + .await; + let home = TempDir::new()?; + let catalog_path = home.path().join("models.json"); + let mut catalog = codex_models_manager::bundled_models_response()?; + let model = catalog + .models + .iter_mut() + .find(|model| model.slug == "gpt-5.5") + .expect("bundled test model"); + model.available_access_programs = Some(ModelAccessPrograms { + cyber: vec![ProtocolCyberAccessProgram::Standard], + daybreak_availability: Default::default(), + }); + std::fs::write(&catalog_path, serde_json::to_vec(&catalog)?)?; + std::fs::write( + home.path().join("config.toml"), + format!( + r#" +model = "gpt-5.5" +approval_policy = "never" +openai_base_url = "{}/v1" +cli_auth_credentials_store = "file" +model_catalog_json = {} + +[features] +goals = true +daybreak_program_propagation = true +enable_request_compression = false +"#, + server.uri(), + serde_json::to_string(&catalog_path)?, + ), + )?; + write_chatgpt_auth( + home.path(), + ChatGptAuthFixture::new("chatgpt-test-token").plan_type("pro"), + AuthCredentialsStoreMode::File, + )?; + let mut app = TestAppServer::builder() + .with_codex_home(home.path()) + .without_managed_config() + .build_initialized() + .await?; + let thread = app + .start_thread(ThreadStartParams { + daybreak_enabled: Some(true), + daybreak_program_propagation_enrolled: Some(enrolled), + ..Default::default() + }) + .await? + .thread; + assert_eq!(thread.daybreak_program_propagation_enrolled, Some(enrolled)); + + for resume in [false, true] { + let goal_params = if resume { + let request = app + .send_thread_metadata_update_request(ThreadMetadataUpdateParams { + thread_id: thread.id.clone(), + daybreak_enabled: Some(false), + project_id: None, + git_info: None, + }) + .await?; + let update: ThreadMetadataUpdateResponse = + timeout(DEFAULT_READ_TIMEOUT, app.read_response(request)).await??; + assert_eq!(update.thread.daybreak_enabled, Some(false)); + json!({"threadId": thread.id, "status": "active"}) + } else { + json!({"threadId": thread.id, "objective": "Original goal", "tokenBudget": 100}) + }; + let request = app + .send_raw_request("thread/goal/set", Some(goal_params)) + .await?; + let goal: ThreadGoalSetResponse = + timeout(DEFAULT_READ_TIMEOUT, app.read_response(request)).await??; + assert_eq!(goal.goal.objective, "Original goal"); + let completed: TurnCompletedNotification = timeout( + DEFAULT_READ_TIMEOUT, + app.read_notification("turn/completed"), + ) + .await??; + if !enrolled { + assert_eq!(completed.turn.status, TurnStatus::Completed); + assert_eq!( + response.single_request().body_json().get("access_programs"), + None + ); + app.shutdown_gracefully().await?; + return Ok(()); + } + assert_eq!(completed.turn.status, TurnStatus::Failed); + assert_eq!( + completed + .turn + .error + .expect("unsupported Daybreak model") + .message, + "Model gpt-5.5 does not advertise Daybreak support. Turn Daybreak off and start a new Goal to apply the change, or choose a compatible model." + ); + timeout(DEFAULT_READ_TIMEOUT, async { + loop { + let update: ThreadGoalUpdatedNotification = + app.read_notification("thread/goal/updated").await?; + if update.goal.status == ThreadGoalStatus::Blocked { + return Ok::<_, anyhow::Error>(()); + } + } + }) + .await??; + assert!(response.requests().is_empty()); + } + + let request = app + .send_raw_request("thread/goal/clear", Some(json!({"threadId": thread.id}))) + .await?; + let clear: ThreadGoalClearResponse = + timeout(DEFAULT_READ_TIMEOUT, app.read_response(request)).await??; + assert!(clear.cleared); + let request = app + .send_raw_request( + "thread/goal/set", + Some(json!({"threadId": thread.id, "objective": "New goal", "tokenBudget": 100})), + ) + .await?; + let _: ThreadGoalSetResponse = + timeout(DEFAULT_READ_TIMEOUT, app.read_response(request)).await??; + let completed: TurnCompletedNotification = timeout( + DEFAULT_READ_TIMEOUT, + app.read_notification("turn/completed"), + ) + .await??; + assert_eq!(completed.turn.status, TurnStatus::Completed); + assert_eq!( + response.single_request().body_json()["access_programs"], + json!({"cyber": "standard"}) + ); + app.shutdown_gracefully().await?; + Ok(()) +} + #[tokio::test] async fn independent_cold_resumes_overlap() -> Result<()> { let responses = create_mock_responses_server_repeating_assistant("Done").await; diff --git a/codex-rs/core/src/agent/control/spawn.rs b/codex-rs/core/src/agent/control/spawn.rs index 4eb55d8cb5..bc8127e42d 100644 --- a/codex-rs/core/src/agent/control/spawn.rs +++ b/codex-rs/core/src/agent/control/spawn.rs @@ -996,6 +996,7 @@ impl LocalAgentControl { cyber_access_program = helper_daybreak::turn::select_program( &model, codex_protocol::openai_models::SavedDaybreakChoice::On, + helper_daybreak::turn::SavedProgramContext::Helper, ) .map_err(CodexErr::InvalidRequest)? .or(Some(inherited)); diff --git a/codex-rs/core/src/agent/helper_daybreak.rs b/codex-rs/core/src/agent/helper_daybreak.rs index c4477c10b6..7bbc60eac7 100644 --- a/codex-rs/core/src/agent/helper_daybreak.rs +++ b/codex-rs/core/src/agent/helper_daybreak.rs @@ -1,5 +1,6 @@ -//! Native helpers inherit the spawning turn's saved Daybreak choice. +//! Account-bound Daybreak intent for native helpers and live goals. +pub(crate) mod goal; pub(crate) mod turn; use crate::session::session::Session; diff --git a/codex-rs/core/src/agent/helper_daybreak/goal.rs b/codex-rs/core/src/agent/helper_daybreak/goal.rs new file mode 100644 index 0000000000..aee5d8c80f --- /dev/null +++ b/codex-rs/core/src/agent/helper_daybreak/goal.rs @@ -0,0 +1,97 @@ +//! Account-bound Daybreak intent for one live goal generation. + +use super::SavedIntent; +use super::eligible_owner; +use super::saved_choice; +use super::turn::SavedProgramContext; +use super::turn::SavedProgramResolution; +use super::turn::explicit_program_for_spawn; +use super::turn::select_program; +use crate::config::Config; +use crate::session::session::Session; +use crate::session::turn_context::TurnContext; +use codex_features::Feature; +use codex_login::AuthOwner; +use codex_protocol::openai_models::SavedDaybreakChoice; + +const ACCOUNT_CHANGED: &str = + "The account for this goal's Daybreak choice has changed. Start a new goal."; + +/// A live goal's request preference, not an entitlement. Only Core can produce +/// this snapshot, and it cannot be persisted or used after the account changes. +#[derive(Clone, Debug)] +pub struct GoalDaybreakSnapshot { + owner: AuthOwner, + choice: Result, +} + +/// Host attachment consumed at idle admission, never saved as a thread default. +pub(crate) struct GoalDaybreakAdmission(pub(crate) GoalDaybreakSnapshot); + +impl GoalDaybreakSnapshot { + pub(crate) async fn capture_saved(session: &Session) -> Option { + let owner = eligible_owner(session)?; + let config = session.get_config().await; + if !supported_config(&config) + || !codex_model_provider::provider_uses_first_party_auth_path(&session.provider().await) + { + return None; + } + let choice = match saved_choice(session).await { + Ok(Some(enabled)) => Ok(SavedDaybreakChoice::from(Some(enabled))), + Ok(None) => return None, + Err(error) => Err(error), + }; + Some(Self { owner, choice }) + } + + pub(crate) fn from_turn(turn: &TurnContext) -> Option { + // An explicit choice is governed only by the explicit continuation path. + if explicit_program_for_spawn(turn).is_some() { + return None; + } + if let Some(snapshot) = turn.extension_data.get::() { + return Some(snapshot.as_ref().clone()); + } + let intent = turn.extension_data.get::()?; + Some(Self { + owner: intent.owner.clone(), + choice: intent.choice.clone(), + }) + } + + pub(crate) fn apply(&self, session: &Session, turn: &mut TurnContext) { + // Keep Core's ordinary explicit request path authoritative. + if turn.cyber_access_program.is_some() || !supported_turn(turn) { + return; + } + let resolved = + if eligible_owner(session).as_ref() != Some(&self.owner) || !self.owner.is_current() { + Err(ACCOUNT_CHANGED.to_owned()) + } else { + self.choice.clone().and_then(|choice| { + select_program(turn.model_info(), choice, SavedProgramContext::Goal) + }) + }; + let bound_owner = resolved.map(|program| { + turn.cyber_access_program = program; + self.owner.clone() + }); + turn.extension_data + .insert(SavedProgramResolution::new(bound_owner, ACCOUNT_CHANGED)); + turn.extension_data.insert(self.clone()); + } +} + +fn supported_config(config: &Config) -> bool { + config.features.enabled(Feature::DaybreakProgramPropagation) + && config.model_provider_id == codex_model_provider_info::OPENAI_PROVIDER_ID + && config + .model_provider + .supports_cyber_access_programs(&config.model_provider_id) +} + +fn supported_turn(turn: &TurnContext) -> bool { + supported_config(&turn.config) + && codex_model_provider::provider_uses_first_party_auth_path(turn.provider.info()) +} diff --git a/codex-rs/core/src/agent/helper_daybreak/turn.rs b/codex-rs/core/src/agent/helper_daybreak/turn.rs index 1e59639b3d..6b0117ae47 100644 --- a/codex-rs/core/src/agent/helper_daybreak/turn.rs +++ b/codex-rs/core/src/agent/helper_daybreak/turn.rs @@ -18,13 +18,17 @@ const ACCOUNT_CHANGED: &str = "The account for this subagent's saved Daybreak choice has changed. Start a new subagent."; /// An implicit program stays bound to the account whose choice selected it. -pub(crate) struct SavedProgramResolution(Result); +pub(crate) struct SavedProgramResolution(Result, &'static str); impl SavedProgramResolution { + pub(crate) fn new(owner: Result, account_changed: &'static str) -> Self { + Self(owner, account_changed) + } + pub(crate) fn validate(&self) -> CodexResult<()> { match &self.0 { Ok(owner) if owner.is_current() => Ok(()), - Ok(_) => Err(CodexErr::InvalidRequest(ACCOUNT_CHANGED.to_owned())), + Ok(_) => Err(CodexErr::InvalidRequest(self.1.to_owned())), Err(error) => Err(CodexErr::InvalidRequest(error.clone())), } } @@ -94,24 +98,30 @@ impl HelperTurnAdmission { { Err(ACCOUNT_CHANGED.to_owned()) } else { - choice - .clone() - .and_then(|choice| select_program(turn.model_info(), choice)) + choice.clone().and_then(|choice| { + select_program(turn.model_info(), choice, SavedProgramContext::Helper) + }) }; let bound_owner = resolution.map(|program| { turn.cyber_access_program = program; owner.clone() }); turn.extension_data - .insert(SavedProgramResolution(bound_owner)); + .insert(SavedProgramResolution::new(bound_owner, ACCOUNT_CHANGED)); } turn.extension_data.insert(SavedIntent { choice, owner }); } } +pub(crate) enum SavedProgramContext { + Helper, + Goal, +} + pub(crate) fn select_program( model: &ModelInfo, choice: SavedDaybreakChoice, + context: SavedProgramContext, ) -> Result, String> { let Some(programs) = model.available_access_programs.as_ref() else { return Ok(None); @@ -120,8 +130,16 @@ pub(crate) fn select_program( if selected.is_none() { match choice { SavedDaybreakChoice::On if !programs.cyber.is_empty() => { + let recovery = match context { + SavedProgramContext::Helper => { + "Turn Daybreak off or choose a compatible model." + } + SavedProgramContext::Goal => { + "Turn Daybreak off and start a new Goal to apply the change, or choose a compatible model." + } + }; return Err(format!( - "Model {} does not advertise Daybreak support. Turn Daybreak off or choose a compatible model.", + "Model {} does not advertise Daybreak support. {recovery}", model.slug )); } @@ -149,15 +167,17 @@ mod tests { .models .remove(0); model.available_access_programs = None; - assert_eq!(select_program(&model, SavedDaybreakChoice::Off), Ok(None)); + let select = + |model: &ModelInfo, choice| select_program(model, choice, SavedProgramContext::Helper); + assert_eq!(select(&model, SavedDaybreakChoice::Off), Ok(None)); for cyber in [vec![], vec![CyberAccessProgram::DaybreakRed]] { model.available_access_programs = Some(ModelAccessPrograms { cyber, daybreak_availability: Default::default(), }); - assert_eq!(select_program(&model, SavedDaybreakChoice::Unset), Ok(None)); + assert_eq!(select(&model, SavedDaybreakChoice::Unset), Ok(None)); assert!( - select_program(&model, SavedDaybreakChoice::Off) + select(&model, SavedDaybreakChoice::Off) .unwrap_err() .contains("does not advertise Standard") ); diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 01171366df..0e8a49fd5a 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -662,6 +662,48 @@ impl CodexThread { } } + /// Starts an automatic goal turn with its live, account-bound preference. + pub async fn start_goal_turn_if_idle( + &self, + request: TurnInputRequest, + snapshot: Option, + ) -> CodexResult { + let Some(snapshot) = snapshot.filter(|_| self.daybreak_program_propagation_enrolled()) + else { + return self.start_turn_if_idle(request).await; + }; + let mut data = codex_extension_api::ExtensionDataInit::new(); + data.insert(crate::agent::helper_daybreak::goal::GoalDaybreakAdmission( + snapshot, + )); + self.start_turn_if_idle(WithTurnExtensionData::new(request, data)) + .await + } + + /// Captures the current saved preference for a newly accepted external goal. + pub async fn capture_saved_goal_daybreak(&self) -> Option { + if !self.daybreak_program_propagation_enrolled() { + return None; + } + crate::GoalDaybreakSnapshot::capture_saved(&self.session).await + } + + /// Captures the exact turn's saved preference, never a later foreground turn's. + pub async fn capture_originating_saved_goal_daybreak( + &self, + expected_turn_id: &str, + ) -> Option { + if !self.daybreak_program_propagation_enrolled() { + return None; + } + let active = self.session.active_turn.lock().await; + let task = active.as_ref()?.task.as_ref()?; + if task.turn_context.sub_id != expected_turn_id || task.cancellation_token.is_cancelled() { + return None; + } + crate::GoalDaybreakSnapshot::from_turn(&task.turn_context) + } + /// Starts a new internal continuation turn when idle, including in Plan mode. /// Rejects if a newer task has started, even if it has already finished. /// Supply an internal response item, or empty input to wake on a result already diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index cea2001ea8..e03033386b 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -37,6 +37,7 @@ mod codex_thread; mod thread_input; pub use thread_input::InputWaitOutcome; mod turn_extension_data; +pub use agent::helper_daybreak::goal::GoalDaybreakSnapshot; pub use turn_extension_data::WithTurnExtensionData; mod compact_model_fallback; mod compact_pending_input; diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index d93b1d7de0..a7f471f09f 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -365,6 +365,7 @@ pub(crate) struct NewTurnContextOptions { pub(crate) prompt_cache_ttl: Option, pub(crate) cyber_access_program: Option, pub(crate) helper_admission: Option, + pub(crate) goal_daybreak: Option, } /// The context needed for a single turn of the thread. @@ -1530,6 +1531,9 @@ impl Session { if let Some(admission) = options.helper_admission { admission.capture_intent(self, &mut turn_context).await; } + if let Some(snapshot) = options.goal_daybreak { + snapshot.apply(self, &mut turn_context); + } // Tool observers retain this turn's selection even after a later turn starts. if let Some(program) = turn_context.cyber_access_program { turn_context.extension_data.insert(program); diff --git a/codex-rs/core/src/session/turn_input.rs b/codex-rs/core/src/session/turn_input.rs index 23ff903a4a..3011d2c681 100644 --- a/codex-rs/core/src/session/turn_input.rs +++ b/codex-rs/core/src/session/turn_input.rs @@ -25,6 +25,7 @@ use super::thread_settings; use super::turn_context::NewTurnContextOptions; use super::turn_context::TurnContext; use crate::WithTurnExtensionData; +use crate::agent::helper_daybreak::goal::GoalDaybreakAdmission; use crate::agent::helper_daybreak::turn::HelperTurnAdmission; use crate::context::ContextualUserFragment; use crate::context::GuardianSenderMessages; @@ -109,6 +110,7 @@ impl TurnStartKind { struct PreparedTurnInputSettings { thread_settings_update: Option, start_options: TurnStartOptions, + goal_daybreak: Option>, } impl PreparedTurnInputSettings { @@ -139,6 +141,7 @@ impl PreparedTurnInputSettings { Ok(Self { thread_settings_update, start_options, + goal_daybreak: None, }) } @@ -189,6 +192,7 @@ impl PreparedTurnInputSettings { prompt_cache_ttl, cyber_access_program, helper_admission, + goal_daybreak: self.goal_daybreak.map(|admission| admission.0.clone()), }; let turn_context = match kind { TurnStartKind::User | TurnStartKind::Recovery => Some( @@ -300,12 +304,21 @@ pub(super) async fn handle_realtime_handoff( )] async fn handle_inner( session: &Arc, - request: WithTurnExtensionData, + mut request: WithTurnExtensionData, mode: TurnInputMode, submission_id: String, realtime_handoff_id: Option, ) -> CodexResult { session.conversation.check_history_recovery()?; + let goal_daybreak = request + .turn_extension_init + .as_mut() + .and_then(codex_extension_api::ExtensionDataInit::remove::); + if goal_daybreak.is_some() { + // Only Core's goal-specific idle entry point can supply this attachment. + // It supplies no other data, so consuming it must not clear host defaults. + request.turn_extension_init = None; + } if request.request.start.service_tier.is_some() && crate::agent::host::host_child_uses_shared_service_tier(session) { @@ -356,6 +369,7 @@ async fn handle_inner( kind, /*expected_previous_turn_id*/ None, realtime_handoff_id, + goal_daybreak.filter(|_| kind == TurnStartKind::Automatic), ) .await } @@ -384,6 +398,7 @@ async fn handle_inner( TurnStartKind::Recovery, Some(expected_previous_turn_id), realtime_handoff_id, + /*goal_daybreak*/ None, ) .await } @@ -438,6 +453,7 @@ pub(super) async fn handle_recovery( TurnStartKind::Recovery, /*expected_previous_turn_id*/ None, /*realtime_handoff_id*/ None, + /*goal_daybreak*/ None, ) .await; if let Ok(TurnInputSubmission::Started { turn_id, .. }) = &result { @@ -614,6 +630,7 @@ async fn start_if_idle( kind: TurnStartKind, expected_previous_turn_id: Option, realtime_handoff_id: Option, + goal_daybreak: Option>, ) -> CodexResult { let WithTurnExtensionData { mut request, @@ -702,7 +719,7 @@ async fn start_if_idle( }); } - let settings = match PreparedTurnInputSettings::prepare( + let mut settings = match PreparedTurnInputSettings::prepare( session, WithTurnExtensionData { request: thread_settings, @@ -718,6 +735,7 @@ async fn start_if_idle( return Err(error); } }; + settings.goal_daybreak = goal_daybreak; let turn_context = match settings .apply_started(session, submission_id.clone(), kind) .await diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 9ea302d35a..a68d1f1342 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -614,6 +614,7 @@ impl Session { prompt_cache_ttl: start_options.prompt_cache_ttl, cyber_access_program: start_options.cyber_access_program, helper_admission: triggered.then_some(helper_admission).flatten(), + goal_daybreak: None, }; let turn_context = self .new_turn_with_configuration(sub_id, configuration, options) diff --git a/codex-rs/core/src/thread_manager/helper_daybreak_tests.rs b/codex-rs/core/src/thread_manager/helper_daybreak_tests.rs index 10207e2fae..2f665a4907 100644 --- a/codex-rs/core/src/thread_manager/helper_daybreak_tests.rs +++ b/codex-rs/core/src/thread_manager/helper_daybreak_tests.rs @@ -557,3 +557,106 @@ async fn copied_program_rechecks_the_spawning_turn_owner() { child.shutdown_and_wait().await.expect("stop child"); root.thread.shutdown_and_wait().await.expect("stop root"); } + +#[tokio::test] +async fn goal_daybreak_retains_saved_choice_without_leaking_to_foreground() { + let home = tempdir().expect("create test home"); + let blue = CyberAccessProgram::DaybreakBlue; + let red = CyberAccessProgram::DaybreakRed; + let standard = CyberAccessProgram::Standard; + let (config, mut manager, mut turns) = + paused_helpers(home.path(), Some(vec![blue, red, standard])).await; + Arc::get_mut(&mut manager.state) + .expect("unshared manager") + .auth_manager = codex_login::AuthManager::from_auth_for_testing_with_home( + CodexAuth::create_dummy_chatgpt_auth_for_testing(), + home.path().to_owned(), + ); + let root = manager + .start_thread(StartThreadOptions::new(config)) + .await + .expect("start root"); + let thread = &root.thread; + save_choice(thread, /*enabled*/ true).await; + let saved = thread.capture_saved_goal_daybreak().await; + assert!(saved.is_some()); + + save_choice(thread, /*enabled*/ false).await; + thread + .start_or_steer_turn( + TurnInputRequest::user_input(text()).on_start(TurnStartOptions { + cyber_access_program: Some(red), + ..Default::default() + }), + ) + .await + .expect("admit foreground turn with explicit override"); + let foreground = admitted_turn(&mut turns, thread).await; + assert_eq!(foreground.cyber_access_program, Some(red)); + + let goal_request = || { + TurnInputRequest::user_input(Vec::new()).on_start(TurnStartOptions { + turn_trigger: Some("goal".to_owned()), + ..Default::default() + }) + }; + assert_eq!( + thread + .start_goal_turn_if_idle(goal_request(), saved.clone()) + .await + .unwrap(), + crate::StartIfIdleSubmission::NotSubmitted { + reason: crate::NotSubmittedReason::NotIdle, + } + ); + + thread + .session + .abort_all_tasks(TurnAbortReason::Interrupted) + .await; + thread + .start_goal_turn_if_idle(goal_request(), saved.clone()) + .await + .unwrap(); + let continuation = admitted_turn(&mut turns, thread).await; + assert_eq!(continuation.cyber_access_program, Some(blue)); + + thread + .session + .abort_all_tasks(TurnAbortReason::Interrupted) + .await; + thread + .start_or_steer_turn(TurnInputRequest::user_input(text())) + .await + .unwrap(); + let next_foreground = admitted_turn(&mut turns, thread).await; + assert_eq!(next_foreground.cyber_access_program, None); + + let auth = manager.auth_manager(); + codex_login::auth::login_with_chatgpt_auth_tokens( + home.path(), + "header.e30.changed", + "other-account", + /*chatgpt_plan_type*/ None, + ) + .expect("switch account"); + auth.reload().await; + thread + .session + .abort_all_tasks(TurnAbortReason::Interrupted) + .await; + thread + .start_goal_turn_if_idle(goal_request(), saved) + .await + .expect("admit and reject old owner's program before sampling"); + let switched = admitted_turn(&mut turns, thread).await; + assert_eq!(switched.cyber_access_program, None); + let error = switched + .extension_data + .get::() + .expect("guard old owner's choice") + .validate() + .expect_err("account switch invalidates old preference"); + assert!(error.to_string().contains("account for this goal")); + thread.shutdown_and_wait().await.expect("shut down root"); +} diff --git a/codex-rs/ext/goal/src/api.rs b/codex-rs/ext/goal/src/api.rs index 2dabd31bf0..ea44bb41aa 100644 --- a/codex-rs/ext/goal/src/api.rs +++ b/codex-rs/ext/goal/src/api.rs @@ -13,6 +13,7 @@ use codex_protocol::protocol::ThreadGoalUpdatedEvent; use codex_protocol::protocol::validate_thread_goal_objective; use codex_rollout::RolloutItem; +use crate::runtime::GoalDaybreakSelection; use crate::runtime::GoalRuntimeHandle; use crate::runtime::PreviousGoalSnapshot; use crate::tool::fill_empty_thread_preview_if_possible; @@ -208,6 +209,28 @@ impl GoalService { ))); } record_user_instruction.await?; + // A paused live goal has not started. Capture once on activation, but do + // not invent a snapshot when resuming older goals without live provenance. + let first_activation = match existing_goal.as_ref() { + None => { + status.unwrap_or(codex_state::ThreadGoalStatus::Active) + == codex_state::ThreadGoalStatus::Active + } + Some(goal) => { + status == Some(codex_state::ThreadGoalStatus::Active) + && runtime + .as_ref() + .is_some_and(|runtime| runtime.daybreak_awaits_activation(&goal.goal_id)) + } + }; + let daybreak = if first_activation + && let Some(runtime) = runtime.as_ref() + && let Some(thread) = runtime.live_thread().await + { + thread.capture_saved_goal_daybreak().await + } else { + None + }; let (goal, previous_goal) = if let Some(objective) = objective { if let Some(existing_goal) = existing_goal.as_ref() { @@ -280,7 +303,15 @@ impl GoalService { }; if let Some(runtime) = runtime.as_ref() { - runtime.reset_goal_continuation(Some(&goal.goal_id)).await; + if first_activation && goal.status == codex_state::ThreadGoalStatus::Active { + runtime.set_daybreak_snapshot( + &goal.goal_id, + daybreak.map(GoalDaybreakSelection::Saved), + ); + } else if previous_goal.is_none() { + runtime.defer_daybreak_until_activation(&goal.goal_id); + } + runtime.clear_pending_turn_start_options().await; } if objective.is_some() { @@ -329,10 +360,9 @@ impl GoalService { GoalServiceError::Internal(format!("failed to clear thread goal: {err}")) })?; let cleared = cleared_goal.is_some(); - if cleared && let Some(runtime) = runtime.as_ref() { - runtime - .reset_goal_continuation(/*remaining_goal_id*/ None) - .await; + if let (Some(goal), Some(runtime)) = (cleared_goal.as_ref(), runtime.as_ref()) { + runtime.clear_daybreak_snapshot(&goal.goal_id); + runtime.clear_pending_turn_start_options().await; } drop(goal_state_permit); drop(runtime); diff --git a/codex-rs/ext/goal/src/extension.rs b/codex-rs/ext/goal/src/extension.rs index d534ec098a..c2a23512c3 100644 --- a/codex-rs/ext/goal/src/extension.rs +++ b/codex-rs/ext/goal/src/extension.rs @@ -584,7 +584,6 @@ where ), GoalToolExecutor::create( &runtime, - self.thread_manager.clone(), Arc::clone(&self.state_dbs), self.analytics.clone(), self.event_emitter.clone(), diff --git a/codex-rs/ext/goal/src/runtime.rs b/codex-rs/ext/goal/src/runtime.rs index ce96d9f6fa..193bded1c4 100644 --- a/codex-rs/ext/goal/src/runtime.rs +++ b/codex-rs/ext/goal/src/runtime.rs @@ -1,8 +1,11 @@ use std::sync::Arc; +use std::sync::Mutex; use std::sync::Weak; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; +use codex_core::CodexThread; +use codex_core::GoalDaybreakSnapshot; use codex_core::StartIfIdleSubmission; use codex_core::ThreadManager; use codex_core::TurnStartOptions; @@ -56,6 +59,19 @@ struct GoalRuntimeInner { tools_available_for_thread: bool, tools_visible_for_thread: bool, goal_state_lock: Semaphore, + daybreak: Mutex>, +} + +enum GoalDaybreakPreference { + AwaitingActivation, + Captured(Option), +} + +/// The source of a Goal's live choice determines how it is resolved. +#[derive(Clone)] +pub(crate) enum GoalDaybreakSelection { + Explicit(Arc), + Saved(GoalDaybreakSnapshot), } pub(crate) struct AccountedGoalProgress { @@ -63,12 +79,6 @@ pub(crate) struct AccountedGoalProgress { pub(crate) goal_id: String, } -/// The live goal keeps this choice across changes to its continuation's turn lineage. -pub(crate) struct ToolCreatedGoalProgram { - pub(crate) goal_id: String, - pub(crate) program: Arc, -} - #[derive(Clone, Debug, PartialEq, Eq)] pub struct PreviousGoalSnapshot { pub goal_id: String, @@ -116,6 +126,7 @@ impl GoalRuntimeHandle { tools_available_for_thread: config.tools_available_for_thread, tools_visible_for_thread: config.tools_visible_for_thread, goal_state_lock: Semaphore::new(/*permits*/ 1), + daybreak: Mutex::new(None), }), } } @@ -148,20 +159,74 @@ impl GoalRuntimeHandle { self.inner.root_accounting_state.clone() } - pub(crate) async fn reset_goal_continuation(&self, remaining_goal_id: Option<&str>) { - let Some(thread_manager) = self.inner.thread_manager.upgrade() else { - return; - }; - let Ok(thread) = thread_manager.get_thread(self.inner.thread_id).await else { - return; - }; - let thread_store = thread.thread_extension_data(); - thread_store.remove::(); - if thread_store - .get::() - .is_some_and(|captured| Some(captured.goal_id.as_str()) != remaining_goal_id) - { - thread_store.remove::(); + pub(crate) async fn live_thread(&self) -> Option> { + self.inner + .thread_manager + .upgrade()? + .get_thread(self.thread_id()) + .await + .ok() + } + + /// Called under the goal mutation permit when a live goal is first accepted. + pub(crate) fn set_daybreak_snapshot( + &self, + goal_id: &str, + snapshot: Option, + ) { + self.set_daybreak(goal_id, GoalDaybreakPreference::Captured(snapshot)); + } + + pub(crate) fn defer_daybreak_until_activation(&self, goal_id: &str) { + self.set_daybreak(goal_id, GoalDaybreakPreference::AwaitingActivation); + } + + fn set_daybreak(&self, goal_id: &str, preference: GoalDaybreakPreference) { + *self + .inner + .daybreak + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + Some((goal_id.to_owned(), preference)); + } + + pub(crate) fn clear_daybreak_snapshot(&self, goal_id: &str) { + let mut daybreak = self + .inner + .daybreak + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if daybreak.as_ref().is_some_and(|(id, _)| id == goal_id) { + *daybreak = None; + } + } + + pub(crate) fn daybreak_awaits_activation(&self, goal_id: &str) -> bool { + self.inner + .daybreak + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .is_some_and(|(id, preference)| { + id == goal_id && matches!(preference, GoalDaybreakPreference::AwaitingActivation) + }) + } + + fn daybreak_for_goal(&self, goal_id: &str) -> Option { + let daybreak = self + .inner + .daybreak + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + match daybreak.as_ref()? { + (id, GoalDaybreakPreference::Captured(snapshot)) if id == goal_id => snapshot.clone(), + _ => None, + } + } + + pub(crate) async fn clear_pending_turn_start_options(&self) { + if let Some(thread) = self.live_thread().await { + thread.thread_extension_data().remove::(); } } @@ -492,26 +557,34 @@ impl GoalRuntimeHandle { self.inner.accounting_state.clear_active_goal(); return Ok(()); } - let thread_store = thread.thread_extension_data(); - let captured_program = thread_store - .get::() - .filter(|captured| captured.goal_id == goal.goal_id); + let mut start_options = thread + .thread_extension_data() + .get::() + .map(|options| options.as_ref().clone()) + .unwrap_or_default(); + let selection = self.daybreak_for_goal(&goal.goal_id); let request = continuation_request( &protocol_goal_from_state(goal), thread.config().await.update_plan_enabled, ); - let mut start_options = thread_store - .get::() - .map(|options| options.as_ref().clone()) - .unwrap_or_default(); - if let Some(captured) = captured_program { - start_options.cyber_access_program = captured.program.for_thread(&thread).await; - } + + let snapshot = match selection { + Some(GoalDaybreakSelection::Explicit(captured)) => { + // Keep the existing explicit-program route and its model/provider/owner checks. + start_options.cyber_access_program = captured.for_thread(&thread).await; + None + } + Some(GoalDaybreakSelection::Saved(snapshot)) => Some(snapshot), + None => None, + }; match thread - .start_turn_if_idle(request.on_start(TurnStartOptions { - turn_trigger: Some("goal".to_string()), - ..start_options - })) + .start_goal_turn_if_idle( + request.on_start(TurnStartOptions { + turn_trigger: Some("goal".to_string()), + ..start_options + }), + snapshot, + ) .await { Ok(StartIfIdleSubmission::Started { turn_id, .. }) => { diff --git a/codex-rs/ext/goal/src/tool.rs b/codex-rs/ext/goal/src/tool.rs index 24d3ff2a96..cc11e8488a 100644 --- a/codex-rs/ext/goal/src/tool.rs +++ b/codex-rs/ext/goal/src/tool.rs @@ -1,6 +1,4 @@ -use codex_core::ThreadManager; use std::sync::Arc; -use std::sync::Weak; use codex_extension_api::FunctionCallError; use codex_extension_api::JsonToolOutput; @@ -22,8 +20,8 @@ use crate::analytics::GoalAnalytics; use crate::analytics::GoalEventAttribution; use crate::events::GoalEventEmitter; use crate::metrics::GoalMetrics; +use crate::runtime::GoalDaybreakSelection; use crate::runtime::GoalRuntimeHandle; -use crate::runtime::ToolCreatedGoalProgram; use crate::spec::CREATE_GOAL_TOOL_NAME; use crate::spec::GET_GOAL_TOOL_NAME; use crate::spec::UPDATE_GOAL_TOOL_NAME; @@ -48,10 +46,7 @@ pub(crate) struct GoalToolExecutor { #[derive(Clone)] enum GoalToolKind { Get, - Create { - thread_manager: Weak, - runtime: GoalRuntimeHandle, - }, + Create(GoalRuntimeHandle), Update, } @@ -106,7 +101,6 @@ impl GoalToolExecutor { pub(crate) fn create( runtime: &GoalRuntimeHandle, - thread_manager: Weak, state_db: Arc, analytics: GoalAnalytics, event_emitter: GoalEventEmitter, @@ -114,10 +108,7 @@ impl GoalToolExecutor { max_goal_token_budget: Option, ) -> Self { Self { - kind: GoalToolKind::Create { - thread_manager, - runtime: runtime.clone(), - }, + kind: GoalToolKind::Create(runtime.clone()), execution_allowed: true, thread_id: runtime.thread_id(), state_db, @@ -155,7 +146,7 @@ impl<'call> ToolExecutor> for GoalToolExecutor { fn tool_name(&self) -> ToolName { ToolName::plain(match self.kind { GoalToolKind::Get => GET_GOAL_TOOL_NAME, - GoalToolKind::Create { .. } => CREATE_GOAL_TOOL_NAME, + GoalToolKind::Create(_) => CREATE_GOAL_TOOL_NAME, GoalToolKind::Update => UPDATE_GOAL_TOOL_NAME, }) } @@ -167,7 +158,7 @@ impl<'call> ToolExecutor> for GoalToolExecutor { fn spec(&self) -> ToolSpec { match self.kind { GoalToolKind::Get => create_get_goal_tool(), - GoalToolKind::Create { .. } => create_create_goal_tool(), + GoalToolKind::Create(_) => create_create_goal_tool(), GoalToolKind::Update => create_update_goal_tool(), } } @@ -187,13 +178,7 @@ impl<'call> ToolExecutor> for GoalToolExecutor { } match &self.kind { GoalToolKind::Get => self.handle_get(invocation).await, - GoalToolKind::Create { - thread_manager, - runtime, - } => { - self.handle_create(invocation, thread_manager, runtime) - .await - } + GoalToolKind::Create(runtime) => self.handle_create(invocation, runtime).await, GoalToolKind::Update => self.handle_update(invocation).await, } }) @@ -221,7 +206,6 @@ impl GoalToolExecutor { async fn handle_create( &self, invocation: ToolCall<'_>, - thread_manager: &Weak, runtime: &GoalRuntimeHandle, ) -> Result, FunctionCallError> { let mut request: CreateGoalRequest = parse_arguments(invocation.function_arguments()?)?; @@ -232,11 +216,11 @@ impl GoalToolExecutor { validate_goal_budget(request.token_budget, self.max_goal_token_budget) .map_err(FunctionCallError::RespondToModel)?; - // Keep the captured program in sync with goal creation and external goal mutations. let _goal_state_permit = runtime .goal_state_permit() .await .map_err(FunctionCallError::RespondToModel)?; + let thread = runtime.live_thread().await; let goal = self .state_db .thread_goals() @@ -258,21 +242,19 @@ impl GoalToolExecutor { let turn_id = self .accounting_state .mark_current_turn_goal_active(goal.goal_id.clone()); - if let Some(manager) = thread_manager.upgrade() - && let Ok(thread) = manager.get_thread(self.thread_id).await - { - let thread_store = thread.thread_extension_data(); - if let Some(program) = thread + if let Some(thread) = thread { + let snapshot = if let Some(program) = thread .active_turn_continuation_program(&invocation.turn_id) .await { - thread_store.insert(ToolCreatedGoalProgram { - goal_id: goal.goal_id.clone(), - program, - }); + Some(GoalDaybreakSelection::Explicit(program)) } else { - thread_store.remove::(); - } + thread + .capture_originating_saved_goal_daybreak(&invocation.turn_id) + .await + .map(GoalDaybreakSelection::Saved) + }; + runtime.set_daybreak_snapshot(&goal.goal_id, snapshot); thread .inject_untrusted_context_for_turn( &invocation.turn_id,