[core] Support durable external thread goals

This commit is contained in:
Adam Van Ymeren
2026-06-27 21:11:14 -07:00
parent dd4ce5314b
commit c4fe2bdf11
9 changed files with 636 additions and 8 deletions
+227
View File
@@ -810,6 +810,13 @@ mod tests {
use codex_app_server_protocol::ConfigRequirementsReadResponse;
use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification;
use codex_app_server_protocol::SessionSource as ApiSessionSource;
use codex_app_server_protocol::ThreadGoal;
use codex_app_server_protocol::ThreadGoalClearParams;
use codex_app_server_protocol::ThreadGoalClearResponse;
use codex_app_server_protocol::ThreadGoalGetParams;
use codex_app_server_protocol::ThreadGoalGetResponse;
use codex_app_server_protocol::ThreadGoalSetParams;
use codex_app_server_protocol::ThreadGoalSetResponse;
use codex_app_server_protocol::ThreadListParams;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
@@ -818,7 +825,9 @@ mod tests {
use codex_app_server_protocol::TurnItemsView;
use codex_app_server_protocol::TurnStatus;
use codex_core::config::ConfigBuilder;
use codex_state::StateRuntime;
use codex_thread_store::InMemoryThreadStore;
use codex_thread_store::ThreadStore;
use pretty_assertions::assert_eq;
use std::path::Path;
use tempfile::TempDir;
@@ -988,6 +997,224 @@ mod tests {
.expect("in-process runtime should shutdown cleanly");
}
#[tokio::test]
async fn external_goal_store_allows_goals_for_rolloutless_threads() {
let codex_home = TempDir::new().expect("temp dir");
std::fs::write(
codex_home.path().join("config.toml"),
"[features]\ngoals = true\n",
)
.expect("write goals config");
let config = Arc::new(build_test_config(codex_home.path()).await);
let state_db = StateRuntime::init(
codex_home.path().join("sqlite"),
config.model_provider_id.clone(),
)
.await
.expect("state db should initialize");
let thread_store = Arc::new(InMemoryThreadStore::with_external_thread_goal_state(
state_db,
));
let args = InProcessStartArgs {
arg0_paths: Arg0DispatchPaths::default(),
config,
cli_overrides: Vec::new(),
loader_overrides: LoaderOverrides::default(),
strict_config: false,
cloud_config_bundle: CloudConfigBundleLoader::default(),
thread_config_loader: Arc::new(codex_config::NoopThreadConfigLoader),
feedback: CodexFeedback::new(),
log_db: None,
state_db: None,
environment_manager: Arc::new(EnvironmentManager::default_for_tests()),
config_warnings: Vec::new(),
session_source: SessionSource::Cli,
enable_codex_api_key_env: false,
initialize: InitializeParams {
client_info: ClientInfo {
name: "codex-in-process-test".to_string(),
title: None,
version: "0.0.0".to_string(),
},
capabilities: None,
},
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
};
let mut client = start_with_options(
args,
InProcessStartOptions::default().with_thread_store(thread_store.clone()),
)
.await
.expect("in-process runtime should start");
client._test_codex_home = Some(codex_home);
let response = client
.request(ClientRequest::ThreadStart {
request_id: RequestId::Integer(4),
params: ThreadStartParams::default(),
})
.await
.expect("request transport should work")
.expect("thread/start should succeed");
let started: ThreadStartResponse =
serde_json::from_value(response).expect("thread/start response should parse");
let thread_id = started.thread.id;
let response = client
.request(ClientRequest::ThreadGoalSet {
request_id: RequestId::Integer(5),
params: ThreadGoalSetParams {
thread_id: thread_id.clone(),
objective: Some("Finish the external goal".to_string()),
status: None,
token_budget: Some(Some(321)),
},
})
.await
.expect("request transport should work")
.expect("external goal store should accept goal/set");
let set: ThreadGoalSetResponse =
serde_json::from_value(response).expect("goal/set response should parse");
assert_eq!(set.goal.objective, "Finish the external goal");
assert_eq!(set.goal.token_budget, Some(321));
let persisted = thread_store
.load_external_thread_goal(
codex_protocol::ThreadId::from_string(thread_id.as_str())
.expect("thread id should parse"),
)
.await
.expect("external goal should load")
.expect("goal snapshot should be durable");
assert_eq!(persisted.objective, "Finish the external goal");
let response = client
.request(ClientRequest::ThreadGoalGet {
request_id: RequestId::Integer(6),
params: ThreadGoalGetParams {
thread_id: thread_id.clone(),
},
})
.await
.expect("request transport should work")
.expect("external goal store should accept goal/get");
let get: ThreadGoalGetResponse =
serde_json::from_value(response).expect("goal/get response should parse");
assert_eq!(
get.goal.map(|goal: ThreadGoal| goal.objective),
Some("Finish the external goal".to_string())
);
let response = client
.request(ClientRequest::ThreadGoalClear {
request_id: RequestId::Integer(7),
params: ThreadGoalClearParams {
thread_id: thread_id.clone(),
},
})
.await
.expect("request transport should work")
.expect("external goal store should accept goal/clear");
let clear: ThreadGoalClearResponse =
serde_json::from_value(response).expect("goal/clear response should parse");
assert!(clear.cleared);
let response = client
.request(ClientRequest::ThreadGoalGet {
request_id: RequestId::Integer(8),
params: ThreadGoalGetParams { thread_id },
})
.await
.expect("request transport should work")
.expect("external goal store should accept cleared goal/get");
let get: ThreadGoalGetResponse =
serde_json::from_value(response).expect("goal/get response should parse");
assert_eq!(get.goal, None);
client
.shutdown()
.await
.expect("in-process runtime should shutdown cleanly");
}
#[tokio::test]
async fn rolloutless_thread_without_external_goal_opt_in_stays_ephemeral() {
let codex_home = TempDir::new().expect("temp dir");
std::fs::write(
codex_home.path().join("config.toml"),
"[features]\ngoals = true\n",
)
.expect("write goals config");
let config = Arc::new(build_test_config(codex_home.path()).await);
let thread_store = Arc::new(InMemoryThreadStore::default());
let args = InProcessStartArgs {
arg0_paths: Arg0DispatchPaths::default(),
config,
cli_overrides: Vec::new(),
loader_overrides: LoaderOverrides::default(),
strict_config: false,
cloud_config_bundle: CloudConfigBundleLoader::default(),
thread_config_loader: Arc::new(codex_config::NoopThreadConfigLoader),
feedback: CodexFeedback::new(),
log_db: None,
state_db: None,
environment_manager: Arc::new(EnvironmentManager::default_for_tests()),
config_warnings: Vec::new(),
session_source: SessionSource::Cli,
enable_codex_api_key_env: false,
initialize: InitializeParams {
client_info: ClientInfo {
name: "codex-in-process-test".to_string(),
title: None,
version: "0.0.0".to_string(),
},
capabilities: None,
},
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
};
let mut client = start_with_options(
args,
InProcessStartOptions::default().with_thread_store(thread_store),
)
.await
.expect("in-process runtime should start");
client._test_codex_home = Some(codex_home);
let response = client
.request(ClientRequest::ThreadStart {
request_id: RequestId::Integer(9),
params: ThreadStartParams::default(),
})
.await
.expect("request transport should work")
.expect("thread/start should succeed");
let started: ThreadStartResponse =
serde_json::from_value(response).expect("thread/start response should parse");
let error = client
.request(ClientRequest::ThreadGoalGet {
request_id: RequestId::Integer(10),
params: ThreadGoalGetParams {
thread_id: started.thread.id,
},
})
.await
.expect("request transport should work")
.expect_err("rolloutless thread without opt-in should reject goals");
assert!(
error
.message
.contains("ephemeral thread does not support goals"),
"unexpected goal/get error: {}",
error.message
);
client
.shutdown()
.await
.expect("in-process runtime should shutdown cleanly");
}
async fn saturated_warning_shutdown(event_delivery: InProcessEventDelivery) -> Vec<String> {
let (codex_home, mut args) =
build_test_start_args(SessionSource::Cli, /*channel_capacity*/ 1).await;
@@ -340,6 +340,9 @@ impl MessageProcessor {
let thread_store = thread_store.unwrap_or_else(|| {
codex_core::thread_store_from_config(config.as_ref(), state_db.clone())
});
// External durable stores can own the same SQLite projection/runtime used by goal
// extensions without exposing a local rollout path.
let state_db = thread_store.state_db_handle().or(state_db);
let environment_manager_for_requests = Arc::clone(&environment_manager);
let environment_manager_for_extensions = Arc::clone(&environment_manager);
let restriction_product = session_source.restriction_product();
@@ -483,6 +486,7 @@ impl MessageProcessor {
thread_state_manager.clone(),
state_db.clone(),
Arc::clone(&goal_service),
Arc::clone(&thread_store),
);
let thread_processor = ThreadRequestProcessor::new(
auth_manager.clone(),
@@ -13,6 +13,7 @@ pub(crate) struct ThreadGoalRequestProcessor {
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
goal_service: Arc<GoalService>,
thread_store: Arc<dyn ThreadStore>,
}
impl ThreadGoalRequestProcessor {
@@ -23,6 +24,7 @@ impl ThreadGoalRequestProcessor {
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
goal_service: Arc<GoalService>,
thread_store: Arc<dyn ThreadStore>,
) -> Self {
Self {
thread_manager,
@@ -31,6 +33,7 @@ impl ThreadGoalRequestProcessor {
thread_state_manager,
state_db,
goal_service,
thread_store,
}
}
@@ -91,6 +94,18 @@ impl ThreadGoalRequestProcessor {
} else {
None
};
if self.thread_store.supports_external_thread_goal_state()
&& let Some(state_db) = thread_goal_state_db.as_ref()
&& let Err(err) = self
.hydrate_external_thread_goal(thread.session_configured().thread_id, state_db)
.await
{
warn!(
"failed to restore external thread goal before running resume snapshot for {}: {}",
thread.session_configured().thread_id,
err.message
);
}
(emit_thread_goal_update, thread_goal_state_db)
}
@@ -134,6 +149,8 @@ impl ThreadGoalRequestProcessor {
)
.await
.map_err(goal_service_error)?;
self.persist_external_thread_goal_if_supported(thread_id, Some(outcome.goal.clone()))
.await?;
let goal = ThreadGoal::from(outcome.goal.clone());
let persist_result = match self.thread_manager.get_thread(thread_id).await {
@@ -172,6 +189,10 @@ impl ThreadGoalRequestProcessor {
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
if self.thread_store.supports_external_thread_goal_state() {
self.hydrate_external_thread_goal(thread_id, &state_db)
.await?;
}
let goal = self
.goal_service
.get_thread_goal(&state_db, thread_id)
@@ -205,6 +226,10 @@ impl ThreadGoalRequestProcessor {
.clear_thread_goal(&state_db, thread_id)
.await
.map_err(goal_service_error)?;
if cleared {
self.persist_external_thread_goal_if_supported(thread_id, None)
.await?;
}
self.outgoing
.send_response(request_id, ThreadGoalClearResponse { cleared })
@@ -220,8 +245,9 @@ impl ThreadGoalRequestProcessor {
&self,
thread_id: ThreadId,
) -> Result<StateDbHandle, JSONRPCErrorError> {
let external_goal_state = self.thread_store.supports_external_thread_goal_state();
if let Ok(thread) = self.thread_manager.get_thread(thread_id).await {
if thread.rollout_path().is_none() {
if thread.rollout_path().is_none() && !external_goal_state {
return Err(invalid_request(format!(
"ephemeral thread does not support goals: {thread_id}"
)));
@@ -229,6 +255,15 @@ impl ThreadGoalRequestProcessor {
if let Some(state_db) = thread.state_db() {
return Ok(state_db);
}
} else if external_goal_state {
self.thread_store
.read_thread(StoreReadThreadParams {
thread_id,
include_archived: true,
include_history: false,
})
.await
.map_err(external_thread_goal_store_error)?;
} else {
codex_rollout::find_thread_path_by_id_str(
&self.config.codex_home,
@@ -252,6 +287,9 @@ impl ThreadGoalRequestProcessor {
thread_id: ThreadId,
state_db: &StateDbHandle,
) -> Result<(), JSONRPCErrorError> {
if self.thread_store.supports_external_thread_goal_state() {
return self.hydrate_external_thread_goal(thread_id, state_db).await;
}
let running_thread = self.thread_manager.get_thread(thread_id).await.ok();
let rollout_path = match running_thread.as_ref() {
Some(thread) => thread.rollout_path().ok_or_else(|| {
@@ -283,6 +321,74 @@ impl ThreadGoalRequestProcessor {
Ok(())
}
async fn hydrate_external_thread_goal(
&self,
thread_id: ThreadId,
state_db: &StateDbHandle,
) -> Result<(), JSONRPCErrorError> {
let external_goal = self
.thread_store
.load_external_thread_goal(thread_id)
.await
.map_err(external_thread_goal_store_error)?;
let local_goal = state_db
.thread_goals()
.get_thread_goal(thread_id)
.await
.map_err(|err| internal_error(format!("failed to read local thread goal: {err}")))?;
match external_goal {
Some(external_goal) => {
if external_goal.thread_id != thread_id {
return Err(internal_error(format!(
"external thread goal snapshot has mismatched thread id: expected {thread_id}, got {}",
external_goal.thread_id
)));
}
if local_goal.as_ref().is_some_and(|local_goal| {
protocol_thread_goal_from_state(local_goal) == external_goal
}) {
return Ok(());
}
state_db
.thread_goals()
.restore_thread_goal(&external_goal)
.await
.map_err(|err| {
internal_error(format!("failed to restore external thread goal: {err}"))
})?;
}
None => {
if local_goal.is_some() {
state_db
.thread_goals()
.delete_thread_goal(thread_id)
.await
.map_err(|err| {
internal_error(format!(
"failed to apply external thread goal clear: {err}"
))
})?;
}
}
}
Ok(())
}
async fn persist_external_thread_goal_if_supported(
&self,
thread_id: ThreadId,
goal: Option<codex_protocol::protocol::ThreadGoal>,
) -> Result<(), JSONRPCErrorError> {
if !self.thread_store.supports_external_thread_goal_state() {
return Ok(());
}
self.thread_store
.persist_external_thread_goal(thread_id, goal)
.await
.map_err(external_thread_goal_store_error)
}
async fn emit_thread_goal_snapshot(&self, thread_id: ThreadId) {
let state_db = match self.state_db_for_materialized_thread(thread_id).await {
Ok(state_db) => state_db,
@@ -294,6 +400,17 @@ impl ThreadGoalRequestProcessor {
return;
}
};
if self.thread_store.supports_external_thread_goal_state()
&& let Err(err) = self
.hydrate_external_thread_goal(thread_id, &state_db)
.await
{
warn!(
"failed to restore external thread goal before emitting resume snapshot for {thread_id}: {}",
err.message
);
return;
}
let listener_command_tx = {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
let thread_state = thread_state.lock().await;
@@ -366,6 +483,55 @@ impl ThreadGoalRequestProcessor {
}
}
fn external_thread_goal_store_error(err: ThreadStoreError) -> JSONRPCErrorError {
match err {
ThreadStoreError::ThreadNotFound { thread_id } => {
invalid_request(format!("thread not found: {thread_id}"))
}
ThreadStoreError::InvalidRequest { message } => invalid_request(message),
ThreadStoreError::Unsupported { operation } => internal_error(format!(
"external thread goal store does not support {operation}"
)),
ThreadStoreError::Conflict { message } | ThreadStoreError::Internal { message } => {
internal_error(format!("external thread goal store failed: {message}"))
}
}
}
fn protocol_thread_goal_from_state(
goal: &codex_state::ThreadGoal,
) -> codex_protocol::protocol::ThreadGoal {
codex_protocol::protocol::ThreadGoal {
thread_id: goal.thread_id,
objective: goal.objective.clone(),
status: match goal.status {
codex_state::ThreadGoalStatus::Active => {
codex_protocol::protocol::ThreadGoalStatus::Active
}
codex_state::ThreadGoalStatus::Paused => {
codex_protocol::protocol::ThreadGoalStatus::Paused
}
codex_state::ThreadGoalStatus::Blocked => {
codex_protocol::protocol::ThreadGoalStatus::Blocked
}
codex_state::ThreadGoalStatus::UsageLimited => {
codex_protocol::protocol::ThreadGoalStatus::UsageLimited
}
codex_state::ThreadGoalStatus::BudgetLimited => {
codex_protocol::protocol::ThreadGoalStatus::BudgetLimited
}
codex_state::ThreadGoalStatus::Complete => {
codex_protocol::protocol::ThreadGoalStatus::Complete
}
},
token_budget: goal.token_budget,
tokens_used: goal.tokens_used,
time_used_seconds: goal.time_used_seconds,
created_at: goal.created_at.timestamp(),
updated_at: goal.updated_at.timestamp(),
}
}
pub(super) fn api_thread_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal {
ThreadGoal {
thread_id: goal.thread_id.to_string(),