File size: 14,528 Bytes
52a9af3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | use super::*;
use async_channel::bounded;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::ThreadLifecycleContributor;
use codex_extension_api::ThreadStartInput;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::McpStartupCompleteEvent;
use codex_protocol::protocol::McpStartupStatus;
use codex_protocol::protocol::McpStartupUpdateEvent;
use codex_protocol::protocol::RawResponseItemEvent;
use codex_protocol::protocol::TurnAbortReason;
use codex_protocol::protocol::TurnAbortedEvent;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use tokio::sync::watch;
use tokio::time::timeout;
struct ThreadStartRecorder(Arc<AtomicUsize>);
impl ThreadLifecycleContributor<Config> for ThreadStartRecorder {
fn on_thread_start<'a>(
&'a self,
_input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
self.0.fetch_add(1, Ordering::SeqCst);
Box::pin(std::future::ready(()))
}
}
#[tokio::test]
async fn forward_events_filters_private_events_before_blocked_send_is_cancelled() {
let (tx_events, rx_events) = bounded(SUBMISSION_CHANNEL_CAPACITY);
let (tx_sub, rx_sub) = bounded(SUBMISSION_CHANNEL_CAPACITY);
let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit);
let io = Arc::new(SessionIo {
tx_sub,
rx_event: rx_events,
agent_status,
session_loop_termination: completed_session_loop_termination(),
});
let (tx_out, rx_out) = bounded(1);
tx_out
.send(Event {
id: "full".to_string(),
msg: EventMsg::TurnAborted(TurnAbortedEvent {
turn_id: Some("turn-1".to_string()),
started_at: None,
reason: TurnAbortReason::Interrupted,
completed_at: None,
duration_ms: None,
}),
})
.await
.unwrap();
let cancel = CancellationToken::new();
let forward = tokio::spawn(forward_events(
Arc::clone(&io),
tx_out.clone(),
cancel.clone(),
));
for msg in [
EventMsg::McpStartupUpdate(McpStartupUpdateEvent {
server: "pending".to_string(),
status: McpStartupStatus::Starting,
}),
EventMsg::McpStartupComplete(McpStartupCompleteEvent::default()),
] {
tx_events
.send(Event {
id: "delegate-startup".to_string(),
msg,
})
.await
.unwrap();
}
let visible_msg = EventMsg::RawResponseItem(RawResponseItemEvent {
item: ResponseItem::CustomToolCall {
id: None,
status: None,
call_id: "call-1".to_string(),
name: "tool".to_string(),
namespace: None,
input: "{}".to_string(),
internal_chat_message_metadata_passthrough: None,
},
});
for id in ["visible-1", "visible-2", "blocked"] {
tx_events
.send(Event {
id: id.to_string(),
msg: visible_msg.clone(),
})
.await
.unwrap();
}
drop(tx_events);
let received = rx_out.recv().await.expect("prefilled event missing");
assert_eq!(received.id, "full");
let received = rx_out.recv().await.expect("visible event missing");
assert_eq!(received.id, "visible-1");
cancel.cancel();
timeout(std::time::Duration::from_millis(1000), forward)
.await
.expect("forward_events hung")
.expect("forward_events join error");
let mut ops = Vec::new();
while let Ok(sub) = rx_sub.try_recv() {
ops.push(sub.op);
}
assert!(
ops.iter().any(|op| matches!(op, Op::Interrupt)),
"expected Interrupt op after cancellation"
);
assert!(
ops.iter().any(|op| matches!(op, Op::Shutdown)),
"expected Shutdown op after cancellation"
);
}
#[tokio::test]
async fn forward_ops_preserves_submission_trace_context() {
let (tx_sub, rx_sub) = bounded(SUBMISSION_CHANNEL_CAPACITY);
let (_tx_events, rx_events) = bounded(SUBMISSION_CHANNEL_CAPACITY);
let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit);
let io = Arc::new(SessionIo {
tx_sub,
rx_event: rx_events,
agent_status,
session_loop_termination: completed_session_loop_termination(),
});
let (tx_ops, rx_ops) = bounded(1);
let cancel = CancellationToken::new();
let forward = tokio::spawn(forward_ops(Arc::clone(&io), rx_ops, cancel));
let submission = Submission {
id: "sub-1".to_string(),
op: Op::Interrupt,
trace: Some(codex_protocol::protocol::W3cTraceContext {
traceparent: Some(
"00-1234567890abcdef1234567890abcdef-1234567890abcdef-01".to_string(),
),
tracestate: Some("vendor=state".to_string()),
}),
parent_turn_id: Some("parent-turn".to_string()),
root_turn_id: Some("root-turn".to_string()),
};
tx_ops.send(submission).await.unwrap();
drop(tx_ops);
let forwarded = timeout(Duration::from_secs(1), rx_sub.recv())
.await
.expect("forward_ops hung")
.expect("forwarded submission missing");
assert_eq!("sub-1", forwarded.id);
assert!(matches!(forwarded.op, Op::Interrupt));
assert_eq!(
forwarded.trace,
Some(codex_protocol::protocol::W3cTraceContext {
traceparent: Some(
"00-1234567890abcdef1234567890abcdef-1234567890abcdef-01".to_string(),
),
tracestate: Some("vendor=state".to_string()),
})
);
assert_eq!(Some("parent-turn".to_string()), forwarded.parent_turn_id);
timeout(Duration::from_secs(1), forward)
.await
.expect("forward_ops did not exit")
.expect("forward_ops join error");
}
#[tokio::test]
async fn run_codex_thread_interactive_respects_pre_cancelled_spawn() {
let (parent_session, parent_ctx, _rx_events) =
crate::session::tests::make_session_and_context_with_rx().await;
let mut config = parent_ctx.config.as_ref().clone();
config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never);
let cancel_token = CancellationToken::new();
cancel_token.cancel();
let parent_environments = parent_ctx.environments.clone();
let result = timeout(
Duration::from_secs(/*secs*/ 1),
run_codex_thread_interactive(
config,
Arc::clone(&parent_session.services.auth_manager),
Arc::clone(&parent_session.services.models_manager),
parent_session,
parent_ctx,
parent_environments,
cancel_token,
SubAgentSource::Review,
codex_extension_api::SessionIsolation::Inherit,
/*initial_history*/ None,
crate::session::GitEnrichmentPolicy::Fresh,
codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
),
)
.await
.expect("cancelled delegate spawn should not hang");
assert!(matches!(
result,
Err(err) if matches!(err.details(), CodexErrorDetails::TurnAborted)
));
}
#[tokio::test]
async fn delegate_start_analytics_honors_child_opt_out_with_enabled_parent() {
use codex_analytics::AnalyticsEventsClient;
use codex_login::CodexAuth;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::path;
let server = MockServer::start().await;
Mock::given(path("/codex/analytics-events/events"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.await;
let client = AnalyticsEventsClient::new(
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
server.uri(),
/*analytics_enabled*/ Some(true),
);
let (mut parent_session, parent_ctx, _rx_events) =
crate::session::tests::make_session_and_context_with_rx().await;
Arc::get_mut(&mut parent_session)
.expect("parent session should be uniquely owned")
.services
.analytics_events_client = client.clone();
parent_session
.set_app_server_client_info(
Some("codex-test".to_string()),
Some("1.0.0".to_string()),
/*mcp_elicitations_auto_deny*/ false,
)
.await
.expect("set parent client metadata");
let mut expected_events = Vec::new();
for analytics_enabled in [false, true] {
let mut config = parent_ctx.config.as_ref().clone();
config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never);
config.analytics_enabled = Some(analytics_enabled);
let (session, io) = run_codex_thread_interactive(
config,
Arc::clone(&parent_session.services.auth_manager),
Arc::clone(&parent_session.services.models_manager),
Arc::clone(&parent_session),
Arc::clone(&parent_ctx),
parent_ctx.environments.clone(),
CancellationToken::new(),
SubAgentSource::Review,
codex_extension_api::SessionIsolation::Inherit,
/*initial_history*/ None,
crate::session::GitEnrichmentPolicy::Fresh,
codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
)
.await
.expect("delegate session should start");
if analytics_enabled {
expected_events.push(serde_json::json!([
"codex_thread_initialized",
session.thread_id().to_string(),
]));
}
io.shutdown_and_wait()
.await
.expect("delegate session should shut down");
}
client.flush().await;
let events = server
.received_requests()
.await
.expect("analytics requests")
.into_iter()
.flat_map(|request| {
let payload: Value = serde_json::from_slice(&request.body).expect("analytics payload");
payload["events"].as_array().expect("events array").clone()
})
.map(|event| serde_json::json!([event["event_type"], event["event_params"]["thread_id"]]))
.collect::<Vec<_>>();
assert_eq!(events, expected_events);
}
#[tokio::test]
async fn delegate_isolation_does_not_depend_on_attribution() {
let (mut parent_session, parent_ctx, _rx_events) =
crate::session::tests::make_session_and_context_with_rx().await;
let thread_starts = Arc::new(AtomicUsize::new(0));
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
extensions
.thread_lifecycle_contributor(Arc::new(ThreadStartRecorder(Arc::clone(&thread_starts))));
Arc::get_mut(&mut parent_session)
.expect("parent session should be uniquely owned")
.services
.extensions = Arc::new(extensions.build());
for (subagent_source, isolation, expected_thread_starts, expected_thread_source) in [
(
SubAgentSource::Other(crate::guardian::GUARDIAN_REVIEWER_NAME.to_string()),
codex_extension_api::SessionIsolation::Isolated,
0,
ThreadSource::GuardianReview,
),
(
SubAgentSource::Review,
codex_extension_api::SessionIsolation::Isolated,
0,
ThreadSource::Subagent,
),
(
SubAgentSource::Review,
codex_extension_api::SessionIsolation::Inherit,
1,
ThreadSource::Subagent,
),
] {
let mut config = parent_ctx.config.as_ref().clone();
config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never);
let (session, io) = run_codex_thread_interactive(
config,
Arc::clone(&parent_session.services.auth_manager),
Arc::clone(&parent_session.services.models_manager),
Arc::clone(&parent_session),
Arc::clone(&parent_ctx),
parent_ctx.environments.clone(),
CancellationToken::new(),
subagent_source,
isolation,
/*initial_history*/ None,
crate::session::GitEnrichmentPolicy::Fresh,
codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
)
.await
.expect("delegate session should start");
assert_eq!(
session
.services
.extensions
.thread_lifecycle_contributors()
.len(),
expected_thread_starts
);
assert_eq!(thread_starts.load(Ordering::SeqCst), expected_thread_starts);
assert_eq!(
session.thread_config_snapshot().await.thread_source,
Some(expected_thread_source)
);
io.shutdown_and_wait()
.await
.expect("delegate session should shut down");
}
}
#[tokio::test]
async fn run_codex_thread_interactive_rejects_approval_policy_that_can_prompt() {
let (parent_session, parent_ctx, _rx_events) =
crate::session::tests::make_session_and_context_with_rx().await;
let mut config = parent_ctx.config.as_ref().clone();
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
let parent_environments = parent_ctx.environments.clone();
let result = run_codex_thread_interactive(
config,
Arc::clone(&parent_session.services.auth_manager),
Arc::clone(&parent_session.services.models_manager),
parent_session,
parent_ctx,
parent_environments,
CancellationToken::new(),
SubAgentSource::Review,
codex_extension_api::SessionIsolation::Inherit,
/*initial_history*/ None,
crate::session::GitEnrichmentPolicy::Fresh,
codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
)
.await;
assert!(matches!(
result,
Err(err)
if matches!(
err.details(),
CodexErrorDetails::InvalidRequest(message)
if message == "Codex delegates require approval policy `never`"
)
));
}
|