Preserve Daybreak selection across automatic goal continuations (#63774)

## What changed

For enrolled threads with Daybreak propagation enabled, carry the
creating turn's explicit access program into automatic continuations
of the same model-created goal. Reuse it only while the account, model,
and provider still match. Editing the objective preserves the selection,
and clearing the goal discards it.

## Testing

App-server regression tests check that automatic continuations honor
enrollment even after an objective edit, that explicit requests retain
their selection regardless of enrollment, and that a replacement goal
created after clearing starts without the previous goal's selection.

GitOrigin-RevId: 346742f6587f14867b1acc9c570383d1fa405d17
This commit is contained in:
eagle-oai
2026-11-25 00:11:12 +00:00
committed by copyberry
parent 17b00277cc
commit 5505daf388
8 changed files with 253 additions and 23 deletions
@@ -26,6 +26,7 @@ use codex_app_server_protocol::ClientInfo;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::CommandExecutionApprovalDecision;
use codex_app_server_protocol::CommandExecutionRequestApprovalResponse;
use codex_app_server_protocol::CyberAccessProgram;
use codex_app_server_protocol::DeprecationNoticeNotification;
use codex_app_server_protocol::FileChangeApprovalDecision;
use codex_app_server_protocol::FileChangeRequestApprovalResponse;
@@ -3945,6 +3946,15 @@ async fn thread_goal_set_edits_objective_without_resetting_usage() -> Result<()>
#[tokio::test]
async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Result<()> {
check_thread_goal_continuation_program(/*enrolled*/ true).await
}
#[tokio::test]
async fn thread_goal_continuation_respects_daybreak_opt_out() -> Result<()> {
check_thread_goal_continuation_program(/*enrolled*/ false).await
}
async fn check_thread_goal_continuation_program(enrolled: bool) -> Result<()> {
let (release_original_turn, original_turn_gate) = oneshot::channel();
let (release_edited_turn, edited_turn_gate) = oneshot::channel();
let (server, _response_completions) = start_streaming_sse_server(vec![
@@ -3982,19 +3992,52 @@ async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Resu
/*total_tokens*/ 100,
),
])),
ungated_goal_response(responses::sse(vec![
responses::ev_response_created("replacement-goal-continuation"),
responses::ev_completed_with_tokens(
"replacement-goal-continuation",
/*total_tokens*/ 100,
),
])),
])
.await;
let codex_home = TempDir::new()?;
mock_responses_config(server.uri())
.enable_feature(Feature::Goals)
.enable_feature(Feature::UntrustedAsToolOutput)
.write(codex_home.path())?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
model = "gpt-5.4"
approval_policy = "never"
openai_base_url = "{}/v1"
cli_auth_credentials_store = "file"
[features]
goals = true
untrusted_as_tool_output = true
daybreak_program_propagation = true
enable_request_compression = false
"#,
server.uri()
),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-test-token").plan_type("pro"),
AuthCredentialsStoreMode::File,
)?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.build_initialized()
.await?;
let thread = mcp.start_thread(ThreadStartParams::default()).await?.thread;
let thread = mcp
.start_thread(ThreadStartParams {
daybreak_program_propagation_enrolled: Some(enrolled),
..Default::default()
})
.await?
.thread;
assert_eq!(thread.daybreak_program_propagation_enrolled, Some(enrolled));
let start_id = mcp
.send_turn_start_request(TurnStartParams {
@@ -4003,6 +4046,7 @@ async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Resu
text: "create the original goal".to_string(),
text_elements: Vec::new(),
}],
cyber_access_program: Some(CyberAccessProgram::DaybreakBlue),
..Default::default()
})
.await?;
@@ -4101,8 +4145,58 @@ async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Resu
.await??;
}
let clear_id = mcp
.send_raw_request("thread/goal/clear", Some(json!({"threadId": thread.id})))
.await?;
let clear: ThreadGoalClearResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(clear_id)).await??;
assert!(clear.cleared);
let replacement_id = mcp
.send_raw_request(
"thread/goal/set",
Some(json!({
"threadId": thread.id,
"objective": "a different goal",
"tokenBudget": 100,
})),
)
.await?;
let replacement: ThreadGoalSetResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(replacement_id)).await??;
assert_eq!(replacement.goal.objective, "a different goal");
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
let requests = server.requests().await;
assert_eq!(requests.len(), 8);
assert_eq!(requests.len(), 9);
// Explicit requests retain their program regardless of enrollment; automatic goal turns
// propagate it only for enrolled threads, including after an objective edit.
let programs = requests
.iter()
.map(|request| {
let body: serde_json::Value = serde_json::from_slice(request)?;
Ok(body["access_programs"]["cyber"].as_str().map(str::to_owned))
})
.collect::<Result<Vec<_>>>()?;
let continuation_program = enrolled.then_some("daybreak_blue");
assert_eq!(
programs.iter().map(Option::as_deref).collect::<Vec<_>>(),
[
Some("daybreak_blue"),
Some("daybreak_blue"),
Some("daybreak_blue"),
None,
continuation_program,
continuation_program,
continuation_program,
continuation_program,
None,
]
);
let reopened_original_request = serde_json::from_slice::<serde_json::Value>(&requests[2])?;
assert_eq!(
reopened_original_request["client_metadata"]["turn_id"].as_str(),
@@ -4132,7 +4226,9 @@ async fn thread_goal_keeps_original_root_until_external_objective_edit() -> Resu
.contains(objective)
);
let mut wire_item = objective.as_object().expect("goal context item").clone();
wire_item.remove("id"); // Generated for each run.
// The snapshot covers the tool output. These fields carry per-run identifiers and timing.
wire_item.remove("id");
wire_item.remove("internal_chat_message_metadata_passthrough");
wire_item.sort_keys();
insta::assert_snapshot!(
"model_written_goal_as_untrusted_tool_output",
+14
View File
@@ -4,6 +4,7 @@ use crate::agent::api::AgentControl;
use crate::config::ConstraintResult;
use crate::context::ContextualUserFragment;
use crate::context::GuardianReviewEvidence;
use crate::cyber_access_program::ContinuationCyberAccessProgram;
use crate::elicitation::ElicitationRegistration;
use crate::session::SessionIo;
use crate::session::SessionSettingsUpdate;
@@ -946,6 +947,19 @@ impl CodexThread {
task.turn_context.turn_metadata_state.root_turn_id()
}
/// Returns the explicit program captured for continuations of the named active turn.
pub async fn active_turn_continuation_program(
&self,
expected_turn_id: &str,
) -> Option<Arc<ContinuationCyberAccessProgram>> {
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 {
return None;
}
task.turn_context.extension_data.get()
}
pub async fn set_app_server_client_info(
&self,
app_server_client_name: Option<String>,
@@ -8,6 +8,8 @@ use codex_protocol::error::Result;
use codex_protocol::turn_input::CyberAccessProgram;
use std::sync::Arc;
pub use crate::session::turn_context::ContinuationCyberAccessProgram;
/// Host requirement for every model request issued by this thread.
///
/// Install in thread extension data before startup and reapply on cold resume.
@@ -1,3 +1,7 @@
mod continuation_cyber_access_program;
pub use continuation_cyber_access_program::ContinuationCyberAccessProgram;
use super::step_settings::ResolvedStepSettings;
use super::token_budget::has_explicit_settings;
use super::token_budget::resolve_token_budget;
@@ -1520,6 +1524,9 @@ impl Session {
turn_context.prompt_cache_ttl = options.prompt_cache_ttl;
turn_context.cyber_access_program =
cyber_access_program::for_provider(&turn_context.config, options.cyber_access_program);
if let Some(program) = ContinuationCyberAccessProgram::capture(self, &turn_context) {
turn_context.extension_data.insert(program);
}
if let Some(admission) = options.helper_admission {
admission.capture_intent(self, &mut turn_context).await;
}
@@ -0,0 +1,61 @@
//! Carry explicit Cyber selection within live work owned by the same account and model.
use super::TurnContext;
use crate::CodexThread;
use crate::agent::helper_daybreak::Enrollment;
use crate::cyber_access_program;
use crate::session::session::Session;
use codex_features::Feature;
use codex_login::AuthOwner;
use codex_model_provider::request_auth_owner;
use codex_protocol::turn_input::CyberAccessProgram;
/// An explicit program captured for a live continuation on the same account and model.
pub struct ContinuationCyberAccessProgram {
program: CyberAccessProgram,
owner: AuthOwner,
model: String,
provider_id: String,
}
impl ContinuationCyberAccessProgram {
pub(super) fn capture(session: &Session, turn: &TurnContext) -> Option<Self> {
session.services.thread_extension_data.get::<Enrollment>()?;
let program = turn.cyber_access_program?;
if !turn
.config
.features
.enabled(Feature::DaybreakProgramPropagation)
{
return None;
}
Some(Self {
program,
owner: request_auth_owner(turn.provider.as_ref())?,
model: turn
.initial_settings
.selected_collaboration_mode()
.model()
.to_string(),
provider_id: turn.config.model_provider_id.clone(),
})
}
/// Reuse the selection only while the current turn configuration still matches its source.
pub async fn for_thread(&self, thread: &CodexThread) -> Option<CyberAccessProgram> {
if !thread.daybreak_program_propagation_enrolled() {
return None;
}
let state = thread.session.state.lock().await;
let current = &state.session_configuration;
let config = &current.original_config_do_not_use;
if !config.features.enabled(Feature::DaybreakProgramPropagation)
|| config.model_provider_id != self.provider_id
|| current.step_settings.collaboration_mode.model() != self.model
|| request_auth_owner(current.provider.as_ref()).as_ref() != Some(&self.owner)
{
return None;
}
cyber_access_program::for_provider(config, Some(self.program))
}
}
+4 -2
View File
@@ -280,7 +280,7 @@ impl GoalService {
};
if let Some(runtime) = runtime.as_ref() {
runtime.clear_pending_turn_start_options().await;
runtime.reset_goal_continuation(Some(&goal.goal_id)).await;
}
if objective.is_some() {
@@ -330,7 +330,9 @@ impl GoalService {
})?;
let cleared = cleared_goal.is_some();
if cleared && let Some(runtime) = runtime.as_ref() {
runtime.clear_pending_turn_start_options().await;
runtime
.reset_goal_continuation(/*remaining_goal_id*/ None)
.await;
}
drop(goal_state_permit);
drop(runtime);
+27 -8
View File
@@ -6,6 +6,7 @@ use std::sync::atomic::Ordering;
use codex_core::StartIfIdleSubmission;
use codex_core::ThreadManager;
use codex_core::TurnStartOptions;
use codex_core::cyber_access_program::ContinuationCyberAccessProgram;
use codex_protocol::ThreadId;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::ThreadGoal;
@@ -62,6 +63,12 @@ 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<ContinuationCyberAccessProgram>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PreviousGoalSnapshot {
pub goal_id: String,
@@ -141,14 +148,21 @@ impl GoalRuntimeHandle {
self.inner.root_accounting_state.clone()
}
pub(crate) async fn clear_pending_turn_start_options(&self) {
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;
};
thread.thread_extension_data().remove::<TurnStartOptions>();
let thread_store = thread.thread_extension_data();
thread_store.remove::<TurnStartOptions>();
if thread_store
.get::<ToolCreatedGoalProgram>()
.is_some_and(|captured| Some(captured.goal_id.as_str()) != remaining_goal_id)
{
thread_store.remove::<ToolCreatedGoalProgram>();
}
}
pub(crate) async fn goal_state_permit(&self) -> Result<SemaphorePermit<'_>, String> {
@@ -478,16 +492,21 @@ impl GoalRuntimeHandle {
self.inner.accounting_state.clear_active_goal();
return Ok(());
}
let start_options = thread
.thread_extension_data()
.get::<TurnStartOptions>()
.map(|options| options.as_ref().clone())
.unwrap_or_default();
let thread_store = thread.thread_extension_data();
let captured_program = thread_store
.get::<ToolCreatedGoalProgram>()
.filter(|captured| captured.goal_id == 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::<TurnStartOptions>()
.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;
}
match thread
.start_turn_if_idle(request.on_start(TurnStartOptions {
turn_trigger: Some("goal".to_string()),
+35 -6
View File
@@ -23,6 +23,7 @@ use crate::analytics::GoalEventAttribution;
use crate::events::GoalEventEmitter;
use crate::metrics::GoalMetrics;
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;
@@ -47,7 +48,10 @@ pub(crate) struct GoalToolExecutor {
#[derive(Clone)]
enum GoalToolKind {
Get,
Create(Weak<ThreadManager>),
Create {
thread_manager: Weak<ThreadManager>,
runtime: GoalRuntimeHandle,
},
Update,
}
@@ -110,7 +114,10 @@ impl GoalToolExecutor {
max_goal_token_budget: Option<i64>,
) -> Self {
Self {
kind: GoalToolKind::Create(thread_manager),
kind: GoalToolKind::Create {
thread_manager,
runtime: runtime.clone(),
},
execution_allowed: true,
thread_id: runtime.thread_id(),
state_db,
@@ -148,7 +155,7 @@ impl<'call> ToolExecutor<ToolCall<'call>> 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,
})
}
@@ -160,7 +167,7 @@ impl<'call> ToolExecutor<ToolCall<'call>> 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(),
}
}
@@ -180,8 +187,12 @@ impl<'call> ToolExecutor<ToolCall<'call>> for GoalToolExecutor {
}
match &self.kind {
GoalToolKind::Get => self.handle_get(invocation).await,
GoalToolKind::Create(thread_manager) => {
self.handle_create(invocation, thread_manager).await
GoalToolKind::Create {
thread_manager,
runtime,
} => {
self.handle_create(invocation, thread_manager, runtime)
.await
}
GoalToolKind::Update => self.handle_update(invocation).await,
}
@@ -211,6 +222,7 @@ impl GoalToolExecutor {
&self,
invocation: ToolCall<'_>,
thread_manager: &Weak<ThreadManager>,
runtime: &GoalRuntimeHandle,
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
let mut request: CreateGoalRequest = parse_arguments(invocation.function_arguments()?)?;
request.objective = request.objective.trim().to_string();
@@ -220,6 +232,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 goal = self
.state_db
.thread_goals()
@@ -244,6 +261,18 @@ impl GoalToolExecutor {
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
.active_turn_continuation_program(&invocation.turn_id)
.await
{
thread_store.insert(ToolCreatedGoalProgram {
goal_id: goal.goal_id.clone(),
program,
});
} else {
thread_store.remove::<ToolCreatedGoalProgram>();
}
thread
.inject_untrusted_context_for_turn(
&invocation.turn_id,