aKode fase 1: niente sync plugin OpenAI, CDN pets, CIMD chatgpt.com, npm registry; pulizia codice morto
This commit is contained in:
2
codex-rs/Cargo.lock
generated
2
codex-rs/Cargo.lock
generated
@@ -3225,7 +3225,6 @@ dependencies = [
|
|||||||
"flate2",
|
"flate2",
|
||||||
"futures",
|
"futures",
|
||||||
"http 1.4.0",
|
"http 1.4.0",
|
||||||
"libc",
|
|
||||||
"pretty_assertions",
|
"pretty_assertions",
|
||||||
"regex",
|
"regex",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -3244,7 +3243,6 @@ dependencies = [
|
|||||||
"url",
|
"url",
|
||||||
"uuid",
|
"uuid",
|
||||||
"wiremock",
|
"wiremock",
|
||||||
"zip",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -122,13 +122,14 @@ async fn runtime_delivery_signs_each_batch_and_strips_cross_origin_auth() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// aKode: the analytics client never creates a delivery queue, so nothing is sent.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn custom_analytics_destination_does_not_initialize_runtime_auth() {
|
async fn analytics_client_never_sends_events() {
|
||||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||||
let server = MockServer::start().await;
|
let server = MockServer::start().await;
|
||||||
Mock::given(path("/codex/analytics-events/events"))
|
Mock::given(path("/codex/analytics-events/events"))
|
||||||
.respond_with(ResponseTemplate::new(200))
|
.respond_with(ResponseTemplate::new(200))
|
||||||
.expect(1)
|
.expect(0)
|
||||||
.mount(&server)
|
.mount(&server)
|
||||||
.await;
|
.await;
|
||||||
let client = AnalyticsEventsClient::new_with_runtime(
|
let client = AnalyticsEventsClient::new_with_runtime(
|
||||||
@@ -139,10 +140,7 @@ async fn custom_analytics_destination_does_not_initialize_runtime_auth() {
|
|||||||
/*api_key_headers*/ Default::default(),
|
/*api_key_headers*/ Default::default(),
|
||||||
);
|
);
|
||||||
emit(&client, "custom").await;
|
emit(&client, "custom").await;
|
||||||
let requests = server.received_requests().await.unwrap();
|
assert!(server.received_requests().await.unwrap().is_empty());
|
||||||
assert_eq!(requests.len(), 1);
|
|
||||||
assert_eq!(requests[0].headers["authorization"], "Bearer key-a");
|
|
||||||
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
|
|
||||||
server.verify().await;
|
server.verify().await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -309,12 +309,7 @@ impl AccountRequestProcessor {
|
|||||||
refresh_config_manager.clone(),
|
refresh_config_manager.clone(),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
thread_manager
|
// aKode: no curated marketplace sync after account changes.
|
||||||
.plugins_manager()
|
|
||||||
.maybe_start_curated_repo_sync_for_config(
|
|
||||||
&plugins_config,
|
|
||||||
Some(Arc::clone(&on_effective_plugins_changed)),
|
|
||||||
);
|
|
||||||
if let Err(err) = runtime_auth {
|
if let Err(err) = runtime_auth {
|
||||||
warn!("failed to initialize runtime auth for remote plugin refresh: {err}");
|
warn!("failed to initialize runtime auth for remote plugin refresh: {err}");
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -539,8 +539,9 @@ fn assert_dynamic_status(response: &ListMcpServerStatusResponse, process_label:
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn oauth_login_automatically_selects_callback_specific_cimd_without_metadata_issuer()
|
// aKode: CIMD (a ChatGPT-hosted client metadata document) is never offered; automatic
|
||||||
-> Result<()> {
|
// registration uses DCR even when the server advertises CIMD.
|
||||||
|
async fn oauth_login_uses_dcr_even_when_cimd_is_advertised() -> Result<()> {
|
||||||
let responses_server = create_mock_responses_server_sequence_unchecked(Vec::new()).await;
|
let responses_server = create_mock_responses_server_sequence_unchecked(Vec::new()).await;
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||||
let base_url = format!("http://{}", listener.local_addr()?);
|
let base_url = format!("http://{}", listener.local_addr()?);
|
||||||
@@ -596,11 +597,16 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada
|
|||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
"/register",
|
"/register",
|
||||||
post(move || {
|
post(move |body: Bytes| {
|
||||||
let registrations = Arc::clone(®istration_count);
|
let registrations = Arc::clone(®istration_count);
|
||||||
async move {
|
async move {
|
||||||
registrations.fetch_add(1, Ordering::SeqCst);
|
registrations.fetch_add(1, Ordering::SeqCst);
|
||||||
Json(json!({"client_id": "unexpected-dcr-client"}))
|
let registration: serde_json::Value =
|
||||||
|
serde_json::from_slice(&body).unwrap_or_default();
|
||||||
|
Json(json!({
|
||||||
|
"client_id": "dcr-client",
|
||||||
|
"redirect_uris": registration["redirect_uris"],
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
@@ -660,14 +666,15 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada
|
|||||||
let callback_id = callback_url
|
let callback_id = callback_url
|
||||||
.path()
|
.path()
|
||||||
.strip_prefix("/callback/")
|
.strip_prefix("/callback/")
|
||||||
.expect("issuerless CIMD should use a resource-specific callback");
|
.expect("issuerless servers should use a resource-specific callback");
|
||||||
let client_id = format!("https://chatgpt.com/oauth/codex/{callback_id}/client.json");
|
assert!(!callback_id.is_empty());
|
||||||
|
let client_id = "dcr-client".to_string();
|
||||||
assert_eq!(parameters.get("client_id"), Some(&client_id));
|
assert_eq!(parameters.get("client_id"), Some(&client_id));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parameters.get("code_challenge_method").map(String::as_str),
|
parameters.get("code_challenge_method").map(String::as_str),
|
||||||
Some("S256")
|
Some("S256")
|
||||||
);
|
);
|
||||||
assert_eq!(registrations.load(Ordering::SeqCst), 0);
|
assert_eq!(registrations.load(Ordering::SeqCst), 1);
|
||||||
|
|
||||||
callback_url
|
callback_url
|
||||||
.query_pairs_mut()
|
.query_pairs_mut()
|
||||||
@@ -682,7 +689,7 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada
|
|||||||
let (token_request, token_authorization) =
|
let (token_request, token_authorization) =
|
||||||
timeout(DEFAULT_READ_TIMEOUT, token_request_rx.recv())
|
timeout(DEFAULT_READ_TIMEOUT, token_request_rx.recv())
|
||||||
.await?
|
.await?
|
||||||
.expect("CIMD authorization should exchange its authorization code");
|
.expect("DCR authorization should exchange its authorization code");
|
||||||
let token_parameters = url::form_urlencoded::parse(token_request.as_bytes())
|
let token_parameters = url::form_urlencoded::parse(token_request.as_bytes())
|
||||||
.into_owned()
|
.into_owned()
|
||||||
.collect::<BTreeMap<String, String>>();
|
.collect::<BTreeMap<String, String>>();
|
||||||
@@ -714,7 +721,7 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada
|
|||||||
error: None,
|
error: None,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
assert_eq!(registrations.load(Ordering::SeqCst), 0);
|
assert_eq!(registrations.load(Ordering::SeqCst), 1);
|
||||||
|
|
||||||
let request_id = app_server
|
let request_id = app_server
|
||||||
.send_raw_request("config/mcpServer/reload", /*params*/ None)
|
.send_raw_request("config/mcpServer/reload", /*params*/ None)
|
||||||
@@ -742,7 +749,7 @@ async fn oauth_login_automatically_selects_callback_specific_cimd_without_metada
|
|||||||
.expect("MCP startup should use the access token"),
|
.expect("MCP startup should use the access token"),
|
||||||
"Bearer cimd-access-token"
|
"Bearer cimd-access-token"
|
||||||
);
|
);
|
||||||
assert_eq!(registrations.load(Ordering::SeqCst), 0);
|
assert_eq!(registrations.load(Ordering::SeqCst), 1);
|
||||||
|
|
||||||
oauth_server_handle.abort();
|
oauth_server_handle.abort();
|
||||||
let _ = oauth_server_handle.await;
|
let _ = oauth_server_handle.await;
|
||||||
|
|||||||
@@ -59,13 +59,11 @@ toml = { workspace = true }
|
|||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
url = { workspace = true }
|
url = { workspace = true }
|
||||||
uuid = { workspace = true, features = ["v4"] }
|
uuid = { workspace = true, features = ["v4"] }
|
||||||
zip = { workspace = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
base64 = { workspace = true }
|
base64 = { workspace = true }
|
||||||
codex-exec-server-test-support = { workspace = true }
|
codex-exec-server-test-support = { workspace = true }
|
||||||
codex-utils-cargo-bin = { workspace = true }
|
codex-utils-cargo-bin = { workspace = true }
|
||||||
libc = { workspace = true }
|
|
||||||
pretty_assertions = { workspace = true }
|
pretty_assertions = { workspace = true }
|
||||||
tempfile = { workspace = true }
|
tempfile = { workspace = true }
|
||||||
tokio = { workspace = true, features = ["test-util"] }
|
tokio = { workspace = true, features = ["test-util"] }
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ use crate::loaded_cache_metrics;
|
|||||||
use crate::loaded_cache_metrics::RequestOutcome;
|
use crate::loaded_cache_metrics::RequestOutcome;
|
||||||
use crate::loader::PluginHookLoadOutcome;
|
use crate::loader::PluginHookLoadOutcome;
|
||||||
use crate::loader::TargetCuratedMarketplace;
|
use crate::loader::TargetCuratedMarketplace;
|
||||||
use crate::loader::configured_curated_plugin_ids_from_codex_home;
|
|
||||||
use crate::loader::curated_plugin_cache_version;
|
use crate::loader::curated_plugin_cache_version;
|
||||||
use crate::loader::load_plugin_apps_from_manifest;
|
use crate::loader::load_plugin_apps_from_manifest;
|
||||||
use crate::loader::load_plugin_hooks;
|
use crate::loader::load_plugin_hooks;
|
||||||
@@ -42,7 +41,6 @@ use crate::loader::log_plugin_load_errors;
|
|||||||
use crate::loader::materialize_marketplace_plugin_source;
|
use crate::loader::materialize_marketplace_plugin_source;
|
||||||
use crate::loader::plugin_capability_summary_from_root;
|
use crate::loader::plugin_capability_summary_from_root;
|
||||||
use crate::loader::plugin_is_eligible_for_target_marketplace;
|
use crate::loader::plugin_is_eligible_for_target_marketplace;
|
||||||
use crate::loader::refresh_curated_plugin_cache;
|
|
||||||
use crate::loader::refresh_non_curated_plugin_cache_detailed;
|
use crate::loader::refresh_non_curated_plugin_cache_detailed;
|
||||||
use crate::loader::refresh_non_curated_plugin_cache_force_reinstall_detailed;
|
use crate::loader::refresh_non_curated_plugin_cache_force_reinstall_detailed;
|
||||||
use crate::loader::remote_installed_plugins_to_config;
|
use crate::loader::remote_installed_plugins_to_config;
|
||||||
@@ -86,11 +84,9 @@ use crate::remote_plugin_id_resolver::RemoteInstalledPluginsSnapshot;
|
|||||||
use crate::remote_plugin_id_resolver::RemotePluginIdResolver;
|
use crate::remote_plugin_id_resolver::RemotePluginIdResolver;
|
||||||
use crate::remote_plugin_id_resolver::persisted_remote_plugin_id_for_installation;
|
use crate::remote_plugin_id_resolver::persisted_remote_plugin_id_for_installation;
|
||||||
use crate::skill_snapshots::new_plugin_skill_snapshots;
|
use crate::skill_snapshots::new_plugin_skill_snapshots;
|
||||||
use crate::startup_sync::OPENAI_PLUGINS_GIT_URL;
|
|
||||||
use crate::startup_sync::curated_plugins_api_marketplace_path;
|
use crate::startup_sync::curated_plugins_api_marketplace_path;
|
||||||
use crate::startup_sync::curated_plugins_repo_path;
|
use crate::startup_sync::curated_plugins_repo_path;
|
||||||
use crate::startup_sync::read_curated_plugins_sha;
|
use crate::startup_sync::read_curated_plugins_sha;
|
||||||
use crate::startup_sync::sync_openai_plugins_repo;
|
|
||||||
use crate::store::PluginInstallResult as StorePluginInstallResult;
|
use crate::store::PluginInstallResult as StorePluginInstallResult;
|
||||||
use crate::store::PluginStore;
|
use crate::store::PluginStore;
|
||||||
use crate::store::PluginStoreError;
|
use crate::store::PluginStoreError;
|
||||||
@@ -146,8 +142,6 @@ use std::sync::Arc;
|
|||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
use std::sync::RwLock;
|
use std::sync::RwLock;
|
||||||
use std::sync::atomic::AtomicBool;
|
|
||||||
use std::sync::atomic::Ordering;
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
use tokio::sync::OnceCell;
|
use tokio::sync::OnceCell;
|
||||||
@@ -158,7 +152,6 @@ use tokio::sync::watch;
|
|||||||
use tracing::instrument;
|
use tracing::instrument;
|
||||||
use tracing::warn;
|
use tracing::warn;
|
||||||
|
|
||||||
static CURATED_REPO_SYNC_STARTED: AtomicBool = AtomicBool::new(false);
|
|
||||||
const FEATURED_PLUGIN_IDS_CACHE_TTL: std::time::Duration =
|
const FEATURED_PLUGIN_IDS_CACHE_TTL: std::time::Duration =
|
||||||
std::time::Duration::from_secs(60 * 60 * 3);
|
std::time::Duration::from_secs(60 * 60 * 3);
|
||||||
const REMOTE_INSTALLED_PLUGIN_SYNC_WAIT_TIMEOUT: Duration = Duration::from_secs(120);
|
const REMOTE_INSTALLED_PLUGIN_SYNC_WAIT_TIMEOUT: Duration = Duration::from_secs(120);
|
||||||
@@ -828,25 +821,6 @@ impl PluginsManager {
|
|||||||
config.remote_plugin_enabled && self.auth_mode().is_some_and(AuthMode::uses_codex_backend)
|
config.remote_plugin_enabled && self.auth_mode().is_some_and(AuthMode::uses_codex_backend)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts the local curated marketplace sync when the remote catalog is unavailable.
|
|
||||||
pub fn maybe_start_curated_repo_sync_for_config(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
config: &PluginsConfigInput,
|
|
||||||
on_effective_plugins_changed: Option<EffectivePluginsChangedCallback>,
|
|
||||||
) {
|
|
||||||
if config.plugins_enabled
|
|
||||||
&& !self.remote_global_catalog_active(config)
|
|
||||||
&& MarketplacePolicy::from_requirements(config.config_layer_stack.requirements())
|
|
||||||
.validate_git_source(OPENAI_PLUGINS_GIT_URL, /*ref_name*/ None)
|
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
self.start_curated_repo_sync(
|
|
||||||
config.http_client_factory.clone(),
|
|
||||||
on_effective_plugins_changed,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_analytics_events_client(&self, analytics_events_client: AnalyticsEventsClient) {
|
pub fn set_analytics_events_client(&self, analytics_events_client: AnalyticsEventsClient) {
|
||||||
let mut stored_client = match self.analytics_events_client.write() {
|
let mut stored_client = match self.analytics_events_client.write() {
|
||||||
Ok(client_guard) => client_guard,
|
Ok(client_guard) => client_guard,
|
||||||
@@ -2947,10 +2921,7 @@ impl PluginsManager {
|
|||||||
upgrade_warnings: mpsc::UnboundedSender<String>,
|
upgrade_warnings: mpsc::UnboundedSender<String>,
|
||||||
) {
|
) {
|
||||||
if config.plugins_enabled {
|
if config.plugins_enabled {
|
||||||
self.maybe_start_curated_repo_sync_for_config(
|
// aKode: the OpenAI curated marketplace is never synced at startup.
|
||||||
config,
|
|
||||||
on_effective_plugins_changed.clone(),
|
|
||||||
);
|
|
||||||
let should_spawn_marketplace_auto_upgrade = {
|
let should_spawn_marketplace_auto_upgrade = {
|
||||||
let mut state = match self.configured_marketplace_upgrade_state.write() {
|
let mut state = match self.configured_marketplace_upgrade_state.write() {
|
||||||
Ok(state) => state,
|
Ok(state) => state,
|
||||||
@@ -3384,66 +3355,6 @@ impl PluginsManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_curated_repo_sync(
|
|
||||||
self: &Arc<Self>,
|
|
||||||
http_client_factory: HttpClientFactory,
|
|
||||||
on_effective_plugins_changed: Option<EffectivePluginsChangedCallback>,
|
|
||||||
) {
|
|
||||||
if CURATED_REPO_SYNC_STARTED.swap(true, Ordering::SeqCst) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let on_effective_plugins_changed =
|
|
||||||
on_effective_plugins_changed.map(|on_effective_plugins_changed| {
|
|
||||||
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
|
|
||||||
return on_effective_plugins_changed;
|
|
||||||
};
|
|
||||||
let callback: EffectivePluginsChangedCallback = Arc::new(move |change| {
|
|
||||||
let on_effective_plugins_changed = Arc::clone(&on_effective_plugins_changed);
|
|
||||||
runtime.spawn(async move {
|
|
||||||
on_effective_plugins_changed(change);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
callback
|
|
||||||
});
|
|
||||||
let manager = Arc::clone(self);
|
|
||||||
let codex_home = self.codex_home.clone();
|
|
||||||
if let Err(err) = std::thread::Builder::new()
|
|
||||||
.name("plugins-curated-repo-sync".to_string())
|
|
||||||
.spawn(move || {
|
|
||||||
match sync_openai_plugins_repo(codex_home.as_path(), http_client_factory) {
|
|
||||||
Ok(curated_plugin_version) => {
|
|
||||||
let configured_curated_plugin_ids =
|
|
||||||
configured_curated_plugin_ids_from_codex_home(codex_home.as_path());
|
|
||||||
match refresh_curated_plugin_cache(
|
|
||||||
codex_home.as_path(),
|
|
||||||
&curated_plugin_version,
|
|
||||||
&configured_curated_plugin_ids,
|
|
||||||
) {
|
|
||||||
Ok(cache_refreshed) => {
|
|
||||||
manager.clear_caches_after_marketplace_source_refresh(
|
|
||||||
cache_refreshed,
|
|
||||||
on_effective_plugins_changed.as_ref(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
manager.clear_cache();
|
|
||||||
CURATED_REPO_SYNC_STARTED.store(false, Ordering::SeqCst);
|
|
||||||
warn!("failed to refresh curated plugin cache after sync: {err}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
CURATED_REPO_SYNC_STARTED.store(false, Ordering::SeqCst);
|
|
||||||
warn!("failed to sync curated plugins repo: {err}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
{
|
|
||||||
CURATED_REPO_SYNC_STARTED.store(false, Ordering::SeqCst);
|
|
||||||
warn!("failed to start curated plugins repo sync task: {err}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn run_remote_installed_plugins_cache_refresh_loop(self: Arc<Self>) {
|
async fn run_remote_installed_plugins_cache_refresh_loop(self: Arc<Self>) {
|
||||||
loop {
|
loop {
|
||||||
let request = {
|
let request = {
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ use crate::PluginLoadOutcome;
|
|||||||
use crate::ToolSuggestDiscoverablePlugin;
|
use crate::ToolSuggestDiscoverablePlugin;
|
||||||
use crate::ToolSuggestPluginDiscoveryInput;
|
use crate::ToolSuggestPluginDiscoveryInput;
|
||||||
use crate::installed_marketplaces::marketplace_install_root;
|
use crate::installed_marketplaces::marketplace_install_root;
|
||||||
|
use crate::loader::configured_curated_plugin_ids_from_codex_home;
|
||||||
use crate::loader::load_plugin_skill_inventory;
|
use crate::loader::load_plugin_skill_inventory;
|
||||||
use crate::loader::load_plugins_from_layer_stack;
|
use crate::loader::load_plugins_from_layer_stack;
|
||||||
use crate::loader::plugin_capability_summary_from_root;
|
use crate::loader::plugin_capability_summary_from_root;
|
||||||
|
use crate::loader::refresh_curated_plugin_cache;
|
||||||
use crate::loader::refresh_non_curated_plugin_cache;
|
use crate::loader::refresh_non_curated_plugin_cache;
|
||||||
use crate::loader::refresh_non_curated_plugin_cache_force_reinstall;
|
use crate::loader::refresh_non_curated_plugin_cache_force_reinstall;
|
||||||
use crate::marketplace::MarketplacePluginInstallPolicy;
|
use crate::marketplace::MarketplacePluginInstallPolicy;
|
||||||
@@ -160,33 +162,6 @@ async fn plugins_manager_reads_auth_mode_from_auth_manager() {
|
|||||||
assert_eq!(manager_with_auth.auth_mode(), Some(AuthMode::Chatgpt));
|
assert_eq!(manager_with_auth.auth_mode(), Some(AuthMode::Chatgpt));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn curated_repo_sync_stays_deferred_for_remote_chatgpt_catalog() {
|
|
||||||
CURATED_REPO_SYNC_STARTED.store(false, std::sync::atomic::Ordering::SeqCst);
|
|
||||||
let tmp = TempDir::new().unwrap();
|
|
||||||
let config = PluginsConfigInput::new(
|
|
||||||
unrestricted_config_layer_stack(),
|
|
||||||
Default::default(),
|
|
||||||
"openai".to_string(),
|
|
||||||
/*plugins_enabled*/ true,
|
|
||||||
/*remote_plugin_enabled*/ true,
|
|
||||||
"https://chatgpt.com".to_string(),
|
|
||||||
test_http_client_factory(),
|
|
||||||
/*product_sku*/ None,
|
|
||||||
);
|
|
||||||
let manager = Arc::new(test_plugins_manager_with_options(
|
|
||||||
tmp.path().to_path_buf(),
|
|
||||||
Some(Product::Codex),
|
|
||||||
Some(AuthMode::Chatgpt),
|
|
||||||
));
|
|
||||||
|
|
||||||
manager.maybe_start_curated_repo_sync_for_config(
|
|
||||||
&config, /*on_effective_plugins_changed*/ None,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(!CURATED_REPO_SYNC_STARTED.load(std::sync::atomic::Ordering::SeqCst));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn marketplace_source_refresh_notifies_only_after_installed_cache_changes() {
|
fn marketplace_source_refresh_notifies_only_after_installed_cache_changes() {
|
||||||
let tmp = TempDir::new().unwrap();
|
let tmp = TempDir::new().unwrap();
|
||||||
|
|||||||
@@ -88,10 +88,6 @@ host_pattern = '^github[.]com$'
|
|||||||
permitted
|
permitted
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
manager.maybe_start_curated_repo_sync_for_config(
|
|
||||||
&blocked, /*on_effective_plugins_changed*/ None,
|
|
||||||
);
|
|
||||||
assert!(!CURATED_REPO_SYNC_STARTED.load(std::sync::atomic::Ordering::SeqCst));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,37 +0,0 @@
|
|||||||
//! HTTP transport for curated plugin startup sync.
|
|
||||||
//!
|
|
||||||
//! Both proxy modes retain the supplied application network policy. The default proxy mode also
|
|
||||||
//! keeps the legacy fallback for invalid custom CA configuration; system-proxy mode fails closed.
|
|
||||||
//! Startup-sync request helpers apply the standard Codex headers.
|
|
||||||
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use crate::http_client_selector::HttpClientSelector;
|
|
||||||
use codex_http_client::ClientRouteClass;
|
|
||||||
use codex_http_client::HttpClientFactory;
|
|
||||||
use codex_http_client::RequestBuilder;
|
|
||||||
use codex_http_client::RouteAwareClientPool;
|
|
||||||
use http::Method;
|
|
||||||
|
|
||||||
pub(super) struct StartupSyncHttpClient(Arc<dyn HttpClientSelector>);
|
|
||||||
|
|
||||||
impl StartupSyncHttpClient {
|
|
||||||
pub(super) fn new(http_client_factory: &HttpClientFactory) -> Self {
|
|
||||||
let http_clients =
|
|
||||||
RouteAwareClientPool::with_chatgpt_cloudflare_cookies_without_request_logging(
|
|
||||||
http_client_factory.clone(),
|
|
||||||
ClientRouteClass::Api,
|
|
||||||
)
|
|
||||||
.with_legacy_custom_ca_fallback();
|
|
||||||
Self(Arc::new(http_clients))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(super) fn route_aware(http_clients: Arc<dyn HttpClientSelector>) -> Self {
|
|
||||||
Self(http_clients)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn request(&self, method: Method, url: &str) -> RequestBuilder {
|
|
||||||
self.0.request(method, url)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,28 +1,11 @@
|
|||||||
//! Feedback event contracts for titles, report grouping, and lossless comment bodies.
|
//! Feedback event contracts for titles, report grouping, and lossless comment bodies.
|
||||||
|
|
||||||
use crate::CodexFeedback;
|
use crate::CodexFeedback;
|
||||||
use crate::FeedbackUploadOptions;
|
|
||||||
use crate::UPLOAD_TIMEOUT;
|
|
||||||
use codex_http_client::HttpClientFactory;
|
|
||||||
use codex_http_client::OutboundProxyPolicy;
|
|
||||||
use flate2::read::GzDecoder;
|
|
||||||
use http::StatusCode;
|
|
||||||
use pretty_assertions::assert_eq;
|
use pretty_assertions::assert_eq;
|
||||||
use sentry::protocol::Event;
|
use sentry::protocol::Event;
|
||||||
use sentry::protocol::Exception;
|
use sentry::protocol::Exception;
|
||||||
use sentry::protocol::Level;
|
use sentry::protocol::Level;
|
||||||
use sentry::protocol::Value;
|
|
||||||
use sentry::protocol::Values;
|
|
||||||
use sentry::protocol::value::to_value;
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::io::Read;
|
|
||||||
use std::time::Instant;
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::MockServer;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::header;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn custom_titles_preserve_comments_and_keep_submissions_separate() {
|
fn custom_titles_preserve_comments_and_keep_submissions_separate() {
|
||||||
@@ -178,79 +161,3 @@ fn reason_tag_previews_preserve_full_comments_in_the_exception() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_sends_safe_reason_tag_and_full_comment() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/api/42/envelope/"))
|
|
||||||
.and(header("Content-Encoding", "gzip"))
|
|
||||||
.respond_with(ResponseTemplate::new(StatusCode::OK))
|
|
||||||
.expect(/*r*/ 1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None);
|
|
||||||
let reason = format!("first\r\nsecond\n{}tail", "界🌍".repeat(120));
|
|
||||||
let tags = BTreeMap::from([("reason".to_string(), "caller override\n".to_string())]);
|
|
||||||
snapshot
|
|
||||||
.upload_feedback_with_dsn(
|
|
||||||
FeedbackUploadOptions {
|
|
||||||
classification: "bug",
|
|
||||||
reason: Some(&reason),
|
|
||||||
tags: Some(&tags),
|
|
||||||
include_logs: false,
|
|
||||||
extra_attachments: Vec::new(),
|
|
||||||
extra_attachment_paths: &[],
|
|
||||||
session_source: None,
|
|
||||||
logs_override: None,
|
|
||||||
},
|
|
||||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
|
||||||
&format!("http://public@{}/42", server.address()),
|
|
||||||
Instant::now() + UPLOAD_TIMEOUT,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let requests = server.received_requests().await.unwrap();
|
|
||||||
assert_eq!(requests.len(), 1);
|
|
||||||
let mut decoded = Vec::new();
|
|
||||||
GzDecoder::new(requests[0].body.as_slice())
|
|
||||||
.read_to_end(&mut decoded)
|
|
||||||
.unwrap();
|
|
||||||
// The first two envelope lines are its header and the event item header.
|
|
||||||
let payload = std::str::from_utf8(&decoded)
|
|
||||||
.unwrap()
|
|
||||||
.splitn(/*n*/ 3, '\n')
|
|
||||||
.nth(/*n*/ 2)
|
|
||||||
.unwrap();
|
|
||||||
let event: Value = payload.parse().unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
event["tags"]["reason"].as_str().unwrap().chars().count(),
|
|
||||||
200
|
|
||||||
);
|
|
||||||
let title = format!("[Bug]: Codex session {}", snapshot.thread_id);
|
|
||||||
let expected_tags = to_value(BTreeMap::from([
|
|
||||||
("thread_id".to_string(), snapshot.thread_id),
|
|
||||||
("classification".to_string(), "bug".to_string()),
|
|
||||||
(
|
|
||||||
"cli_version".to_string(),
|
|
||||||
env!("CARGO_PKG_VERSION").to_string(),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"reason".to_string(),
|
|
||||||
format!("first second {}", "界🌍".repeat(93)),
|
|
||||||
),
|
|
||||||
]))
|
|
||||||
.unwrap();
|
|
||||||
let expected_exception = to_value(Values::from(vec![Exception {
|
|
||||||
ty: title,
|
|
||||||
value: Some(reason),
|
|
||||||
..Default::default()
|
|
||||||
}]))
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
(&event["tags"], &event["exception"]),
|
|
||||||
(&expected_tags, &expected_exception)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,27 +4,14 @@
|
|||||||
|
|
||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::sync::atomic::AtomicUsize;
|
|
||||||
use std::sync::atomic::Ordering;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::FeedbackDiagnostic;
|
use crate::FeedbackDiagnostic;
|
||||||
use codex_http_client::OutboundProxyPolicy;
|
use codex_http_client::OutboundProxyPolicy;
|
||||||
use flate2::Compression;
|
|
||||||
use flate2::read::GzDecoder;
|
|
||||||
use flate2::write::GzEncoder;
|
|
||||||
use http::StatusCode;
|
|
||||||
use pretty_assertions::assert_eq;
|
use pretty_assertions::assert_eq;
|
||||||
use tracing_subscriber::layer::SubscriberExt;
|
use tracing_subscriber::layer::SubscriberExt;
|
||||||
use tracing_subscriber::util::SubscriberInitExt;
|
use tracing_subscriber::util::SubscriberInitExt;
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::MockServer;
|
use wiremock::MockServer;
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::header;
|
|
||||||
use wiremock::matchers::header_exists;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn ring_buffer_drops_front_when_full() {
|
fn ring_buffer_drops_front_when_full() {
|
||||||
@@ -133,462 +120,17 @@ async fn upload_test_feedback(
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// aKode: feedback is never uploaded; the upload path fails without sending any request.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn feedback_upload_allows_slow_reports() {
|
async fn feedback_upload_is_disabled_and_sends_nothing() {
|
||||||
let server = MockServer::start().await;
|
let server = MockServer::start().await;
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/api/42/envelope/"))
|
|
||||||
.respond_with(
|
|
||||||
ResponseTemplate::new(StatusCode::OK).set_delay(Duration::from_secs(/*secs*/ 4)),
|
|
||||||
)
|
|
||||||
.expect(/*r*/ 3)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let dsn = format!("http://public@{}/42", server.address());
|
|
||||||
let attachment = FeedbackAttachment {
|
|
||||||
filename: "later.txt".to_string(),
|
|
||||||
content_type: None,
|
|
||||||
buffer: b"later diagnostic".to_vec(),
|
|
||||||
};
|
|
||||||
upload_test_feedback(&CodexFeedback::new(), &dsn, vec![attachment])
|
|
||||||
.await
|
|
||||||
.expect("all three envelopes should finish across twelve seconds of network waits");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_deadline_stops_retries_and_later_attachments() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let attempt = AtomicUsize::default();
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/api/42/envelope/"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
match attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) {
|
|
||||||
0 | 2 => ResponseTemplate::new(StatusCode::OK)
|
|
||||||
.set_delay(Duration::from_secs(/*secs*/ 1)),
|
|
||||||
1 => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
|
||||||
.set_delay(Duration::from_secs(/*secs*/ 1)),
|
|
||||||
_ => ResponseTemplate::new(StatusCode::OK)
|
|
||||||
.set_delay(Duration::from_secs(/*secs*/ 20)),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 4)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let dsn = format!("http://public@{}/42", server.address());
|
|
||||||
let attachments = ["stalled.txt", "later.txt"].map(|filename| FeedbackAttachment {
|
|
||||||
filename: filename.to_string(),
|
|
||||||
content_type: None,
|
|
||||||
buffer: filename.as_bytes().to_vec(),
|
|
||||||
});
|
|
||||||
let snapshot = CodexFeedback::new()
|
|
||||||
.snapshot(/*session_id*/ None)
|
|
||||||
.with_feedback_diagnostics(FeedbackDiagnostics::default());
|
|
||||||
let error = tokio::time::timeout(
|
|
||||||
Duration::from_secs(/*secs*/ 10),
|
|
||||||
snapshot.upload_feedback_with_dsn(
|
|
||||||
FeedbackUploadOptions {
|
|
||||||
classification: "bug",
|
|
||||||
reason: None,
|
|
||||||
tags: None,
|
|
||||||
include_logs: true,
|
|
||||||
extra_attachments: attachments.into(),
|
|
||||||
extra_attachment_paths: &[],
|
|
||||||
session_source: Some(SessionSource::Cli),
|
|
||||||
logs_override: Some(b"log contents".to_vec()),
|
|
||||||
},
|
|
||||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
|
||||||
&dsn,
|
|
||||||
Instant::now() + Duration::from_secs(/*secs*/ 8),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.expect("each request must use only the time left in the report deadline")
|
|
||||||
.expect_err("the accepted report must report incomplete attachments");
|
|
||||||
assert_eq!(
|
|
||||||
error.to_string(),
|
|
||||||
"feedback report was accepted, but some attachments failed to upload"
|
|
||||||
);
|
|
||||||
let requests = server.received_requests().await.unwrap();
|
|
||||||
assert_eq!(requests.len(), 4);
|
|
||||||
assert_eq!(requests[1].body, requests[2].body);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_retries_diagnostics_without_replaying_core() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let attempt = AtomicUsize::default();
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/api/42/envelope/"))
|
|
||||||
.and(header_exists("X-Sentry-Auth"))
|
|
||||||
.and(header("Content-Encoding", "gzip"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
match attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) {
|
|
||||||
// Accept the core once; accept logs only on their second attempt.
|
|
||||||
0 => ResponseTemplate::new(StatusCode::OK).insert_header(
|
|
||||||
"X-Sentry-Rate-Limits",
|
|
||||||
"0:attachment:project,60:transaction:project",
|
|
||||||
),
|
|
||||||
2 => ResponseTemplate::new(StatusCode::OK).insert_header("Retry-After", "0"),
|
|
||||||
6 => ResponseTemplate::new(StatusCode::OK)
|
|
||||||
.insert_header("X-Sentry-Rate-Limits", "60:transaction:project"),
|
|
||||||
1 => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
|
||||||
.insert_header("Retry-After", "2"),
|
|
||||||
5 => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
|
||||||
.insert_header("Retry-After", "8"),
|
|
||||||
_ => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
|
||||||
.insert_header("Retry-After", "0"),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 7)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let dsn = format!("http://public@{}/42", server.address());
|
|
||||||
let attachments = ["retry-exhausted.txt", "later.txt"].map(|filename| FeedbackAttachment {
|
|
||||||
filename: filename.to_string(),
|
|
||||||
content_type: Some("text/plain".to_string()),
|
|
||||||
buffer: filename.as_bytes().to_vec(),
|
|
||||||
});
|
|
||||||
let started = Instant::now();
|
|
||||||
upload_test_feedback(&CodexFeedback::new(), &dsn, attachments.into())
|
|
||||||
.await
|
|
||||||
.expect_err("legacy uploads report incomplete diagnostics");
|
|
||||||
assert!(started.elapsed() >= Duration::from_secs(2));
|
|
||||||
let requests = server.received_requests().await.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
requests[1].body, requests[2].body,
|
|
||||||
"retry exact request bytes"
|
|
||||||
);
|
|
||||||
// Exhausting one diagnostic must not delay later.txt or replay earlier files.
|
|
||||||
assert!(
|
|
||||||
requests[3..6]
|
|
||||||
.iter()
|
|
||||||
.all(|request| request.body == requests[3].body)
|
|
||||||
);
|
|
||||||
let mut decoded = String::new();
|
|
||||||
GzDecoder::new(requests[1].body.as_slice())
|
|
||||||
.read_to_string(&mut decoded)
|
|
||||||
.unwrap();
|
|
||||||
assert!(decoded.ends_with("private log contents\n"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_delivers_large_files_intact() {
|
|
||||||
let suffix = ThreadId::new();
|
|
||||||
let first_path = std::env::temp_dir().join(format!("feedback-first-{suffix}.jsonl"));
|
|
||||||
let second_path = std::env::temp_dir().join(format!("feedback-second-{suffix}.jsonl"));
|
|
||||||
let binary_path = std::env::temp_dir().join(format!("feedback-archive-{suffix}.jsonl.gz"));
|
|
||||||
let pending_path = second_path.with_extension("pending");
|
|
||||||
let block = "{\"type\":\"event_msg\",\"payload\":{\"type\":\"agent_message\",\"message\":\"diagnostic fixture 🍵\"}}\n"
|
|
||||||
.repeat(1024);
|
|
||||||
let block_counts = [65, 80].map(|mib| mib * 1024 * 1024 / block.len() + 1);
|
|
||||||
for (path, blocks) in [&first_path, &pending_path].into_iter().zip(block_counts) {
|
|
||||||
let mut file = fs::File::create(path).unwrap();
|
|
||||||
for _ in 0..blocks {
|
|
||||||
file.write_all(block.as_bytes()).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Repeats beyond gzip's window keep the archive above the former 38.1 MiB cap.
|
|
||||||
let record_block = (0..4096)
|
|
||||||
.flat_map(|_| sentry::types::Uuid::new_v4().into_bytes())
|
|
||||||
.map(|byte| {
|
|
||||||
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
|
||||||
[usize::from(byte % 64)]
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let mut file = GzEncoder::new(fs::File::create(&binary_path).unwrap(), Compression::fast());
|
|
||||||
for mib in [32, 30] {
|
|
||||||
file.write_all(b"{\"message\":\"").unwrap();
|
|
||||||
for _ in 0..mib * 1024 * 1024 / record_block.len() {
|
|
||||||
file.write_all(&record_block).unwrap();
|
|
||||||
}
|
|
||||||
file.write_all(b"\"}\n").unwrap();
|
|
||||||
}
|
|
||||||
file.finish().unwrap();
|
|
||||||
assert!(fs::metadata(&binary_path).unwrap().len() > 40_000_000);
|
|
||||||
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let attempt = AtomicUsize::default();
|
|
||||||
let ready_path = second_path.clone();
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/api/42/envelope/"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
if attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) == 1 {
|
|
||||||
// The next file becomes readable only after the first file arrives.
|
|
||||||
fs::rename(&pending_path, &ready_path).unwrap();
|
|
||||||
}
|
|
||||||
ResponseTemplate::new(StatusCode::OK)
|
|
||||||
})
|
|
||||||
.expect(/*r*/ 4)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
CodexFeedback::new()
|
|
||||||
.snapshot(/*session_id*/ None)
|
|
||||||
.upload_feedback_with_dsn(
|
|
||||||
FeedbackUploadOptions {
|
|
||||||
classification: "bug",
|
|
||||||
reason: Some("large diagnostic upload"),
|
|
||||||
tags: None,
|
|
||||||
include_logs: false,
|
|
||||||
extra_attachments: Vec::new(),
|
|
||||||
extra_attachment_paths: &[
|
|
||||||
FeedbackAttachmentPath {
|
|
||||||
path: first_path.clone(),
|
|
||||||
attachment_filename_override: None,
|
|
||||||
},
|
|
||||||
FeedbackAttachmentPath {
|
|
||||||
path: second_path.clone(),
|
|
||||||
attachment_filename_override: None,
|
|
||||||
},
|
|
||||||
FeedbackAttachmentPath {
|
|
||||||
path: binary_path.clone(),
|
|
||||||
attachment_filename_override: None,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
session_source: Some(SessionSource::Cli),
|
|
||||||
logs_override: None,
|
|
||||||
},
|
|
||||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
|
||||||
&format!("http://public@{}/42", server.address()),
|
|
||||||
Instant::now() + UPLOAD_TIMEOUT,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let requests = server.received_requests().await.unwrap();
|
|
||||||
assert_eq!(requests.len(), 4);
|
|
||||||
let mut event = String::new();
|
|
||||||
GzDecoder::new(requests[0].body.as_slice())
|
|
||||||
.read_to_string(&mut event)
|
|
||||||
.unwrap();
|
|
||||||
for (request, (filename, source_path)) in requests[1..].iter().zip([
|
|
||||||
(format!("feedback-first-{suffix}.jsonl"), &first_path),
|
|
||||||
(format!("feedback-second-{suffix}.jsonl"), &second_path),
|
|
||||||
(format!("feedback-archive-{suffix}.jsonl.gz"), &binary_path),
|
|
||||||
]) {
|
|
||||||
let mut decoded = Vec::new();
|
|
||||||
if request.headers.contains_key("Content-Encoding") {
|
|
||||||
GzDecoder::new(request.body.as_slice())
|
|
||||||
.read_to_end(&mut decoded)
|
|
||||||
.unwrap();
|
|
||||||
} else {
|
|
||||||
decoded.extend_from_slice(&request.body);
|
|
||||||
}
|
|
||||||
assert!(decoded.len() <= MAX_DECODED_UPLOAD_BYTES);
|
|
||||||
let mut parts = decoded.splitn(3, |byte| *byte == b'\n');
|
|
||||||
assert_eq!(
|
|
||||||
parts.next().unwrap(),
|
|
||||||
event.lines().next().unwrap().as_bytes()
|
|
||||||
);
|
|
||||||
let header = std::str::from_utf8(parts.next().unwrap()).unwrap();
|
|
||||||
assert!(header.contains(&format!("\"filename\":\"{filename}\"")));
|
|
||||||
let payload = parts.next().unwrap().strip_suffix(b"\n").unwrap();
|
|
||||||
let mut source = fs::File::open(source_path).unwrap();
|
|
||||||
let original_bytes = source.metadata().unwrap().len() as usize;
|
|
||||||
assert_eq!(payload.len(), original_bytes);
|
|
||||||
if filename.ends_with(".jsonl") {
|
|
||||||
let text = std::str::from_utf8(payload).unwrap();
|
|
||||||
assert!(text.ends_with('\n'));
|
|
||||||
} else {
|
|
||||||
let mut archive = GzDecoder::new(payload);
|
|
||||||
io::copy(&mut archive, &mut io::sink()).expect("received archive must be intact");
|
|
||||||
}
|
|
||||||
let mut expected = [0; 64 * 1024];
|
|
||||||
for chunk in payload.chunks(expected.len()) {
|
|
||||||
source.read_exact(&mut expected[..chunk.len()]).unwrap();
|
|
||||||
assert_eq!(chunk, &expected[..chunk.len()]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fs::remove_file(first_path).unwrap();
|
|
||||||
fs::remove_file(second_path).unwrap();
|
|
||||||
fs::remove_file(binary_path).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_reports_unreadable_or_oversized_attachments() {
|
|
||||||
let oversized_path =
|
|
||||||
std::env::temp_dir().join(format!("feedback-oversized-{}", ThreadId::new()));
|
|
||||||
fs::File::create(&oversized_path)
|
|
||||||
.unwrap()
|
|
||||||
.set_len(MAX_DECODED_UPLOAD_BYTES as u64 + 1)
|
|
||||||
.unwrap();
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.respond_with(ResponseTemplate::new(StatusCode::OK))
|
|
||||||
.expect(/*r*/ 2)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
for path in [
|
|
||||||
oversized_path.clone(),
|
|
||||||
oversized_path.with_extension("missing"),
|
|
||||||
] {
|
|
||||||
let result = CodexFeedback::new()
|
|
||||||
.snapshot(/*session_id*/ None)
|
|
||||||
.upload_feedback_with_dsn(
|
|
||||||
FeedbackUploadOptions {
|
|
||||||
classification: "bug",
|
|
||||||
reason: None,
|
|
||||||
tags: None,
|
|
||||||
include_logs: false,
|
|
||||||
extra_attachments: Vec::new(),
|
|
||||||
extra_attachment_paths: &[FeedbackAttachmentPath {
|
|
||||||
path,
|
|
||||||
attachment_filename_override: None,
|
|
||||||
}],
|
|
||||||
session_source: Some(SessionSource::Cli),
|
|
||||||
logs_override: None,
|
|
||||||
},
|
|
||||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
|
||||||
&format!("http://public@{}/42", server.address()),
|
|
||||||
Instant::now() + UPLOAD_TIMEOUT,
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_eq!(
|
|
||||||
result.unwrap_err().to_string(),
|
|
||||||
"feedback report was accepted, but some attachments failed to upload"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
assert_eq!(
|
|
||||||
fs::metadata(&oversized_path).unwrap().len(),
|
|
||||||
MAX_DECODED_UPLOAD_BYTES as u64 + 1
|
|
||||||
);
|
|
||||||
fs::remove_file(oversized_path).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_stops_diagnostics_for_sentry_rate_limits() {
|
|
||||||
for (accepted_before_limit, rate_limit) in [
|
|
||||||
(1, ResponseTemplate::new(StatusCode::TOO_MANY_REQUESTS)),
|
|
||||||
(
|
|
||||||
1,
|
|
||||||
ResponseTemplate::new(StatusCode::TOO_MANY_REQUESTS)
|
|
||||||
.insert_header("X-Sentry-Rate-Limits", "60:attachment:project")
|
|
||||||
.insert_header("Retry-After", "0"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
0,
|
|
||||||
ResponseTemplate::new(StatusCode::OK)
|
|
||||||
.insert_header("X-Sentry-Rate-Limits", "60:attachment:project"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
1,
|
|
||||||
ResponseTemplate::new(StatusCode::OK)
|
|
||||||
.insert_header("X-Sentry-Rate-Limits", "60::project"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
0,
|
|
||||||
ResponseTemplate::new(StatusCode::OK).insert_header("Retry-After", "60"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
1,
|
|
||||||
ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
|
||||||
.insert_header("Retry-After", "300"),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
1,
|
|
||||||
ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
|
||||||
.insert_header("Retry-After", "invalid"),
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
let attempt = AtomicUsize::default();
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/api/42/envelope/"))
|
|
||||||
.respond_with(move |_: &wiremock::Request| {
|
|
||||||
if attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) < accepted_before_limit {
|
|
||||||
ResponseTemplate::new(StatusCode::OK)
|
|
||||||
} else {
|
|
||||||
rate_limit.clone()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.expect((accepted_before_limit + 1) as u64)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let dsn = format!("http://public@{}/42", server.address());
|
|
||||||
let later = FeedbackAttachment {
|
|
||||||
filename: "later.txt".to_string(),
|
|
||||||
content_type: None,
|
|
||||||
buffer: b"later diagnostic".to_vec(),
|
|
||||||
};
|
|
||||||
upload_test_feedback(&CodexFeedback::new(), &dsn, vec![later])
|
|
||||||
.await
|
|
||||||
.expect_err("legacy uploads report rate-limited diagnostics");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_reports_rejected_sentry_response_without_exposing_feedback() {
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/api/42/envelope/"))
|
|
||||||
.respond_with(ResponseTemplate::new(503))
|
|
||||||
.expect(1)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let feedback = CodexFeedback::new();
|
|
||||||
let dsn = format!("http://public@{}/42", server.address());
|
let dsn = format!("http://public@{}/42", server.address());
|
||||||
|
|
||||||
let error = upload_test_feedback(&feedback, &dsn, Vec::new())
|
upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new())
|
||||||
.await
|
.await
|
||||||
.expect_err("rejected Sentry responses must fail feedback uploads");
|
.expect_err("feedback upload must be disabled");
|
||||||
|
|
||||||
let error = format!("{error:#}");
|
assert!(server.received_requests().await.unwrap().is_empty());
|
||||||
assert!(error.contains("503"));
|
|
||||||
assert!(!error.contains("private feedback"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_does_not_forward_private_data_to_redirect_target() {
|
|
||||||
let sentry_server = MockServer::start().await;
|
|
||||||
let redirect_target = MockServer::start().await;
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/api/42/envelope/"))
|
|
||||||
.respond_with(
|
|
||||||
ResponseTemplate::new(307)
|
|
||||||
.insert_header("Location", format!("{}/capture", redirect_target.uri())),
|
|
||||||
)
|
|
||||||
.expect(1)
|
|
||||||
.mount(&sentry_server)
|
|
||||||
.await;
|
|
||||||
let dsn = format!("http://public@{}/42", sentry_server.address());
|
|
||||||
let error = upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new())
|
|
||||||
.await
|
|
||||||
.expect_err("redirected feedback uploads must be rejected");
|
|
||||||
|
|
||||||
assert!(error.to_string().contains("307"));
|
|
||||||
assert!(
|
|
||||||
redirect_target
|
|
||||||
.received_requests()
|
|
||||||
.await
|
|
||||||
.expect("redirect target should record requests")
|
|
||||||
.is_empty()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_reports_transport_failures() {
|
|
||||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")
|
|
||||||
.expect("unused local address should be available");
|
|
||||||
let address = listener
|
|
||||||
.local_addr()
|
|
||||||
.expect("listener should have an address");
|
|
||||||
drop(listener);
|
|
||||||
|
|
||||||
let dsn = format!("http://public@{address}/42");
|
|
||||||
let error = upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new())
|
|
||||||
.await
|
|
||||||
.expect_err("transport failures must fail feedback uploads");
|
|
||||||
|
|
||||||
assert!(
|
|
||||||
error
|
|
||||||
.downcast_ref::<codex_http_client::RouteAwareRequestError>()
|
|
||||||
.is_some_and(codex_http_client::RouteAwareRequestError::is_connect)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -46,97 +46,6 @@ impl Drop for Fixture {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn feedback_upload_archives_readable_rollouts_and_undecodable_sources() -> Result<()> {
|
|
||||||
use codex_http_client::OutboundProxyPolicy;
|
|
||||||
use flate2::read::GzDecoder;
|
|
||||||
use sentry::protocol::Envelope;
|
|
||||||
use sentry::protocol::EnvelopeItem;
|
|
||||||
use wiremock::Mock;
|
|
||||||
use wiremock::MockServer;
|
|
||||||
use wiremock::ResponseTemplate;
|
|
||||||
use wiremock::matchers::method;
|
|
||||||
use wiremock::matchers::path;
|
|
||||||
|
|
||||||
let fixture = Fixture::new();
|
|
||||||
let damaged = Fixture::new();
|
|
||||||
let damaged_bytes = &COMPRESSED[..10];
|
|
||||||
fs::write(&damaged.compressed, damaged_bytes)?;
|
|
||||||
let second_filename = format!("rollout-2026-09-09T12-00-00-{}.jsonl", ThreadId::new());
|
|
||||||
let second_bytes = b"{\"message\":\"second rollout\"}\n";
|
|
||||||
let server = MockServer::start().await;
|
|
||||||
Mock::given(method("POST"))
|
|
||||||
.and(path("/api/42/envelope/"))
|
|
||||||
.respond_with(ResponseTemplate::new(200))
|
|
||||||
.expect(/*r*/ 2)
|
|
||||||
.mount(&server)
|
|
||||||
.await;
|
|
||||||
let dsn = format!("http://public@{}/42", server.address());
|
|
||||||
CodexFeedback::new()
|
|
||||||
.snapshot(/*session_id*/ None)
|
|
||||||
.with_feedback_diagnostics(FeedbackDiagnostics::default())
|
|
||||||
.upload_feedback_with_dsn(
|
|
||||||
FeedbackUploadOptions {
|
|
||||||
classification: "bug",
|
|
||||||
reason: None,
|
|
||||||
tags: None,
|
|
||||||
include_logs: false,
|
|
||||||
extra_attachments: vec![FeedbackAttachment {
|
|
||||||
filename: second_filename.clone(),
|
|
||||||
content_type: Some("text/plain".to_string()),
|
|
||||||
buffer: second_bytes.to_vec(),
|
|
||||||
}],
|
|
||||||
extra_attachment_paths: &[fixture.attachment(), damaged.attachment()],
|
|
||||||
session_source: None,
|
|
||||||
logs_override: None,
|
|
||||||
},
|
|
||||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
|
||||||
&dsn,
|
|
||||||
Instant::now() + UPLOAD_TIMEOUT,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let requests = server.received_requests().await.unwrap();
|
|
||||||
assert_eq!(requests.len(), 2);
|
|
||||||
let mut body = requests[1].body.clone();
|
|
||||||
if body.starts_with(&[0x1f, 0x8b]) {
|
|
||||||
let mut decoded = Vec::new();
|
|
||||||
GzDecoder::new(body.as_slice()).read_to_end(&mut decoded)?;
|
|
||||||
body = decoded;
|
|
||||||
}
|
|
||||||
let envelope = Envelope::from_slice(&body)?;
|
|
||||||
let mut items = envelope.items();
|
|
||||||
let Some(EnvelopeItem::Attachment(attachment)) = items.next() else {
|
|
||||||
anyhow::bail!("expected a rollout archive attachment");
|
|
||||||
};
|
|
||||||
assert_eq!(attachment.filename, "rollouts.tar.gz");
|
|
||||||
assert!(items.next().is_none());
|
|
||||||
|
|
||||||
let extracted = tempfile::tempdir()?;
|
|
||||||
tar::Archive::new(GzDecoder::new(attachment.buffer.as_slice())).unpack(extracted.path())?;
|
|
||||||
let files = fs::read_dir(extracted.path())?
|
|
||||||
.map(|entry| {
|
|
||||||
let entry = entry?;
|
|
||||||
Ok((entry.file_name(), fs::read(entry.path())?))
|
|
||||||
})
|
|
||||||
.collect::<io::Result<BTreeMap<_, _>>>()?;
|
|
||||||
assert_eq!(
|
|
||||||
files,
|
|
||||||
BTreeMap::from([
|
|
||||||
(
|
|
||||||
fixture.plain.file_name().unwrap().to_owned(),
|
|
||||||
JSONL.to_vec()
|
|
||||||
),
|
|
||||||
(second_filename.into(), second_bytes.to_vec()),
|
|
||||||
(
|
|
||||||
damaged.compressed.file_name().unwrap().to_owned(),
|
|
||||||
damaged_bytes.to_vec(),
|
|
||||||
),
|
|
||||||
])
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn compressed_paths_keep_canonical_names_and_filename_overrides() {
|
fn compressed_paths_keep_canonical_names_and_filename_overrides() {
|
||||||
let mut fixture = Fixture::new();
|
let mut fixture = Fixture::new();
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ use rmcp::transport::AuthorizationRequest;
|
|||||||
use rmcp::transport::AuthorizationSession;
|
use rmcp::transport::AuthorizationSession;
|
||||||
use rmcp::transport::auth::OAuthHttpClient;
|
use rmcp::transport::auth::OAuthHttpClient;
|
||||||
use rmcp::transport::auth::OAuthState;
|
use rmcp::transport::auth::OAuthState;
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::oauth::validate_authorization_server_endpoints;
|
use crate::oauth::validate_authorization_server_endpoints;
|
||||||
use crate::oauth_callback::McpOAuthCallbackMode;
|
use crate::oauth_callback::McpOAuthCallbackMode;
|
||||||
@@ -18,10 +17,12 @@ use crate::oauth_callback::validate_callback_redirect;
|
|||||||
/// OAuth client-registration strategy for one interactive HTTP MCP login.
|
/// OAuth client-registration strategy for one interactive HTTP MCP login.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
pub enum McpOAuthClientRegistration {
|
pub enum McpOAuthClientRegistration {
|
||||||
/// Prefer a supported native CIMD and otherwise use advertised DCR.
|
/// Use the advertised Dynamic Client Registration endpoint.
|
||||||
|
// aKode: upstream preferred a ChatGPT-hosted CIMD here; only DCR is used now.
|
||||||
#[default]
|
#[default]
|
||||||
Auto,
|
Auto,
|
||||||
/// Require a ChatGPT-hosted Codex public native Client ID Metadata Document.
|
/// Client ID Metadata Document registration.
|
||||||
|
// aKode: always rejected; upstream pointed at a ChatGPT-hosted metadata document.
|
||||||
Cimd,
|
Cimd,
|
||||||
/// Require the authorization server's Dynamic Client Registration endpoint.
|
/// Require the authorization server's Dynamic Client Registration endpoint.
|
||||||
Dcr,
|
Dcr,
|
||||||
@@ -42,6 +43,11 @@ pub(crate) async fn start_authorization(
|
|||||||
callback_id: &str,
|
callback_id: &str,
|
||||||
client_registration: McpOAuthClientRegistration,
|
client_registration: McpOAuthClientRegistration,
|
||||||
) -> Result<PreparedOAuthLogin> {
|
) -> Result<PreparedOAuthLogin> {
|
||||||
|
// aKode: CIMD is disabled because its client identifier was a ChatGPT-hosted document.
|
||||||
|
if client_registration == McpOAuthClientRegistration::Cimd {
|
||||||
|
bail!("MCP OAuth CIMD client registration is not supported; use dynamic client registration");
|
||||||
|
}
|
||||||
|
|
||||||
let mut auth_manager =
|
let mut auth_manager =
|
||||||
AuthorizationManager::new_with_oauth_http_client(server_url, http_client).await?;
|
AuthorizationManager::new_with_oauth_http_client(server_url, http_client).await?;
|
||||||
auth_manager.set_allow_missing_issuer(true);
|
auth_manager.set_allow_missing_issuer(true);
|
||||||
@@ -50,79 +56,18 @@ pub(crate) async fn start_authorization(
|
|||||||
let authorization_server_issuer = metadata.issuer.clone();
|
let authorization_server_issuer = metadata.issuer.clone();
|
||||||
let callback_mode = callback_mode(&metadata)?;
|
let callback_mode = callback_mode(&metadata)?;
|
||||||
|
|
||||||
let cimd_advertised = metadata
|
|
||||||
.additional_fields
|
|
||||||
.get("client_id_metadata_document_supported")
|
|
||||||
.and_then(serde_json::Value::as_bool)
|
|
||||||
.unwrap_or(false);
|
|
||||||
let public_client_auth_supported = metadata
|
|
||||||
.additional_fields
|
|
||||||
.get("token_endpoint_auth_methods_supported")
|
|
||||||
.and_then(serde_json::Value::as_array)
|
|
||||||
.is_some_and(|methods| methods.iter().any(|method| method.as_str() == Some("none")));
|
|
||||||
|
|
||||||
let uses_shared_callback = callback_mode == McpOAuthCallbackMode::IssuerBound;
|
let uses_shared_callback = callback_mode == McpOAuthCallbackMode::IssuerBound;
|
||||||
let redirect_uri = if uses_shared_callback {
|
let redirect_uri = if uses_shared_callback {
|
||||||
redirect_uri.to_string()
|
redirect_uri.to_string()
|
||||||
} else {
|
} else {
|
||||||
append_callback_id_to_redirect_uri(redirect_uri, callback_id)?
|
append_callback_id_to_redirect_uri(redirect_uri, callback_id)?
|
||||||
};
|
};
|
||||||
let parsed_redirect_uri = Url::parse(&redirect_uri)?;
|
|
||||||
let expected_callback_path = if uses_shared_callback {
|
|
||||||
"/callback".to_string()
|
|
||||||
} else {
|
|
||||||
format!("/callback/{callback_id}")
|
|
||||||
};
|
|
||||||
let native_redirect_supported = parsed_redirect_uri.scheme() == "http"
|
|
||||||
&& matches!(
|
|
||||||
parsed_redirect_uri.host_str(),
|
|
||||||
Some("127.0.0.1" | "localhost")
|
|
||||||
)
|
|
||||||
&& parsed_redirect_uri.port().is_some_and(|port| port > 0)
|
|
||||||
&& parsed_redirect_uri.path() == expected_callback_path
|
|
||||||
&& parsed_redirect_uri.query().is_none()
|
|
||||||
&& parsed_redirect_uri.fragment().is_none()
|
|
||||||
&& parsed_redirect_uri.username().is_empty()
|
|
||||||
&& parsed_redirect_uri.password().is_none();
|
|
||||||
validate_callback_redirect(&redirect_uri, callback_id, callback_mode)?;
|
validate_callback_redirect(&redirect_uri, callback_id, callback_mode)?;
|
||||||
// MCP 2026-07-28 priority: pre-registered clients never reach this path; offer
|
// Pre-registered clients never reach this path; rmcp uses the advertised DCR endpoint.
|
||||||
// advertised CIMD here and otherwise let rmcp fall back to DCR.
|
|
||||||
// https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration
|
|
||||||
let offer_cimd = match client_registration {
|
|
||||||
McpOAuthClientRegistration::Auto => {
|
|
||||||
cimd_advertised && native_redirect_supported && public_client_auth_supported
|
|
||||||
}
|
|
||||||
McpOAuthClientRegistration::Cimd => {
|
|
||||||
if !cimd_advertised || !public_client_auth_supported {
|
|
||||||
bail!(
|
|
||||||
"MCP authorization server does not advertise CIMD with token endpoint auth method `none`"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if !native_redirect_supported {
|
|
||||||
bail!(
|
|
||||||
"MCP OAuth CIMD requires an ephemeral loopback callback at `{expected_callback_path}`"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
|
||||||
McpOAuthClientRegistration::Dcr => false,
|
|
||||||
};
|
|
||||||
|
|
||||||
auth_manager.set_metadata(metadata);
|
auth_manager.set_metadata(metadata);
|
||||||
let mut request = AuthorizationRequest::new(redirect_uri.clone())
|
let request = AuthorizationRequest::new(redirect_uri.clone())
|
||||||
.with_scopes(scopes.iter().copied())
|
.with_scopes(scopes.iter().copied())
|
||||||
.with_client_name("Codex");
|
.with_client_name("Codex");
|
||||||
if offer_cimd {
|
|
||||||
// CIMD is an active IETF Internet-Draft: this HTTPS client identifier resolves
|
|
||||||
// to its self-referential JSON metadata document.
|
|
||||||
// https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/
|
|
||||||
let client_metadata_url = if uses_shared_callback {
|
|
||||||
"https://chatgpt.com/oauth/codex/client.json".to_string()
|
|
||||||
} else {
|
|
||||||
format!("https://chatgpt.com/oauth/codex/{callback_id}/client.json")
|
|
||||||
};
|
|
||||||
request = request.with_client_metadata_url(client_metadata_url);
|
|
||||||
}
|
|
||||||
let session = AuthorizationSession::new(auth_manager, request)
|
let session = AuthorizationSession::new(auth_manager, request)
|
||||||
.await
|
.await
|
||||||
.map_err(|(_auth_manager, error)| error)?;
|
.map_err(|(_auth_manager, error)| error)?;
|
||||||
|
|||||||
@@ -127,68 +127,28 @@ async fn authorization(
|
|||||||
Ok((state, query))
|
Ok((state, query))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// aKode: CIMD (a ChatGPT-hosted client metadata document) is never offered; automatic
|
||||||
|
// registration always uses DCR, even when the server advertises CIMD support.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn automatic_cimd_uses_stable_or_callback_specific_identity() -> Result<()> {
|
async fn automatic_registration_uses_dcr_even_when_cimd_is_advertised() -> Result<()> {
|
||||||
for (host, supports_issuer, expected_client_id, expected_redirect) in [
|
for (host, supports_issuer, expected_redirect) in [
|
||||||
(
|
(
|
||||||
"127.0.0.1",
|
"127.0.0.1",
|
||||||
false,
|
false,
|
||||||
"https://chatgpt.com/oauth/codex/abc123ABC_-x/client.json",
|
|
||||||
"http://127.0.0.1:43123/callback/abc123ABC_-x",
|
"http://127.0.0.1:43123/callback/abc123ABC_-x",
|
||||||
),
|
),
|
||||||
(
|
("127.0.0.1", true, "http://127.0.0.1:43123/callback"),
|
||||||
"localhost",
|
|
||||||
false,
|
|
||||||
"https://chatgpt.com/oauth/codex/abc123ABC_-x/client.json",
|
|
||||||
"http://localhost:43123/callback/abc123ABC_-x",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"127.0.0.1",
|
|
||||||
true,
|
|
||||||
"https://chatgpt.com/oauth/codex/client.json",
|
|
||||||
"http://127.0.0.1:43123/callback",
|
|
||||||
),
|
|
||||||
] {
|
] {
|
||||||
let server = oauth_server(json!({
|
let server = oauth_server(json!({
|
||||||
"authorization_response_iss_parameter_supported": supports_issuer,
|
"authorization_response_iss_parameter_supported": supports_issuer,
|
||||||
}))
|
}))
|
||||||
.await;
|
.await;
|
||||||
let redirect = format!("http://{host}:43123/callback");
|
let redirect = format!("http://{host}:43123/callback");
|
||||||
let (mut state, query) =
|
let (_, query) =
|
||||||
authorization(&server, &redirect, McpOAuthClientRegistration::Auto).await?;
|
authorization(&server, &redirect, McpOAuthClientRegistration::Auto).await?;
|
||||||
assert_eq!(query["client_id"], expected_client_id);
|
assert_eq!(query["client_id"], "dcr-client");
|
||||||
assert_eq!(query["redirect_uri"], expected_redirect);
|
assert_eq!(query["redirect_uri"], expected_redirect);
|
||||||
assert_eq!(query["code_challenge_method"], "S256");
|
assert_eq!(requests_to(&server, "/register").await.len(), 1);
|
||||||
assert_eq!(query["scope"], "read offline_access");
|
|
||||||
|
|
||||||
state
|
|
||||||
.handle_callback_with_issuer(
|
|
||||||
"valid-authorization-code",
|
|
||||||
&query["state"],
|
|
||||||
supports_issuer
|
|
||||||
.then(|| format!("{}/mcp", server.uri()))
|
|
||||||
.as_deref(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let token_requests = requests_to(&server, "/token").await;
|
|
||||||
assert_eq!(token_requests.len(), 1);
|
|
||||||
let request = &token_requests[0];
|
|
||||||
let body: HashMap<_, _> = url::form_urlencoded::parse(&request.body)
|
|
||||||
.into_owned()
|
|
||||||
.collect();
|
|
||||||
assert_eq!(body["client_id"], expected_client_id);
|
|
||||||
assert_eq!(body["redirect_uri"], expected_redirect);
|
|
||||||
assert_eq!(body["grant_type"], "authorization_code");
|
|
||||||
assert!(body.contains_key("code_verifier"));
|
|
||||||
assert!(!body.contains_key("client_secret"));
|
|
||||||
assert!(!request.headers.contains_key("authorization"));
|
|
||||||
assert!(requests_to(&server, "/register").await.is_empty());
|
|
||||||
assert_eq!(
|
|
||||||
requests_to(&server, "/.well-known/oauth-authorization-server/mcp")
|
|
||||||
.await
|
|
||||||
.len(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -510,57 +470,21 @@ async fn resource_headers_follow_same_origin_registration_redirect_and_sdk_auth_
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn invalid_cimd_metadata_and_redirects_fail_without_dynamic_registration() {
|
async fn explicit_cimd_is_rejected_without_contacting_the_server() {
|
||||||
let valid = "http://127.0.0.1:43123/callback/abc123ABC_-x";
|
let valid = "http://127.0.0.1:43123/callback/abc123ABC_-x";
|
||||||
for (metadata, redirect, expected_error) in [
|
let server = oauth_server(json!({})).await;
|
||||||
(
|
let error = authorization(&server, valid, McpOAuthClientRegistration::Cimd)
|
||||||
json!({
|
|
||||||
"authorization_response_iss_parameter_supported": true,
|
|
||||||
"issuer": null,
|
|
||||||
}),
|
|
||||||
valid,
|
|
||||||
"issuer-bound callbacks require an authorization server issuer",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
json!({"token_endpoint_auth_methods_supported": ["private_key_jwt"]}),
|
|
||||||
valid,
|
|
||||||
"token endpoint auth method `none`",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
json!({}),
|
|
||||||
"http://127.0.0.1.evil.example:43123/callback/abc123ABC_-x",
|
|
||||||
"ephemeral loopback callback",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
json!({}),
|
|
||||||
"http://127.0.0.1/callback/abc123ABC_-x",
|
|
||||||
"ephemeral loopback callback",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
json!({}),
|
|
||||||
"http://127.0.0.1:43123/callback/wrong-id",
|
|
||||||
"ephemeral loopback callback",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
json!({}),
|
|
||||||
"http://127.0.0.1:43123/callback/abc123ABC_-x?unexpected=true",
|
|
||||||
"ephemeral loopback callback",
|
|
||||||
),
|
|
||||||
(
|
|
||||||
json!({}),
|
|
||||||
"http://[::1]:43123/callback/abc123ABC_-x",
|
|
||||||
"ephemeral loopback callback",
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
let server = oauth_server(metadata).await;
|
|
||||||
let error = authorization(&server, redirect, McpOAuthClientRegistration::Cimd)
|
|
||||||
.await
|
.await
|
||||||
.err()
|
.err()
|
||||||
.expect("invalid CIMD metadata or callback should fail");
|
.expect("CIMD should be rejected");
|
||||||
assert!(error.to_string().contains(expected_error));
|
assert!(error.to_string().contains("CIMD client registration is not supported"));
|
||||||
assert!(requests_to(&server, "/register").await.is_empty());
|
assert!(
|
||||||
assert!(requests_to(&server, "/token").await.is_empty());
|
server
|
||||||
}
|
.received_requests()
|
||||||
|
.await
|
||||||
|
.expect("mock server should record requests")
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
|
||||||
let server = oauth_server(json!({"registration_endpoint": null})).await;
|
let server = oauth_server(json!({"registration_endpoint": null})).await;
|
||||||
let error = authorization(&server, valid, McpOAuthClientRegistration::Dcr)
|
let error = authorization(&server, valid, McpOAuthClientRegistration::Dcr)
|
||||||
|
|||||||
@@ -1864,7 +1864,7 @@ enabled = false
|
|||||||
.rebuild_config_for_permission_profile(":workspace")
|
.rebuild_config_for_permission_profile(":workspace")
|
||||||
.await?;
|
.await?;
|
||||||
let pet_url =
|
let pet_url =
|
||||||
"https://persistent.oaistatic.com/codex/pets/v1/dewey-spritesheet-v4.webp".parse()?;
|
"https://example.com/pets/dewey-spritesheet.webp".parse()?;
|
||||||
for config in [&app.config, &new_config, &permission_config] {
|
for config in [&app.config, &new_config, &permission_config] {
|
||||||
assert_eq!(config.application_network_policy, controller.policy());
|
assert_eq!(config.application_network_policy, controller.policy());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
@@ -114,14 +114,12 @@ impl App {
|
|||||||
let frame_requester = tui.frame_requester();
|
let frame_requester = tui.frame_requester();
|
||||||
let animations_enabled = self.local_settings.tui.animations;
|
let animations_enabled = self.local_settings.tui.animations;
|
||||||
let tx = self.app_event_tx.clone();
|
let tx = self.app_event_tx.clone();
|
||||||
let pet_http_client = self.chat_widget.pet_http_client.clone();
|
|
||||||
std::mem::drop(tokio::spawn(async move {
|
std::mem::drop(tokio::spawn(async move {
|
||||||
let result = crate::pets::load_pet_with_assets(
|
let result = crate::pets::load_pet_with_assets(
|
||||||
pet_id.clone(),
|
pet_id.clone(),
|
||||||
codex_home,
|
codex_home,
|
||||||
frame_requester,
|
frame_requester,
|
||||||
animations_enabled,
|
animations_enabled,
|
||||||
&pet_http_client,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map(Some)
|
.map(Some)
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ async fn terminal_size_telemetry_respects_reloaded_exporter_and_consent() -> Res
|
|||||||
app.local_settings = local_settings;
|
app.local_settings = local_settings;
|
||||||
enabled.push(crate::terminal_size_telemetry::enabled(&app.config));
|
enabled.push(crate::terminal_size_telemetry::enabled(&app.config));
|
||||||
}
|
}
|
||||||
assert_eq!(enabled, vec![true, false, false, true]);
|
// aKode: Statsig never enables terminal-size observations.
|
||||||
|
assert_eq!(enabled, vec![false, false, false, true]);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -671,8 +671,6 @@ pub(crate) struct ChatWidget {
|
|||||||
review: ReviewState,
|
review: ReviewState,
|
||||||
// Active hook runs render in a dedicated live cell so they can run alongside tools.
|
// Active hook runs render in a dedicated live cell so they can run alongside tools.
|
||||||
active_hook_cell: Option<HookCell>,
|
active_hook_cell: Option<HookCell>,
|
||||||
// Reused for built-in pet CDN requests so redirects remain route-aware.
|
|
||||||
pub(crate) pet_http_client: codex_http_client::RouteAwareClientPool,
|
|
||||||
// Ambient companion rendered over the transcript area, never inside the footer rows.
|
// Ambient companion rendered over the transcript area, never inside the footer rows.
|
||||||
ambient_pet: Option<crate::pets::AmbientPet>,
|
ambient_pet: Option<crate::pets::AmbientPet>,
|
||||||
configured_pet_load_generation: ConfiguredPetLoadGeneration,
|
configured_pet_load_generation: ConfiguredPetLoadGeneration,
|
||||||
|
|||||||
@@ -90,16 +90,11 @@ impl ChatWidget {
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|keymap| keymap.chat.clone())
|
.map(|keymap| keymap.chat.clone())
|
||||||
.unwrap_or_else(|| default_keymap.chat.clone());
|
.unwrap_or_else(|| default_keymap.chat.clone());
|
||||||
let pet_http_client = codex_http_client::RouteAwareClientPool::new(
|
|
||||||
config.http_client_factory(),
|
|
||||||
codex_http_client::ClientRouteClass::Other,
|
|
||||||
);
|
|
||||||
let configured_pet_load_generation = pets::start_configured_pet_load_if_needed(
|
let configured_pet_load_generation = pets::start_configured_pet_load_if_needed(
|
||||||
&local_settings,
|
&local_settings,
|
||||||
/*ambient_pet_missing*/ true,
|
/*ambient_pet_missing*/ true,
|
||||||
frame_requester.clone(),
|
frame_requester.clone(),
|
||||||
app_event_tx.clone(),
|
app_event_tx.clone(),
|
||||||
pet_http_client.clone(),
|
|
||||||
);
|
);
|
||||||
let config_panel_tui = local_settings.tui.clone();
|
let config_panel_tui = local_settings.tui.clone();
|
||||||
let mut widget = Self {
|
let mut widget = Self {
|
||||||
@@ -231,7 +226,6 @@ impl ChatWidget {
|
|||||||
status_state: StatusState::default(),
|
status_state: StatusState::default(),
|
||||||
review: ReviewState::default(),
|
review: ReviewState::default(),
|
||||||
active_hook_cell: None,
|
active_hook_cell: None,
|
||||||
pet_http_client,
|
|
||||||
ambient_pet: None,
|
ambient_pet: None,
|
||||||
configured_pet_load_generation,
|
configured_pet_load_generation,
|
||||||
pet_picker_preview_state: crate::pets::PetPickerPreviewState::default(),
|
pet_picker_preview_state: crate::pets::PetPickerPreviewState::default(),
|
||||||
|
|||||||
@@ -42,7 +42,6 @@ pub(super) fn start_configured_pet_load_if_needed(
|
|||||||
ambient_pet_missing: bool,
|
ambient_pet_missing: bool,
|
||||||
frame_requester: FrameRequester,
|
frame_requester: FrameRequester,
|
||||||
app_event_tx: AppEventSender,
|
app_event_tx: AppEventSender,
|
||||||
pet_http_client: codex_http_client::RouteAwareClientPool,
|
|
||||||
) -> ConfiguredPetLoadGeneration {
|
) -> ConfiguredPetLoadGeneration {
|
||||||
let generation = next_configured_pet_load_generation();
|
let generation = next_configured_pet_load_generation();
|
||||||
let Some(pet_id) = config.tui.pet.clone() else {
|
let Some(pet_id) = config.tui.pet.clone() else {
|
||||||
@@ -62,7 +61,6 @@ pub(super) fn start_configured_pet_load_if_needed(
|
|||||||
codex_home,
|
codex_home,
|
||||||
frame_requester,
|
frame_requester,
|
||||||
animations_enabled,
|
animations_enabled,
|
||||||
&pet_http_client,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map(Some)
|
.map(Some)
|
||||||
@@ -234,7 +232,6 @@ impl ChatWidget {
|
|||||||
/*ambient_pet_missing*/ self.ambient_pet.is_none(),
|
/*ambient_pet_missing*/ self.ambient_pet.is_none(),
|
||||||
self.frame_requester.clone(),
|
self.frame_requester.clone(),
|
||||||
self.app_event_tx.clone(),
|
self.app_event_tx.clone(),
|
||||||
self.pet_http_client.clone(),
|
|
||||||
);
|
);
|
||||||
self.apply_ambient_pet_image_support_override_for_tests();
|
self.apply_ambient_pet_image_support_override_for_tests();
|
||||||
self.request_redraw();
|
self.request_redraw();
|
||||||
@@ -306,7 +303,6 @@ impl ChatWidget {
|
|||||||
let codex_home = self.local_settings.codex_home.clone();
|
let codex_home = self.local_settings.codex_home.clone();
|
||||||
let frame_requester = self.frame_requester.clone();
|
let frame_requester = self.frame_requester.clone();
|
||||||
let tx = self.app_event_tx.clone();
|
let tx = self.app_event_tx.clone();
|
||||||
let pet_http_client = self.pet_http_client.clone();
|
|
||||||
spawn_pet_load(
|
spawn_pet_load(
|
||||||
async move {
|
async move {
|
||||||
crate::pets::load_pet_with_assets(
|
crate::pets::load_pet_with_assets(
|
||||||
@@ -314,7 +310,6 @@ impl ChatWidget {
|
|||||||
codex_home,
|
codex_home,
|
||||||
frame_requester,
|
frame_requester,
|
||||||
/*animations_enabled*/ false,
|
/*animations_enabled*/ false,
|
||||||
&pet_http_client,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|err| err.to_string())
|
.map_err(|err| err.to_string())
|
||||||
|
|||||||
@@ -102,7 +102,6 @@ async fn shared_pet_load_uses_cached_builtin_assets() {
|
|||||||
AbsolutePathBuf::from_absolute_path(codex_home.path()).expect("absolute temporary path"),
|
AbsolutePathBuf::from_absolute_path(codex_home.path()).expect("absolute temporary path"),
|
||||||
chat.frame_requester.clone(),
|
chat.frame_requester.clone(),
|
||||||
/*animations_enabled*/ false,
|
/*animations_enabled*/ false,
|
||||||
&chat.pet_http_client,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.expect("load cached built-in pet");
|
.expect("load cached built-in pet");
|
||||||
|
|||||||
@@ -191,8 +191,6 @@ mod motion;
|
|||||||
mod multi_agents;
|
mod multi_agents;
|
||||||
mod named_session_lookup;
|
mod named_session_lookup;
|
||||||
mod notifications;
|
mod notifications;
|
||||||
#[cfg(any(not(debug_assertions), test))]
|
|
||||||
mod npm_registry;
|
|
||||||
pub(crate) mod onboarding;
|
pub(crate) mod onboarding;
|
||||||
mod oss_selection;
|
mod oss_selection;
|
||||||
mod pager_overlay;
|
mod pager_overlay;
|
||||||
@@ -1267,8 +1265,7 @@ async fn run_ratatui_app(
|
|||||||
let uses_remote_workspace = app_server_target.uses_remote_workspace();
|
let uses_remote_workspace = app_server_target.uses_remote_workspace();
|
||||||
let workload_identity_selected = is_workload_identity_selected();
|
let workload_identity_selected = is_workload_identity_selected();
|
||||||
color_eyre::install()?;
|
color_eyre::install()?;
|
||||||
|
// aKode: no remote announcement-tip prewarm.
|
||||||
tooltips::announcement::prewarm(initial_config.http_client_factory());
|
|
||||||
|
|
||||||
// Forward panic reports through tracing so they appear in the UI status
|
// Forward panic reports through tracing so they appear in the UI status
|
||||||
// line, but do not swallow the default/color-eyre panic handler.
|
// line, but do not swallow the default/color-eyre panic handler.
|
||||||
|
|||||||
@@ -1,130 +0,0 @@
|
|||||||
use serde::Deserialize;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
#[cfg(not(debug_assertions))]
|
|
||||||
pub(crate) const PACKAGE_URL: &str = "https://registry.npmjs.org/@openai%2fcodex";
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
|
||||||
pub(crate) struct NpmPackageInfo {
|
|
||||||
#[serde(rename = "dist-tags")]
|
|
||||||
dist_tags: HashMap<String, String>,
|
|
||||||
versions: HashMap<String, NpmPackageVersionInfo>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
|
||||||
struct NpmPackageVersionInfo {
|
|
||||||
dist: Option<NpmPackageDist>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
|
||||||
struct NpmPackageDist {
|
|
||||||
tarball: Option<String>,
|
|
||||||
integrity: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn ensure_version_ready(
|
|
||||||
package_info: &NpmPackageInfo,
|
|
||||||
version: &str,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let version = version.trim();
|
|
||||||
|
|
||||||
match package_info.dist_tags.get("latest").map(String::as_str) {
|
|
||||||
Some(latest) if latest == version => {}
|
|
||||||
Some(latest) => anyhow::bail!(
|
|
||||||
"npm latest dist-tag points to {latest}, expected GitHub release {version}"
|
|
||||||
),
|
|
||||||
None => anyhow::bail!("npm package is missing latest dist-tag"),
|
|
||||||
}
|
|
||||||
|
|
||||||
version_info_with_dist(package_info, version)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn version_info_with_dist<'a>(
|
|
||||||
package_info: &'a NpmPackageInfo,
|
|
||||||
version: &str,
|
|
||||||
) -> anyhow::Result<&'a NpmPackageVersionInfo> {
|
|
||||||
let info = package_info
|
|
||||||
.versions
|
|
||||||
.get(version)
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("npm package version {version} is missing"))?;
|
|
||||||
let Some(dist) = info.dist.as_ref() else {
|
|
||||||
anyhow::bail!("npm package version {version} is missing dist metadata");
|
|
||||||
};
|
|
||||||
let has_tarball = dist
|
|
||||||
.tarball
|
|
||||||
.as_deref()
|
|
||||||
.is_some_and(|tarball| !tarball.is_empty());
|
|
||||||
if !has_tarball {
|
|
||||||
anyhow::bail!("npm package version {version} is missing dist.tarball");
|
|
||||||
}
|
|
||||||
let has_integrity = dist
|
|
||||||
.integrity
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|integrity| !integrity.is_empty());
|
|
||||||
if !has_integrity {
|
|
||||||
anyhow::bail!("npm package version {version} is missing dist.integrity");
|
|
||||||
}
|
|
||||||
Ok(info)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn version_json(version: &str) -> serde_json::Value {
|
|
||||||
serde_json::json!({
|
|
||||||
"dist": {
|
|
||||||
"integrity": format!("sha512-{version}"),
|
|
||||||
"tarball": format!("https://registry.npmjs.org/@openai/codex/-/codex-{version}.tgz"),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn package_info(github_latest: &str, npm_latest: &str) -> NpmPackageInfo {
|
|
||||||
let mut versions = serde_json::Map::new();
|
|
||||||
versions.insert(github_latest.to_string(), version_json(github_latest));
|
|
||||||
|
|
||||||
serde_json::from_value(serde_json::json!({
|
|
||||||
"dist-tags": { "latest": npm_latest },
|
|
||||||
"versions": serde_json::Value::Object(versions),
|
|
||||||
}))
|
|
||||||
.expect("valid npm package metadata")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ready_version_requires_latest_dist_tag_and_root_dist() {
|
|
||||||
let latest = "1.2.3";
|
|
||||||
let package_info = package_info(latest, latest);
|
|
||||||
|
|
||||||
ensure_version_ready(&package_info, latest).expect("npm package is ready");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ready_version_rejects_stale_latest_dist_tag() {
|
|
||||||
let package_info = package_info("1.2.3", "1.2.2");
|
|
||||||
|
|
||||||
let err = ensure_version_ready(&package_info, "1.2.3")
|
|
||||||
.expect_err("npm latest dist-tag must match GitHub latest");
|
|
||||||
assert!(
|
|
||||||
err.to_string().contains("latest dist-tag"),
|
|
||||||
"error should name stale latest dist-tag: {err}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ready_version_rejects_missing_root_dist() {
|
|
||||||
let package_info: NpmPackageInfo = serde_json::from_value(serde_json::json!({
|
|
||||||
"dist-tags": { "latest": "1.2.3" },
|
|
||||||
"versions": { "1.2.3": {} },
|
|
||||||
}))
|
|
||||||
.expect("valid npm package metadata");
|
|
||||||
|
|
||||||
let err = ensure_version_ready(&package_info, "1.2.3")
|
|
||||||
.expect_err("root package must have dist metadata");
|
|
||||||
assert!(
|
|
||||||
err.to_string().contains("missing dist metadata"),
|
|
||||||
"error should name missing dist metadata: {err}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,167 +1,50 @@
|
|||||||
//! Built-in pet asset acquisition and cache ownership.
|
//! Built-in pet asset cache ownership.
|
||||||
//!
|
//!
|
||||||
//! Unlike custom pets, built-in pets are not checked into the TUI package as
|
//! Unlike custom pets, built-in pets are not checked into the TUI package as
|
||||||
//! local spritesheets. The TUI resolves them from the public Codex pets CDN on
|
//! local spritesheets. They are looked up in a versioned cache under
|
||||||
//! first use, verifies that the downloaded file has the expected spritesheet
|
//! CODEX_HOME and validated for the expected spritesheet geometry.
|
||||||
//! geometry, and installs it into a versioned cache under CODEX_HOME.
|
|
||||||
//!
|
//!
|
||||||
//! This module deliberately stops at "a validated spritesheet exists at this
|
//! aKode: upstream downloaded missing spritesheets from an OpenAI CDN. That
|
||||||
//! path". Higher layers remain responsible for deciding when downloads are
|
//! download was removed; a built-in pet whose spritesheet is not already in the
|
||||||
//! allowed, when previews should block on them, and when a successfully loaded
|
//! local cache is simply reported as unavailable and is never fetched.
|
||||||
//! built-in pet is safe to persist to config.
|
|
||||||
|
|
||||||
use std::fs;
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use codex_http_client::RouteAwareClientPool;
|
|
||||||
use url::Url;
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
use super::catalog;
|
use super::catalog;
|
||||||
|
|
||||||
const PET_PACK_VERSION: &str = "v1";
|
const PET_PACK_VERSION: &str = "v1";
|
||||||
const PET_PACK_DIR: &str = "cache/tui-pets";
|
const PET_PACK_DIR: &str = "cache/tui-pets";
|
||||||
const PET_CDN_BASE_URL: &str = "https://persistent.oaistatic.com/codex/pets/v1";
|
|
||||||
const PET_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(60);
|
|
||||||
const PET_MAX_DOWNLOAD_BYTES: u64 = 4 * 1024 * 1024;
|
|
||||||
|
|
||||||
pub(crate) fn builtin_spritesheet_path(codex_home: &Path, file: &str) -> PathBuf {
|
pub(crate) fn builtin_spritesheet_path(codex_home: &Path, file: &str) -> PathBuf {
|
||||||
pack_dir(codex_home).join("assets").join(file)
|
pack_dir(codex_home).join("assets").join(file)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ensure that a built-in pet's spritesheet is present and structurally valid.
|
/// Ensure that a built-in pet's spritesheet is present locally and structurally valid.
|
||||||
///
|
///
|
||||||
/// The cache key is the CDN-facing filename, so updating a built-in pet means
|
/// Callers should treat any error here as "the asset is unavailable".
|
||||||
/// publishing a new versioned filename rather than mutating an existing one in
|
pub(crate) async fn ensure_builtin_pet(codex_home: &Path, pet: catalog::BuiltinPet) -> Result<()> {
|
||||||
/// place. If a cached file is missing or invalid, this downloads a fresh copy,
|
|
||||||
/// validates the decoded image dimensions, and installs it atomically. Callers
|
|
||||||
/// should treat any error here as "the asset is unavailable", not as a partial
|
|
||||||
/// install they can safely ignore.
|
|
||||||
pub(crate) async fn ensure_builtin_pet(
|
|
||||||
codex_home: &Path,
|
|
||||||
pet: catalog::BuiltinPet,
|
|
||||||
http_client: &RouteAwareClientPool,
|
|
||||||
) -> Result<()> {
|
|
||||||
let destination = builtin_spritesheet_path(codex_home, pet.spritesheet_file);
|
let destination = builtin_spritesheet_path(codex_home, pet.spritesheet_file);
|
||||||
let cache_destination = destination.clone();
|
|
||||||
let cache_valid = tokio::task::spawn_blocking(move || {
|
|
||||||
validate_cached_spritesheet(&cache_destination).is_ok()
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.context("join pet spritesheet cache validation task")?;
|
|
||||||
if cache_valid {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let url = builtin_pet_url(pet)?;
|
|
||||||
let bytes = download_bytes_with_limit(http_client, &url, PET_MAX_DOWNLOAD_BYTES).await?;
|
|
||||||
tokio::task::spawn_blocking(move || {
|
tokio::task::spawn_blocking(move || {
|
||||||
let parent = destination
|
validate_cached_spritesheet(&destination).with_context(|| {
|
||||||
.parent()
|
format!(
|
||||||
.context("pet spritesheet path should include an assets directory")?;
|
"built-in pet spritesheet {} is not available locally",
|
||||||
fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
|
destination.display()
|
||||||
|
)
|
||||||
let staging = destination.with_file_name(format!(
|
})
|
||||||
".{}.download-{}.webp",
|
|
||||||
pet.spritesheet_file,
|
|
||||||
Uuid::new_v4()
|
|
||||||
));
|
|
||||||
fs::write(&staging, &bytes).with_context(|| format!("write {}", staging.display()))?;
|
|
||||||
if let Err(err) = validate_cached_spritesheet(&staging) {
|
|
||||||
let _ = fs::remove_file(&staging);
|
|
||||||
return Err(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
if install_downloaded_spritesheet(&staging, &destination).is_ok() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
if validate_cached_spritesheet(&destination).is_ok() {
|
|
||||||
let _ = fs::remove_file(&staging);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
if destination.exists() {
|
|
||||||
fs::remove_file(&destination)
|
|
||||||
.with_context(|| format!("remove {}", destination.display()))?;
|
|
||||||
}
|
|
||||||
install_downloaded_spritesheet(&staging, &destination)
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.context("join pet spritesheet install task")?
|
.context("join pet spritesheet cache validation task")?
|
||||||
}
|
|
||||||
|
|
||||||
fn builtin_pet_url(pet: catalog::BuiltinPet) -> Result<String> {
|
|
||||||
let url = format!("{PET_CDN_BASE_URL}/{}", pet.spritesheet_file);
|
|
||||||
validate_download_url(&url)?;
|
|
||||||
Ok(url)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pack_dir(codex_home: &Path) -> PathBuf {
|
fn pack_dir(codex_home: &Path) -> PathBuf {
|
||||||
codex_home.join(PET_PACK_DIR).join(PET_PACK_VERSION)
|
codex_home.join(PET_PACK_DIR).join(PET_PACK_VERSION)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn download_bytes_with_limit(
|
|
||||||
http_client: &RouteAwareClientPool,
|
|
||||||
url: &str,
|
|
||||||
max_bytes: u64,
|
|
||||||
) -> Result<Vec<u8>> {
|
|
||||||
validate_download_url(url)?;
|
|
||||||
let mut response = http_client
|
|
||||||
.get(url)
|
|
||||||
.timeout(PET_DOWNLOAD_TIMEOUT)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.with_context(|| format!("download pet asset from {url}"))?
|
|
||||||
.error_for_status()
|
|
||||||
.with_context(|| format!("download pet asset from {url}"))?;
|
|
||||||
validate_download_url(response.url().as_str())?;
|
|
||||||
|
|
||||||
if response.content_length().is_some_and(|len| len > max_bytes) {
|
|
||||||
bail!("pet asset download from {url} exceeded {max_bytes} bytes");
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut bytes = Vec::new();
|
|
||||||
while let Some(chunk) = response
|
|
||||||
.chunk()
|
|
||||||
.await
|
|
||||||
.with_context(|| format!("read pet asset download from {url}"))?
|
|
||||||
{
|
|
||||||
append_download_chunk(&mut bytes, &chunk, max_bytes, url)?;
|
|
||||||
}
|
|
||||||
Ok(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn append_download_chunk(
|
|
||||||
bytes: &mut Vec<u8>,
|
|
||||||
chunk: &[u8],
|
|
||||||
max_bytes: u64,
|
|
||||||
url: &str,
|
|
||||||
) -> Result<()> {
|
|
||||||
if (bytes.len() as u64).saturating_add(chunk.len() as u64) > max_bytes {
|
|
||||||
bail!("pet asset download from {url} exceeded {max_bytes} bytes");
|
|
||||||
}
|
|
||||||
bytes.extend_from_slice(chunk);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn install_downloaded_spritesheet(staging: &Path, destination: &Path) -> Result<()> {
|
|
||||||
fs::rename(staging, destination).with_context(|| format!("install {}", destination.display()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate_download_url(value: &str) -> Result<()> {
|
|
||||||
let url = Url::parse(value).with_context(|| format!("parse pet asset download URL {value}"))?;
|
|
||||||
if url.scheme() != "https" {
|
|
||||||
bail!("unsupported pet asset download URL scheme {}", url.scheme());
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate_cached_spritesheet(path: &Path) -> Result<()> {
|
fn validate_cached_spritesheet(path: &Path) -> Result<()> {
|
||||||
let (width, height) =
|
let (width, height) =
|
||||||
image::image_dimensions(path).with_context(|| format!("read {}", path.display()))?;
|
image::image_dimensions(path).with_context(|| format!("read {}", path.display()))?;
|
||||||
@@ -181,7 +64,7 @@ fn validate_cached_spritesheet(path: &Path) -> Result<()> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) fn write_test_pack(codex_home: &Path) {
|
pub(crate) fn write_test_pack(codex_home: &Path) {
|
||||||
let assets_dir = pack_dir(codex_home).join("assets");
|
let assets_dir = pack_dir(codex_home).join("assets");
|
||||||
fs::create_dir_all(&assets_dir).unwrap();
|
std::fs::create_dir_all(&assets_dir).unwrap();
|
||||||
for pet in catalog::BUILTIN_PETS {
|
for pet in catalog::BUILTIN_PETS {
|
||||||
let path = assets_dir.join(pet.spritesheet_file);
|
let path = assets_dir.join(pet.spritesheet_file);
|
||||||
catalog::write_test_spritesheet(&path);
|
catalog::write_test_spritesheet(&path);
|
||||||
@@ -191,35 +74,6 @@ pub(crate) fn write_test_pack(codex_home: &Path) {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use pretty_assertions::assert_eq;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn builtin_pet_url_uses_public_cdn_path() {
|
|
||||||
let pet = catalog::builtin_pet("dewey").unwrap();
|
|
||||||
|
|
||||||
let url = builtin_pet_url(pet).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
url,
|
|
||||||
"https://persistent.oaistatic.com/codex/pets/v1/dewey-spritesheet-v4.webp"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn oversized_download_chunk_is_rejected() {
|
|
||||||
let url = "https://example.com/pet.webp";
|
|
||||||
let mut bytes = Vec::new();
|
|
||||||
|
|
||||||
append_download_chunk(&mut bytes, b"1234", /*max_bytes*/ 8, url).unwrap();
|
|
||||||
let error = append_download_chunk(&mut bytes, b"56789", /*max_bytes*/ 8, url)
|
|
||||||
.expect_err("chunk should exceed the download limit");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
error.to_string(),
|
|
||||||
"pet asset download from https://example.com/pet.webp exceeded 8 bytes"
|
|
||||||
);
|
|
||||||
assert_eq!(bytes, b"1234");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn write_test_pack_installs_all_builtins() {
|
fn write_test_pack_installs_all_builtins() {
|
||||||
@@ -233,4 +87,12 @@ mod tests {
|
|||||||
validate_cached_spritesheet(&path).unwrap();
|
validate_cached_spritesheet(&path).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn missing_builtin_pet_is_unavailable_without_network() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let pet = catalog::builtin_pet("dewey").unwrap();
|
||||||
|
|
||||||
|
assert!(ensure_builtin_pet(dir.path(), pet).await.is_err());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ mod sixel;
|
|||||||
|
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use codex_http_client::RouteAwareClientPool;
|
|
||||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||||
|
|
||||||
use crate::tui::FrameRequester;
|
use crate::tui::FrameRequester;
|
||||||
@@ -61,16 +60,12 @@ pub(crate) const DISABLED_PET_ID: &str = "disabled";
|
|||||||
/// Ensure that a selected built-in pet has a locally cached spritesheet.
|
/// Ensure that a selected built-in pet has a locally cached spritesheet.
|
||||||
///
|
///
|
||||||
/// Custom pets are intentionally a no-op here because their source of truth is
|
/// Custom pets are intentionally a no-op here because their source of truth is
|
||||||
/// already local. Preparing this before loading keeps first-use preview and
|
/// already local. Checking this before loading keeps first-use preview and
|
||||||
/// persistence failures at the asset-fetch boundary rather than surfacing as
|
/// persistence failures at the asset boundary rather than surfacing as deeper
|
||||||
/// deeper image-loading errors.
|
/// image-loading errors.
|
||||||
async fn ensure_builtin_pack_for_pet(
|
async fn ensure_builtin_pack_for_pet(pet_id: &str, codex_home: &std::path::Path) -> Result<()> {
|
||||||
pet_id: &str,
|
|
||||||
codex_home: &std::path::Path,
|
|
||||||
http_client: &RouteAwareClientPool,
|
|
||||||
) -> Result<()> {
|
|
||||||
if let Some(pet) = catalog::builtin_pet(pet_id) {
|
if let Some(pet) = catalog::builtin_pet(pet_id) {
|
||||||
asset_pack::ensure_builtin_pet(codex_home, pet, http_client).await?;
|
asset_pack::ensure_builtin_pet(codex_home, pet).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -81,9 +76,8 @@ pub(crate) async fn load_pet_with_assets(
|
|||||||
codex_home: AbsolutePathBuf,
|
codex_home: AbsolutePathBuf,
|
||||||
frame_requester: FrameRequester,
|
frame_requester: FrameRequester,
|
||||||
animations_enabled: bool,
|
animations_enabled: bool,
|
||||||
http_client: &RouteAwareClientPool,
|
|
||||||
) -> Result<AmbientPet> {
|
) -> Result<AmbientPet> {
|
||||||
ensure_builtin_pack_for_pet(&pet_id, &codex_home, http_client).await?;
|
ensure_builtin_pack_for_pet(&pet_id, &codex_home).await?;
|
||||||
tokio::task::spawn_blocking(move || {
|
tokio::task::spawn_blocking(move || {
|
||||||
AmbientPet::load(
|
AmbientPet::load(
|
||||||
Some(&pet_id),
|
Some(&pet_id),
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/tooltips.rs
|
|
||||||
expression: rendered
|
|
||||||
---
|
|
||||||
Line::from_iter([Span::from("Tip:").fg(Color::Reset).bold(), Span::from(" Use the "), Span::from("desktop app").fg(Color::Reset).bold(), Span::from(". Install it")]) []
|
|
||||||
Line::from("from") []
|
|
||||||
Line::from(Span::from("https://learn.chatgpt.com/docs/linux/linux-app").fg(Color::Reset).underlined()) [TerminalHyperlink { columns: 0..46, destination: "https://learn.chatgpt.com/docs/linux/linux-app", destination_kind: Web }]
|
|
||||||
Line::from_iter([Span::from("and run "), Span::from("chatgpt").fg(Color::Rgb(166, 227, 161)), Span::from(".")]) []
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/tooltips.rs
|
|
||||||
expression: rendered
|
|
||||||
---
|
|
||||||
Line::from_iter([Span::from("Tip:").fg(Color::Reset).bold(), Span::from(" Use the "), Span::from("desktop app").fg(Color::Reset).bold(), Span::from(". Run "), Span::from("codex app").fg(Color::Rgb(166, 227, 161))]) []
|
|
||||||
Line::from("to open it. It installs automatically if") []
|
|
||||||
Line::from("needed.") []
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
---
|
|
||||||
source: tui/src/tooltips.rs
|
|
||||||
expression: rendered
|
|
||||||
---
|
|
||||||
Line::from_iter([Span::from("Tip:").fg(Color::Reset).bold(), Span::from(" Use the "), Span::from("desktop app").fg(Color::Reset).bold(), Span::from(". Install it")]) []
|
|
||||||
Line::from("from") []
|
|
||||||
Line::from(Span::from("https://chatgpt.com/codex?app-landing-page=true").fg(Color::Reset).underlined()) [TerminalHyperlink { columns: 0..47, destination: "https://chatgpt.com/codex?app-landing-page=true", destination_kind: Web }]
|
|
||||||
Line::from_iter([Span::from("and run "), Span::from("codex app").fg(Color::Rgb(166, 227, 161)), Span::from(".")]) []
|
|
||||||
@@ -8,8 +8,8 @@ pub(crate) type LaunchTags = Vec<(&'static str, &'static str)>;
|
|||||||
|
|
||||||
pub(crate) fn enabled(config: &Config) -> bool {
|
pub(crate) fn enabled(config: &Config) -> bool {
|
||||||
match config.otel.metrics_exporter {
|
match config.otel.metrics_exporter {
|
||||||
OtelExporterKind::None => false,
|
// aKode: Statsig export is disabled; only user-configured OTLP exporters observe sizes.
|
||||||
OtelExporterKind::Statsig => config.analytics_enabled != Some(false),
|
OtelExporterKind::None | OtelExporterKind::Statsig => false,
|
||||||
OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } => true,
|
OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } => true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,17 +13,6 @@ use std::path::Path;
|
|||||||
#[path = "tooltips/keybinding_tests.rs"]
|
#[path = "tooltips/keybinding_tests.rs"]
|
||||||
mod keybinding_tests;
|
mod keybinding_tests;
|
||||||
|
|
||||||
const ANNOUNCEMENT_TIP_URL: &str =
|
|
||||||
"https://raw.githubusercontent.com/openai/codex/main/announcement_tip.toml";
|
|
||||||
|
|
||||||
const IS_MACOS: bool = cfg!(target_os = "macos");
|
|
||||||
const IS_WINDOWS: bool = cfg!(target_os = "windows");
|
|
||||||
|
|
||||||
const WINDOWS_APP_TOOLTIP: &str = "Use the **desktop app**. Install it from https://chatgpt.com/codex?app-landing-page=true and run `codex app`.";
|
|
||||||
const MACOS_APP_TOOLTIP: &str =
|
|
||||||
"Use the **desktop app**. Run `codex app` to open it. It installs automatically if needed.";
|
|
||||||
const LINUX_APP_TOOLTIP: &str = "Use the **desktop app**. Install it from https://learn.chatgpt.com/docs/linux/linux-app and run `chatgpt`.";
|
|
||||||
|
|
||||||
const RAW_TOOLTIPS: &str = include_str!("../assets/tooltips.txt");
|
const RAW_TOOLTIPS: &str = include_str!("../assets/tooltips.txt");
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
@@ -31,7 +20,6 @@ lazy_static! {
|
|||||||
.lines()
|
.lines()
|
||||||
.map(str::trim)
|
.map(str::trim)
|
||||||
.filter(|line| !line.is_empty() && !line.starts_with('#'))
|
.filter(|line| !line.is_empty() && !line.starts_with('#'))
|
||||||
.chain(app_tooltip())
|
|
||||||
.collect();
|
.collect();
|
||||||
static ref ALL_TOOLTIPS: Vec<&'static str> = {
|
static ref ALL_TOOLTIPS: Vec<&'static str> = {
|
||||||
let mut tips = Vec::new();
|
let mut tips = Vec::new();
|
||||||
@@ -46,62 +34,10 @@ lazy_static! {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Pick a random tooltip to show to the user when starting Codex.
|
/// Pick a random tooltip to show to the user when starting Codex.
|
||||||
pub(crate) fn get_tooltip(plan: Option<PlanType>, keymap: &TuiKeymap) -> Option<String> {
|
// aKode: remote announcement tips and desktop-app promotions were removed; only local tips remain.
|
||||||
|
pub(crate) fn get_tooltip(_plan: Option<PlanType>, keymap: &TuiKeymap) -> Option<String> {
|
||||||
let mut rng = rand::rng();
|
let mut rng = rand::rng();
|
||||||
preferred_tooltip(&mut rng, plan).or_else(|| pick_tooltip(&mut rng, keymap))
|
pick_tooltip(&mut rng, keymap)
|
||||||
}
|
|
||||||
|
|
||||||
/// Apply the shared announcement and promotion policy before falling back to local tips.
|
|
||||||
/// The announcement lookup only reads the prewarmed cache.
|
|
||||||
pub(crate) fn preferred_tooltip<R: Rng + ?Sized>(
|
|
||||||
rng: &mut R,
|
|
||||||
plan: Option<PlanType>,
|
|
||||||
) -> Option<String> {
|
|
||||||
if let Some(announcement) = announcement::fetch_announcement_tip(plan) {
|
|
||||||
return Some(announcement);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Leave small chance for a random tooltip to be shown.
|
|
||||||
if rng.random_ratio(/*numerator*/ 8, /*denominator*/ 10) {
|
|
||||||
return app_tooltip().map(str::to_string);
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
struct LinuxDesktopSession {
|
|
||||||
has_display: bool,
|
|
||||||
is_wsl: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LinuxDesktopSession {
|
|
||||||
fn current() -> Self {
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
{
|
|
||||||
Self {
|
|
||||||
has_display: std::env::var_os("DISPLAY").is_some_and(|value| !value.is_empty())
|
|
||||||
|| std::env::var_os("WAYLAND_DISPLAY").is_some_and(|value| !value.is_empty()),
|
|
||||||
is_wsl: crate::clipboard_paste::is_probably_wsl(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "linux"))]
|
|
||||||
{
|
|
||||||
Self {
|
|
||||||
has_display: false,
|
|
||||||
is_wsl: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn linux_app_tooltip(session: LinuxDesktopSession) -> Option<&'static str> {
|
|
||||||
(session.has_display && !session.is_wsl).then_some(LINUX_APP_TOOLTIP)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn app_tooltip() -> Option<&'static str> {
|
|
||||||
// aKode: no desktop-app promotion.
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pick_tooltip<R: Rng + ?Sized>(rng: &mut R, keymap: &TuiKeymap) -> Option<String> {
|
fn pick_tooltip<R: Rng + ?Sized>(rng: &mut R, keymap: &TuiKeymap) -> Option<String> {
|
||||||
@@ -155,210 +91,9 @@ pub(crate) fn render_tooltip(mut template: &str, keymap: Option<&RuntimeKeymap>)
|
|||||||
Some(rendered)
|
Some(rendered)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) mod announcement {
|
|
||||||
use crate::tooltips::ANNOUNCEMENT_TIP_URL;
|
|
||||||
use crate::version::CODEX_CLI_VERSION;
|
|
||||||
use chrono::NaiveDate;
|
|
||||||
use chrono::Utc;
|
|
||||||
use codex_http_client::ClientRouteClass;
|
|
||||||
use codex_http_client::HttpClientFactory;
|
|
||||||
use codex_http_client::RouteAwareClientPool;
|
|
||||||
use codex_protocol::account::PlanType;
|
|
||||||
use regex_lite::Regex;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use std::sync::OnceLock;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
static ANNOUNCEMENT_TIP: OnceLock<Option<AnnouncementTips>> = OnceLock::new();
|
|
||||||
const CURRENT_OS: TargetOs = TargetOs::current();
|
|
||||||
|
|
||||||
/// Prewarm the cache of the announcement tip.
|
|
||||||
pub(crate) fn prewarm(http_client_factory: HttpClientFactory) {
|
|
||||||
// aKode: announcement tips are never fetched from the network.
|
|
||||||
let _ = http_client_factory;
|
|
||||||
let _ = ANNOUNCEMENT_TIP.set(None);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fetch the announcement tip, return None if the prewarm is not done yet.
|
|
||||||
pub(crate) fn fetch_announcement_tip(plan: Option<PlanType>) -> Option<String> {
|
|
||||||
ANNOUNCEMENT_TIP
|
|
||||||
.get()
|
|
||||||
.and_then(Option::as_ref)
|
|
||||||
.and_then(|tips| tips.select(plan))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct AnnouncementTipRaw {
|
|
||||||
content: String,
|
|
||||||
from_date: Option<String>,
|
|
||||||
to_date: Option<String>,
|
|
||||||
version_regex: Option<String>,
|
|
||||||
target_app: Option<String>,
|
|
||||||
target_plan_types: Option<Vec<PlanType>>,
|
|
||||||
target_oses: Option<Vec<TargetOs>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct AnnouncementTipDocument {
|
|
||||||
announcements: Vec<AnnouncementTipRaw>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct AnnouncementTip {
|
|
||||||
content: String,
|
|
||||||
from_date: Option<NaiveDate>,
|
|
||||||
to_date: Option<NaiveDate>,
|
|
||||||
version_regex: Option<Regex>,
|
|
||||||
target_app: String,
|
|
||||||
target_plan_types: Option<Vec<PlanType>>,
|
|
||||||
target_oses: Option<Vec<TargetOs>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Copy, Clone, PartialEq, Eq)]
|
|
||||||
#[serde(rename_all = "lowercase")]
|
|
||||||
enum TargetOs {
|
|
||||||
Linux,
|
|
||||||
Macos,
|
|
||||||
Windows,
|
|
||||||
#[serde(other)]
|
|
||||||
Unknown,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TargetOs {
|
|
||||||
const fn current() -> Self {
|
|
||||||
if cfg!(target_os = "macos") {
|
|
||||||
Self::Macos
|
|
||||||
} else if cfg!(target_os = "windows") {
|
|
||||||
Self::Windows
|
|
||||||
} else {
|
|
||||||
// Codex currently publishes CLI builds for macOS, Windows, and Linux.
|
|
||||||
Self::Linux
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn fetch_announcement_tip_text(http_client_factory: HttpClientFactory) -> Option<String> {
|
|
||||||
let client = RouteAwareClientPool::new(http_client_factory, ClientRouteClass::Other);
|
|
||||||
let response = client
|
|
||||||
.get(ANNOUNCEMENT_TIP_URL)
|
|
||||||
.timeout(Duration::from_millis(2000))
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.ok()?;
|
|
||||||
response.error_for_status().ok()?.text().await.ok()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parsed once during prewarming; eligibility stays current across redraws and account changes.
|
|
||||||
pub(super) struct AnnouncementTips(Vec<AnnouncementTip>);
|
|
||||||
|
|
||||||
impl AnnouncementTips {
|
|
||||||
pub(super) fn parse(text: &str) -> Option<Self> {
|
|
||||||
let announcements = toml::from_str::<AnnouncementTipDocument>(text)
|
|
||||||
.map(|doc| doc.announcements)
|
|
||||||
.or_else(|_| toml::from_str::<Vec<AnnouncementTipRaw>>(text))
|
|
||||||
.ok()?;
|
|
||||||
Some(Self(
|
|
||||||
announcements
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(AnnouncementTip::from_raw)
|
|
||||||
.collect(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn select(&self, plan: Option<PlanType>) -> Option<String> {
|
|
||||||
let today = Utc::now().date_naive();
|
|
||||||
self.0
|
|
||||||
.iter()
|
|
||||||
.rev()
|
|
||||||
.find(|tip| {
|
|
||||||
let plan_matches = tip.target_plan_types.as_ref().is_none_or(|target_plans| {
|
|
||||||
plan.is_some_and(|plan| target_plans.contains(&plan))
|
|
||||||
});
|
|
||||||
let os_matches = tip
|
|
||||||
.target_oses
|
|
||||||
.as_ref()
|
|
||||||
.is_none_or(|target_oses| target_oses.contains(&CURRENT_OS));
|
|
||||||
tip.version_matches(CODEX_CLI_VERSION)
|
|
||||||
&& tip.date_matches(today)
|
|
||||||
&& tip.target_app == "cli"
|
|
||||||
&& plan_matches
|
|
||||||
&& os_matches
|
|
||||||
})
|
|
||||||
.map(|tip| tip.content.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnnouncementTip {
|
|
||||||
fn from_raw(raw: AnnouncementTipRaw) -> Option<Self> {
|
|
||||||
let content = raw.content.trim();
|
|
||||||
if content.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let from_date = match raw.from_date {
|
|
||||||
Some(date) => Some(NaiveDate::parse_from_str(&date, "%Y-%m-%d").ok()?),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
let to_date = match raw.to_date {
|
|
||||||
Some(date) => Some(NaiveDate::parse_from_str(&date, "%Y-%m-%d").ok()?),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
let version_regex = match raw.version_regex {
|
|
||||||
Some(pattern) => Some(Regex::new(&pattern).ok()?),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
let target_plan_types = raw.target_plan_types;
|
|
||||||
if target_plan_types
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|plans| plans.contains(&PlanType::Unknown))
|
|
||||||
{
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let target_oses = raw.target_oses;
|
|
||||||
if target_oses
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|oses| oses.contains(&TargetOs::Unknown))
|
|
||||||
{
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(Self {
|
|
||||||
content: content.to_string(),
|
|
||||||
from_date,
|
|
||||||
to_date,
|
|
||||||
version_regex,
|
|
||||||
target_app: raw.target_app.unwrap_or("cli".to_string()).to_lowercase(),
|
|
||||||
target_plan_types,
|
|
||||||
target_oses,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn version_matches(&self, version: &str) -> bool {
|
|
||||||
self.version_regex
|
|
||||||
.as_ref()
|
|
||||||
.is_none_or(|regex| regex.is_match(version))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn date_matches(&self, today: NaiveDate) -> bool {
|
|
||||||
if let Some(from) = self.from_date
|
|
||||||
&& today < from
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if let Some(to) = self.to_date
|
|
||||||
&& today >= to
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::tooltips::announcement::AnnouncementTips;
|
|
||||||
use pretty_assertions::assert_eq;
|
use pretty_assertions::assert_eq;
|
||||||
use rand::SeedableRng;
|
use rand::SeedableRng;
|
||||||
use rand::rngs::StdRng;
|
use rand::rngs::StdRng;
|
||||||
@@ -379,292 +114,4 @@ mod tests {
|
|||||||
let mut rng = StdRng::seed_from_u64(7);
|
let mut rng = StdRng::seed_from_u64(7);
|
||||||
assert_eq!(expected, pick_tooltip(&mut rng, &TuiKeymap::default()));
|
assert_eq!(expected, pick_tooltip(&mut rng, &TuiKeymap::default()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn desktop_app_tips_render_at_narrow_width() {
|
|
||||||
let cwd = std::env::current_dir().unwrap();
|
|
||||||
for (platform, tip) in [
|
|
||||||
("macos", MACOS_APP_TOOLTIP),
|
|
||||||
("windows", WINDOWS_APP_TOOLTIP),
|
|
||||||
("linux", LINUX_APP_TOOLTIP),
|
|
||||||
] {
|
|
||||||
let rendered = render_tooltip_lines(tip, /*width*/ 40, &cwd)
|
|
||||||
.iter()
|
|
||||||
.map(|line| format!("{:?} {:?}", line.line, line.hyperlinks))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n");
|
|
||||||
insta::assert_snapshot!(format!("desktop_app_tip_{platform}"), rendered);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn desktop_app_tooltip_uses_supported_platform_launcher() {
|
|
||||||
let tooltip = TOOLTIPS
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.find(|tip| tip.contains("desktop app"));
|
|
||||||
|
|
||||||
if linux_app_tooltip(LinuxDesktopSession::current()).is_some() {
|
|
||||||
let tooltip = tooltip.expect("Linux should advertise the desktop app");
|
|
||||||
assert_eq!(app_tooltip(), Some(tooltip));
|
|
||||||
} else if IS_MACOS {
|
|
||||||
let tooltip = tooltip.expect("macOS should advertise the desktop app");
|
|
||||||
assert_eq!(app_tooltip(), Some(tooltip));
|
|
||||||
} else if IS_WINDOWS {
|
|
||||||
let tooltip = tooltip.expect("Windows should advertise the desktop app");
|
|
||||||
assert_eq!(app_tooltip(), Some(tooltip));
|
|
||||||
} else {
|
|
||||||
assert_eq!(tooltip, None);
|
|
||||||
assert_eq!(app_tooltip(), None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn linux_desktop_app_tooltip_requires_graphical_native_session() {
|
|
||||||
assert_eq!(
|
|
||||||
linux_app_tooltip(LinuxDesktopSession {
|
|
||||||
has_display: true,
|
|
||||||
is_wsl: false,
|
|
||||||
}),
|
|
||||||
Some(LINUX_APP_TOOLTIP)
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
linux_app_tooltip(LinuxDesktopSession {
|
|
||||||
has_display: false,
|
|
||||||
is_wsl: false,
|
|
||||||
}),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
linux_app_tooltip(LinuxDesktopSession {
|
|
||||||
has_display: true,
|
|
||||||
is_wsl: true,
|
|
||||||
}),
|
|
||||||
None
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn plans_use_platform_app_tip() {
|
|
||||||
for plan in [
|
|
||||||
Some(PlanType::Free),
|
|
||||||
Some(PlanType::Go),
|
|
||||||
Some(PlanType::Plus),
|
|
||||||
Some(PlanType::Pro),
|
|
||||||
None,
|
|
||||||
] {
|
|
||||||
let mut seen = std::collections::BTreeSet::new();
|
|
||||||
for seed in 0..32 {
|
|
||||||
let mut rng = StdRng::seed_from_u64(seed);
|
|
||||||
seen.insert(preferred_tooltip(&mut rng, plan));
|
|
||||||
}
|
|
||||||
assert_eq!(
|
|
||||||
seen,
|
|
||||||
std::collections::BTreeSet::from([None, app_tooltip().map(str::to_string)])
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn announcement_tip_toml_picks_last_matching() {
|
|
||||||
let toml = r#"
|
|
||||||
[[announcements]]
|
|
||||||
content = "first"
|
|
||||||
from_date = "2000-01-01"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "latest match"
|
|
||||||
version_regex = ".*"
|
|
||||||
target_app = "cli"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "should not match"
|
|
||||||
to_date = "2000-01-01"
|
|
||||||
"#;
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
Some("latest match".to_string()),
|
|
||||||
AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None))
|
|
||||||
);
|
|
||||||
|
|
||||||
let toml = r#"
|
|
||||||
[[announcements]]
|
|
||||||
content = "first"
|
|
||||||
from_date = "2000-01-01"
|
|
||||||
target_app = "cli"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "latest match"
|
|
||||||
version_regex = ".*"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "should not match"
|
|
||||||
to_date = "2000-01-01"
|
|
||||||
"#;
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
Some("latest match".to_string()),
|
|
||||||
AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn announcement_tip_toml_picks_no_match() {
|
|
||||||
let toml = r#"
|
|
||||||
[[announcements]]
|
|
||||||
content = "first"
|
|
||||||
from_date = "2000-01-01"
|
|
||||||
to_date = "2000-01-05"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "latest match"
|
|
||||||
version_regex = "invalid_version_name"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "should not match either "
|
|
||||||
target_app = "vsce"
|
|
||||||
"#;
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
None,
|
|
||||||
AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn announcement_tip_toml_bad_deserialization() {
|
|
||||||
let toml = r#"
|
|
||||||
[[announcements]]
|
|
||||||
content = 123
|
|
||||||
from_date = "2000-01-01"
|
|
||||||
"#;
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
None,
|
|
||||||
AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn announcement_tip_toml_parse_comments() {
|
|
||||||
let toml = r#"
|
|
||||||
# Example announcement tips for Codex TUI.
|
|
||||||
# Each [[announcements]] entry is evaluated in order; the last matching one is shown.
|
|
||||||
# Dates are UTC, formatted as YYYY-MM-DD. The from_date is inclusive and the to_date is exclusive.
|
|
||||||
# version_regex matches against the CLI version (env!("CARGO_PKG_VERSION")); omit to apply to all versions.
|
|
||||||
# target_app specify which app should display the announcement (cli, vsce, ...).
|
|
||||||
# target_plan_types optionally restricts the announcement to plan types like ["plus", "pro"].
|
|
||||||
# target_oses optionally restricts the announcement to operating systems like ["macos", "windows"].
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "Welcome to Codex! Check out the new onboarding flow."
|
|
||||||
from_date = "2024-10-01"
|
|
||||||
to_date = "2024-10-15"
|
|
||||||
target_app = "cli"
|
|
||||||
version_regex = "^0\\.0\\.0$"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "This is a test announcement"
|
|
||||||
"#;
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
Some("This is a test announcement".to_string()),
|
|
||||||
AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn announcement_tip_toml_matches_target_plan_type() {
|
|
||||||
let toml = r#"
|
|
||||||
[[announcements]]
|
|
||||||
content = "all plans"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "pro announcement"
|
|
||||||
target_plan_types = ["pro", "enterprise"]
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "free announcement"
|
|
||||||
target_plan_types = ["free"]
|
|
||||||
"#;
|
|
||||||
|
|
||||||
let tips = AnnouncementTips::parse(toml).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
Some("pro announcement".to_string()),
|
|
||||||
tips.select(Some(PlanType::Pro))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
Some("free announcement".to_string()),
|
|
||||||
tips.select(Some(PlanType::Free))
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
Some("all plans".to_string()),
|
|
||||||
tips.select(Some(PlanType::Plus))
|
|
||||||
);
|
|
||||||
assert_eq!(Some("all plans".to_string()), tips.select(/*plan*/ None));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn announcement_tip_toml_rejects_unknown_target_plan_type() {
|
|
||||||
let toml = r#"
|
|
||||||
[[announcements]]
|
|
||||||
content = "all plans"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "typo announcement"
|
|
||||||
target_plan_types = ["prp"]
|
|
||||||
"#;
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
Some("all plans".to_string()),
|
|
||||||
AnnouncementTips::parse(toml).and_then(|tips| tips.select(Some(PlanType::Unknown)))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn announcement_tip_toml_matches_target_os() {
|
|
||||||
let toml = r#"
|
|
||||||
[[announcements]]
|
|
||||||
content = "linux announcement"
|
|
||||||
target_oses = ["linux"]
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "macos announcement"
|
|
||||||
target_oses = ["macos"]
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "windows announcement"
|
|
||||||
target_oses = ["windows"]
|
|
||||||
"#;
|
|
||||||
|
|
||||||
let expected = if cfg!(target_os = "macos") {
|
|
||||||
"macos announcement"
|
|
||||||
} else if cfg!(target_os = "windows") {
|
|
||||||
"windows announcement"
|
|
||||||
} else {
|
|
||||||
"linux announcement"
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
Some(expected.to_string()),
|
|
||||||
AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn announcement_tip_toml_rejects_unknown_target_os() {
|
|
||||||
let toml = r#"
|
|
||||||
[[announcements]]
|
|
||||||
content = "all operating systems"
|
|
||||||
|
|
||||||
[[announcements]]
|
|
||||||
content = "typo announcement"
|
|
||||||
target_oses = ["amiga"]
|
|
||||||
"#;
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
Some("all operating systems".to_string()),
|
|
||||||
AnnouncementTips::parse(toml).and_then(|tips| tips.select(/*plan*/ None))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,4 @@
|
|||||||
#[cfg(any(not(debug_assertions), test))]
|
// aKode: release-tag and npm version helpers were removed with the remote update checks.
|
||||||
pub(crate) fn is_newer(latest: &str, current: &str) -> Option<bool> {
|
|
||||||
match (parse_version(latest), parse_version(current)) {
|
|
||||||
(Some(l), Some(c)) => Some(l > c),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(not(debug_assertions), test))]
|
|
||||||
pub(crate) fn extract_version_from_latest_tag(latest_tag_name: &str) -> anyhow::Result<String> {
|
|
||||||
latest_tag_name
|
|
||||||
.strip_prefix("rust-v")
|
|
||||||
.map(str::to_owned)
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("Failed to parse latest tag name '{latest_tag_name}'"))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(not(debug_assertions), test))]
|
|
||||||
pub(crate) fn is_source_build_version(version: &str) -> bool {
|
|
||||||
parse_version(version) == Some((0, 0, 0))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub(crate) enum ServerVersionNoticeKind {
|
pub(crate) enum ServerVersionNoticeKind {
|
||||||
Older,
|
Older,
|
||||||
@@ -43,59 +23,11 @@ pub(crate) fn server_version_notice_kind(
|
|||||||
.then_some(ServerVersionNoticeKind::Older)
|
.then_some(ServerVersionNoticeKind::Older)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(not(debug_assertions), test))]
|
|
||||||
fn parse_version(v: &str) -> Option<(u64, u64, u64)> {
|
|
||||||
let mut iter = v.trim().split('.');
|
|
||||||
let maj = iter.next()?.parse::<u64>().ok()?;
|
|
||||||
let min = iter.next()?.parse::<u64>().ok()?;
|
|
||||||
let pat = iter.next()?.parse::<u64>().ok()?;
|
|
||||||
Some((maj, min, pat))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use pretty_assertions::assert_eq;
|
use pretty_assertions::assert_eq;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extracts_version_from_latest_tag() {
|
|
||||||
assert_eq!(
|
|
||||||
extract_version_from_latest_tag("rust-v1.5.0").expect("failed to parse version"),
|
|
||||||
"1.5.0"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn latest_tag_without_prefix_is_invalid() {
|
|
||||||
assert!(extract_version_from_latest_tag("v1.5.0").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn prerelease_version_is_not_considered_newer() {
|
|
||||||
assert_eq!(is_newer("0.11.0-beta.1", "0.11.0"), None);
|
|
||||||
assert_eq!(is_newer("1.0.0-rc.1", "1.0.0"), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn plain_semver_comparisons_work() {
|
|
||||||
assert_eq!(is_newer("0.11.1", "0.11.0"), Some(true));
|
|
||||||
assert_eq!(is_newer("0.11.0", "0.11.1"), Some(false));
|
|
||||||
assert_eq!(is_newer("1.0.0", "0.9.9"), Some(true));
|
|
||||||
assert_eq!(is_newer("0.9.9", "1.0.0"), Some(false));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn source_build_version_is_not_checked() {
|
|
||||||
assert!(is_source_build_version("0.0.0"));
|
|
||||||
assert!(!is_source_build_version("0.1.0"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn whitespace_is_ignored() {
|
|
||||||
assert_eq!(parse_version(" 1.2.3 \n"), Some((1, 2, 3)));
|
|
||||||
assert_eq!(is_newer(" 1.2.3 ", "1.2.2"), Some(true));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn stable_clients_only_warn_for_older_releases() {
|
fn stable_clients_only_warn_for_older_releases() {
|
||||||
for (client, server, expected) in [
|
for (client, server, expected) in [
|
||||||
|
|||||||
@@ -1,26 +1,6 @@
|
|||||||
#![cfg(not(debug_assertions))]
|
#![cfg(not(debug_assertions))]
|
||||||
|
|
||||||
use crate::legacy_core::config::Config;
|
use crate::legacy_core::config::Config;
|
||||||
use crate::npm_registry;
|
|
||||||
use crate::npm_registry::NpmPackageInfo;
|
|
||||||
use crate::update_action;
|
|
||||||
use crate::update_action::UpdateAction;
|
|
||||||
use crate::update_versions::extract_version_from_latest_tag;
|
|
||||||
use crate::update_versions::is_newer;
|
|
||||||
use crate::update_versions::is_source_build_version;
|
|
||||||
use crate::updates_cache::VersionInfo;
|
|
||||||
use crate::updates_cache::read_version_info;
|
|
||||||
use crate::updates_cache::version_filepath;
|
|
||||||
use chrono::Duration;
|
|
||||||
use chrono::Utc;
|
|
||||||
use codex_http_client::ClientRouteClass;
|
|
||||||
use codex_http_client::HttpClientFactory;
|
|
||||||
use codex_http_client::RouteAwareClientPool;
|
|
||||||
use codex_login::default_client::default_headers;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use crate::version::CODEX_CLI_VERSION;
|
|
||||||
|
|
||||||
pub(crate) use crate::updates_cache::dismiss_version;
|
pub(crate) use crate::updates_cache::dismiss_version;
|
||||||
|
|
||||||
@@ -30,96 +10,6 @@ pub fn get_upgrade_version(config: &Config) -> Option<String> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
// We use the latest version from the cask if installation is via homebrew - homebrew does not immediately pick up the latest release and can lag behind.
|
|
||||||
const HOMEBREW_CASK_API_URL: &str = "https://formulae.brew.sh/api/cask/codex.json";
|
|
||||||
const LATEST_RELEASE_URL: &str = "https://api.github.com/repos/openai/codex/releases/latest";
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
|
||||||
struct ReleaseInfo {
|
|
||||||
tag_name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
|
||||||
struct HomebrewCaskInfo {
|
|
||||||
version: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn check_for_update(
|
|
||||||
version_file: &Path,
|
|
||||||
action: Option<UpdateAction>,
|
|
||||||
http_client_factory: HttpClientFactory,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let client_pool = RouteAwareClientPool::with_chatgpt_cloudflare_cookies(
|
|
||||||
http_client_factory,
|
|
||||||
ClientRouteClass::Other,
|
|
||||||
)
|
|
||||||
.with_legacy_custom_ca_fallback();
|
|
||||||
let latest_version = match action {
|
|
||||||
Some(UpdateAction::Daemon(_)) => return Ok(()),
|
|
||||||
Some(UpdateAction::BrewUpgrade) => {
|
|
||||||
let HomebrewCaskInfo { version } = client_pool
|
|
||||||
.get(HOMEBREW_CASK_API_URL)
|
|
||||||
.headers(default_headers())
|
|
||||||
.send()
|
|
||||||
.await?
|
|
||||||
.error_for_status()?
|
|
||||||
.json::<HomebrewCaskInfo>()
|
|
||||||
.await?;
|
|
||||||
version
|
|
||||||
}
|
|
||||||
Some(UpdateAction::NpmGlobalLatest)
|
|
||||||
| Some(UpdateAction::BunGlobalLatest)
|
|
||||||
| Some(UpdateAction::VitePlusGlobalLatest)
|
|
||||||
| Some(UpdateAction::PnpmGlobalLatest) => {
|
|
||||||
let latest_version = fetch_latest_github_release_version(&client_pool).await?;
|
|
||||||
let package_info = client_pool
|
|
||||||
.get(npm_registry::PACKAGE_URL)
|
|
||||||
.headers(default_headers())
|
|
||||||
.send()
|
|
||||||
.await?
|
|
||||||
.error_for_status()?
|
|
||||||
.json::<NpmPackageInfo>()
|
|
||||||
.await?;
|
|
||||||
npm_registry::ensure_version_ready(&package_info, &latest_version)?;
|
|
||||||
latest_version
|
|
||||||
}
|
|
||||||
Some(UpdateAction::StandaloneUnix) | Some(UpdateAction::StandaloneWindows) | None => {
|
|
||||||
fetch_latest_github_release_version(&client_pool).await?
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Preserve any previously dismissed version if present.
|
|
||||||
let prev_info = read_version_info(version_file).ok();
|
|
||||||
let info = VersionInfo {
|
|
||||||
latest_version,
|
|
||||||
last_checked_at: Utc::now(),
|
|
||||||
dismissed_version: prev_info.and_then(|p| p.dismissed_version),
|
|
||||||
};
|
|
||||||
|
|
||||||
let json_line = format!("{}\n", serde_json::to_string(&info)?);
|
|
||||||
if let Some(parent) = version_file.parent() {
|
|
||||||
tokio::fs::create_dir_all(parent).await?;
|
|
||||||
}
|
|
||||||
tokio::fs::write(version_file, json_line).await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn fetch_latest_github_release_version(
|
|
||||||
client_pool: &RouteAwareClientPool,
|
|
||||||
) -> anyhow::Result<String> {
|
|
||||||
let ReleaseInfo {
|
|
||||||
tag_name: latest_tag_name,
|
|
||||||
} = client_pool
|
|
||||||
.get(LATEST_RELEASE_URL)
|
|
||||||
.headers(default_headers())
|
|
||||||
.send()
|
|
||||||
.await?
|
|
||||||
.error_for_status()?
|
|
||||||
.json::<ReleaseInfo>()
|
|
||||||
.await?;
|
|
||||||
extract_version_from_latest_tag(&latest_tag_name)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the latest version to show in a popup, if it should be shown.
|
/// Returns the latest version to show in a popup, if it should be shown.
|
||||||
/// This respects the user's dismissal choice for the current latest version.
|
/// This respects the user's dismissal choice for the current latest version.
|
||||||
pub fn get_upgrade_version_for_popup(config: &Config) -> Option<String> {
|
pub fn get_upgrade_version_for_popup(config: &Config) -> Option<String> {
|
||||||
|
|||||||
Reference in New Issue
Block a user