mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Merge remote-tracking branch 'origin/main' into codex/se-8030-nonblocking-optional-mcp-startup
# Conflicts: # codex-rs/core/src/session/turn.rs # codex-rs/core/src/session/world_state.rs
This commit is contained in:
Generated
+16
@@ -4485,6 +4485,22 @@ dependencies = [
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-websocket-client"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"codex-http-client",
|
||||
"codex-utils-rustls-provider",
|
||||
"futures",
|
||||
"pretty_assertions",
|
||||
"rcgen",
|
||||
"rustls",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-tungstenite",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-windows-sandbox"
|
||||
version = "0.0.0"
|
||||
|
||||
@@ -90,6 +90,7 @@ members = [
|
||||
"tui",
|
||||
"tools",
|
||||
"v8-poc",
|
||||
"websocket-client",
|
||||
"utils/absolute-path",
|
||||
"utils/path-uri",
|
||||
"utils/cargo-bin",
|
||||
@@ -427,6 +428,7 @@ thiserror = "2.0.17"
|
||||
time = "0.3.47"
|
||||
tiny_http = "0.12"
|
||||
tokio = "1"
|
||||
tokio-rustls = "0.26.4"
|
||||
tokio-stream = "0.1.18"
|
||||
tokio-test = "0.4"
|
||||
tokio-tungstenite = { version = "0.28.0", features = [
|
||||
|
||||
@@ -600,6 +600,7 @@ impl ThreadHistoryBuilder {
|
||||
let should_upsert = match item {
|
||||
codex_protocol::items::TurnItem::Plan(plan) => !plan.text.is_empty(),
|
||||
codex_protocol::items::TurnItem::Sleep(_)
|
||||
| codex_protocol::items::TurnItem::HookPrompt(_)
|
||||
| codex_protocol::items::TurnItem::CommandExecution(_)
|
||||
| codex_protocol::items::TurnItem::DynamicToolCall(_)
|
||||
| codex_protocol::items::TurnItem::CollabAgentToolCall(_)
|
||||
@@ -608,7 +609,6 @@ impl ThreadHistoryBuilder {
|
||||
| codex_protocol::items::TurnItem::EnteredReviewMode(_)
|
||||
| codex_protocol::items::TurnItem::ExitedReviewMode(_) => true,
|
||||
codex_protocol::items::TurnItem::UserMessage(_)
|
||||
| codex_protocol::items::TurnItem::HookPrompt(_)
|
||||
| codex_protocol::items::TurnItem::AgentMessage(_)
|
||||
| codex_protocol::items::TurnItem::Reasoning(_)
|
||||
| codex_protocol::items::TurnItem::WebSearch(_)
|
||||
@@ -4027,6 +4027,37 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_hook_prompt_completion_updates_turn_history() {
|
||||
let hook_prompt = CoreTurnItem::HookPrompt(codex_protocol::items::HookPromptItem {
|
||||
id: "hook-prompt-1".into(),
|
||||
fragments: vec![CoreHookPromptFragment::from_single_hook(
|
||||
"Retry with tests.",
|
||||
"hook-run-1",
|
||||
)],
|
||||
});
|
||||
let expected_item = ThreadItem::from(hook_prompt.clone());
|
||||
let mut builder = ThreadHistoryBuilder::new();
|
||||
builder.handle_event(&EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: "turn-a".into(),
|
||||
trace_id: None,
|
||||
started_at: None,
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
}));
|
||||
builder.handle_event(&EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
thread_id: ThreadId::new(),
|
||||
turn_id: "turn-a".into(),
|
||||
item: hook_prompt,
|
||||
completed_at_ms: 0,
|
||||
}));
|
||||
|
||||
assert_eq!(
|
||||
builder.active_turn_snapshot().expect("active turn").items,
|
||||
vec![expected_item]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_plain_user_response_items_in_rollout_replay() {
|
||||
let items = vec![
|
||||
|
||||
@@ -89,7 +89,6 @@ use codex_core::ThreadManager;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::items::CollabAgentTool as CoreCollabAgentTool;
|
||||
use codex_protocol::items::TurnItem as CoreTurnItem;
|
||||
use codex_protocol::items::parse_hook_prompt_message;
|
||||
use codex_protocol::models::AdditionalPermissionProfile as CoreAdditionalPermissionProfile;
|
||||
use codex_protocol::plan_tool::UpdatePlanArgs;
|
||||
use codex_protocol::protocol::CodexErrorInfo as CoreCodexErrorInfo;
|
||||
@@ -1022,13 +1021,6 @@ pub(crate) async fn apply_bespoke_event_handling(
|
||||
.await;
|
||||
}
|
||||
EventMsg::RawResponseItem(raw_response_item_event) => {
|
||||
maybe_emit_hook_prompt_item_completed(
|
||||
conversation_id,
|
||||
&event_turn_id,
|
||||
&raw_response_item_event.item,
|
||||
&outgoing,
|
||||
)
|
||||
.await;
|
||||
maybe_emit_raw_response_item_completed(
|
||||
conversation_id,
|
||||
&event_turn_id,
|
||||
@@ -1406,45 +1398,6 @@ async fn maybe_emit_raw_response_item_completed(
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(crate) async fn maybe_emit_hook_prompt_item_completed(
|
||||
conversation_id: ThreadId,
|
||||
turn_id: &str,
|
||||
item: &codex_protocol::models::ResponseItem,
|
||||
outgoing: &ThreadScopedOutgoingMessageSender,
|
||||
) {
|
||||
let codex_protocol::models::ResponseItem::Message {
|
||||
role, content, id, ..
|
||||
} = item
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
if role != "user" {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(hook_prompt) = parse_hook_prompt_message(id.as_ref(), content) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let notification = ItemCompletedNotification {
|
||||
thread_id: conversation_id.to_string(),
|
||||
turn_id: turn_id.to_string(),
|
||||
completed_at_ms: now_unix_timestamp_ms(),
|
||||
item: ThreadItem::HookPrompt {
|
||||
id: hook_prompt.id,
|
||||
fragments: hook_prompt
|
||||
.fragments
|
||||
.into_iter()
|
||||
.map(codex_app_server_protocol::HookPromptFragment::from)
|
||||
.collect(),
|
||||
},
|
||||
};
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::ItemCompleted(notification))
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn find_and_remove_turn_summary(
|
||||
_conversation_id: ThreadId,
|
||||
thread_state: &Arc<Mutex<ThreadState>>,
|
||||
@@ -2104,10 +2057,8 @@ mod tests {
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::items::DynamicToolCallItem;
|
||||
use codex_protocol::items::DynamicToolCallStatus as CoreDynamicToolCallStatus;
|
||||
use codex_protocol::items::HookPromptFragment;
|
||||
use codex_protocol::items::SubAgentActivityItem;
|
||||
use codex_protocol::items::TurnItem as CoreTurnItem;
|
||||
use codex_protocol::items::build_hook_prompt_message;
|
||||
use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions;
|
||||
use codex_protocol::models::NetworkPermissions as CoreNetworkPermissions;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
@@ -3993,55 +3944,4 @@ mod tests {
|
||||
assert!(rx.try_recv().is_err(), "no extra messages expected");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_hook_prompt_raw_response_emits_item_completed() -> Result<()> {
|
||||
let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY);
|
||||
let outgoing = Arc::new(OutgoingMessageSender::new(
|
||||
tx,
|
||||
codex_analytics::AnalyticsEventsClient::disabled(),
|
||||
));
|
||||
let conversation_id = ThreadId::new();
|
||||
let outgoing = ThreadScopedOutgoingMessageSender::new(
|
||||
outgoing,
|
||||
vec![ConnectionId(1)],
|
||||
conversation_id,
|
||||
);
|
||||
let item = build_hook_prompt_message(&[
|
||||
HookPromptFragment::from_single_hook("Retry with tests.", "hook-run-1"),
|
||||
HookPromptFragment::from_single_hook("Then summarize cleanly.", "hook-run-2"),
|
||||
])
|
||||
.expect("hook prompt message");
|
||||
|
||||
maybe_emit_hook_prompt_item_completed(conversation_id, "turn-1", &item, &outgoing).await;
|
||||
|
||||
let msg = recv_broadcast_message(&mut rx).await?;
|
||||
match msg {
|
||||
OutgoingMessage::AppServerNotification(ServerNotification::ItemCompleted(
|
||||
notification,
|
||||
)) => {
|
||||
assert_eq!(notification.thread_id, conversation_id.to_string());
|
||||
assert_eq!(notification.turn_id, "turn-1");
|
||||
assert_eq!(
|
||||
notification.item,
|
||||
ThreadItem::HookPrompt {
|
||||
id: notification.item.id().to_string(),
|
||||
fragments: vec![
|
||||
codex_app_server_protocol::HookPromptFragment {
|
||||
text: "Retry with tests.".into(),
|
||||
hook_run_id: "hook-run-1".into(),
|
||||
},
|
||||
codex_app_server_protocol::HookPromptFragment {
|
||||
text: "Then summarize cleanly.".into(),
|
||||
hook_run_id: "hook-run-2".into(),
|
||||
},
|
||||
],
|
||||
}
|
||||
);
|
||||
}
|
||||
other => bail!("unexpected message: {other:?}"),
|
||||
}
|
||||
assert!(rx.try_recv().is_err(), "no extra messages expected");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::bespoke_event_handling::apply_bespoke_event_handling;
|
||||
use crate::bespoke_event_handling::maybe_emit_hook_prompt_item_completed;
|
||||
use crate::command_exec::CommandExecManager;
|
||||
use crate::command_exec::StartCommandExecParams;
|
||||
use crate::config_manager::ConfigManager;
|
||||
|
||||
@@ -316,6 +316,9 @@ pub(super) async fn ensure_listener_task_running(
|
||||
thread_state.track_current_turn_event(&event.id, &event.msg);
|
||||
thread_state.experimental_raw_events
|
||||
};
|
||||
if matches!(&event.msg, EventMsg::RawResponseItem(_)) && !raw_events_enabled {
|
||||
continue;
|
||||
}
|
||||
let subscribed_connection_ids = thread_state_manager
|
||||
.subscribed_connection_ids(conversation_id)
|
||||
.await;
|
||||
@@ -325,19 +328,6 @@ pub(super) async fn ensure_listener_task_running(
|
||||
conversation_id,
|
||||
);
|
||||
|
||||
if let EventMsg::RawResponseItem(raw_response_item_event) = &event.msg
|
||||
&& !raw_events_enabled
|
||||
{
|
||||
maybe_emit_hook_prompt_item_completed(
|
||||
conversation_id,
|
||||
&event.id,
|
||||
&raw_response_item_event.item,
|
||||
&thread_outgoing,
|
||||
)
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
|
||||
apply_bespoke_event_handling(
|
||||
event.clone(),
|
||||
conversation_id,
|
||||
|
||||
@@ -615,6 +615,8 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
|
||||
let recent_timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
|
||||
let session_dir = external_agent_home(codex_home.path()).join("projects/repo");
|
||||
let session_path = session_dir.join("session.jsonl");
|
||||
let control_request = "<ide_selection>src/auth.rs:1-5</ide_selection>";
|
||||
let first_request = "Fix auth flow";
|
||||
std::fs::create_dir_all(&project_root)?;
|
||||
std::fs::create_dir_all(&session_dir)?;
|
||||
std::fs::write(
|
||||
@@ -624,7 +626,14 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
|
||||
"type": "user",
|
||||
"cwd": &project_root,
|
||||
"timestamp": &recent_timestamp,
|
||||
"message": { "content": "first request" },
|
||||
"message": { "content": control_request },
|
||||
})
|
||||
.to_string(),
|
||||
serde_json::json!({
|
||||
"type": "user",
|
||||
"cwd": &project_root,
|
||||
"timestamp": &recent_timestamp,
|
||||
"message": { "content": first_request },
|
||||
})
|
||||
.to_string(),
|
||||
serde_json::json!({
|
||||
@@ -634,11 +643,6 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
|
||||
"message": { "content": "first answer" },
|
||||
})
|
||||
.to_string(),
|
||||
serde_json::json!({
|
||||
"type": "custom-title",
|
||||
"customTitle": "source session title",
|
||||
})
|
||||
.to_string(),
|
||||
]
|
||||
.join("\n"),
|
||||
)?;
|
||||
@@ -667,6 +671,14 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
|
||||
.await??;
|
||||
let detected: ExternalAgentConfigDetectResponse = to_response(response)?;
|
||||
assert_eq!(detected.items.len(), 1);
|
||||
assert_eq!(
|
||||
detected.items[0]
|
||||
.details
|
||||
.as_ref()
|
||||
.and_then(|details| details.sessions.first())
|
||||
.and_then(|session| session.title.as_deref()),
|
||||
Some("Fix auth flow")
|
||||
);
|
||||
|
||||
let request_id = mcp
|
||||
.send_raw_request(
|
||||
@@ -743,8 +755,8 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
|
||||
.expect("expected imported thread")
|
||||
.clone();
|
||||
assert_eq!(imported_thread_id, thread.id.to_string());
|
||||
assert_eq!(thread.preview, "first request");
|
||||
assert_eq!(thread.name.as_deref(), Some("source session title"));
|
||||
assert_eq!(thread.preview, control_request);
|
||||
assert_eq!(thread.name.as_deref(), Some("Fix auth flow"));
|
||||
|
||||
let request_id = mcp
|
||||
.send_thread_read_request(ThreadReadParams {
|
||||
@@ -758,13 +770,39 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
|
||||
)
|
||||
.await??;
|
||||
let response: ThreadReadResponse = to_response(response)?;
|
||||
assert_eq!(response.thread.turns.len(), 1);
|
||||
let items = &response.thread.turns[0].items;
|
||||
assert_eq!(items.len(), 3);
|
||||
assert_eq!(response.thread.turns.len(), 2);
|
||||
let control_items = &response.thread.turns[0].items;
|
||||
assert_eq!(control_items.len(), 1);
|
||||
match &control_items[0] {
|
||||
ThreadItem::UserMessage { content, .. } => {
|
||||
assert_eq!(
|
||||
content,
|
||||
&vec![UserInput::Text {
|
||||
text: control_request.to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
other => panic!("expected user message item, got {other:?}"),
|
||||
}
|
||||
let imported_items = &response.thread.turns[1].items;
|
||||
assert_eq!(imported_items.len(), 3);
|
||||
match &imported_items[0] {
|
||||
ThreadItem::UserMessage { content, .. } => {
|
||||
assert_eq!(
|
||||
content,
|
||||
&vec![UserInput::Text {
|
||||
text: first_request.to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
other => panic!("expected user message item, got {other:?}"),
|
||||
}
|
||||
assert_eq!(
|
||||
items.last(),
|
||||
imported_items.last(),
|
||||
Some(&ThreadItem::AgentMessage {
|
||||
id: "item-3".into(),
|
||||
id: "item-4".into(),
|
||||
text: "<EXTERNAL SESSION IMPORTED>".into(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
@@ -818,8 +856,8 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
|
||||
)
|
||||
.await??;
|
||||
let response: ThreadReadResponse = to_response(response)?;
|
||||
assert_eq!(response.thread.turns.len(), 2);
|
||||
match &response.thread.turns[1].items[1] {
|
||||
assert_eq!(response.thread.turns.len(), 3);
|
||||
match &response.thread.turns[2].items[1] {
|
||||
ThreadItem::AgentMessage { text, .. } => assert_eq!(text, "follow-up answer"),
|
||||
other => panic!("expected agent message item, got {other:?}"),
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ use crate::environment_selection::TurnEnvironmentSnapshot;
|
||||
use crate::session::McpRuntimeSnapshot;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use codex_exec_server::ResolvedSelectedCapabilityRoot;
|
||||
use codex_mcp::ToolInfo;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
/// Request-scoped state that may change between model sampling requests.
|
||||
#[derive(Debug)]
|
||||
@@ -15,6 +17,8 @@ pub(crate) struct StepContext {
|
||||
pub(crate) selected_capability_roots: Vec<ResolvedSelectedCapabilityRoot>,
|
||||
/// The exact MCP config and manager used to advertise and execute tools for this step.
|
||||
pub(crate) mcp: Arc<McpRuntimeSnapshot>,
|
||||
/// The fixed MCP tool list used for this exact sampling request.
|
||||
mcp_tool_snapshot: OnceCell<Vec<ToolInfo>>,
|
||||
/// The canonical AGENTS.md value observed with this environment snapshot.
|
||||
pub(crate) loaded_agents_md: Option<Arc<LoadedAgentsMd>>,
|
||||
}
|
||||
@@ -32,7 +36,14 @@ impl StepContext {
|
||||
environments,
|
||||
selected_capability_roots,
|
||||
mcp,
|
||||
mcp_tool_snapshot: OnceCell::new(),
|
||||
loaded_agents_md,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn mcp_tools(&self) -> &[ToolInfo] {
|
||||
self.mcp_tool_snapshot
|
||||
.get_or_init(|| self.mcp.manager().list_all_tools_for_turn())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,8 @@ use codex_otel::TelemetryAuthMode;
|
||||
use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::config_types::Settings;
|
||||
use codex_protocol::items::HookPromptFragment;
|
||||
use codex_protocol::items::build_hook_prompt_message;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::InternalChatMessageMetadataPassthrough;
|
||||
@@ -1763,6 +1765,44 @@ async fn record_conversation_items_stamps_missing_turn_id_and_preserves_existing
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn record_response_item_and_emit_turn_item_emits_hook_prompt_lifecycle() {
|
||||
let (session, turn_context, rx) = make_session_and_context_with_rx().await;
|
||||
let response_item = build_hook_prompt_message(&[HookPromptFragment::from_single_hook(
|
||||
"Retry with tests.",
|
||||
"hook-run-1",
|
||||
)])
|
||||
.expect("hook prompt message");
|
||||
let response_item_id = response_item.id().expect("hook prompt id").to_string();
|
||||
|
||||
session
|
||||
.record_response_item_and_emit_turn_item(&turn_context, response_item)
|
||||
.await;
|
||||
|
||||
let raw_response = rx.recv().await.expect("raw response item event");
|
||||
assert!(matches!(raw_response.msg, EventMsg::RawResponseItem(_)));
|
||||
|
||||
let started = rx.recv().await.expect("started hook prompt event");
|
||||
assert!(matches!(
|
||||
started.msg,
|
||||
EventMsg::ItemStarted(ItemStartedEvent {
|
||||
item: TurnItem::HookPrompt(item),
|
||||
..
|
||||
}) if item.id == response_item_id
|
||||
));
|
||||
|
||||
let completed = rx.recv().await.expect("completed hook prompt event");
|
||||
assert!(matches!(
|
||||
completed.msg,
|
||||
EventMsg::ItemCompleted(ItemCompletedEvent {
|
||||
item: TurnItem::HookPrompt(item),
|
||||
..
|
||||
}) if item.id == response_item_id
|
||||
));
|
||||
|
||||
assert!(rx.try_recv().is_err(), "no extra events expected");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn record_inter_agent_communication_sets_turn_id_in_rollout_and_resume() {
|
||||
let (mut session, turn_context) = make_session_and_context().await;
|
||||
|
||||
@@ -382,9 +382,9 @@ pub(crate) async fn run_turn(
|
||||
if let Some(hook_prompt_message) =
|
||||
build_hook_prompt_message(&stop_outcome.continuation_fragments)
|
||||
{
|
||||
sess.record_conversation_items(
|
||||
sess.record_response_item_and_emit_turn_item(
|
||||
&turn_context,
|
||||
std::slice::from_ref(&hook_prompt_message),
|
||||
hook_prompt_message,
|
||||
)
|
||||
.await;
|
||||
stop_hook_active = true;
|
||||
@@ -1222,8 +1222,8 @@ pub(crate) async fn built_tools(
|
||||
let turn_context = step_context.turn.as_ref();
|
||||
let mcp_connection_manager = step_context.mcp.manager();
|
||||
let has_mcp_servers = mcp_connection_manager.has_servers();
|
||||
let all_mcp_tools = mcp_connection_manager
|
||||
.list_all_tools_for_turn()
|
||||
let all_mcp_tools = step_context
|
||||
.mcp_tools()
|
||||
.or_cancel(cancellation_token)
|
||||
.await?;
|
||||
let loaded_plugins = sess
|
||||
@@ -1236,7 +1236,7 @@ pub(crate) async fn built_tools(
|
||||
|
||||
let apps_enabled = turn_context.apps_enabled();
|
||||
let accessible_connectors =
|
||||
apps_enabled.then(|| connectors::accessible_connectors_from_mcp_tools(&all_mcp_tools));
|
||||
apps_enabled.then(|| connectors::accessible_connectors_from_mcp_tools(all_mcp_tools));
|
||||
let accessible_connectors_with_enabled_state =
|
||||
accessible_connectors.as_ref().map(|connectors| {
|
||||
connectors::with_app_enabled_state(connectors.clone(), &turn_context.config)
|
||||
@@ -1329,7 +1329,7 @@ pub(crate) async fn built_tools(
|
||||
.await
|
||||
};
|
||||
let mcp_tool_exposure = build_mcp_tool_exposure(
|
||||
&all_mcp_tools,
|
||||
all_mcp_tools,
|
||||
connectors.as_deref(),
|
||||
&turn_context.config,
|
||||
search_tool_enabled(turn_context),
|
||||
|
||||
@@ -41,9 +41,9 @@ impl Session {
|
||||
}
|
||||
let apps_available =
|
||||
if turn_context.config.include_apps_instructions && turn_context.apps_enabled() {
|
||||
let tools = step_context.mcp.manager().list_all_tools_for_turn().await;
|
||||
let tools = step_context.mcp_tools().await;
|
||||
connectors::with_app_enabled_state(
|
||||
connectors::accessible_connectors_from_mcp_tools(&tools),
|
||||
connectors::accessible_connectors_from_mcp_tools(tools),
|
||||
&turn_context.config,
|
||||
)
|
||||
.into_iter()
|
||||
|
||||
@@ -3,7 +3,6 @@ use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::tools::context::SharedTurnDiffTracker;
|
||||
use crate::tools::sandboxing::ToolError;
|
||||
use crate::turn_timing::now_unix_timestamp_ms;
|
||||
use codex_apply_patch::AppliedPatchDelta;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::SandboxErr;
|
||||
@@ -14,8 +13,6 @@ use codex_protocol::items::FileChangeItem;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::parse_command::ParsedCommand;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::ExecCommandBeginEvent;
|
||||
use codex_protocol::protocol::ExecCommandEndEvent;
|
||||
use codex_protocol::protocol::ExecCommandSource;
|
||||
use codex_protocol::protocol::ExecCommandStatus;
|
||||
use codex_protocol::protocol::FileChange;
|
||||
@@ -104,25 +101,6 @@ pub(crate) async fn emit_exec_command_begin(
|
||||
interaction_input: Option<String>,
|
||||
process_id: Option<&str>,
|
||||
) {
|
||||
if matches!(source, ExecCommandSource::UnifiedExecInteraction) {
|
||||
ctx.session
|
||||
.send_event(
|
||||
ctx.turn,
|
||||
EventMsg::ExecCommandBegin(ExecCommandBeginEvent {
|
||||
call_id: ctx.call_id.to_string(),
|
||||
process_id: process_id.map(str::to_owned),
|
||||
turn_id: ctx.turn.sub_id.clone(),
|
||||
started_at_ms: now_unix_timestamp_ms(),
|
||||
command: command.to_vec(),
|
||||
cwd: cwd.clone(),
|
||||
parsed_cmd: parsed_cmd.to_vec(),
|
||||
source,
|
||||
interaction_input,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
ctx.session
|
||||
.emit_turn_item_started(
|
||||
ctx.turn,
|
||||
@@ -568,32 +546,6 @@ async fn emit_exec_end(
|
||||
exec_input: ExecCommandInput<'_>,
|
||||
exec_result: ExecCommandResult,
|
||||
) {
|
||||
if matches!(exec_input.source, ExecCommandSource::UnifiedExecInteraction) {
|
||||
ctx.session
|
||||
.send_event(
|
||||
ctx.turn,
|
||||
EventMsg::ExecCommandEnd(ExecCommandEndEvent {
|
||||
call_id: ctx.call_id.to_string(),
|
||||
process_id: exec_input.process_id.map(str::to_owned),
|
||||
turn_id: ctx.turn.sub_id.clone(),
|
||||
completed_at_ms: now_unix_timestamp_ms(),
|
||||
command: exec_input.command.to_vec(),
|
||||
cwd: exec_input.cwd.clone(),
|
||||
parsed_cmd: exec_input.parsed_cmd.to_vec(),
|
||||
source: exec_input.source,
|
||||
interaction_input: exec_input.interaction_input.map(str::to_owned),
|
||||
stdout: exec_result.stdout,
|
||||
stderr: exec_result.stderr,
|
||||
aggregated_output: exec_result.aggregated_output,
|
||||
exit_code: exec_result.exit_code,
|
||||
duration: exec_result.duration,
|
||||
formatted_output: exec_result.formatted_output,
|
||||
status: exec_result.status,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
ctx.session
|
||||
.emit_turn_item_completed(
|
||||
ctx.turn,
|
||||
|
||||
@@ -3,6 +3,9 @@ use crate::ImportedExternalAgentSession;
|
||||
use crate::MessageRole;
|
||||
use crate::records::read_session_import;
|
||||
use crate::summarize_for_label;
|
||||
use crate::title::IMPORTED_SESSION_FALLBACK_TITLE;
|
||||
use crate::title::SessionTitleCandidates;
|
||||
use crate::title::fallback_title_from_user_message;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::AgentMessageEvent;
|
||||
@@ -36,11 +39,22 @@ pub(crate) fn load_session_for_import_with_content_sha256(
|
||||
return Ok(None);
|
||||
};
|
||||
let messages = parsed.messages;
|
||||
let first_user_message = messages
|
||||
let first_user_message_text = messages
|
||||
.iter()
|
||||
.find(|message| message.role == MessageRole::User)
|
||||
.map(|message| summarize_for_label(&message.text));
|
||||
let title = parsed.source_title.or_else(|| first_user_message.clone());
|
||||
.map(|message| message.text.as_str());
|
||||
let first_user_message = first_user_message_text.map(summarize_for_label);
|
||||
let fallback_title = messages
|
||||
.iter()
|
||||
.filter(|message| message.role == MessageRole::User)
|
||||
.find_map(|message| fallback_title_from_user_message(&message.text))
|
||||
.or_else(|| first_user_message_text.map(|_| IMPORTED_SESSION_FALLBACK_TITLE.to_string()));
|
||||
let title = SessionTitleCandidates {
|
||||
custom_title: parsed.custom_title,
|
||||
ai_title: parsed.ai_title,
|
||||
fallback_title,
|
||||
}
|
||||
.select();
|
||||
let rollout_items = rollout_items_from_messages(messages);
|
||||
if rollout_items.is_empty() {
|
||||
return Ok(None);
|
||||
@@ -373,6 +387,91 @@ mod tests {
|
||||
assert_eq!(imported.title.as_deref(), Some("named by source app"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitizes_only_the_imported_session_fallback_title() {
|
||||
let root = TempDir::new().expect("tempdir");
|
||||
let project_root = root.path().join("repo");
|
||||
std::fs::create_dir_all(&project_root).expect("project root");
|
||||
let path = root.path().join("session.jsonl");
|
||||
let message = "<system-reminder>\ncontrol context\n</system-reminder>\nFix auth flow";
|
||||
std::fs::write(&path, jsonl(&[record("user", message, &project_root)])).expect("session");
|
||||
|
||||
let imported = load_session_for_import(&path)
|
||||
.expect("load")
|
||||
.expect("session");
|
||||
let imported_user_message = imported.rollout_items.iter().find_map(|item| match item {
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(event)) => Some(event.message.as_str()),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
assert_eq!(imported.title.as_deref(), Some("Fix auth flow"));
|
||||
assert_eq!(
|
||||
imported.first_user_message.as_deref(),
|
||||
Some("<system-reminder>")
|
||||
);
|
||||
assert_eq!(imported_user_message, Some(message));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_control_only_user_messages_when_choosing_fallback_title() {
|
||||
let root = TempDir::new().expect("tempdir");
|
||||
let project_root = root.path().join("repo");
|
||||
std::fs::create_dir_all(&project_root).expect("project root");
|
||||
let path = root.path().join("session.jsonl");
|
||||
let control_message = "<ide_selection>src/auth.rs:1-5</ide_selection>";
|
||||
std::fs::write(
|
||||
&path,
|
||||
jsonl(&[
|
||||
record("user", control_message, &project_root),
|
||||
record("user", "Fix auth flow", &project_root),
|
||||
]),
|
||||
)
|
||||
.expect("session");
|
||||
|
||||
let imported = load_session_for_import(&path)
|
||||
.expect("load")
|
||||
.expect("session");
|
||||
|
||||
assert_eq!(imported.title.as_deref(), Some("Fix auth flow"));
|
||||
assert_eq!(
|
||||
imported.first_user_message.as_deref(),
|
||||
Some(control_message)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_safe_fallback_after_all_user_messages_are_control_only() {
|
||||
let root = TempDir::new().expect("tempdir");
|
||||
let project_root = root.path().join("repo");
|
||||
std::fs::create_dir_all(&project_root).expect("project root");
|
||||
let path = root.path().join("session.jsonl");
|
||||
std::fs::write(
|
||||
&path,
|
||||
jsonl(&[
|
||||
record(
|
||||
"user",
|
||||
"<ide_selection>src/auth.rs:1-5</ide_selection>",
|
||||
&project_root,
|
||||
),
|
||||
record(
|
||||
"user",
|
||||
"<local-command-stderr>tests failed</local-command-stderr>",
|
||||
&project_root,
|
||||
),
|
||||
]),
|
||||
)
|
||||
.expect("session");
|
||||
|
||||
let imported = load_session_for_import(&path)
|
||||
.expect("load")
|
||||
.expect("session");
|
||||
|
||||
assert_eq!(
|
||||
imported.title.as_deref(),
|
||||
Some(IMPORTED_SESSION_FALLBACK_TITLE)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emits_token_usage_for_imported_history() {
|
||||
let root = TempDir::new().expect("tempdir");
|
||||
|
||||
@@ -4,6 +4,7 @@ mod detect;
|
||||
mod export;
|
||||
mod ledger;
|
||||
mod records;
|
||||
mod title;
|
||||
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use std::io;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use crate::ConversationMessage;
|
||||
use crate::ExternalAgentSessionMigration;
|
||||
use crate::MessageRole;
|
||||
use crate::summarize_for_label;
|
||||
use crate::title::IMPORTED_SESSION_FALLBACK_TITLE;
|
||||
use crate::title::SessionTitleCandidates;
|
||||
use crate::title::fallback_title_from_user_message;
|
||||
use crate::truncate;
|
||||
use serde_json::Value as JsonValue;
|
||||
use sha2::Digest;
|
||||
@@ -25,7 +27,8 @@ pub struct SessionSummary {
|
||||
|
||||
pub(super) struct ParsedSessionImport {
|
||||
pub cwd: Option<PathBuf>,
|
||||
pub source_title: Option<String>,
|
||||
pub custom_title: Option<String>,
|
||||
pub ai_title: Option<String>,
|
||||
pub messages: Vec<ConversationMessage>,
|
||||
pub content_sha256: String,
|
||||
}
|
||||
@@ -36,7 +39,8 @@ pub fn summarize_session(path: &Path) -> io::Result<Option<SessionSummary>> {
|
||||
let mut cwd = None;
|
||||
let mut custom_title = None;
|
||||
let mut ai_title = None;
|
||||
let mut title = None;
|
||||
let mut fallback_title = None;
|
||||
let mut saw_user_message = false;
|
||||
let mut latest_timestamp = None;
|
||||
let mut saw_message = false;
|
||||
|
||||
@@ -65,8 +69,11 @@ pub fn summarize_session(path: &Path) -> io::Result<Option<SessionSummary>> {
|
||||
continue;
|
||||
};
|
||||
saw_message = true;
|
||||
if title.is_none() && message.role == MessageRole::User {
|
||||
title = Some(summarize_for_label(&message.text));
|
||||
if message.role == MessageRole::User {
|
||||
saw_user_message = true;
|
||||
if fallback_title.is_none() {
|
||||
fallback_title = fallback_title_from_user_message(&message.text);
|
||||
}
|
||||
}
|
||||
if let Some(timestamp) = message.timestamp {
|
||||
latest_timestamp =
|
||||
@@ -88,7 +95,14 @@ pub fn summarize_session(path: &Path) -> io::Result<Option<SessionSummary>> {
|
||||
migration: ExternalAgentSessionMigration {
|
||||
path: path.to_path_buf(),
|
||||
cwd,
|
||||
title: custom_title.or(ai_title).or(title),
|
||||
title: SessionTitleCandidates {
|
||||
custom_title,
|
||||
ai_title,
|
||||
fallback_title: fallback_title.or_else(|| {
|
||||
saw_user_message.then(|| IMPORTED_SESSION_FALLBACK_TITLE.to_string())
|
||||
}),
|
||||
}
|
||||
.select(),
|
||||
},
|
||||
}))
|
||||
}
|
||||
@@ -133,7 +147,8 @@ pub(super) fn read_session_import(path: &Path) -> io::Result<ParsedSessionImport
|
||||
}
|
||||
Ok(ParsedSessionImport {
|
||||
cwd,
|
||||
source_title: custom_title.or(ai_title),
|
||||
custom_title,
|
||||
ai_title,
|
||||
messages,
|
||||
content_sha256: format!("{:x}", hasher.finalize()),
|
||||
})
|
||||
@@ -373,7 +388,8 @@ mod tests {
|
||||
let parsed = read_session_import(&path).expect("parse session");
|
||||
|
||||
assert_eq!(parsed.cwd.as_deref(), Some(root.path()));
|
||||
assert_eq!(parsed.source_title.as_deref(), Some("custom title"));
|
||||
assert_eq!(parsed.custom_title.as_deref(), Some("custom title"));
|
||||
assert_eq!(parsed.ai_title.as_deref(), Some("generated title"));
|
||||
assert_eq!(parsed.messages.len(), 1);
|
||||
assert_eq!(parsed.messages[0].text, "first request");
|
||||
assert_eq!(
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
use crate::SESSION_TITLE_MAX_LEN;
|
||||
use crate::truncate;
|
||||
|
||||
pub(super) const IMPORTED_SESSION_FALLBACK_TITLE: &str = "Imported session";
|
||||
const RECOGNIZED_CONTROL_WRAPPERS: [(&str, &str); 10] = [
|
||||
("<command-message>", "</command-message>"),
|
||||
("<command-name>", "</command-name>"),
|
||||
("<command-args>", "</command-args>"),
|
||||
("<local-command-caveat>", "</local-command-caveat>"),
|
||||
("<local-command-stderr>", "</local-command-stderr>"),
|
||||
("<local-command-stdout>", "</local-command-stdout>"),
|
||||
("<task-notification>", "</task-notification>"),
|
||||
("<system-reminder>", "</system-reminder>"),
|
||||
("<ide_opened_file>", "</ide_opened_file>"),
|
||||
("<ide_selection>", "</ide_selection>"),
|
||||
];
|
||||
|
||||
pub(super) struct SessionTitleCandidates {
|
||||
pub custom_title: Option<String>,
|
||||
pub ai_title: Option<String>,
|
||||
pub fallback_title: Option<String>,
|
||||
}
|
||||
|
||||
impl SessionTitleCandidates {
|
||||
pub fn select(self) -> Option<String> {
|
||||
self.custom_title.or(self.ai_title).or(self.fallback_title)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn fallback_title_from_user_message(message: &str) -> Option<String> {
|
||||
let message = strip_leading_control_wrappers(message);
|
||||
message
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find(|line| !line.is_empty())
|
||||
.map(|line| truncate(line, SESSION_TITLE_MAX_LEN))
|
||||
}
|
||||
|
||||
fn strip_leading_control_wrappers(message: &str) -> &str {
|
||||
let mut remainder = message.trim_start();
|
||||
while let Some(wrapper_end) = leading_control_wrapper_end(remainder) {
|
||||
remainder = remainder[wrapper_end..].trim_start();
|
||||
}
|
||||
remainder
|
||||
}
|
||||
|
||||
fn leading_control_wrapper_end(text: &str) -> Option<usize> {
|
||||
let (outer_tag, opening_len) = recognized_opening_tag(text)?;
|
||||
let mut open_tags = vec![outer_tag];
|
||||
let mut cursor = opening_len;
|
||||
|
||||
while !open_tags.is_empty() {
|
||||
cursor += text.get(cursor..)?.find('<')?;
|
||||
let candidate = text.get(cursor..)?;
|
||||
if let Some((tag, token_len)) = recognized_opening_tag(candidate) {
|
||||
open_tags.push(tag);
|
||||
cursor += token_len;
|
||||
continue;
|
||||
}
|
||||
if let Some((tag, token_len)) = recognized_closing_tag(candidate) {
|
||||
if open_tags.last().copied() != Some(tag) {
|
||||
return None;
|
||||
}
|
||||
open_tags.pop();
|
||||
cursor += token_len;
|
||||
continue;
|
||||
}
|
||||
cursor += 1;
|
||||
}
|
||||
|
||||
Some(cursor)
|
||||
}
|
||||
|
||||
fn recognized_opening_tag(text: &str) -> Option<(usize, usize)> {
|
||||
RECOGNIZED_CONTROL_WRAPPERS
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find_map(|(index, (opening, _closing))| {
|
||||
text.starts_with(opening).then_some((index, opening.len()))
|
||||
})
|
||||
}
|
||||
|
||||
fn recognized_closing_tag(text: &str) -> Option<(usize, usize)> {
|
||||
RECOGNIZED_CONTROL_WRAPPERS
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find_map(|(index, (_opening, closing))| {
|
||||
text.starts_with(closing).then_some((index, closing.len()))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "title_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,123 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preserves_valid_custom_title_unchanged() {
|
||||
let custom_title = "<system-reminder>Keep this custom title</system-reminder>";
|
||||
|
||||
assert_eq!(
|
||||
SessionTitleCandidates {
|
||||
custom_title: Some(custom_title.to_string()),
|
||||
ai_title: Some("AI title".to_string()),
|
||||
fallback_title: Some("fallback title".to_string()),
|
||||
}
|
||||
.select(),
|
||||
Some(custom_title.to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_valid_ai_title_unchanged_without_custom_title() {
|
||||
let ai_title = "<command-message>Keep this AI title</command-message>";
|
||||
|
||||
assert_eq!(
|
||||
SessionTitleCandidates {
|
||||
custom_title: None,
|
||||
ai_title: Some(ai_title.to_string()),
|
||||
fallback_title: Some("fallback title".to_string()),
|
||||
}
|
||||
.select(),
|
||||
Some(ai_title.to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_nested_repeated_and_multiline_leading_control_wrappers() {
|
||||
let message = "\
|
||||
<system-reminder>\n\
|
||||
outer context\n\
|
||||
<command-message>\n\
|
||||
nested context\n\
|
||||
</command-message>\n\
|
||||
</system-reminder>\n\
|
||||
<ide_opened_file>\n\
|
||||
src/auth.rs\n\
|
||||
</ide_opened_file>\n\
|
||||
\n\
|
||||
Fix auth flow\n\
|
||||
Additional details";
|
||||
|
||||
assert_eq!(
|
||||
fallback_title_from_user_message(message),
|
||||
Some("Fix auth flow".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_observed_external_agent_control_wrapper_families() {
|
||||
let cases = [
|
||||
"<task-notification>\n\
|
||||
<task-id>abc123</task-id>\n\
|
||||
<status>completed</status>\n\
|
||||
</task-notification>\n\
|
||||
Fix auth flow",
|
||||
"<command-message>review</command-message>\n\
|
||||
<command-name>/review</command-name>\n\
|
||||
<command-args>src/auth.rs</command-args>\n\
|
||||
Fix auth flow",
|
||||
"<local-command-caveat>Command output follows</local-command-caveat>\n\
|
||||
<local-command-stdout>tests passed</local-command-stdout>\n\
|
||||
Fix auth flow",
|
||||
"<local-command-stderr>tests failed</local-command-stderr>\n\
|
||||
Fix auth flow",
|
||||
"<ide_selection>src/auth.rs:1-5</ide_selection>\n\
|
||||
Fix auth flow",
|
||||
];
|
||||
|
||||
for message in cases {
|
||||
assert_eq!(
|
||||
fallback_title_from_user_message(message),
|
||||
Some("Fix auth flow".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_no_candidate_for_empty_or_control_only_messages() {
|
||||
assert_eq!(fallback_title_from_user_message(""), None);
|
||||
assert_eq!(
|
||||
fallback_title_from_user_message(
|
||||
"<command-message>review</command-message>\n\
|
||||
<system-reminder>context</system-reminder>"
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_first_meaningful_line_from_ordinary_messages() {
|
||||
assert_eq!(
|
||||
fallback_title_from_user_message("\n \n Fix auth flow \nAdditional details"),
|
||||
Some("Fix auth flow".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_unknown_and_user_authored_angle_bracket_text() {
|
||||
assert_eq!(
|
||||
fallback_title_from_user_message("<user-note>Keep this text</user-note> Fix auth flow"),
|
||||
Some("<user-note>Keep this text</user-note> Fix auth flow".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
fallback_title_from_user_message("Explain <system-reminder> tags"),
|
||||
Some("Explain <system-reminder> tags".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_fallback_titles_to_120_characters() {
|
||||
let message = "x".repeat(121);
|
||||
let title = fallback_title_from_user_message(&message).expect("title");
|
||||
|
||||
assert_eq!(title.chars().count(), SESSION_TITLE_MAX_LEN);
|
||||
assert_eq!(title, format!("{}...", "x".repeat(117)));
|
||||
}
|
||||
@@ -19,26 +19,28 @@ pub(crate) fn static_model_catalog() -> ModelsResponse {
|
||||
gpt_5_bedrock_model(
|
||||
GPT_5_5_OPENAI_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_5_5_MODEL_ID,
|
||||
"GPT-5.5",
|
||||
/*priority*/ 0,
|
||||
),
|
||||
gpt_5_bedrock_model(
|
||||
GPT_5_4_OPENAI_MODEL_ID,
|
||||
AMAZON_BEDROCK_GPT_5_4_MODEL_ID,
|
||||
"GPT-5.4",
|
||||
/*priority*/ 1,
|
||||
),
|
||||
gpt_5_6_bedrock_model(
|
||||
AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID,
|
||||
"Sol",
|
||||
"GPT-5.6 Sol",
|
||||
/*priority*/ 2,
|
||||
),
|
||||
gpt_5_6_bedrock_model(
|
||||
AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID,
|
||||
"Terra",
|
||||
"GPT-5.6 Terra",
|
||||
/*priority*/ 3,
|
||||
),
|
||||
gpt_5_6_bedrock_model(
|
||||
AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID,
|
||||
"Luna",
|
||||
"GPT-5.6 Luna",
|
||||
/*priority*/ 4,
|
||||
),
|
||||
],
|
||||
@@ -55,9 +57,15 @@ pub(crate) fn with_default_only_service_tier(mut catalog: ModelsResponse) -> Mod
|
||||
catalog
|
||||
}
|
||||
|
||||
fn gpt_5_bedrock_model(openai_slug: &str, bedrock_slug: &str, priority: i32) -> ModelInfo {
|
||||
fn gpt_5_bedrock_model(
|
||||
openai_slug: &str,
|
||||
bedrock_slug: &str,
|
||||
display_name: &str,
|
||||
priority: i32,
|
||||
) -> ModelInfo {
|
||||
let mut model = bundled_openai_model(openai_slug);
|
||||
model.slug = bedrock_slug.to_string();
|
||||
model.display_name = display_name.to_string();
|
||||
model.priority = priority;
|
||||
model.context_window = Some(GPT_5_BEDROCK_CONTEXT_WINDOW);
|
||||
model.max_context_window = Some(GPT_5_BEDROCK_CONTEXT_WINDOW);
|
||||
@@ -67,8 +75,12 @@ fn gpt_5_bedrock_model(openai_slug: &str, bedrock_slug: &str, priority: i32) ->
|
||||
}
|
||||
|
||||
fn gpt_5_6_bedrock_model(bedrock_slug: &str, display_name: &str, priority: i32) -> ModelInfo {
|
||||
let mut model = gpt_5_bedrock_model(GPT_5_5_OPENAI_MODEL_ID, bedrock_slug, priority);
|
||||
model.display_name = display_name.to_string();
|
||||
let mut model = gpt_5_bedrock_model(
|
||||
GPT_5_5_OPENAI_MODEL_ID,
|
||||
bedrock_slug,
|
||||
display_name,
|
||||
priority,
|
||||
);
|
||||
model
|
||||
.supported_reasoning_levels
|
||||
.push(ReasoningEffortPreset {
|
||||
@@ -148,9 +160,9 @@ mod tests {
|
||||
.expect("Bedrock catalog should include GPT-5.5");
|
||||
|
||||
for (slug, display_name, priority) in [
|
||||
(AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID, "Sol", 2),
|
||||
(AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID, "Terra", 3),
|
||||
(AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID, "Luna", 4),
|
||||
(AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID, "GPT-5.6 Sol", 2),
|
||||
(AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID, "GPT-5.6 Terra", 3),
|
||||
(AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID, "GPT-5.6 Luna", 4),
|
||||
] {
|
||||
let mut expected = gpt_5_5.clone();
|
||||
expected.slug = slug.to_string();
|
||||
|
||||
@@ -657,20 +657,20 @@ mod tests {
|
||||
provider.models_manager(test_codex_home(), /*config_model_catalog*/ None);
|
||||
|
||||
let catalog = manager.raw_model_catalog(RefreshStrategy::Online).await;
|
||||
let model_ids = catalog
|
||||
let models = catalog
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| model.slug.as_str())
|
||||
.map(|model| (model.slug.as_str(), model.display_name.as_str()))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(
|
||||
model_ids,
|
||||
models,
|
||||
vec![
|
||||
"openai.gpt-5.5",
|
||||
"openai.gpt-5.4",
|
||||
"openai.gpt-5.6-sol",
|
||||
"openai.gpt-5.6-terra",
|
||||
"openai.gpt-5.6-luna",
|
||||
("openai.gpt-5.5", "GPT-5.5"),
|
||||
("openai.gpt-5.4", "GPT-5.4"),
|
||||
("openai.gpt-5.6-sol", "GPT-5.6 Sol"),
|
||||
("openai.gpt-5.6-terra", "GPT-5.6 Terra"),
|
||||
("openai.gpt-5.6-luna", "GPT-5.6 Luna"),
|
||||
]
|
||||
);
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
const ULTRA_REASONING_CONCURRENCY_WARNING_THRESHOLD: usize = 8;
|
||||
|
||||
impl ChatWidget {
|
||||
/// Open a popup to choose a quick auto model. Selecting "All models"
|
||||
/// opens the full picker with every available preset.
|
||||
@@ -102,7 +104,7 @@ impl ChatWidget {
|
||||
model.as_str(),
|
||||
Some(preset.default_reasoning_effort.clone()),
|
||||
);
|
||||
let actions = Self::model_selection_actions(
|
||||
let actions = self.model_selection_actions(
|
||||
model.clone(),
|
||||
Some(preset.default_reasoning_effort.clone()),
|
||||
should_prompt_plan_mode_scope,
|
||||
@@ -214,10 +216,14 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
fn model_selection_actions(
|
||||
&self,
|
||||
model_for_action: String,
|
||||
effort_for_action: Option<ReasoningEffortConfig>,
|
||||
should_prompt_plan_mode_scope: bool,
|
||||
) -> Vec<SelectionAction> {
|
||||
let warning = effort_for_action
|
||||
.as_ref()
|
||||
.and_then(|effort| self.ultra_reasoning_concurrency_warning(effort));
|
||||
vec![Box::new(move |tx| {
|
||||
if should_prompt_plan_mode_scope {
|
||||
tx.send(AppEvent::OpenPlanReasoningScopePrompt {
|
||||
@@ -233,6 +239,11 @@ impl ChatWidget {
|
||||
model: model_for_action.clone(),
|
||||
effort: effort_for_action.clone(),
|
||||
});
|
||||
if let Some(warning) = warning.clone() {
|
||||
tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
history_cell::new_warning_event(warning),
|
||||
)));
|
||||
}
|
||||
})]
|
||||
}
|
||||
|
||||
@@ -299,14 +310,23 @@ impl ChatWidget {
|
||||
"Set the global default reasoning level and the Plan mode override. This replaces the current {plan_reasoning_source}."
|
||||
);
|
||||
let subtitle = format!("Choose where to apply {reasoning_phrase}.");
|
||||
let warning = effort
|
||||
.as_ref()
|
||||
.and_then(|effort| self.ultra_reasoning_concurrency_warning(effort));
|
||||
|
||||
let plan_only_actions: Vec<SelectionAction> = vec![Box::new({
|
||||
let model = model.clone();
|
||||
let effort = effort.clone();
|
||||
let warning = warning.clone();
|
||||
move |tx| {
|
||||
tx.send(AppEvent::UpdateModel(model.clone()));
|
||||
tx.send(AppEvent::UpdatePlanModeReasoningEffort(effort.clone()));
|
||||
tx.send(AppEvent::PersistPlanModeReasoningEffort(effort.clone()));
|
||||
if let Some(warning) = warning.clone() {
|
||||
tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
history_cell::new_warning_event(warning),
|
||||
)));
|
||||
}
|
||||
}
|
||||
})];
|
||||
let all_modes_actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
|
||||
@@ -318,6 +338,11 @@ impl ChatWidget {
|
||||
model: model.clone(),
|
||||
effort: effort.clone(),
|
||||
});
|
||||
if let Some(warning) = warning.clone() {
|
||||
tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
history_cell::new_warning_event(warning),
|
||||
)));
|
||||
}
|
||||
})];
|
||||
|
||||
self.bottom_pane.show_selection_view(SelectionViewParams {
|
||||
@@ -427,6 +452,7 @@ impl ChatWidget {
|
||||
let mut items: Vec<SelectionItem> = Vec::new();
|
||||
for choice in choices.iter() {
|
||||
let effort = choice.clone();
|
||||
let warning = self.ultra_reasoning_concurrency_warning(&effort);
|
||||
let mut effort_label = Self::reasoning_effort_label(&effort);
|
||||
if Some(choice) == default_choice.as_ref() {
|
||||
effort_label.push_str(" (default)");
|
||||
@@ -469,6 +495,11 @@ impl ChatWidget {
|
||||
model: model_for_action.clone(),
|
||||
effort: choice_effort.clone(),
|
||||
});
|
||||
if let Some(warning) = warning.clone() {
|
||||
tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
history_cell::new_warning_event(warning),
|
||||
)));
|
||||
}
|
||||
}
|
||||
})];
|
||||
|
||||
@@ -518,14 +549,47 @@ impl ChatWidget {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn ultra_reasoning_concurrency_warning(
|
||||
&self,
|
||||
effort: &ReasoningEffortConfig,
|
||||
) -> Option<String> {
|
||||
if effort != &ReasoningEffortConfig::Ultra {
|
||||
return None;
|
||||
}
|
||||
|
||||
let max_threads = self
|
||||
.config
|
||||
.multi_agent_v2
|
||||
.max_concurrent_threads_per_session;
|
||||
if max_threads < ULTRA_REASONING_CONCURRENCY_WARNING_THRESHOLD {
|
||||
return None;
|
||||
}
|
||||
|
||||
let max_subagents = max_threads.saturating_sub(1);
|
||||
Some(format!(
|
||||
"Ultra reasoning may proactively use multiple agents. This session is configured for \
|
||||
{max_threads} concurrent threads with up to {max_subagents} subagents which can \
|
||||
increase usage quickly. Consider setting \
|
||||
features.multi_agent_v2.max_concurrent_threads_per_session below 8."
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn apply_model_and_effort_without_persist(
|
||||
&self,
|
||||
model: String,
|
||||
effort: Option<ReasoningEffortConfig>,
|
||||
) {
|
||||
let warning = effort
|
||||
.as_ref()
|
||||
.and_then(|effort| self.ultra_reasoning_concurrency_warning(effort));
|
||||
self.app_event_tx.send(AppEvent::UpdateModel(model));
|
||||
self.app_event_tx
|
||||
.send(AppEvent::UpdateReasoningEffort(effort));
|
||||
if let Some(warning) = warning {
|
||||
self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
history_cell::new_warning_event(warning),
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_model_and_effort(&self, model: String, effort: Option<ReasoningEffortConfig>) {
|
||||
|
||||
@@ -110,8 +110,14 @@ impl ChatWidget {
|
||||
};
|
||||
|
||||
if self.collaboration_modes_enabled() && self.active_mode_kind() == ModeKind::Plan {
|
||||
let warning = self.ultra_reasoning_concurrency_warning(&next_effort);
|
||||
self.app_event_tx
|
||||
.send(AppEvent::UpdatePlanModeReasoningEffort(Some(next_effort)));
|
||||
if let Some(warning) = warning {
|
||||
self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
crate::history_cell::new_warning_event(warning),
|
||||
)));
|
||||
}
|
||||
} else {
|
||||
self.apply_model_and_effort_without_persist(current_model, Some(next_effort));
|
||||
}
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/popups_and_settings.rs
|
||||
expression: "&warnings[0]"
|
||||
---
|
||||
⚠ Ultra reasoning may proactively use multiple agents. This session is
|
||||
configured for 8 concurrent threads with up to 7 subagents which can increase
|
||||
usage quickly. Consider setting
|
||||
features.multi_agent_v2.max_concurrent_threads_per_session below 8.
|
||||
@@ -3236,6 +3236,68 @@ async fn model_reasoning_selection_popup_applies_custom_effort() {
|
||||
);
|
||||
}
|
||||
|
||||
async fn select_ultra_with_multi_agent_thread_limit(max_threads: usize) -> (bool, Vec<String>) {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
|
||||
chat.config
|
||||
.multi_agent_v2
|
||||
.max_concurrent_threads_per_session = max_threads;
|
||||
chat.set_reasoning_effort(Some(ReasoningEffortConfig::High));
|
||||
|
||||
let mut preset = get_available_model(&chat, "gpt-5.4");
|
||||
preset.default_reasoning_effort = ReasoningEffortConfig::High;
|
||||
preset.supported_reasoning_efforts = vec![
|
||||
ReasoningEffortPreset {
|
||||
effort: ReasoningEffortConfig::High,
|
||||
description: "High reasoning".to_string(),
|
||||
},
|
||||
ReasoningEffortPreset {
|
||||
effort: ReasoningEffortConfig::Ultra,
|
||||
description: "Ultra reasoning".to_string(),
|
||||
},
|
||||
];
|
||||
chat.open_reasoning_popup(preset);
|
||||
while rx.try_recv().is_ok() {}
|
||||
|
||||
chat.handle_key_event(KeyEvent::from(KeyCode::Down));
|
||||
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
|
||||
|
||||
let mut selected_ultra = false;
|
||||
let mut warnings = Vec::new();
|
||||
while let Ok(event) = rx.try_recv() {
|
||||
match event {
|
||||
AppEvent::UpdateReasoningEffort(Some(ReasoningEffortConfig::Ultra)) => {
|
||||
selected_ultra = true;
|
||||
}
|
||||
AppEvent::InsertHistoryCell(cell) => {
|
||||
warnings.push(lines_to_single_string(&cell.display_lines(/*width*/ 80)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
(selected_ultra, warnings)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ultra_reasoning_selection_warns_for_high_multi_agent_concurrency() {
|
||||
let (selected_ultra, warnings) =
|
||||
select_ultra_with_multi_agent_thread_limit(/*max_threads*/ 8).await;
|
||||
|
||||
assert!(selected_ultra);
|
||||
assert_eq!(warnings.len(), 1);
|
||||
assert_chatwidget_snapshot!(
|
||||
"ultra_reasoning_selection_high_multi_agent_concurrency_warning",
|
||||
&warnings[0]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ultra_reasoning_selection_skips_warning_below_threshold() {
|
||||
let below_threshold = select_ultra_with_multi_agent_thread_limit(/*max_threads*/ 7).await;
|
||||
|
||||
assert_eq!(below_threshold, (true, Vec::new()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_reasoning_selection_popup_extra_high_warning_snapshot() {
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.2")).await;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "websocket-client",
|
||||
crate_name = "codex_websocket_client",
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "codex-websocket-client"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
codex-http-client = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
rustls = { workspace = true }
|
||||
tokio = { workspace = true, features = ["net", "rt", "time"] }
|
||||
tokio-rustls = { workspace = true }
|
||||
tokio-tungstenite = { workspace = true }
|
||||
url = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
codex-utils-rustls-provider = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
rcgen = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
@@ -0,0 +1,256 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_http_client::OutboundProxyRoute;
|
||||
use futures::StreamExt;
|
||||
use futures::stream::FuturesUnordered;
|
||||
use rustls::ClientConfig;
|
||||
use rustls::pki_types::ServerName;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::sleep_until;
|
||||
use tokio_rustls::TlsConnector;
|
||||
use tokio_tungstenite::Connector;
|
||||
use tokio_tungstenite::client_async_tls_with_config;
|
||||
use tokio_tungstenite::connect_async_tls_with_config;
|
||||
use tokio_tungstenite::proxy::connect_via_proxy;
|
||||
use tokio_tungstenite::tungstenite::Error as WebSocketError;
|
||||
use tokio_tungstenite::tungstenite::error::TlsError;
|
||||
use tokio_tungstenite::tungstenite::error::UrlError;
|
||||
use tokio_tungstenite::tungstenite::handshake::client::Request;
|
||||
use tokio_tungstenite::tungstenite::handshake::client::Response;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
use tokio_tungstenite::tungstenite::proxy::ProxyConfig;
|
||||
|
||||
use crate::AsyncIo;
|
||||
use crate::ConnectionInner;
|
||||
|
||||
const HAPPY_EYEBALLS_DELAY: Duration = Duration::from_millis(250);
|
||||
|
||||
pub(crate) async fn connect(
|
||||
request: Request,
|
||||
config: WebSocketConfig,
|
||||
tls_config: Arc<ClientConfig>,
|
||||
proxy_route: OutboundProxyRoute,
|
||||
) -> Result<(ConnectionInner, Response), WebSocketError> {
|
||||
let stream: Box<dyn AsyncIo> = match proxy_route {
|
||||
OutboundProxyRoute::TransportDefault => {
|
||||
// The workspace enables tokio-tungstenite's `proxy` feature, so its default dialer
|
||||
// resolves HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and NO_PROXY before opening the socket.
|
||||
let (stream, response) = connect_async_tls_with_config(
|
||||
request,
|
||||
Some(config),
|
||||
false, // Preserve Tungstenite's recommended Nagle default.
|
||||
Some(Connector::Rustls(tls_config)),
|
||||
)
|
||||
.await?;
|
||||
return Ok((ConnectionInner::TransportDefault(stream), response));
|
||||
}
|
||||
OutboundProxyRoute::Direct => {
|
||||
let host = websocket_host(&request)?;
|
||||
let port = websocket_port(&request)?;
|
||||
Box::new(
|
||||
connect_tcp(host_port(host, port))
|
||||
.await
|
||||
.map_err(WebSocketError::Io)?,
|
||||
)
|
||||
}
|
||||
OutboundProxyRoute::Proxy { url } => {
|
||||
let proxy = ProxyEndpoint::parse(&url)?;
|
||||
let host = websocket_host(&request)?;
|
||||
let port = websocket_port(&request)?;
|
||||
let stream = connect_tcp(proxy.config.authority())
|
||||
.await
|
||||
.map_err(WebSocketError::Io)?;
|
||||
let stream: Box<dyn AsyncIo> = if proxy.tls {
|
||||
let server_name = ServerName::try_from(proxy.config.host.clone())
|
||||
.map_err(|_| WebSocketError::Tls(TlsError::InvalidDnsName))?;
|
||||
let stream = TlsConnector::from(Arc::clone(&tls_config))
|
||||
.connect(server_name, stream)
|
||||
.await
|
||||
.map_err(WebSocketError::Io)?;
|
||||
Box::new(stream)
|
||||
} else {
|
||||
Box::new(stream)
|
||||
};
|
||||
connect_via_proxy(stream, &proxy.config, host, port).await?
|
||||
}
|
||||
};
|
||||
|
||||
let (stream, response) = client_async_tls_with_config(
|
||||
request,
|
||||
stream,
|
||||
Some(config),
|
||||
Some(Connector::Rustls(tls_config)),
|
||||
)
|
||||
.await?;
|
||||
Ok((ConnectionInner::Routed(stream), response))
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct ProxyEndpoint {
|
||||
config: ProxyConfig,
|
||||
tls: bool,
|
||||
}
|
||||
|
||||
impl ProxyEndpoint {
|
||||
fn parse(url: &str) -> Result<Self, WebSocketError> {
|
||||
let mut parsed_url = url::Url::parse(url).map_err(|_| invalid_proxy_config())?;
|
||||
let tls = parsed_url.scheme() == "https";
|
||||
if tls {
|
||||
// Capture the HTTPS default before changing schemes: `Url` normalizes default ports,
|
||||
// so setting 443 before rewriting to HTTP would discard it and later imply port 80.
|
||||
let port = parsed_url
|
||||
.port_or_known_default()
|
||||
.ok_or_else(invalid_proxy_config)?;
|
||||
parsed_url
|
||||
.set_scheme("http")
|
||||
.map_err(|_| invalid_proxy_config())?;
|
||||
parsed_url
|
||||
.set_port(Some(port))
|
||||
.map_err(|_| invalid_proxy_config())?;
|
||||
}
|
||||
let config = ProxyConfig::parse(parsed_url.as_str()).map_err(|error| match error {
|
||||
WebSocketError::Url(UrlError::UnsupportedProxyScheme) => error,
|
||||
_ => invalid_proxy_config(),
|
||||
})?;
|
||||
Ok(Self { config, tls })
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_proxy_config() -> WebSocketError {
|
||||
WebSocketError::Url(UrlError::InvalidProxyConfig("<redacted>".to_string()))
|
||||
}
|
||||
|
||||
fn websocket_host(request: &Request) -> Result<&str, WebSocketError> {
|
||||
request
|
||||
.uri()
|
||||
.host()
|
||||
.ok_or(WebSocketError::Url(UrlError::NoHostName))
|
||||
}
|
||||
|
||||
fn websocket_port(request: &Request) -> Result<u16, WebSocketError> {
|
||||
request
|
||||
.uri()
|
||||
.port_u16()
|
||||
.or_else(|| match request.uri().scheme_str() {
|
||||
Some("ws") => Some(80),
|
||||
Some("wss") => Some(443),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or(WebSocketError::Url(UrlError::UnsupportedUrlScheme))
|
||||
}
|
||||
|
||||
fn host_port(host: &str, port: u16) -> String {
|
||||
if host.contains(':') && !host.starts_with('[') {
|
||||
format!("[{host}]:{port}")
|
||||
} else {
|
||||
format!("{host}:{port}")
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_tcp(address: String) -> io::Result<TcpStream> {
|
||||
let addresses = tokio::net::lookup_host(address).await?.collect::<Vec<_>>();
|
||||
connect_happy_eyeballs(addresses, TcpStream::connect).await
|
||||
}
|
||||
|
||||
async fn connect_happy_eyeballs<T, F, Fut>(
|
||||
addresses: Vec<SocketAddr>,
|
||||
mut connect: F,
|
||||
) -> io::Result<T>
|
||||
where
|
||||
F: FnMut(SocketAddr) -> Fut,
|
||||
Fut: Future<Output = io::Result<T>>,
|
||||
{
|
||||
let mut addresses = addresses.into_iter();
|
||||
let Some(first_address) = addresses.next() else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"could not resolve to any address",
|
||||
));
|
||||
};
|
||||
|
||||
let first_is_ipv4 = first_address.is_ipv4();
|
||||
let mut preferred = VecDeque::new();
|
||||
let mut alternate = VecDeque::new();
|
||||
for address in addresses {
|
||||
if address.is_ipv4() == first_is_ipv4 {
|
||||
preferred.push_back(address);
|
||||
} else {
|
||||
alternate.push_back(address);
|
||||
}
|
||||
}
|
||||
|
||||
let mut addresses = VecDeque::new();
|
||||
while !preferred.is_empty() || !alternate.is_empty() {
|
||||
if let Some(address) = alternate.pop_front() {
|
||||
addresses.push_back(address);
|
||||
}
|
||||
if let Some(address) = preferred.pop_front() {
|
||||
addresses.push_back(address);
|
||||
}
|
||||
}
|
||||
|
||||
let mut attempts = FuturesUnordered::new();
|
||||
attempts.push(connect(first_address));
|
||||
let mut next_attempt_at = Instant::now() + HAPPY_EYEBALLS_DELAY;
|
||||
let mut last_error = None;
|
||||
|
||||
loop {
|
||||
if addresses.is_empty() {
|
||||
match attempts.next().await {
|
||||
Some(Ok(stream)) => return Ok(stream),
|
||||
Some(Err(error)) => {
|
||||
if attempts.is_empty() {
|
||||
return Err(error);
|
||||
}
|
||||
last_error = Some(error);
|
||||
}
|
||||
None => {
|
||||
return Err(last_error.unwrap_or_else(|| {
|
||||
io::Error::other("connection attempts ended without an error")
|
||||
}));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
result = attempts.next() => {
|
||||
match result {
|
||||
Some(Ok(stream)) => return Ok(stream),
|
||||
Some(Err(error)) => {
|
||||
last_error = Some(error);
|
||||
let address = take_next_address(&mut addresses)?;
|
||||
attempts.push(connect(address));
|
||||
next_attempt_at = Instant::now() + HAPPY_EYEBALLS_DELAY;
|
||||
}
|
||||
None => {
|
||||
let address = take_next_address(&mut addresses)?;
|
||||
attempts.push(connect(address));
|
||||
next_attempt_at = Instant::now() + HAPPY_EYEBALLS_DELAY;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = sleep_until(next_attempt_at) => {
|
||||
let address = take_next_address(&mut addresses)?;
|
||||
attempts.push(connect(address));
|
||||
next_attempt_at = Instant::now() + HAPPY_EYEBALLS_DELAY;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn take_next_address(addresses: &mut VecDeque<SocketAddr>) -> io::Result<SocketAddr> {
|
||||
addresses
|
||||
.pop_front()
|
||||
.ok_or_else(|| io::Error::other("connection address queue unexpectedly empty"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "dialer_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,297 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::OutboundProxyRoute;
|
||||
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rcgen::CertifiedKey;
|
||||
use rcgen::generate_simple_self_signed;
|
||||
use rustls::ClientConfig;
|
||||
use rustls::RootCertStore;
|
||||
use rustls::ServerConfig;
|
||||
use rustls::pki_types::PrivateKeyDer;
|
||||
use rustls::pki_types::PrivatePkcs8KeyDer;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tokio_tungstenite::accept_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
use tokio_tungstenite::tungstenite::proxy::ProxyScheme;
|
||||
|
||||
use super::*;
|
||||
use crate::AsyncIo;
|
||||
use crate::WebSocketConnection;
|
||||
use crate::WebSocketConnector;
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_connector_uses_factory_and_exposes_stream_and_sink() {
|
||||
let (target_addr, target_task) = start_plain_echo_websocket_server().await;
|
||||
let request = format!("ws://localhost:{}/v1/responses", target_addr.port())
|
||||
.into_client_request()
|
||||
.expect("websocket request should build");
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
let connector = WebSocketConnector::new(&factory).expect("connector should build");
|
||||
|
||||
let (mut websocket, _) = connector
|
||||
.connect(request, WebSocketConfig::default())
|
||||
.await
|
||||
.expect("websocket handshake should succeed");
|
||||
let expected = Message::Text("hello".into());
|
||||
websocket
|
||||
.send(expected.clone())
|
||||
.await
|
||||
.expect("websocket should send");
|
||||
let actual = websocket
|
||||
.next()
|
||||
.await
|
||||
.expect("websocket should receive a message")
|
||||
.expect("websocket message should be valid");
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
target_task.await.expect("target task should finish");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_route_connects_secure_websocket() {
|
||||
let (tls_config, acceptor) = test_tls_configs();
|
||||
let (target_addr, target_task) = start_tls_websocket_server(acceptor).await;
|
||||
let request = format!("wss://localhost:{}/v1/responses", target_addr.port())
|
||||
.into_client_request()
|
||||
.expect("websocket request should build");
|
||||
|
||||
let (inner, _) = connect(
|
||||
request,
|
||||
WebSocketConfig::default(),
|
||||
tls_config,
|
||||
OutboundProxyRoute::Direct,
|
||||
)
|
||||
.await
|
||||
.expect("direct websocket handshake should succeed");
|
||||
drop(WebSocketConnection { inner });
|
||||
|
||||
target_task.await.expect("target task should finish");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_proxy_tunnels_secure_websocket_before_handshake() {
|
||||
assert_proxy_tunnels_secure_websocket(/*proxy_tls*/ false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn https_proxy_tunnels_secure_websocket_before_handshake() {
|
||||
assert_proxy_tunnels_secure_websocket(/*proxy_tls*/ true).await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn https_proxy_defaults_to_port_443_and_preserves_explicit_port() {
|
||||
let default_port = ProxyEndpoint::parse("https://proxy.example")
|
||||
.expect("HTTPS proxy without a port should parse");
|
||||
let explicit_port = ProxyEndpoint::parse("https://proxy.example:8443")
|
||||
.expect("HTTPS proxy with a port should parse");
|
||||
|
||||
assert_eq!(
|
||||
default_port,
|
||||
ProxyEndpoint {
|
||||
config: ProxyConfig {
|
||||
scheme: ProxyScheme::Http,
|
||||
host: "proxy.example".to_string(),
|
||||
port: 443,
|
||||
auth: None,
|
||||
},
|
||||
tls: true,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
explicit_port,
|
||||
ProxyEndpoint {
|
||||
config: ProxyConfig {
|
||||
scheme: ProxyScheme::Http,
|
||||
host: "proxy.example".to_string(),
|
||||
port: 8443,
|
||||
auth: None,
|
||||
},
|
||||
tls: true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn happy_eyeballs_does_not_wait_for_stalled_preferred_family() {
|
||||
let stalled = "[2001:db8::1]:443"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("stalled address should parse");
|
||||
let reachable = "127.0.0.1:443"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("reachable address should parse");
|
||||
|
||||
let connected = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
connect_happy_eyeballs(vec![stalled, reachable], |address| async move {
|
||||
if address == stalled {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
Ok(address)
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("alternate family should start before timeout")
|
||||
.expect("alternate family should connect");
|
||||
|
||||
assert_eq!(connected, reachable);
|
||||
}
|
||||
|
||||
async fn start_plain_echo_websocket_server() -> (SocketAddr, JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("target listener should bind");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("target listener should have an address");
|
||||
let task = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.expect("target should accept");
|
||||
let mut websocket = accept_async(stream)
|
||||
.await
|
||||
.expect("target websocket handshake should succeed");
|
||||
let message = websocket
|
||||
.next()
|
||||
.await
|
||||
.expect("target should receive a message")
|
||||
.expect("target websocket message should be valid");
|
||||
websocket
|
||||
.send(message)
|
||||
.await
|
||||
.expect("target should echo the message");
|
||||
});
|
||||
(address, task)
|
||||
}
|
||||
|
||||
async fn assert_proxy_tunnels_secure_websocket(proxy_tls: bool) {
|
||||
let (tls_config, acceptor) = test_tls_configs();
|
||||
let (target_addr, target_task) = start_tls_websocket_server(acceptor.clone()).await;
|
||||
|
||||
let proxy_listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("proxy listener should bind");
|
||||
let proxy_addr = proxy_listener
|
||||
.local_addr()
|
||||
.expect("proxy listener should have an address");
|
||||
let connect_request = Arc::new(Mutex::new(None));
|
||||
let proxy_connect_request = Arc::clone(&connect_request);
|
||||
let proxy_task = tokio::spawn(async move {
|
||||
let (client, _) = proxy_listener.accept().await.expect("proxy should accept");
|
||||
let mut client: Box<dyn AsyncIo> = if proxy_tls {
|
||||
Box::new(
|
||||
acceptor
|
||||
.accept(client)
|
||||
.await
|
||||
.expect("proxy TLS handshake should succeed"),
|
||||
)
|
||||
} else {
|
||||
Box::new(client)
|
||||
};
|
||||
let mut request = Vec::new();
|
||||
let mut byte = [0_u8; 1];
|
||||
while !request.ends_with(b"\r\n\r\n") {
|
||||
client
|
||||
.read_exact(&mut byte)
|
||||
.await
|
||||
.expect("proxy should read CONNECT request");
|
||||
request.push(byte[0]);
|
||||
}
|
||||
*proxy_connect_request.lock().await =
|
||||
Some(String::from_utf8(request).expect("CONNECT request should contain valid UTF-8"));
|
||||
|
||||
let mut target = tokio::net::TcpStream::connect(target_addr)
|
||||
.await
|
||||
.expect("proxy should connect to target");
|
||||
client
|
||||
.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
.await
|
||||
.expect("proxy should acknowledge CONNECT");
|
||||
let _ = tokio::io::copy_bidirectional(&mut client, &mut target).await;
|
||||
});
|
||||
|
||||
let target_authority = format!("localhost:{}", target_addr.port());
|
||||
let proxy_scheme = if proxy_tls { "https" } else { "http" };
|
||||
let request = format!("wss://{target_authority}/v1/responses")
|
||||
.into_client_request()
|
||||
.expect("websocket request should build");
|
||||
let (inner, _) = connect(
|
||||
request,
|
||||
WebSocketConfig::default(),
|
||||
tls_config,
|
||||
OutboundProxyRoute::Proxy {
|
||||
url: format!("{proxy_scheme}://localhost:{}", proxy_addr.port()),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("proxied websocket handshake should succeed");
|
||||
drop(WebSocketConnection { inner });
|
||||
|
||||
target_task.await.expect("target task should finish");
|
||||
proxy_task.await.expect("proxy task should finish");
|
||||
let request = connect_request
|
||||
.lock()
|
||||
.await
|
||||
.clone()
|
||||
.expect("proxy should record CONNECT request");
|
||||
let expected_request_line = format!("CONNECT {target_authority} HTTP/1.1");
|
||||
assert_eq!(request.lines().next(), Some(expected_request_line.as_str()));
|
||||
}
|
||||
|
||||
async fn start_tls_websocket_server(acceptor: TlsAcceptor) -> (SocketAddr, JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("target listener should bind");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("target listener should have an address");
|
||||
let task = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.expect("target should accept");
|
||||
let stream = acceptor
|
||||
.accept(stream)
|
||||
.await
|
||||
.expect("target TLS handshake should succeed");
|
||||
let mut websocket = accept_async(stream)
|
||||
.await
|
||||
.expect("target websocket handshake should succeed");
|
||||
let _ = websocket.close(None).await;
|
||||
});
|
||||
(address, task)
|
||||
}
|
||||
|
||||
fn test_tls_configs() -> (Arc<ClientConfig>, TlsAcceptor) {
|
||||
ensure_rustls_crypto_provider();
|
||||
let CertifiedKey { cert, signing_key } =
|
||||
generate_simple_self_signed(vec!["localhost".to_string()])
|
||||
.expect("test certificate should generate");
|
||||
let certificate = cert.der().clone();
|
||||
let private_key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(signing_key.serialize_der()));
|
||||
let server_config = ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![certificate.clone()], private_key)
|
||||
.expect("test server config should build");
|
||||
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots
|
||||
.add(certificate)
|
||||
.expect("test certificate should be trusted");
|
||||
let client_config = ClientConfig::builder()
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth();
|
||||
|
||||
(
|
||||
Arc::new(client_config),
|
||||
TlsAcceptor::from(Arc::new(server_config)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Proxy-aware WebSocket connection setup shared by Codex API clients.
|
||||
|
||||
mod dialer;
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
|
||||
use codex_http_client::BuildCustomCaTransportError;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::build_rustls_client_config_with_custom_ca;
|
||||
use futures::Sink;
|
||||
use futures::Stream;
|
||||
use rustls::ClientConfig;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_tungstenite::MaybeTlsStream;
|
||||
use tokio_tungstenite::WebSocketStream as TungsteniteStream;
|
||||
use tokio_tungstenite::tungstenite::Error as WebSocketError;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::tungstenite::handshake::client::Request;
|
||||
use tokio_tungstenite::tungstenite::handshake::client::Response;
|
||||
use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
|
||||
|
||||
/// Connects WebSockets using the outbound proxy policy resolved by application configuration.
|
||||
///
|
||||
/// Construct this from the effective [`HttpClientFactory`] rather than selecting proxy behavior at
|
||||
/// individual call sites. Each connection resolves its destination through that factory before
|
||||
/// opening a socket.
|
||||
#[derive(Clone)]
|
||||
pub struct WebSocketConnector {
|
||||
http_client_factory: HttpClientFactory,
|
||||
tls_config: Arc<ClientConfig>,
|
||||
}
|
||||
|
||||
impl WebSocketConnector {
|
||||
/// Creates a connector using native roots and any configured Codex custom CA bundle.
|
||||
pub fn new(
|
||||
http_client_factory: &HttpClientFactory,
|
||||
) -> Result<Self, BuildCustomCaTransportError> {
|
||||
Ok(Self {
|
||||
http_client_factory: http_client_factory.clone(),
|
||||
tls_config: build_rustls_client_config_with_custom_ca()?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Connects a WebSocket after resolving the request destination through the configured proxy
|
||||
/// policy.
|
||||
pub async fn connect(
|
||||
&self,
|
||||
request: Request,
|
||||
config: WebSocketConfig,
|
||||
) -> Result<(WebSocketConnection, Response), WebSocketError> {
|
||||
let proxy_route = self
|
||||
.http_client_factory
|
||||
.resolve_proxy_route(&request.uri().to_string());
|
||||
let (inner, response) =
|
||||
dialer::connect(request, config, Arc::clone(&self.tls_config), proxy_route).await?;
|
||||
Ok((WebSocketConnection { inner }, response))
|
||||
}
|
||||
}
|
||||
|
||||
/// An established WebSocket independent of its direct, proxy, and TLS transport layers.
|
||||
///
|
||||
/// This implements [`Stream`] and [`Sink`] so protocol clients can process Tungstenite messages
|
||||
/// without knowing which concrete network stream route selection produced.
|
||||
pub struct WebSocketConnection {
|
||||
inner: ConnectionInner,
|
||||
}
|
||||
|
||||
impl Stream for WebSocketConnection {
|
||||
type Item = Result<Message, WebSocketError>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
match &mut self.get_mut().inner {
|
||||
ConnectionInner::TransportDefault(stream) => Pin::new(stream).poll_next(context),
|
||||
ConnectionInner::Routed(stream) => Pin::new(stream).poll_next(context),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<Message> for WebSocketConnection {
|
||||
type Error = WebSocketError;
|
||||
|
||||
fn poll_ready(
|
||||
self: Pin<&mut Self>,
|
||||
context: &mut Context<'_>,
|
||||
) -> Poll<Result<(), Self::Error>> {
|
||||
match &mut self.get_mut().inner {
|
||||
ConnectionInner::TransportDefault(stream) => Pin::new(stream).poll_ready(context),
|
||||
ConnectionInner::Routed(stream) => Pin::new(stream).poll_ready(context),
|
||||
}
|
||||
}
|
||||
|
||||
fn start_send(self: Pin<&mut Self>, message: Message) -> Result<(), Self::Error> {
|
||||
match &mut self.get_mut().inner {
|
||||
ConnectionInner::TransportDefault(stream) => Pin::new(stream).start_send(message),
|
||||
ConnectionInner::Routed(stream) => Pin::new(stream).start_send(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(
|
||||
self: Pin<&mut Self>,
|
||||
context: &mut Context<'_>,
|
||||
) -> Poll<Result<(), Self::Error>> {
|
||||
match &mut self.get_mut().inner {
|
||||
ConnectionInner::TransportDefault(stream) => Pin::new(stream).poll_flush(context),
|
||||
ConnectionInner::Routed(stream) => Pin::new(stream).poll_flush(context),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_close(
|
||||
self: Pin<&mut Self>,
|
||||
context: &mut Context<'_>,
|
||||
) -> Poll<Result<(), Self::Error>> {
|
||||
match &mut self.get_mut().inner {
|
||||
ConnectionInner::TransportDefault(stream) => Pin::new(stream).poll_close(context),
|
||||
ConnectionInner::Routed(stream) => Pin::new(stream).poll_close(context),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum ConnectionInner {
|
||||
TransportDefault(TungsteniteStream<MaybeTlsStream<TcpStream>>),
|
||||
Routed(TungsteniteStream<MaybeTlsStream<Box<dyn AsyncIo>>>),
|
||||
}
|
||||
|
||||
/// Async network I/O carried through optional proxy and target TLS handshakes.
|
||||
pub(crate) trait AsyncIo: AsyncRead + AsyncWrite + Send + Unpin {}
|
||||
|
||||
impl<T> AsyncIo for T where T: AsyncRead + AsyncWrite + Send + Unpin {}
|
||||
@@ -10,20 +10,22 @@ use windows_sys::Win32::Security::OBJECT_INHERIT_ACE;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_EXECUTE;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "setup_runtime_bin_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
pub(super) fn ensure_codex_app_runtime_paths_readable(
|
||||
sandbox_group_psid: *mut c_void,
|
||||
refresh_errors: &mut Vec<String>,
|
||||
log: &mut dyn Write,
|
||||
) -> Result<()> {
|
||||
let local_app_data = local_app_data_root();
|
||||
let Some(local_app_data) = local_app_data else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let read_execute_mask = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE;
|
||||
let codex_root = local_app_data.join("OpenAI").join("Codex");
|
||||
let runtime_paths = runtime_paths(
|
||||
local_app_data_root(),
|
||||
std::env::var_os("USERPROFILE").map(PathBuf::from),
|
||||
);
|
||||
|
||||
for runtime_path in [codex_root.join("bin"), codex_root.join("runtimes")] {
|
||||
for runtime_path in runtime_paths {
|
||||
if !runtime_path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
@@ -86,6 +88,20 @@ pub(super) fn ensure_codex_app_runtime_paths_readable(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn runtime_paths(local_app_data: Option<PathBuf>, user_profile: Option<PathBuf>) -> Vec<PathBuf> {
|
||||
let mut runtime_paths = Vec::new();
|
||||
if let Some(local_app_data) = local_app_data {
|
||||
let codex_root = local_app_data.join("OpenAI").join("Codex");
|
||||
runtime_paths.extend([codex_root.join("bin"), codex_root.join("runtimes")]);
|
||||
}
|
||||
// The managed primary runtime is installed outside the LocalAppData runtime roots.
|
||||
if let Some(user_profile) = user_profile {
|
||||
runtime_paths.push(user_profile.join(".cache").join("codex-runtimes"));
|
||||
}
|
||||
|
||||
runtime_paths
|
||||
}
|
||||
|
||||
fn local_app_data_root() -> Option<PathBuf> {
|
||||
std::env::var_os("LOCALAPPDATA")
|
||||
.map(PathBuf::from)
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
use super::runtime_paths;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn runtime_paths_include_desktop_and_primary_runtime_roots() {
|
||||
let local_app_data = PathBuf::from(r"C:\Users\user\AppData\Local");
|
||||
let user_profile = PathBuf::from(r"C:\Users\user");
|
||||
|
||||
assert_eq!(
|
||||
runtime_paths(Some(local_app_data), Some(user_profile)),
|
||||
vec![
|
||||
PathBuf::from(r"C:\Users\user\AppData\Local\OpenAI\Codex\bin"),
|
||||
PathBuf::from(r"C:\Users\user\AppData\Local\OpenAI\Codex\runtimes"),
|
||||
PathBuf::from(r"C:\Users\user\.cache\codex-runtimes"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primary_runtime_path_does_not_depend_on_local_app_data() {
|
||||
let user_profile = PathBuf::from(r"C:\Users\user");
|
||||
|
||||
assert_eq!(
|
||||
runtime_paths(/*local_app_data*/ None, Some(user_profile)),
|
||||
vec![PathBuf::from(r"C:\Users\user\.cache\codex-runtimes")]
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user