Preserve accepted prompts when turn setup is interrupted (#63523)

## Why

Interrupting a turn during extension setup or Git root discovery could
leave its prompt missing from resumed history. Interrupting a blocking
start hook could also cause the next turn to skip that hook.

## What changed

Run the input hooks and record accepted input before setting up skills
and plugins or resolving diff display roots. Run those setup steps
concurrently and cancel diff root discovery when the turn is cancelled.

Keep each start hook event queued until its outcome has been handled so
the next turn can retry it after forced teardown. If cancellation has
already been requested, defer events with matching synchronous hooks
while still processing events that match only asynchronous hooks.

## Testing

Add regression coverage for resuming with the interrupted prompt and
the turn-aborted marker, retrying a blocking start hook after
interruption, and handling synchronous and asynchronous hook matches on
a cancelled turn.

GitOrigin-RevId: 7ee1ca6a099f6af65aa0074897af51963b9cdca7
This commit is contained in:
Eric Traut
2026-11-24 03:53:31 +00:00
committed by copyberry
parent 9ba0ceac1a
commit 98835f5eba
6 changed files with 212 additions and 56 deletions
+20 -5
View File
@@ -58,6 +58,7 @@ use codex_utils_absolute_path::AbsolutePathBuf;
use serde_json::Map;
use serde_json::Value;
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use tracing::instrument;
use crate::context::ContextualUserFragment;
@@ -133,8 +134,9 @@ impl From<UserPromptSubmitOutcome> for ContextInjectingHookOutcome {
pub(crate) async fn run_pending_session_start_hooks(
sess: &Arc<Session>,
turn_context: &Arc<TurnContext>,
cancellation_token: &CancellationToken,
) -> bool {
while let Some(session_start_source) = sess.take_pending_session_start_source().await {
while let Some(session_start_source) = sess.pending_session_start_source().await {
// Spawned subagents can start fresh or fork their parent's history, so both
// sources dispatch SubagentStart. Internal/system subagents skip start hooks.
let target = match &turn_context.session_source {
@@ -152,7 +154,10 @@ pub(crate) async fn run_pending_session_start_hooks(
agent_type: context.agent_type,
}
}
SessionSource::SubAgent(_) => return false,
SessionSource::SubAgent(_) => {
sess.take_pending_session_start_source().await;
return false;
}
_ => StartHookTarget::SessionStart {
source: session_start_source,
},
@@ -172,7 +177,16 @@ pub(crate) async fn run_pending_session_start_hooks(
&turn_context.initial_environments.refresh_readiness(),
);
let preview_runs = hooks.preview_session_start(&request);
if run_context_injecting_hook(
if cancellation_token.is_cancelled()
&& preview_runs
.iter()
.any(|run| run.execution_mode == HookExecutionMode::Sync)
{
return true;
}
// Only the running turn consumes sources. Keep this one queued until
// its outcome is handled so forced teardown cannot skip a blocking hook.
let should_stop = run_context_injecting_hook(
sess,
turn_context,
preview_runs,
@@ -180,8 +194,9 @@ pub(crate) async fn run_pending_session_start_hooks(
)
.await
.record_additional_contexts(sess, turn_context)
.await
{
.await;
sess.take_pending_session_start_source().await;
if should_stop {
return true;
}
}
+11
View File
@@ -6249,6 +6249,17 @@ impl Session {
Some(rollout_path)
}
pub(crate) async fn pending_session_start_source(
&self,
) -> Option<codex_hooks::SessionStartSource> {
self.state
.lock()
.await
.pending_session_start_sources
.front()
.copied()
}
pub(crate) async fn take_pending_session_start_source(
&self,
) -> Option<codex_hooks::SessionStartSource> {
+44
View File
@@ -1840,6 +1840,50 @@ async fn reload_user_config_layer_updates_base_and_selected_profile_layers() {
);
}
#[test_case("startup", true; "sync and async hooks match")]
#[test_case("resume", false; "only async hook matches")]
#[tokio::test]
async fn cancelled_turn_defers_only_blocking_session_start_hooks(
sync_matcher: &str,
deferred: bool,
) -> anyhow::Result<()> {
let session = make_session_with_config(|config| {
config.bypass_hook_trust = true;
config.features.enable(Feature::CodexHooks).unwrap();
config.config_layer_stack = config
.config_layer_stack
.with_user_config(
&config.codex_home.join(CONFIG_TOML_FILE),
toml::from_str(&format!(
r#"[[hooks.SessionStart]]
matcher = "startup"
hooks = [{{ type = "command", command = "echo async", async = true }}]
[[hooks.SessionStart]]
matcher = "{sync_matcher}"
hooks = [{{ type = "command", command = "echo startup" }}]
"#
))
.unwrap(),
)
.unwrap();
})
.await?;
let turn = session.new_default_turn().await;
let cancellation = tokio_util::sync::CancellationToken::new();
cancellation.cancel();
assert_eq!(
crate::hook_runtime::run_pending_session_start_hooks(&session, &turn, &cancellation).await,
deferred
);
assert_eq!(
session.pending_session_start_source().await.is_some(),
deferred
);
Ok(())
}
#[tokio::test]
async fn reload_user_config_layer_refreshes_hooks() -> anyhow::Result<()> {
let session = make_session_with_config(|config| {
+51 -45
View File
@@ -376,53 +376,15 @@ pub(crate) async fn run_turn(
}
Err(err) => return Err(err),
};
// Record initial context while preparing diff display roots.
let (record_context, display_roots) = tokio::join!(
preserve_initial_input_during(
&sess,
&turn_context,
&mut input,
sess.record_context_updates_and_set_reference_context_item(first_step_context.as_ref()),
),
async {
// Guardian must not wait for remote Git discovery just to display diff paths.
if crate::guardian::is_basic_session_source(&turn_context.session_source)
|| first_step_context
.turn
.config
.features
.enabled(Feature::CwdRelativeTurnDiffs)
{
first_step_context
.environments
.turn_environments()
.map(|environment| {
(
environment.selection().environment_id,
environment.cwd().clone(),
)
})
.collect()
} else {
turn_diff_display_roots(first_step_context.as_ref()).await
}
},
);
let mut world_state = record_context??;
let Some((injection_items, explicitly_enabled_connectors)) = build_skills_and_plugins(
let mut world_state = preserve_initial_input_during(
&sess,
first_step_context.as_ref(),
&user_input,
&mentioned_plugins,
&cancellation_token,
&turn_context,
&mut input,
sess.record_context_updates_and_set_reference_context_item(first_step_context.as_ref()),
)
.await
else {
return Ok(None);
};
.await??;
if run_pending_session_start_hooks(&sess, &turn_context).await {
if run_pending_session_start_hooks(&sess, &turn_context, &cancellation_token).await {
// A queued steer can reuse this turn context after the initial input is discarded.
turn_context
.extension_data
@@ -496,6 +458,24 @@ pub(crate) async fn run_turn(
turn_context.session_telemetry.user_prompt(&user_input);
}
// Neither extension setup nor diff path discovery should delay recording accepted input.
let (extensions, display_roots) = tokio::join!(
build_skills_and_plugins(
&sess,
first_step_context.as_ref(),
&user_input,
&mentioned_plugins,
&cancellation_token,
),
cancellation_token
.run_until_cancelled(turn_diff_display_roots(first_step_context.as_ref())),
);
let (Some((injection_items, explicitly_enabled_connectors)), Some(display_roots)) =
(extensions, display_roots)
else {
return Ok(None);
};
// Only speculate after hooks accept the turn, using its finalized tools and permissions.
{
let mut state = sess.state.lock().await;
@@ -839,7 +819,13 @@ pub(crate) async fn run_turn(
.await;
match compacted {
Ok(true) => {
if run_pending_session_start_hooks(&sess, &turn_context).await {
if run_pending_session_start_hooks(
&sess,
&turn_context,
&cancellation_token,
)
.await
{
return Ok(None);
}
// After interrupted sampling, drain pending input even if compaction
@@ -1149,6 +1135,26 @@ impl TurnCompletionHooks {
#[instrument(level = "trace", skip_all)]
async fn turn_diff_display_roots(step_context: &StepContext) -> Vec<(String, PathUri)> {
// Guardian must not wait for remote Git discovery just to display diff paths.
if crate::guardian::is_basic_session_source(&step_context.turn.session_source)
|| step_context
.turn
.config
.features
.enabled(Feature::CwdRelativeTurnDiffs)
{
return step_context
.environments
.turn_environments()
.map(|environment| {
(
environment.selection().environment_id,
environment.cwd().clone(),
)
})
.collect();
}
let mut display_roots = Vec::new();
for turn_environment in step_context.environments.turn_environments() {
let cwd = turn_environment.cwd();
+16
View File
@@ -1516,6 +1516,21 @@ print(json.dumps({{"continue": False}}))
// SessionStart must run the Python hook installed in the host test home.
.build(&server)
.await?;
// Force teardown while the hook is running. The next turn must retry it.
test.codex
.start_turn_if_idle(TurnInputRequest::user_input(vec![UserInput::Text {
text: "interrupted prompt".to_owned(),
text_elements: Vec::new(),
}]))
.await?;
let (interrupted_hook, _) = timeout(Duration::from_secs(10), hook_gate.accept()).await??;
test.codex.submit(Op::Interrupt).await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnAborted(_))
})
.await;
drop(interrupted_hook);
let context = BTreeMap::from([(
"continuation".to_owned(),
AdditionalContextEntry::new(
@@ -1560,6 +1575,7 @@ print(json.dumps({{"continue": False}}))
let texts = requests[0].message_input_texts("user");
assert!(texts.iter().any(|text| text == "queued steer"));
assert!(!texts.iter().any(|text| text == "stopped prompt"));
assert!(!texts.iter().any(|text| text == "interrupted prompt"));
assert!(!requests[0].has_content_kinds(&["additional_content.continuation"]));
assert!(requests[1].has_content_kinds(&["additional_content.continuation"]));
Ok(())
@@ -26,6 +26,7 @@ use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EnvironmentConfigState;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::user_input::UserInput;
use codex_skills_extension::SkillsExtensionConfig;
@@ -49,12 +50,16 @@ use core_test_support::test_codex::turn_permission_fields;
use core_test_support::wait_for_event;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::sync::Notify;
const PRETURN_CONTEXT_DIFF_CWD: &str = "PRETURN_CONTEXT_DIFF_CWD";
struct RecordingTurnInputContributor(Arc<Mutex<Vec<RecordedTurnInputEnvironment>>>);
enum TestTurnInputContributor {
RecordEnvironments(Arc<Mutex<Vec<RecordedTurnInputEnvironment>>>),
Block(Arc<Notify>),
}
impl TurnInputContributor for RecordingTurnInputContributor {
impl TurnInputContributor for TestTurnInputContributor {
fn contribute<'a>(
&'a self,
input: TurnInputContext<'a>,
@@ -64,7 +69,15 @@ impl TurnInputContributor for RecordingTurnInputContributor {
_turn_store: &'a ExtensionData,
) -> ExtensionFuture<'a, Vec<Box<dyn ContextualUserFragment + Send>>> {
Box::pin(async move {
let mut recorded_environments = self.0.lock().expect("recorded environments lock");
let environments = match self {
Self::RecordEnvironments(environments) => environments,
Self::Block(started) => {
started.notify_one();
return std::future::pending().await;
}
};
let mut recorded_environments =
environments.lock().expect("recorded environments lock");
for environment in input.environments {
recorded_environments.push(RecordedTurnInputEnvironment {
environment_id: environment.environment_id,
@@ -165,9 +178,9 @@ async fn turn_input_contributors_receive_foreign_environment_cwds() -> Result<()
.await;
let recorded_environments = Arc::new(Mutex::new(Vec::new()));
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
extensions.turn_input_contributor(Arc::new(RecordingTurnInputContributor(Arc::clone(
&recorded_environments,
))));
extensions.turn_input_contributor(Arc::new(TestTurnInputContributor::RecordEnvironments(
Arc::clone(&recorded_environments),
)));
let mut builder = test_codex()
.with_extensions(Arc::new(extensions.build()))
.with_config(|config| config.project_doc_max_bytes = 0);
@@ -203,6 +216,57 @@ async fn turn_input_contributors_receive_foreign_environment_cwds() -> Result<()
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn interrupt_during_extension_setup_preserves_prompt_on_resume() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let response = mount_sse_once(
&server,
sse(vec![ev_response_created("resume"), ev_completed("resume")]),
)
.await;
let started = Arc::new(Notify::new());
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
extensions.turn_input_contributor(Arc::new(TestTurnInputContributor::Block(Arc::clone(
&started,
))));
let initial = test_codex()
.with_extensions(Arc::new(extensions.build()))
.build_with_auto_env(&server)
.await?;
let prompt = "Investigate the failing login test";
initial
.codex
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: prompt.into(),
text_elements: Vec::new(),
}]))
.await?;
started.notified().await;
initial.codex.submit(Op::Interrupt).await?;
wait_for_event(&initial.codex, |event| {
matches!(event, EventMsg::TurnAborted(_))
})
.await;
let resumed = test_codex()
.restart_with_auto_env(&server, &initial)
.await?;
let follow_up = "Just explain the cause";
resumed.submit_text_turn(follow_up).await?;
let messages = response.single_request().message_input_texts("user");
let expected = [prompt, "<turn_aborted>", follow_up];
let history = messages
.iter()
.filter_map(|text| text.lines().next())
.filter(|line| expected.contains(line))
.collect::<Vec<_>>();
assert_eq!(history, expected);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn model_visible_environment_context_preserves_foreign_workspace_roots() -> Result<()> {
skip_if_no_network!(Ok(()));