WIP fase 2b-3: rimozione sottosistemi solo-ChatGPT (plugin remoti, image gen, daybreak, cyber, attestation, cloud config, app/connettori) - test in corso

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:07:22 +01:00
parent 231e8cd136
commit 5afc7e9f7f
1223 changed files with 6225 additions and 113722 deletions

View File

@@ -1,6 +1,11 @@
//! Sandbox coverage for extension-contributed tools.
//!
//! A test-only probe extension reads and writes files through the turn's environment
//! filesystem and issues HTTP requests through the configured client factory, so these
//! tests exercise the permissions and network policy every extension tool inherits.
use core_test_support::test_codex::local_requests;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Context;
@@ -8,15 +13,27 @@ use anyhow::Result;
use codex_core::TurnInputRequest;
use codex_core::config::Config;
use codex_core::config::Constrained;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistry;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_items::ExtensionItem;
use codex_extension_items::image_generation::GeneratedImageRef;
use codex_extension_api::FunctionCallError;
use codex_extension_api::JsonToolOutput;
use codex_extension_api::ResponsesApiTool;
use codex_extension_api::ThreadLifecycleContributor;
use codex_extension_api::ThreadStartInput;
use codex_extension_api::ToolCall;
use codex_extension_api::ToolContributor;
use codex_extension_api::ToolExecutor;
use codex_extension_api::ToolExecutorFuture;
use codex_extension_api::ToolName;
use codex_extension_api::ToolOutput;
use codex_extension_api::ToolSpec;
use codex_features::Feature;
use codex_history::RolloutItem;
use codex_http_client::ClientRouteClass;
use codex_http_client::DestinationPolicy;
use codex_http_client::HttpClientFactory;
use codex_http_client::NetworkPolicyController;
use codex_image_generation_extension::install as install_image_generation_extension;
use codex_login::CodexAuth;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::CollaborationMode;
@@ -24,11 +41,7 @@ use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::Settings;
use codex_protocol::config_types::WebSearchMode;
use codex_protocol::models::FileSystemPermissions;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::ImageReference;
use codex_protocol::models::PermissionProfile;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::InputModality;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
@@ -38,13 +51,14 @@ use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::request_permissions::PermissionGrantScope;
use codex_protocol::request_permissions::RequestPermissionProfile;
use codex_protocol::request_permissions::RequestPermissionsResponse;
use codex_protocol::user_input::UserInput;
use codex_tools::JsonSchema;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_sandbox;
@@ -52,177 +66,153 @@ use core_test_support::skip_if_target_windows;
use core_test_support::test_codex::test_codex;
use core_test_support::test_codex::turn_permission_fields;
use core_test_support::wait_for_event;
use core_test_support::wait_for_event_match;
use pretty_assertions::assert_eq;
use serde::Deserialize;
use serde_json::json;
use test_case::test_case;
use wiremock::Mock;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::image_rollout::RecordingFileAttachmentStore;
const PROBE_TOOL_NAME: &str = "sandbox_probe";
const PROBE_FETCH_PATH: &str = "/probe/fetch";
const PROBE_FILE_BYTES: &[u8] = b"sandbox probe payload";
const TINY_PNG_BYTES: &[u8] = &[
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0,
0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, 120, 156, 99, 248, 207, 192, 240, 31, 0,
5, 0, 1, 255, 137, 153, 61, 29, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
];
const TINY_PNG_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
const TINY_PNG_DATA_URL: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
#[derive(Clone)]
struct ProbeConfig {
http_client_factory: HttpClientFactory,
}
fn image_generation_extensions(
auth: &CodexAuth,
resolve_save_root: impl Fn(&Config) -> Option<AbsolutePathBuf> + Send + Sync + 'static,
) -> Arc<ExtensionRegistry<Config>> {
let auth_manager = codex_core::test_support::auth_manager_from_auth(auth.clone());
struct SandboxProbeExtension;
impl ThreadLifecycleContributor<Config> for SandboxProbeExtension {
fn on_thread_start<'a>(
&'a self,
input: ThreadStartInput<'a, Config>,
) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.thread_store.insert(ProbeConfig {
http_client_factory: input.config.http_client_factory(),
});
})
}
}
impl ToolContributor for SandboxProbeExtension {
fn tools(
&self,
_session_store: &ExtensionData,
thread_store: &ExtensionData,
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
let Some(config) = thread_store.get::<ProbeConfig>() else {
return Vec::new();
};
vec![Arc::new(SandboxProbeTool {
http_client_factory: config.http_client_factory.clone(),
})]
}
}
/// Reads `path` through the turn environment, copies it to `copy_to`, and optionally fetches
/// `fetch_url` through the configured HTTP client factory first.
struct SandboxProbeTool {
http_client_factory: HttpClientFactory,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ProbeArgs {
path: AbsolutePathBuf,
copy_to: Option<AbsolutePathBuf>,
fetch_url: Option<String>,
}
impl<'call> ToolExecutor<ToolCall<'call>> for SandboxProbeTool {
fn tool_name(&self) -> ToolName {
ToolName::plain(PROBE_TOOL_NAME)
}
fn spec(&self) -> ToolSpec {
let properties = ["path", "copy_to", "fetch_url"]
.into_iter()
.map(|name| (name.to_string(), JsonSchema::string(/*description*/ None)))
.collect();
ToolSpec::Function(ResponsesApiTool {
name: PROBE_TOOL_NAME.to_string(),
description: "Test probe for extension sandboxing.".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
properties,
Some(vec!["path".to_string()]),
Some(false.into()),
),
output_schema: None,
})
}
fn handle<'a>(&'a self, call: ToolCall<'call>) -> ToolExecutorFuture<'a>
where
'call: 'a,
{
Box::pin(async move {
let args: ProbeArgs = serde_json::from_str(call.function_arguments()?)
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
if let Some(fetch_url) = args.fetch_url.as_deref() {
let client = self
.http_client_factory
.build_client(fetch_url, ClientRouteClass::Api)
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
client.get(fetch_url).send().await.map_err(|error| {
FunctionCallError::RespondToModel(format!("probe fetch failed: {error}"))
})?;
}
let Some(environment) = call.environments.first() else {
return Err(FunctionCallError::RespondToModel(
"no environment available".to_string(),
));
};
let bytes = environment
.fs()
.read_file(&PathUri::from_abs_path(&args.path), Default::default())
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
"unable to read file at `{}`: {error}",
args.path.display()
))
})?;
if let Some(copy_to) = args.copy_to.as_ref() {
environment
.fs()
.write_file(
&PathUri::from_abs_path(copy_to),
bytes.clone(),
Default::default(),
)
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
"unable to write file at `{}`: {error}",
copy_to.display()
))
})?;
}
let output = json!({ "contents": String::from_utf8_lossy(&bytes) });
Ok(Box::new(JsonToolOutput::new(output)) as Box<dyn ToolOutput>)
})
}
}
fn probe_extensions() -> Arc<ExtensionRegistry<Config>> {
let extension = Arc::new(SandboxProbeExtension);
let mut extension_builder = ExtensionRegistryBuilder::<Config>::new();
install_image_generation_extension(&mut extension_builder, auth_manager, resolve_save_root);
extension_builder.thread_lifecycle_contributor(extension.clone());
extension_builder.tool_contributor(extension);
Arc::new(extension_builder.build())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn generated_image_ui_item_is_file_backed_in_rollout() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
Mock::given(method("POST"))
.and(path("/v1/images/generations"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"created": 1,
"data": [{"b64_json": TINY_PNG_BASE64}],
})))
.expect(1)
.mount(&server)
.await;
let auth = CodexAuth::from_api_key("Test API Key");
let extensions = image_generation_extensions(&auth, |_config| None);
let image_store = Arc::new(RecordingFileAttachmentStore::default());
let image_call_id = "image-generate-file-backed";
responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_function_call_with_namespace(
image_call_id,
"image_gen",
"imagegen",
&json!({"prompt": "paint a blue whale"}).to_string(),
),
responses::ev_completed("resp-1"),
]),
responses::sse(vec![
responses::ev_response_created("resp-2"),
responses::ev_assistant_message("msg-1", "done"),
responses::ev_completed("resp-2"),
]),
],
)
.await;
let test = test_codex()
.with_auth(auth)
.with_extensions(extensions)
.with_image_store(image_store.clone())
.with_history_mode(ThreadHistoryMode::Paginated)
.with_model_info_override("gpt-5.4", |model_info| {
model_info.use_responses_lite = true;
model_info.input_modalities = vec![InputModality::Text, InputModality::Image];
})
.build(&server)
.await?;
test.codex
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: "generate an image".to_string(),
text_elements: Vec::new(),
}]))
.await?;
let live_image =
wait_for_event_match(&test.codex, |event| match event {
EventMsg::ItemCompleted(event) => match &event.item {
codex_protocol::items::TurnItem::Extension(ExtensionItem::ImageGeneration(
image,
)) if image.id == image_call_id => Some(image.clone()),
_ => None,
},
_ => None,
})
.await;
assert_eq!(
live_image.image,
GeneratedImageRef::File {
file_id: "file_uploaded_image".to_string(),
}
);
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
test.codex.flush_rollout().await?;
{
let uploads = image_store.uploads.lock().expect("uploads lock");
let [item_upload, model_upload] = uploads.as_slice() else {
panic!("expected separate item and model uploads");
};
assert_eq!(
item_upload.thread_id,
test.session_configured.thread_id.to_string()
);
assert!(!item_upload.ephemeral);
assert_eq!(
item_upload.tags,
HashMap::from([("usage".to_string(), "image_gen".to_string())])
);
assert_eq!(item_upload.data, TINY_PNG_BYTES);
assert_eq!(model_upload.tags, HashMap::new());
}
let rollout_path = test.codex.rollout_path().context("rollout path")?;
let rollout = std::fs::read_to_string(rollout_path)?
.lines()
.filter_map(|line| codex_rollout::parse_rollout_line(line).ok())
.map(|line| line.item)
.collect::<Vec<_>>();
let image =
rollout.iter().find_map(|item| match item {
RolloutItem::EventMsg(EventMsg::ItemCompleted(event)) => match &event.item {
codex_protocol::items::TurnItem::Extension(ExtensionItem::ImageGeneration(
image,
)) if image.id == image_call_id => Some(image),
_ => None,
},
_ => None,
});
let image = image.context("persisted image-generation item")?;
assert_eq!(image, &live_image);
let output_image = rollout.iter().find_map(|item| match item {
RolloutItem::ResponseItem(envelope) => match &envelope.item {
ResponseItem::FunctionCallOutput {
call_id: Some(call_id),
output,
..
} if call_id == image_call_id => output.content_items().and_then(|items| {
items.iter().find_map(|item| match item {
FunctionCallOutputContentItem::InputImage { image, .. } => Some(image),
_ => None,
})
}),
_ => None,
},
_ => None,
});
assert_eq!(
output_image,
Some(&ImageReference::File {
file_id: "file_uploaded_image".to_string(),
})
);
Ok(())
fn probe_output_contents(output: &serde_json::Value) -> Option<String> {
let text = output["output"].as_str()?;
let value: serde_json::Value = serde_json::from_str(text).ok()?;
value["contents"].as_str().map(str::to_string)
}
#[test_case(false; "file_access")]
@@ -234,14 +224,9 @@ async fn extension_tool_respects_restrictions(deny_network: bool) -> Result<()>
let server = responses::start_mock_server().await;
let responses_url = format!("{}/v1/responses", server.uri()).parse()?;
let auth = CodexAuth::from_api_key("Test API Key");
let extensions = image_generation_extensions(&auth, |config| Some(config.codex_home.clone()));
let mut builder = test_codex()
.with_auth(auth)
.with_extensions(extensions)
.with_model_info_override("gpt-5.4", |model_info| {
model_info.use_responses_lite = true;
model_info.input_modalities = vec![InputModality::Text, InputModality::Image];
})
.with_extensions(probe_extensions())
.with_config(move |config| {
assert!(config.web_search_mode.set(WebSearchMode::Live).is_ok());
if deny_network {
@@ -255,23 +240,27 @@ async fn extension_tool_respects_restrictions(deny_network: bool) -> Result<()>
}
});
let test = builder.build(&server).await?;
let denied_path = test.config.cwd.join("denied.png");
std::fs::write(&denied_path, TINY_PNG_BYTES)?;
let denied_path = test.config.cwd.join("denied.txt");
std::fs::write(&denied_path, PROBE_FILE_BYTES)?;
let fetch_url = format!("{}{PROBE_FETCH_PATH}", server.uri());
let call_id = "image-edit-denied";
let call_id = "probe-denied";
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_function_call_with_namespace(
responses::ev_function_call(
call_id,
"image_gen",
"imagegen",
&json!({
"prompt": "edit the image",
"referenced_image_paths": [denied_path.display().to_string()],
})
PROBE_TOOL_NAME,
&if deny_network {
json!({
"path": denied_path.display().to_string(),
"fetch_url": fetch_url,
})
} else {
json!({ "path": denied_path.display().to_string() })
}
.to_string(),
),
responses::ev_completed("resp-1"),
@@ -302,7 +291,7 @@ async fn extension_tool_respects_restrictions(deny_network: bool) -> Result<()>
NetworkSandboxPolicy::Restricted,
);
test.submit_turn_with_permission_profile("edit the denied image", permission_profile)
test.submit_turn_with_permission_profile("read the denied file", permission_profile)
.await?;
let request = response_mock
@@ -320,16 +309,16 @@ async fn extension_tool_respects_restrictions(deny_network: bool) -> Result<()>
let requests = server
.received_requests()
.await
.context("image request history should be recorded")?;
.context("request history should be recorded")?;
assert!(
requests
.iter()
.all(|request| !request.url.path().starts_with("/v1/images/"))
.all(|request| request.url.path() != PROBE_FETCH_PATH)
);
} else {
assert!(
output.starts_with(&format!(
"unable to read referenced image at `{}`:",
"unable to read file at `{}`:",
denied_path.display()
)),
"unexpected extension error: {output}"
@@ -346,18 +335,8 @@ async fn extension_tool_uses_granted_turn_permissions_without_host_local_persist
skip_if_sandbox!(Ok(()));
let server = responses::start_mock_server().await;
Mock::given(method("POST"))
.and(path("/v1/images/edits"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"created": 1,
"data": [{"b64_json": TINY_PNG_BASE64}],
})))
.expect(1)
.mount(&server)
.await;
let auth = CodexAuth::from_api_key("Test API Key");
let extensions = image_generation_extensions(&auth, |_config| None);
let base_permission_profile = PermissionProfile::workspace_write_with(
&[],
NetworkSandboxPolicy::Restricted,
@@ -367,11 +346,7 @@ async fn extension_tool_uses_granted_turn_permissions_without_host_local_persist
let permission_profile_for_config = base_permission_profile.clone();
let mut builder = test_codex()
.with_auth(auth)
.with_extensions(extensions)
.with_model_info_override("gpt-5.4", |model_info| {
model_info.use_responses_lite = true;
model_info.input_modalities = vec![InputModality::Text, InputModality::Image];
})
.with_extensions(probe_extensions())
.with_config(move |config| {
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
config
@@ -388,20 +363,26 @@ async fn extension_tool_uses_granted_turn_permissions_without_host_local_persist
});
let test = builder.build(&server).await?;
let image_dir = tempfile::tempdir()?;
let image_path = image_dir.path().canonicalize()?.join("granted.png");
std::fs::write(&image_path, TINY_PNG_BYTES)?;
let probe_dir = tempfile::tempdir()?;
let probe_path = probe_dir.path().canonicalize()?.join("granted.txt");
std::fs::write(&probe_path, PROBE_FILE_BYTES)?;
let requested_permissions = RequestPermissionProfile {
file_system: Some(FileSystemPermissions::from_read_write_roots(
Some(vec![AbsolutePathBuf::try_from(
image_dir.path().canonicalize()?,
probe_dir.path().canonicalize()?,
)?]),
Some(Vec::new()),
)),
..RequestPermissionProfile::default()
};
let permissions_call_id = "permissions-call";
let image_call_id = "image-edit-granted";
let probe_call_id = "probe-granted";
let copy_path = test
.config
.cwd
.join("probe_output")
.join("probe-granted.txt");
std::fs::create_dir_all(test.config.cwd.join("probe_output"))?;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
@@ -411,7 +392,7 @@ async fn extension_tool_uses_granted_turn_permissions_without_host_local_persist
permissions_call_id,
"request_permissions",
&serde_json::to_string(&json!({
"reason": "Read an image outside the workspace",
"reason": "Read a file outside the workspace",
"permissions": requested_permissions,
}))?,
),
@@ -419,13 +400,12 @@ async fn extension_tool_uses_granted_turn_permissions_without_host_local_persist
]),
responses::sse(vec![
responses::ev_response_created("resp-2"),
responses::ev_function_call_with_namespace(
image_call_id,
"image_gen",
"imagegen",
responses::ev_function_call(
probe_call_id,
PROBE_TOOL_NAME,
&json!({
"prompt": "edit the image",
"referenced_image_paths": [image_path.display().to_string()],
"path": probe_path.display().to_string(),
"copy_to": copy_path.display().to_string(),
})
.to_string(),
),
@@ -445,7 +425,7 @@ async fn extension_tool_uses_granted_turn_permissions_without_host_local_persist
test.codex
.start_or_steer_turn(
TurnInputRequest::user_input(vec![UserInput::Text {
text: "request access and edit the image".to_string(),
text: "request access and read the file".to_string(),
text_elements: Vec::new(),
}])
.with_thread_settings(ThreadSettingsOverrides {
@@ -495,27 +475,14 @@ async fn extension_tool_uses_granted_turn_permissions_without_host_local_persist
let request = response_mock
.last_request()
.context("missing request containing extension output")?;
let output = request.function_call_output(image_call_id);
let expected_path = test
.config
.cwd
.join("generated_images")
.join("image-edit-granted.png");
let output = request.function_call_output(probe_call_id);
assert_eq!(
output["output"][0],
json!({
"type": "input_image",
"image_url": TINY_PNG_DATA_URL,
})
probe_output_contents(&output).as_deref(),
Some(std::str::from_utf8(PROBE_FILE_BYTES)?),
"{output}"
);
assert_eq!(output["output"].as_array().map(Vec::len), Some(2));
assert!(
output["output"][1]["text"]
.as_str()
.is_some_and(|hint| hint.contains(&expected_path.display().to_string()))
);
assert_eq!(std::fs::read(expected_path.as_path())?, TINY_PNG_BYTES);
assert!(!test.config.codex_home.join("generated_images").exists());
assert_eq!(std::fs::read(copy_path.as_path())?, PROBE_FILE_BYTES);
assert!(!test.config.codex_home.join("probe_output").exists());
Ok(())
}
@@ -535,21 +502,8 @@ async fn extension_tool_rebinds_granted_permissions_on_each_turn(
);
let server = responses::start_mock_server().await;
Mock::given(method("POST"))
.and(path("/v1/images/edits"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"created": 1,
"data": [{"b64_json": TINY_PNG_BASE64}],
})))
.expect(match grant_scope {
PermissionGrantScope::Turn => 1,
PermissionGrantScope::Session => 2,
})
.mount(&server)
.await;
let auth = CodexAuth::from_api_key("Test API Key");
let extensions = image_generation_extensions(&auth, |_config| None);
let base_permission_profile = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
@@ -570,11 +524,7 @@ async fn extension_tool_rebinds_granted_permissions_on_each_turn(
let permission_profile_for_config = base_permission_profile.clone();
let mut builder = test_codex()
.with_auth(auth)
.with_extensions(extensions)
.with_model_info_override("gpt-5.4", |model_info| {
model_info.use_responses_lite = true;
model_info.input_modalities = vec![InputModality::Text, InputModality::Image];
})
.with_extensions(probe_extensions())
.with_config(move |config| {
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
config
@@ -591,21 +541,23 @@ async fn extension_tool_rebinds_granted_permissions_on_each_turn(
});
let test = builder.build(&server).await?;
let image_dir = tempfile::tempdir()?;
let image_path = image_dir.path().canonicalize()?.join("granted.png");
std::fs::write(&image_path, TINY_PNG_BYTES)?;
let probe_dir = tempfile::tempdir()?;
let probe_path = probe_dir.path().canonicalize()?.join("granted.txt");
std::fs::write(&probe_path, PROBE_FILE_BYTES)?;
let requested_permissions = RequestPermissionProfile {
file_system: Some(FileSystemPermissions::from_read_write_roots(
Some(vec![AbsolutePathBuf::try_from(
image_dir.path().canonicalize()?,
probe_dir.path().canonicalize()?,
)?]),
Some(Vec::new()),
)),
..RequestPermissionProfile::default()
};
let permissions_call_id = "permissions-call";
let image_call_id = "image-edit-granted";
let next_image_call_id = "image-edit-next-turn";
let probe_call_id = "probe-granted";
let next_probe_call_id = "probe-next-turn";
let copy_path = test.config.cwd.join("probe-granted.txt");
let next_copy_path = test.config.cwd.join("probe-next-turn.txt");
let response_mock = responses::mount_sse_sequence(
&server,
vec![
@@ -615,7 +567,7 @@ async fn extension_tool_rebinds_granted_permissions_on_each_turn(
permissions_call_id,
"request_permissions",
&serde_json::to_string(&json!({
"reason": "Read an image outside the workspace",
"reason": "Read a file outside the workspace",
"permissions": requested_permissions,
}))?,
),
@@ -623,13 +575,12 @@ async fn extension_tool_rebinds_granted_permissions_on_each_turn(
]),
responses::sse(vec![
responses::ev_response_created("resp-2"),
responses::ev_function_call_with_namespace(
image_call_id,
"image_gen",
"imagegen",
responses::ev_function_call(
probe_call_id,
PROBE_TOOL_NAME,
&json!({
"prompt": "edit the image",
"referenced_image_paths": [image_path.display().to_string()],
"path": probe_path.display().to_string(),
"copy_to": copy_path.display().to_string(),
})
.to_string(),
),
@@ -642,13 +593,12 @@ async fn extension_tool_rebinds_granted_permissions_on_each_turn(
]),
responses::sse(vec![
responses::ev_response_created("resp-4"),
responses::ev_function_call_with_namespace(
next_image_call_id,
"image_gen",
"imagegen",
responses::ev_function_call(
next_probe_call_id,
PROBE_TOOL_NAME,
&json!({
"prompt": "edit the image again",
"referenced_image_paths": [image_path.display().to_string()],
"path": probe_path.display().to_string(),
"copy_to": next_copy_path.display().to_string(),
})
.to_string(),
),
@@ -668,7 +618,7 @@ async fn extension_tool_rebinds_granted_permissions_on_each_turn(
test.codex
.start_or_steer_turn(
TurnInputRequest::user_input(vec![UserInput::Text {
text: "request access and edit the image".to_string(),
text: "request access and read the file".to_string(),
text_elements: Vec::new(),
}])
.with_thread_settings(ThreadSettingsOverrides {
@@ -718,16 +668,14 @@ async fn extension_tool_rebinds_granted_permissions_on_each_turn(
let request = response_mock
.last_request()
.context("missing request containing extension output")?;
let output = request.function_call_output(image_call_id);
let output = request.function_call_output(probe_call_id);
assert_eq!(
output["output"][0],
json!({
"type": "input_image",
"image_url": TINY_PNG_DATA_URL,
})
probe_output_contents(&output).as_deref(),
Some(std::str::from_utf8(PROBE_FILE_BYTES)?),
"{output}"
);
test.submit_text_turn("edit the same image in a new turn")
test.submit_text_turn("read the same file in a new turn")
.await?;
let next_request = response_mock
.last_request()
@@ -735,35 +683,26 @@ async fn extension_tool_rebinds_granted_permissions_on_each_turn(
match grant_scope {
PermissionGrantScope::Turn => {
let output = next_request
.function_call_output_content_and_success(next_image_call_id)
.function_call_output_content_and_success(next_probe_call_id)
.and_then(|(content, _)| content)
.context("expired turn grant should produce an extension error")?;
assert!(
output.starts_with(&format!(
"unable to read referenced image at `{}`:",
image_path.display()
"unable to read file at `{}`:",
probe_path.display()
)),
"unexpected extension error: {output}"
);
assert!(!next_copy_path.exists());
}
PermissionGrantScope::Session => {
let output = next_request.function_call_output(next_image_call_id);
let output = next_request.function_call_output(next_probe_call_id);
assert_eq!(
output["output"][0],
json!({
"type": "input_image",
"image_url": TINY_PNG_DATA_URL,
})
);
assert_eq!(
std::fs::read(
test.config
.cwd
.join("generated_images")
.join("image-edit-next-turn.png")
)?,
TINY_PNG_BYTES
probe_output_contents(&output).as_deref(),
Some(std::str::from_utf8(PROBE_FILE_BYTES)?),
"{output}"
);
assert_eq!(std::fs::read(next_copy_path.as_path())?, PROBE_FILE_BYTES);
}
}