aKode fase 1: niente sync plugin OpenAI, CDN pets, CIMD chatgpt.com, npm registry; pulizia codice morto

This commit is contained in:
Andrea
2026-11-09 12:06:16 +01:00
parent 5b5b83964d
commit 39a103d16f
34 changed files with 136 additions and 4668 deletions

View File

@@ -1864,7 +1864,7 @@ enabled = false
.rebuild_config_for_permission_profile(":workspace")
.await?;
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] {
assert_eq!(config.application_network_policy, controller.policy());
assert_eq!(

View File

@@ -114,14 +114,12 @@ impl App {
let frame_requester = tui.frame_requester();
let animations_enabled = self.local_settings.tui.animations;
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 {
let result = crate::pets::load_pet_with_assets(
pet_id.clone(),
codex_home,
frame_requester,
animations_enabled,
&pet_http_client,
)
.await
.map(Some)

View File

@@ -25,6 +25,7 @@ async fn terminal_size_telemetry_respects_reloaded_exporter_and_consent() -> Res
app.local_settings = local_settings;
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(())
}

View File

@@ -671,8 +671,6 @@ pub(crate) struct ChatWidget {
review: ReviewState,
// Active hook runs render in a dedicated live cell so they can run alongside tools.
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_pet: Option<crate::pets::AmbientPet>,
configured_pet_load_generation: ConfiguredPetLoadGeneration,

View File

@@ -90,16 +90,11 @@ impl ChatWidget {
.as_ref()
.map(|keymap| 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(
&local_settings,
/*ambient_pet_missing*/ true,
frame_requester.clone(),
app_event_tx.clone(),
pet_http_client.clone(),
);
let config_panel_tui = local_settings.tui.clone();
let mut widget = Self {
@@ -231,7 +226,6 @@ impl ChatWidget {
status_state: StatusState::default(),
review: ReviewState::default(),
active_hook_cell: None,
pet_http_client,
ambient_pet: None,
configured_pet_load_generation,
pet_picker_preview_state: crate::pets::PetPickerPreviewState::default(),

View File

@@ -42,7 +42,6 @@ pub(super) fn start_configured_pet_load_if_needed(
ambient_pet_missing: bool,
frame_requester: FrameRequester,
app_event_tx: AppEventSender,
pet_http_client: codex_http_client::RouteAwareClientPool,
) -> ConfiguredPetLoadGeneration {
let generation = next_configured_pet_load_generation();
let Some(pet_id) = config.tui.pet.clone() else {
@@ -62,7 +61,6 @@ pub(super) fn start_configured_pet_load_if_needed(
codex_home,
frame_requester,
animations_enabled,
&pet_http_client,
)
.await
.map(Some)
@@ -234,7 +232,6 @@ impl ChatWidget {
/*ambient_pet_missing*/ self.ambient_pet.is_none(),
self.frame_requester.clone(),
self.app_event_tx.clone(),
self.pet_http_client.clone(),
);
self.apply_ambient_pet_image_support_override_for_tests();
self.request_redraw();
@@ -306,7 +303,6 @@ impl ChatWidget {
let codex_home = self.local_settings.codex_home.clone();
let frame_requester = self.frame_requester.clone();
let tx = self.app_event_tx.clone();
let pet_http_client = self.pet_http_client.clone();
spawn_pet_load(
async move {
crate::pets::load_pet_with_assets(
@@ -314,7 +310,6 @@ impl ChatWidget {
codex_home,
frame_requester,
/*animations_enabled*/ false,
&pet_http_client,
)
.await
.map_err(|err| err.to_string())

View File

@@ -102,7 +102,6 @@ async fn shared_pet_load_uses_cached_builtin_assets() {
AbsolutePathBuf::from_absolute_path(codex_home.path()).expect("absolute temporary path"),
chat.frame_requester.clone(),
/*animations_enabled*/ false,
&chat.pet_http_client,
)
.await
.expect("load cached built-in pet");

View File

@@ -191,8 +191,6 @@ mod motion;
mod multi_agents;
mod named_session_lookup;
mod notifications;
#[cfg(any(not(debug_assertions), test))]
mod npm_registry;
pub(crate) mod onboarding;
mod oss_selection;
mod pager_overlay;
@@ -1267,8 +1265,7 @@ async fn run_ratatui_app(
let uses_remote_workspace = app_server_target.uses_remote_workspace();
let workload_identity_selected = is_workload_identity_selected();
color_eyre::install()?;
tooltips::announcement::prewarm(initial_config.http_client_factory());
// aKode: no remote announcement-tip prewarm.
// Forward panic reports through tracing so they appear in the UI status
// line, but do not swallow the default/color-eyre panic handler.

View File

@@ -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}"
);
}
}

View File

@@ -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
//! local spritesheets. The TUI resolves them from the public Codex pets CDN on
//! first use, verifies that the downloaded file has the expected spritesheet
//! geometry, and installs it into a versioned cache under CODEX_HOME.
//! local spritesheets. They are looked up in a versioned cache under
//! CODEX_HOME and validated for the expected spritesheet geometry.
//!
//! This module deliberately stops at "a validated spritesheet exists at this
//! path". Higher layers remain responsible for deciding when downloads are
//! allowed, when previews should block on them, and when a successfully loaded
//! built-in pet is safe to persist to config.
//! aKode: upstream downloaded missing spritesheets from an OpenAI CDN. That
//! download was removed; a built-in pet whose spritesheet is not already in the
//! local cache is simply reported as unavailable and is never fetched.
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use codex_http_client::RouteAwareClientPool;
use url::Url;
use uuid::Uuid;
use super::catalog;
const PET_PACK_VERSION: &str = "v1";
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 {
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
/// publishing a new versioned filename rather than mutating an existing one in
/// 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<()> {
/// Callers should treat any error here as "the asset is unavailable".
pub(crate) async fn ensure_builtin_pet(codex_home: &Path, pet: catalog::BuiltinPet) -> Result<()> {
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 || {
let parent = destination
.parent()
.context("pet spritesheet path should include an assets directory")?;
fs::create_dir_all(parent).with_context(|| format!("create {}", parent.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)
validate_cached_spritesheet(&destination).with_context(|| {
format!(
"built-in pet spritesheet {} is not available locally",
destination.display()
)
})
})
.await
.context("join pet spritesheet install 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)
.context("join pet spritesheet cache validation task")?
}
fn pack_dir(codex_home: &Path) -> PathBuf {
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<()> {
let (width, height) =
image::image_dimensions(path).with_context(|| format!("read {}", path.display()))?;
@@ -181,7 +64,7 @@ fn validate_cached_spritesheet(path: &Path) -> Result<()> {
#[cfg(test)]
pub(crate) fn write_test_pack(codex_home: &Path) {
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 {
let path = assets_dir.join(pet.spritesheet_file);
catalog::write_test_spritesheet(&path);
@@ -191,35 +74,6 @@ pub(crate) fn write_test_pack(codex_home: &Path) {
#[cfg(test)]
mod tests {
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]
fn write_test_pack_installs_all_builtins() {
@@ -233,4 +87,12 @@ mod tests {
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());
}
}

View File

@@ -27,7 +27,6 @@ mod sixel;
use anyhow::Context;
use anyhow::Result;
use codex_http_client::RouteAwareClientPool;
use codex_utils_absolute_path::AbsolutePathBuf;
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.
///
/// 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
/// persistence failures at the asset-fetch boundary rather than surfacing as
/// deeper image-loading errors.
async fn ensure_builtin_pack_for_pet(
pet_id: &str,
codex_home: &std::path::Path,
http_client: &RouteAwareClientPool,
) -> Result<()> {
/// already local. Checking this before loading keeps first-use preview and
/// persistence failures at the asset boundary rather than surfacing as deeper
/// image-loading errors.
async fn ensure_builtin_pack_for_pet(pet_id: &str, codex_home: &std::path::Path) -> Result<()> {
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(())
}
@@ -81,9 +76,8 @@ pub(crate) async fn load_pet_with_assets(
codex_home: AbsolutePathBuf,
frame_requester: FrameRequester,
animations_enabled: bool,
http_client: &RouteAwareClientPool,
) -> 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 || {
AmbientPet::load(
Some(&pet_id),

View File

@@ -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(".")]) []

View File

@@ -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.") []

View File

@@ -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(".")]) []

View File

@@ -8,8 +8,8 @@ pub(crate) type LaunchTags = Vec<(&'static str, &'static str)>;
pub(crate) fn enabled(config: &Config) -> bool {
match config.otel.metrics_exporter {
OtelExporterKind::None => false,
OtelExporterKind::Statsig => config.analytics_enabled != Some(false),
// aKode: Statsig export is disabled; only user-configured OTLP exporters observe sizes.
OtelExporterKind::None | OtelExporterKind::Statsig => false,
OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. } => true,
}
}

View File

@@ -13,17 +13,6 @@ use std::path::Path;
#[path = "tooltips/keybinding_tests.rs"]
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");
lazy_static! {
@@ -31,7 +20,6 @@ lazy_static! {
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.chain(app_tooltip())
.collect();
static ref ALL_TOOLTIPS: Vec<&'static str> = {
let mut tips = Vec::new();
@@ -46,62 +34,10 @@ lazy_static! {
}
/// 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();
preferred_tooltip(&mut rng, plan).or_else(|| 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
pick_tooltip(&mut rng, keymap)
}
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)
}
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)]
mod tests {
use super::*;
use crate::tooltips::announcement::AnnouncementTips;
use pretty_assertions::assert_eq;
use rand::SeedableRng;
use rand::rngs::StdRng;
@@ -379,292 +114,4 @@ mod tests {
let mut rng = StdRng::seed_from_u64(7);
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))
);
}
}

View File

@@ -1,24 +1,4 @@
#[cfg(any(not(debug_assertions), test))]
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))
}
// aKode: release-tag and npm version helpers were removed with the remote update checks.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ServerVersionNoticeKind {
Older,
@@ -43,59 +23,11 @@ pub(crate) fn server_version_notice_kind(
.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)]
mod tests {
use super::*;
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]
fn stable_clients_only_warn_for_older_releases() {
for (client, server, expected) in [

View File

@@ -1,26 +1,6 @@
#![cfg(not(debug_assertions))]
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;
@@ -30,96 +10,6 @@ pub fn get_upgrade_version(config: &Config) -> Option<String> {
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.
/// This respects the user's dismissal choice for the current latest version.
pub fn get_upgrade_version_for_popup(config: &Config) -> Option<String> {