From 07ba31d492ae050b2678550e37b08a6f4c844348 Mon Sep 17 00:00:00 2001 From: "andrea.difonzo" Date: Tue, 17 Nov 2026 14:35:07 +0100 Subject: [PATCH] Ripristinato `akode update` verso il Gitea dell'utente (come in 0.9.2, senza il sync del daemon) Da 9494b768, e1ce139a e 1c278642: crate akode-update (ultima release da git.difonzo.net/andrea/imeai-aKode, confronto semver, download solo dallo stesso host, verifica SHA-256, sostituzione atomica), `akode update [--check]`, riga di avviso nella TUI, controllo in background all'avvio al massimo ogni 24 h (disattivabile con [update] check_on_startup = false; non installa mai nulla da solo). Nessun contatto con OpenAI o altri domini; il sistema upstream (curl chatgpt.com/codex/install.sh, npm, brew) resta rimosso. Lasciato fuori l'allineamento del daemon (95f4ddcd). Co-Authored-By: Claude Sonnet 5.5 --- akode-rs/Cargo.lock | 22 + akode-rs/Cargo.toml | 2 + akode-rs/cli/Cargo.toml | 1 + akode-rs/cli/src/doctor/updates.rs | 123 ++-- akode-rs/cli/src/main.rs | 36 +- akode-rs/cli/src/update_cmd.rs | 90 +++ akode-rs/cli/tests/update.rs | 63 ++ akode-rs/config/src/config_toml.rs | 4 + akode-rs/config/src/types.rs | 14 + akode-rs/core/config.schema.json | 23 + akode-rs/core/src/config/mod.rs | 18 + akode-rs/thread-manager-sample/src/main.rs | 2 + akode-rs/tui/Cargo.toml | 1 + akode-rs/tui/src/app.rs | 1 + .../src/app/empty_state_animation_tests.rs | 6 + akode-rs/tui/src/app/startup.rs | 35 + akode-rs/tui/src/history_cell/notices.rs | 43 ++ akode-rs/tui/src/history_cell/tests.rs | 14 + akode-rs/update/BUILD.bazel | 6 + akode-rs/update/Cargo.toml | 31 + akode-rs/update/src/lib.rs | 606 ++++++++++++++++++ akode-rs/update/src/lib_tests.rs | 472 ++++++++++++++ 22 files changed, 1538 insertions(+), 75 deletions(-) create mode 100644 akode-rs/cli/src/update_cmd.rs create mode 100644 akode-rs/cli/tests/update.rs create mode 100644 akode-rs/update/BUILD.bazel create mode 100644 akode-rs/update/Cargo.toml create mode 100644 akode-rs/update/src/lib.rs create mode 100644 akode-rs/update/src/lib_tests.rs diff --git a/akode-rs/Cargo.lock b/akode-rs/Cargo.lock index 9ecaf047..a0da719d 100644 --- a/akode-rs/Cargo.lock +++ b/akode-rs/Cargo.lock @@ -733,6 +733,7 @@ dependencies = [ "akode-terminal-detection", "akode-thread-store", "akode-tui", + "akode-update", "akode-utils-absolute-path", "akode-utils-cargo-bin", "akode-utils-cli", @@ -2992,6 +2993,7 @@ dependencies = [ "akode-state", "akode-terminal-detection", "akode-uds", + "akode-update", "akode-utils-absolute-path", "akode-utils-approval-presets", "akode-utils-cargo-bin", @@ -3095,6 +3097,26 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "akode-update" +version = "0.10.0-pulito" +dependencies = [ + "akode-utils-rustls-provider", + "anyhow", + "chrono", + "flate2", + "pretty_assertions", + "reqwest 0.12.28", + "semver", + "serde", + "serde_json", + "sha2 0.10.9", + "tar", + "tempfile", + "tokio", + "wiremock", +] + [[package]] name = "akode-user-verification" version = "0.10.0-pulito" diff --git a/akode-rs/Cargo.toml b/akode-rs/Cargo.toml index 7ee4afac..fd7d6368 100644 --- a/akode-rs/Cargo.toml +++ b/akode-rs/Cargo.toml @@ -22,6 +22,7 @@ members = [ "feedback", "features", "install-context", + "update", "code-mode", "code-mode-host", "code-mode-protocol", @@ -227,6 +228,7 @@ akode-experimental-api-macros = { path = "akode-experimental-api-macros" } akode-features = { path = "features" } akode-feedback = { path = "feedback" } akode-install-context = { path = "install-context" } +akode-update = { path = "update" } akode-file-search = { path = "file-search" } akode-file-watcher = { path = "file-watcher" } akode-git-utils = { path = "git-utils" } diff --git a/akode-rs/cli/Cargo.toml b/akode-rs/cli/Cargo.toml index c52d7c32..7d259a7f 100644 --- a/akode-rs/cli/Cargo.toml +++ b/akode-rs/cli/Cargo.toml @@ -56,6 +56,7 @@ akode-multi-env-copy-file = { workspace = true } akode-git-attribution = { workspace = true } akode-git-utils = { workspace = true } akode-install-context = { workspace = true } +akode-update = { workspace = true } akode-login = { workspace = true } akode-memories-write = { workspace = true } akode-mcp = { workspace = true } diff --git a/akode-rs/cli/src/doctor/updates.rs b/akode-rs/cli/src/doctor/updates.rs index 528082e6..5b30f613 100644 --- a/akode-rs/cli/src/doctor/updates.rs +++ b/akode-rs/cli/src/doctor/updates.rs @@ -1,41 +1,26 @@ -//! Diagnoses whether Codex update paths target the running installation. +//! Reports how `akode update` is configured, from local state only. //! -//! aKode: diagnostics are local only (cached version metadata and install-channel hints). -//! There are no latest-version probes (GitHub, Homebrew) and no desktop appcast probes. +//! The doctor never contacts the release repository; it shows the configured source and the +//! result of the last startup check recorded in `update-check.json`. use std::path::Path; use akode_core::config::Config; -use akode_install_context::InstallContext; -use akode_install_context::InstallMethod; use serde::Deserialize; use super::CheckStatus; use super::DoctorCheck; -use super::doctor_install_context; -use super::doctor_managed_by_npm; -const VERSION_FILE_NAME: &str = "version.json"; +const CHECK_STATE_FILE_NAME: &str = "update-check.json"; /// Builds the update-health row for the current installation from local state only. pub(super) async fn updates_check(config: &Config) -> DoctorCheck { - let current_exe = std::env::current_exe().ok(); - let install_context = doctor_install_context(current_exe.as_deref()); let mut details = vec![ - format!( - "check for update on startup: {}", - config.check_for_update_on_startup - ), - format!("update action: {}", update_action_label(&install_context)), + format!("release repository: {}", config.update_repo_url), + format!("check on startup: {}", config.update_check_on_startup), + "update command: akode update".to_string(), ]; - let version_file = config.codex_home.join(VERSION_FILE_NAME); - push_cached_version_details(&mut details, &version_file); - - if doctor_managed_by_npm(current_exe.as_deref()) { - details - .push("npm update target: not inspected (PATH helpers are not executed)".to_string()); - } - details.push("latest version probe: disabled (no network update checks)".to_string()); + push_last_check_details(&mut details, &config.codex_home.join(CHECK_STATE_FILE_NAME)); DoctorCheck::new( "updates.status", @@ -46,47 +31,38 @@ pub(super) async fn updates_check(config: &Config) -> DoctorCheck { .details(details) } -fn push_cached_version_details(details: &mut Vec, version_file: &Path) { - details.push(format!("version cache: {}", version_file.display())); - match std::fs::read_to_string(version_file) { - Ok(contents) => match serde_json::from_str::(&contents) { - Ok(info) => { - details.push(format!("cached latest version: {}", info.latest_version)); - if let Some(last_checked_at) = info.last_checked_at { - details.push(format!("last checked at: {last_checked_at}")); - } - if let Some(dismissed_version) = info.dismissed_version { - details.push(format!("dismissed version: {dismissed_version}")); +fn push_last_check_details(details: &mut Vec, state_file: &Path) { + match std::fs::read_to_string(state_file) { + Ok(contents) => match serde_json::from_str::(&contents) { + Ok(state) => { + details.push(format!("last checked at: {}", state.last_checked_at)); + details.push(format!( + "latest version: {}", + state + .latest_version + .as_deref() + .unwrap_or("no release published") + )); + if state.latest_version.as_deref().is_some_and(|latest| { + akode_update::is_newer_str(env!("CARGO_PKG_VERSION"), latest) + }) { + details.push("latest version status: newer version is available".to_string()); } } - Err(err) => details.push(format!("version cache parse: {err}")), + Err(err) => details.push(format!("update check state parse: {err}")), }, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - details.push("version cache: missing".to_string()); + details.push("last checked at: never".to_string()); } - Err(err) => details.push(format!("version cache read: {err}")), - } -} - -fn update_action_label(context: &InstallContext) -> &'static str { - match &context.method { - InstallMethod::Npm => "npm install -g @openai/codex", - InstallMethod::Bun => "bun install -g @openai/codex", - InstallMethod::VitePlus => "vp install -g @openai/codex", - InstallMethod::Pnpm => "pnpm add -g @openai/codex", - InstallMethod::Brew => "brew upgrade --cask codex", - InstallMethod::Standalone { .. } => "standalone installer", - InstallMethod::Other => "manual or unknown", + Err(err) => details.push(format!("update check state read: {err}")), } } #[derive(Deserialize)] -struct VersionInfo { - latest_version: String, +struct CheckState { + last_checked_at: String, #[serde(default)] - last_checked_at: Option, - #[serde(default)] - dismissed_version: Option, + latest_version: Option, } #[cfg(test)] @@ -95,27 +71,26 @@ mod tests { use pretty_assertions::assert_eq; #[test] - fn update_action_labels_install_contexts() { + fn last_check_details_read_the_startup_check_state() { + let dir = tempfile::tempdir().unwrap(); + let state_file = dir.path().join(CHECK_STATE_FILE_NAME); + let mut details = Vec::new(); + push_last_check_details(&mut details, &state_file); + assert_eq!(details, vec!["last checked at: never".to_string()]); + + std::fs::write( + &state_file, + r#"{"last_checked_at":"2026-11-11T10:00:00Z","latest_version":null}"#, + ) + .unwrap(); + let mut details = Vec::new(); + push_last_check_details(&mut details, &state_file); assert_eq!( - update_action_label(&InstallContext { - method: InstallMethod::Npm, - package_layout: None, - }), - "npm install -g @openai/codex" - ); - assert_eq!( - update_action_label(&InstallContext { - method: InstallMethod::Pnpm, - package_layout: None, - }), - "pnpm add -g @openai/codex" - ); - assert_eq!( - update_action_label(&InstallContext { - method: InstallMethod::Other, - package_layout: None, - }), - "manual or unknown" + details, + vec![ + "last checked at: 2026-11-11T10:00:00Z".to_string(), + "latest version: no release published".to_string(), + ] ); } } diff --git a/akode-rs/cli/src/main.rs b/akode-rs/cli/src/main.rs index 4a6b3e38..092eac18 100644 --- a/akode-rs/cli/src/main.rs +++ b/akode-rs/cli/src/main.rs @@ -60,6 +60,7 @@ mod sandbox_setup; mod sandbox_uninstall; mod state_db_recovery; #[cfg(not(windows))] +mod update_cmd; use crate::mcp_cmd::McpCli; use crate::plugin_cmd::PluginCli; @@ -154,6 +155,9 @@ enum Subcommand { /// Generate shell completion scripts. Completion(CompletionCommand), + /// Update aKode to the latest release published on the configured repository. + Update(update_cmd::UpdateCommand), + /// Diagnose local aKode installation, config, auth, and runtime health. Doctor(DoctorCommand), @@ -705,7 +709,7 @@ fn handle_app_exit( Ok(()) } -/// Run the update action and print the result. +/// Run the daemon update requested from the TUI and print the result. fn run_update_action( action: UpdateAction, cli_executable: Option<&std::path::Path>, @@ -1461,6 +1465,17 @@ async fn dispatch_cli( )?; print_completion(completion_cli); } + Some(Subcommand::Update(update_cli)) => { + reject_remote_mode_for_subcommand( + root_remote.as_deref(), + root_remote_auth_token_env.as_deref(), + "update", + )?; + let config = + local_config::load_config(&root_config_overrides, LoaderOverrides::default()) + .await?; + update_cmd::run(update_cli, &config).await?; + } Some(Subcommand::Doctor(doctor_cli)) => { reject_remote_mode_for_subcommand( root_remote.as_deref(), @@ -2069,6 +2084,7 @@ fn unsupported_subcommand_name_for_strict_config( Some(Subcommand::Login(_)) => Some("login"), Some(Subcommand::Logout(_)) => Some("logout"), Some(Subcommand::Completion(_)) => Some("completion"), + Some(Subcommand::Update(_)) => Some("update"), Some(Subcommand::Sandbox(_)) => Some("sandbox"), Some(Subcommand::Debug(_)) => Some("debug"), Some(Subcommand::Execpolicy(_)) => Some("execpolicy"), @@ -3229,6 +3245,24 @@ enabled = true assert!(matches!(cli.subcommand, Some(Subcommand::Plugin(_)))); } + #[test] + fn update_parses_as_update_subcommand() { + let cli = MultitoolCli::try_parse_from(["akode", "update"]).expect("parse"); + assert!(matches!( + cli.subcommand, + Some(Subcommand::Update(update_cmd::UpdateCommand { + check: false + })) + )); + let cli = MultitoolCli::try_parse_from(["akode", "update", "--check"]).expect("parse"); + assert!(matches!( + cli.subcommand, + Some(Subcommand::Update(update_cmd::UpdateCommand { + check: true + })) + )); + } + #[test] fn archive_merges_scoped_tui_flags() { let (target, interactive, remote) = finalize_archive_from_args( diff --git a/akode-rs/cli/src/update_cmd.rs b/akode-rs/cli/src/update_cmd.rs new file mode 100644 index 00000000..450bc5d0 --- /dev/null +++ b/akode-rs/cli/src/update_cmd.rs @@ -0,0 +1,90 @@ +//! `akode update`: installs the latest aKode release from the configured Gitea repository. +//! The release archive is verified against its published SHA-256 before anything changes. + +use std::path::PathBuf; + +use akode_core::config::Config; +use akode_install_context::InstallContext; +use akode_update::CheckResult; +use akode_update::InstallOutcome; +use akode_update::InstallTarget; +use anyhow::Context; + +#[derive(Debug, Default, clap::Parser)] +pub struct UpdateCommand { + /// Only report whether a newer release exists, without installing it. + #[arg(long)] + pub check: bool, +} + +pub async fn run(cmd: UpdateCommand, config: &Config) -> anyhow::Result<()> { + let current = env!("CARGO_PKG_VERSION"); + let repo_url = config.update_repo_url.as_str(); + let client = akode_update::http_client(akode_update::COMMAND_TIMEOUT)?; + println!("Controllo degli aggiornamenti su {repo_url}…"); + let release = match akode_update::check(&client, repo_url, current).await? { + CheckResult::UpToDate { latest: None } => { + println!("Nessuna release pubblicata: aKode {current} è la versione più recente."); + return Ok(()); + } + CheckResult::UpToDate { + latest: Some(latest), + } => { + println!("aKode {current} è aggiornato (ultima release: {latest})."); + return Ok(()); + } + CheckResult::Available(release) => release, + }; + if cmd.check { + println!( + "È disponibile aKode {} (installata: {current}). Esegui \"akode update\" per installarla.", + release.version + ); + return Ok(()); + } + + let target = akode_update::current_target() + .context("aKode non pubblica release per questa piattaforma")?; + let install = install_target()?; + println!("Download di aKode {} ({target})…", release.version); + let outcome = akode_update::install_release(&client, repo_url, &release, target, &install) + .await + .context("aggiornamento non riuscito; la versione installata non è stata modificata")?; + match outcome { + InstallOutcome::Binary { backup } => println!( + "aKode aggiornato da {current} a {}. Copia della versione precedente: {}", + release.version, + backup.display() + ), + InstallOutcome::Package { backup } => println!( + "Pacchetto aKode aggiornato da {current} a {}. Copia del pacchetto precedente: {}", + release.version, + backup.display() + ), + } + if config + .codex_home + .join("packages/app-server-daemon/current") + .symlink_metadata() + .is_ok() + { + println!( + "Il server in background usa ancora il pacchetto precedente: esegui \"akode app-server daemon update --from-cli\" per allinearlo." + ); + } + println!("Riavvia aKode per usare la nuova versione."); + Ok(()) +} + +/// The real file behind the running binary, and its package directory if it is packaged. +fn install_target() -> anyhow::Result { + let exe = std::env::current_exe() + .and_then(|exe| exe.canonicalize()) + .context("impossibile individuare il binario di aKode in esecuzione")?; + let package_dir = InstallContext::current() + .package_layout + .as_ref() + .filter(|layout| exe.starts_with(layout.bin_dir.as_path())) + .map(|layout| PathBuf::from(layout.package_dir.as_path())); + Ok(InstallTarget { exe, package_dir }) +} diff --git a/akode-rs/cli/tests/update.rs b/akode-rs/cli/tests/update.rs new file mode 100644 index 00000000..e8315006 --- /dev/null +++ b/akode-rs/cli/tests/update.rs @@ -0,0 +1,63 @@ +use anyhow::Result; +use predicates::str::contains; +use std::path::Path; +use tempfile::TempDir; +use wiremock::Mock; +use wiremock::MockServer; +use wiremock::ResponseTemplate; +use wiremock::matchers::method; +use wiremock::matchers::path; + +const LATEST_PATH: &str = "/api/v1/repos/andrea/aKode/releases/latest"; + +fn akode_update(akode_home: &Path, server: &MockServer) -> Result { + let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?); + cmd.env("AKODE_HOME", akode_home).args([ + "-c", + &format!("update.repo_url=\"{}/andrea/aKode\"", server.uri()), + "update", + ]); + Ok(cmd) +} + +#[tokio::test] +async fn update_without_published_release_reports_up_to_date() -> Result<()> { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path(LATEST_PATH)) + .respond_with(ResponseTemplate::new(404)) + .expect(1) + .mount(&server) + .await; + let akode_home = TempDir::new()?; + + akode_update(akode_home.path(), &server)? + .assert() + .success() + .stdout(contains("Nessuna release pubblicata")); + + Ok(()) +} + +#[tokio::test] +async fn update_check_reports_newer_release_without_installing() -> Result<()> { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path(LATEST_PATH)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "tag_name": "v999.0.0", + "assets": [], + }))) + .expect(1) + .mount(&server) + .await; + let akode_home = TempDir::new()?; + + akode_update(akode_home.path(), &server)? + .arg("--check") + .assert() + .success() + .stdout(contains("È disponibile aKode 999.0.0")); + + Ok(()) +} diff --git a/akode-rs/config/src/config_toml.rs b/akode-rs/config/src/config_toml.rs index 8b4e91d4..5b508f01 100644 --- a/akode-rs/config/src/config_toml.rs +++ b/akode-rs/config/src/config_toml.rs @@ -28,6 +28,7 @@ use crate::types::ShellEnvironmentPolicyToml; use crate::types::SkillsConfig; use crate::types::ToolSuggestConfig; use crate::types::Tui; +use crate::types::UpdateConfigToml; use crate::types::UriBasedFileOpener; use crate::types::WindowsToml; use akode_features::FeaturesToml; @@ -540,6 +541,9 @@ pub struct ConfigToml { /// Defaults to `true`. pub feedback: Option, + /// Release source and startup check for `akode update`. + pub update: Option, + /// Settings for app-specific controls. #[serde(default)] pub apps: Option, diff --git a/akode-rs/config/src/types.rs b/akode-rs/config/src/types.rs index e1c19d11..41e00b64 100644 --- a/akode-rs/config/src/types.rs +++ b/akode-rs/config/src/types.rs @@ -237,6 +237,20 @@ pub enum HistoryPersistence { None, } +/// Public Gitea repository that publishes aKode releases. +pub const DEFAULT_UPDATE_REPO_URL: &str = "https://git.difonzo.net/andrea/imeai-aKode"; + +/// `[update]`: where `akode update` looks for releases and whether the TUI checks on startup. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct UpdateConfigToml { + /// Gitea repository URL (`https://host/owner/repo`) whose latest release is checked. + /// Defaults to the public aKode repository. + pub repo_url: Option, + /// When `false`, the TUI never checks for a newer release on startup. Defaults to `true`. + pub check_on_startup: Option, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct FeedbackConfigToml { diff --git a/akode-rs/core/config.schema.json b/akode-rs/core/config.schema.json index 12f8f6c1..a0b225bd 100644 --- a/akode-rs/core/config.schema.json +++ b/akode-rs/core/config.schema.json @@ -7210,6 +7210,21 @@ }, "type": "object" }, + "UpdateConfigToml": { + "additionalProperties": false, + "description": "`[update]`: where `akode update` looks for releases and whether the TUI checks on startup.", + "properties": { + "check_on_startup": { + "description": "When `false`, the TUI never checks for a newer release on startup. Defaults to `true`.", + "type": "boolean" + }, + "repo_url": { + "description": "Gitea repository URL (`https://host/owner/repo`) whose latest release is checked. Defaults to the public aKode repository.", + "type": "string" + } + }, + "type": "object" + }, "UpdatePlanToolConfig": { "additionalProperties": false, "properties": { @@ -8658,6 +8673,14 @@ ], "description": "Collection of settings that are specific to the TUI." }, + "update": { + "allOf": [ + { + "$ref": "#/definitions/UpdateConfigToml" + } + ], + "description": "Release source and startup check for `akode update`." + }, "web_search": { "allOf": [ { diff --git a/akode-rs/core/src/config/mod.rs b/akode-rs/core/src/config/mod.rs index 43955cb0..6e79d439 100644 --- a/akode-rs/core/src/config/mod.rs +++ b/akode-rs/core/src/config/mod.rs @@ -1251,6 +1251,13 @@ pub struct Config { /// Defaults to `true`. pub check_for_update_on_startup: bool, + /// Gitea repository checked by `akode update` (`[update] repo_url`). + pub update_repo_url: String, + + /// Whether the TUI checks for a newer aKode release on startup + /// (`[update] check_on_startup`, also off when `check_for_update_on_startup = false`). + pub update_check_on_startup: bool, + /// When true, disables burst-paste detection for typed input entirely. /// All characters are inserted as they are received, and no buffering /// or placeholder replacement will occur for fast keypress bursts. @@ -4772,6 +4779,17 @@ impl Config { active_project, notices, check_for_update_on_startup, + update_repo_url: cfg + .update + .as_ref() + .and_then(|update| update.repo_url.clone()) + .unwrap_or_else(|| akode_config::types::DEFAULT_UPDATE_REPO_URL.to_string()), + update_check_on_startup: check_for_update_on_startup + && cfg + .update + .as_ref() + .and_then(|update| update.check_on_startup) + .unwrap_or(true), disable_paste_burst: cfg .tui .as_ref() diff --git a/akode-rs/thread-manager-sample/src/main.rs b/akode-rs/thread-manager-sample/src/main.rs index 0941bbe4..5f4949e5 100644 --- a/akode-rs/thread-manager-sample/src/main.rs +++ b/akode-rs/thread-manager-sample/src/main.rs @@ -394,6 +394,8 @@ async fn new_config( active_project: ProjectConfig { trust_level: None }, notices: Notice::default(), check_for_update_on_startup: false, + update_repo_url: String::new(), + update_check_on_startup: false, disable_paste_burst: false, feedback_enabled: false, tool_suggest: ToolSuggestConfig::default(), diff --git a/akode-rs/tui/Cargo.toml b/akode-rs/tui/Cargo.toml index b30e0fd0..3653c0b8 100644 --- a/akode-rs/tui/Cargo.toml +++ b/akode-rs/tui/Cargo.toml @@ -34,6 +34,7 @@ akode-app-server-daemon = { workspace = true } akode-app-server-protocol = { workspace = true } akode-arg0 = { workspace = true } akode-install-context = { workspace = true } +akode-update = { workspace = true } akode-config = { workspace = true } akode-context-fragments = { workspace = true } akode-core-plugins = { workspace = true } diff --git a/akode-rs/tui/src/app.rs b/akode-rs/tui/src/app.rs index 876c2cb0..1916d8e6 100644 --- a/akode-rs/tui/src/app.rs +++ b/akode-rs/tui/src/app.rs @@ -46,6 +46,7 @@ use crate::external_editor; use crate::file_search::FileSearchManager; use crate::history_cell; use crate::history_cell::HistoryCell; +use crate::history_cell::UpdateAvailableHistoryCell; use crate::hooks_rpc::HookTrustUpdate; use crate::key_hint::KeyBinding; use crate::key_hint::KeyBindingListExt; diff --git a/akode-rs/tui/src/app/empty_state_animation_tests.rs b/akode-rs/tui/src/app/empty_state_animation_tests.rs index 52b4e4e1..056a7ebe 100644 --- a/akode-rs/tui/src/app/empty_state_animation_tests.rs +++ b/akode-rs/tui/src/app/empty_state_animation_tests.rs @@ -124,6 +124,12 @@ async fn non_startup_history_dismisses_logo_until_a_new_thread() -> Result<()> { }, )), ); + app.insert_history_cell( + &mut tui, + Box::new(history_cell::UpdateAvailableHistoryCell::new( + "99.0.0".into(), + )), + ); app.insert_history_cell( &mut tui, Box::new(history_cell::SessionNoticeCell( diff --git a/akode-rs/tui/src/app/startup.rs b/akode-rs/tui/src/app/startup.rs index e9eae3d8..230647f9 100644 --- a/akode-rs/tui/src/app/startup.rs +++ b/akode-rs/tui/src/app/startup.rs @@ -18,6 +18,39 @@ use crate::session_start::complete_session_start; use crate::unarchive_prompt::run_unarchive_prompt; use color_eyre::eyre::ContextCompat; +/// Checks the configured release repository in the background (at most once per day) and +/// announces a newer aKode release with a one-line notice. Never blocks startup and never +/// installs anything. +fn spawn_startup_update_check(app_event_tx: &AppEventSender, config: &Config) { + if !config.update_check_on_startup { + return; + } + let app_event_tx = app_event_tx.clone(); + let akode_home = config.codex_home.to_path_buf(); + let repo_url = config.update_repo_url.clone(); + tokio::spawn(async move { + let Ok(client) = akode_update::http_client(akode_update::STARTUP_CHECK_TIMEOUT) else { + return; + }; + let check = akode_update::StartupCheck { + akode_home: &akode_home, + repo_url: &repo_url, + enabled: true, + current_version: env!("CARGO_PKG_VERSION"), + }; + let latest = tokio::time::timeout( + akode_update::STARTUP_CHECK_TIMEOUT, + check.run(&client, chrono::Utc::now()), + ) + .await; + if let Ok(Some(latest)) = latest { + app_event_tx.send(AppEvent::InsertHistoryCell(Box::new( + UpdateAvailableHistoryCell::new(latest.to_string()), + ))); + } + }); +} + fn spawn_startup_thread_start( app_server: &AppServerSession, local_settings: crate::local_settings::LocalSettings, @@ -964,6 +997,7 @@ See the aKode keymap documentation for supported actions and examples." ) }); let runtime_keymap = startup_try!(runtime_keymap); + let agents_overview = agents_overview::AgentsOverviewState::new(local_settings.tui.agents_overview_grouping); let mut app = Self { @@ -1240,6 +1274,7 @@ See the aKode keymap documentation for supported actions and examples." let mut waiting_for_initial_session_configured = wait_for_initial_session_configured; let mut waiting_for_initial_session_header = true; + spawn_startup_update_check(&app.app_event_tx, &app.config); let pre_loop_exit_reason: Option = None; let mut backends = diff --git a/akode-rs/tui/src/history_cell/notices.rs b/akode-rs/tui/src/history_cell/notices.rs index cd1d5af3..3b24a005 100644 --- a/akode-rs/tui/src/history_cell/notices.rs +++ b/akode-rs/tui/src/history_cell/notices.rs @@ -9,6 +9,49 @@ use crate::wrapping::adaptive_wrap_line_to_width; #[cfg_attr(not(test), allow(dead_code))] const RECAP_HEADING: &str = "Conversation recap"; +/// One-line startup notice for a newer aKode release (`akode update` installs it). +#[derive(Debug)] +pub(crate) struct UpdateAvailableHistoryCell { + latest_version: String, +} + +impl UpdateAvailableHistoryCell { + pub(crate) fn new(latest_version: String) -> Self { + Self { latest_version } + } +} + +impl HistoryCell for UpdateAvailableHistoryCell { + fn display_lines(&self, width: u16) -> Vec> { + let line = Line::from(vec![ + "È disponibile aKode ".fg(accent_color()), + self.latest_version.clone().bold().fg(accent_color()), + " — esegui ".into(), + "\"akode update\"".bold(), + ]); + vec![ + crate::line_truncation::truncate_line_with_ellipsis_if_overflow( + line, + usize::from(width), + ), + ] + } + + fn raw_lines(&self) -> Vec> { + vec![Line::from(format!( + "È disponibile aKode {} — esegui \"akode update\"", + self.latest_version + ))] + } + + fn display_hyperlink_lines(&self, width: u16) -> Vec { + crate::terminal_hyperlinks::annotate_web_urls(self.display_lines(width)) + } + + fn transcript_hyperlink_lines(&self, width: u16) -> Vec { + self.display_hyperlink_lines(width) + } +} pub(crate) fn new_warning_event(message: String) -> WarningHistoryCell { let style = crate::style::status_style(crate::style::StatusTone::Attention); WarningHistoryCell { diff --git a/akode-rs/tui/src/history_cell/tests.rs b/akode-rs/tui/src/history_cell/tests.rs index 7f4fad71..ede9659e 100644 --- a/akode-rs/tui/src/history_cell/tests.rs +++ b/akode-rs/tui/src/history_cell/tests.rs @@ -1326,6 +1326,20 @@ fn web_search_history_cell_snapshot() { insta::assert_snapshot!(rendered); } +#[test] +fn update_available_history_cell_is_one_italian_line() { + let cell = UpdateAvailableHistoryCell::new("9.9.9".to_string()); + + assert_eq!( + render_lines(&cell.display_lines(/*width*/ 110)), + vec!["È disponibile aKode 9.9.9 — esegui \"akode update\"".to_string()] + ); + assert_eq!( + render_lines(&cell.raw_lines()), + vec!["È disponibile aKode 9.9.9 — esegui \"akode update\"".to_string()] + ); +} + #[test] fn web_search_history_cell_without_detail_snapshot() { let cell = new_web_search_call("call-1".to_string(), String::new(), WebSearchAction::Other); diff --git a/akode-rs/update/BUILD.bazel b/akode-rs/update/BUILD.bazel new file mode 100644 index 00000000..fce31297 --- /dev/null +++ b/akode-rs/update/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "update", + crate_name = "akode_update", +) diff --git a/akode-rs/update/Cargo.toml b/akode-rs/update/Cargo.toml new file mode 100644 index 00000000..ec5ca9de --- /dev/null +++ b/akode-rs/update/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "akode-update" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +name = "akode_update" +path = "src/lib.rs" +doctest = false + +[lints] +workspace = true + +[dependencies] +akode-utils-rustls-provider = { workspace = true } +anyhow = { workspace = true } +chrono = { workspace = true, features = ["serde"] } +flate2 = { workspace = true } +reqwest = { workspace = true, features = ["json", "rustls-tls", "rustls-tls-native-roots"] } +semver = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +sha2 = { workspace = true } +tar = { workspace = true } +tempfile = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } +wiremock = { workspace = true } diff --git a/akode-rs/update/src/lib.rs b/akode-rs/update/src/lib.rs new file mode 100644 index 00000000..013a8f58 --- /dev/null +++ b/akode-rs/update/src/lib.rs @@ -0,0 +1,606 @@ +//! aKode self-update. +//! +//! Releases are read from the configured Gitea repository only (`[update] repo_url`): the +//! latest-release API, then the release's own assets, which must live on the same host. +//! Nothing is ever installed automatically: callers decide when to call [`install_release`]. +//! There is no telemetry; the only request is the release lookup and the asset downloads. + +use std::path::Path; +use std::path::PathBuf; +use std::time::Duration; + +use anyhow::Context; +use anyhow::Result; +use anyhow::anyhow; +use anyhow::bail; +use anyhow::ensure; +use chrono::DateTime; +use chrono::Utc; +use semver::Version; +use serde::Deserialize; +use serde::Serialize; +use sha2::Digest; +use sha2::Sha256; + +/// The startup check contacts the repository at most once per interval. +pub const CHECK_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60); +/// Timeout for the non-blocking startup check. +pub const STARTUP_CHECK_TIMEOUT: Duration = Duration::from_secs(5); +/// Timeout for the explicit `akode update` requests (asset downloads included). +pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(300); + +const STATE_FILE_NAME: &str = "update-check.json"; +const PACKAGE_MANIFEST_FILE_NAME: &str = "akode-package.json"; +const USER_AGENT: &str = concat!("akode/", env!("CARGO_PKG_VERSION")); + +/// A downloadable file attached to a release. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct ReleaseAsset { + pub name: String, + pub browser_download_url: String, +} + +/// The latest published release of the repository. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Release { + pub version: Version, + pub tag: String, + pub assets: Vec, +} + +#[derive(Deserialize)] +struct GiteaRelease { + tag_name: String, + #[serde(default)] + assets: Vec, +} + +/// Result of comparing the running version with the latest release. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CheckResult { + /// No release is published, or none is newer than the running version. + UpToDate { + latest: Option, + }, + Available(Release), +} + +/// Where the running installation lives. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InstallTarget { + /// The binary to replace. + pub exe: PathBuf, + /// Package directory (with `akode-package.json`) when the binary belongs to a package layout. + pub package_dir: Option, +} + +/// What [`install_release`] replaced, and where the previous version was kept. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum InstallOutcome { + Binary { backup: PathBuf }, + Package { backup: PathBuf }, +} + +/// HTTP client for update requests. Honors the standard proxy environment variables. +pub fn http_client(timeout: Duration) -> Result { + akode_utils_rustls_provider::ensure_rustls_crypto_provider(); + reqwest::Client::builder() + .use_rustls_tls() + .user_agent(USER_AGENT) + .connect_timeout(timeout.min(Duration::from_secs(10))) + .timeout(timeout) + .build() + .context("impossibile creare il client HTTP per gli aggiornamenti") +} + +/// Gitea API URL for the latest release of `repo_url` (`https://host/owner/repo`). +pub fn latest_release_api_url(repo_url: &str) -> Result { + let repo = parse_repo_url(repo_url)?; + let segments: Vec<&str> = repo + .path_segments() + .map(|segments| segments.filter(|segment| !segment.is_empty()).collect()) + .unwrap_or_default(); + let [prefix @ .., owner, name] = segments.as_slice() else { + bail!( + "[update] repo_url deve avere la forma https://host/proprietario/repository: {repo_url}" + ); + }; + let name = name.strip_suffix(".git").unwrap_or(name); + let prefix: String = prefix.iter().map(|segment| format!("/{segment}")).collect(); + let mut api = repo.clone(); + api.set_path(&format!( + "{prefix}/api/v1/repos/{owner}/{name}/releases/latest" + )); + api.set_query(None); + api.set_fragment(None); + Ok(api) +} + +fn parse_repo_url(repo_url: &str) -> Result { + let url = reqwest::Url::parse(repo_url.trim().trim_end_matches('/')) + .with_context(|| format!("[update] repo_url non valido: {repo_url}"))?; + ensure!( + matches!(url.scheme(), "https" | "http") && url.host_str().is_some(), + "[update] repo_url deve essere un URL http(s): {repo_url}" + ); + Ok(url) +} + +/// Reads the latest release. A repository without releases (HTTP 404) yields `None`. +pub async fn fetch_latest_release( + client: &reqwest::Client, + repo_url: &str, +) -> Result> { + let url = latest_release_api_url(repo_url)?; + let response = client + .get(url.clone()) + .header(reqwest::header::ACCEPT, "application/json") + .send() + .await + .with_context(|| { + format!( + "impossibile contattare {}", + url.origin().ascii_serialization() + ) + })?; + if response.status() == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + ensure!( + response.status().is_success(), + "il server delle release ha risposto {}", + response.status() + ); + let release: GiteaRelease = response + .json() + .await + .context("risposta non valida dal server delle release")?; + let version = parse_version(&release.tag_name).with_context(|| { + format!( + "il tag della release {} non è una versione valida", + release.tag_name + ) + })?; + Ok(Some(Release { + version, + tag: release.tag_name, + assets: release.assets, + })) +} + +fn parse_version(tag: &str) -> Result { + let trimmed = tag.trim(); + let trimmed = trimmed + .strip_prefix('v') + .or_else(|| trimmed.strip_prefix('V')) + .unwrap_or(trimmed); + Ok(Version::parse(trimmed)?) +} + +/// Whether `latest` is newer than the running `current` version. +/// Unparseable current versions never report an update. +pub fn is_newer(current: &str, latest: &Version) -> bool { + Version::parse(current.trim()).is_ok_and(|current| *latest > current) +} + +/// [`is_newer`] for a version string; unparseable versions are never newer. +pub fn is_newer_str(current: &str, latest: &str) -> bool { + Version::parse(latest.trim()).is_ok_and(|latest| is_newer(current, &latest)) +} + +/// Compares the latest release with `current_version`. +pub async fn check( + client: &reqwest::Client, + repo_url: &str, + current_version: &str, +) -> Result { + Ok(match fetch_latest_release(client, repo_url).await? { + Some(release) if is_newer(current_version, &release.version) => { + CheckResult::Available(release) + } + Some(release) => CheckResult::UpToDate { + latest: Some(release.version), + }, + None => CheckResult::UpToDate { latest: None }, + }) +} + +/// Target triple used in release asset names, for the platforms aKode publishes. +pub fn current_target() -> Option<&'static str> { + if cfg!(all(target_os = "macos", target_arch = "aarch64")) { + Some("aarch64-apple-darwin") + } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) { + Some("x86_64-apple-darwin") + } else if cfg!(all( + target_os = "linux", + target_arch = "x86_64", + target_env = "musl" + )) { + Some("x86_64-unknown-linux-musl") + } else if cfg!(all( + target_os = "linux", + target_arch = "aarch64", + target_env = "musl" + )) { + Some("aarch64-unknown-linux-musl") + } else if cfg!(all(target_os = "linux", target_arch = "x86_64")) { + Some("x86_64-unknown-linux-gnu") + } else if cfg!(all(target_os = "linux", target_arch = "aarch64")) { + Some("aarch64-unknown-linux-gnu") + } else if cfg!(all(target_os = "windows", target_arch = "x86_64")) { + Some("x86_64-pc-windows-msvc") + } else if cfg!(all(target_os = "windows", target_arch = "aarch64")) { + Some("aarch64-pc-windows-msvc") + } else { + None + } +} + +/// Name of the archive asset for `version` on `target`. +pub fn archive_asset_name(version: &Version, target: &str) -> String { + format!("akode-{version}-{target}.tar.gz") +} + +/// Downloads the release archive for `target` and verifies it against its `.sha256` asset. +pub async fn download_verified_archive( + client: &reqwest::Client, + repo_url: &str, + release: &Release, + target: &str, +) -> Result> { + let archive_name = archive_asset_name(&release.version, target); + let checksum_name = format!("{archive_name}.sha256"); + let find = |name: &str| { + release + .assets + .iter() + .find(|asset| asset.name == name) + .ok_or_else(|| { + anyhow!( + "la release {} non contiene {name} per questa piattaforma", + release.tag + ) + }) + }; + let archive_asset = find(&archive_name)?; + let checksum_asset = find(&checksum_name)?; + let repo = parse_repo_url(repo_url)?; + + let checksum_text = download(client, &repo, checksum_asset).await?; + let checksum_text = + String::from_utf8(checksum_text).context("il file .sha256 non è testo UTF-8")?; + let expected = parse_sha256(&checksum_text, &archive_name)?; + let archive = download(client, &repo, archive_asset).await?; + let actual = hex(&Sha256::digest(&archive)); + ensure!( + actual == expected, + "checksum SHA-256 non corrispondente per {archive_name} (atteso {expected}, ottenuto {actual}): aggiornamento annullato" + ); + Ok(archive) +} + +async fn download( + client: &reqwest::Client, + repo: &reqwest::Url, + asset: &ReleaseAsset, +) -> Result> { + let url = reqwest::Url::parse(&asset.browser_download_url) + .with_context(|| format!("URL non valido per {}", asset.name))?; + // Downloads stay on the configured repository's origin. + ensure!( + url.origin() == repo.origin(), + "{} è ospitato fuori dal repository configurato ({}): download rifiutato", + asset.name, + url.origin().ascii_serialization() + ); + let response = client + .get(url) + .send() + .await + .with_context(|| format!("download di {} non riuscito", asset.name))?; + ensure!( + response.status().is_success(), + "download di {} non riuscito: HTTP {}", + asset.name, + response.status() + ); + Ok(response + .bytes() + .await + .with_context(|| format!("download di {} interrotto", asset.name))? + .to_vec()) +} + +/// Accepts `` or `sha256sum` output (` `), possibly listing several files. +fn parse_sha256(text: &str, archive_name: &str) -> Result { + let lines: Vec> = text + .lines() + .map(|line| line.split_whitespace().collect::>()) + .filter(|tokens| !tokens.is_empty()) + .collect(); + let line = match lines.as_slice() { + [only] => only, + many => many + .iter() + .find(|tokens| { + tokens + .get(1) + .is_some_and(|file| file.trim_start_matches('*') == archive_name) + }) + .ok_or_else(|| anyhow!("il file .sha256 non elenca {archive_name}"))?, + }; + let digest = line[0].to_ascii_lowercase(); + ensure!( + digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()), + "il file .sha256 di {archive_name} non contiene un hash SHA-256 valido" + ); + Ok(digest) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +/// Downloads, verifies and installs `release`. Nothing on disk changes unless the +/// archive matches its published checksum. +pub async fn install_release( + client: &reqwest::Client, + repo_url: &str, + release: &Release, + target: &str, + install: &InstallTarget, +) -> Result { + let archive = download_verified_archive(client, repo_url, release, target).await?; + install_archive(&archive, install, &release.version) +} + +/// Extracts a verified `.tar.gz` and swaps it in. The previous binary (or package) is kept +/// as `*.old` and restored if the swap fails. +pub fn install_archive( + archive: &[u8], + install: &InstallTarget, + version: &Version, +) -> Result { + let exe_dir = install + .exe + .parent() + .context("il binario installato non ha una cartella")?; + // Stage next to the destination so the final renames never cross file systems. + let staging_parent = match &install.package_dir { + Some(package_dir) => package_dir + .parent() + .context("il pacchetto installato non ha una cartella")?, + None => exe_dir, + }; + let staging = tempfile::Builder::new() + .prefix(".akode-update-") + .tempdir_in(staging_parent) + .with_context(|| { + format!( + "impossibile scrivere in {} (servono i permessi di scrittura)", + staging_parent.display() + ) + })?; + let extract_dir = staging.path().join("extract"); + std::fs::create_dir(&extract_dir)?; + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(archive)); + tar.set_preserve_permissions(true); + tar.unpack(&extract_dir) + .context("l'archivio della release non è un .tar.gz valido")?; + let root = archive_root(&extract_dir)?; + + if let Some(package_dir) = &install.package_dir + && root.join(PACKAGE_MANIFEST_FILE_NAME).is_file() + { + let backup = replace_package_dir(&root, package_dir)?; + return Ok(InstallOutcome::Package { backup }); + } + + let new_binary = find_binary(&root)?; + let staged_manifest = match &install.package_dir { + Some(package_dir) => Some(stage_manifest_version( + package_dir, + version, + staging.path(), + )?), + None => None, + }; + let backup = replace_binary(&new_binary, &install.exe)?; + if let (Some(staged), Some(package_dir)) = (staged_manifest, &install.package_dir) + && let Err(err) = std::fs::rename(&staged, package_dir.join(PACKAGE_MANIFEST_FILE_NAME)) + { + restore_binary(&backup, &install.exe); + return Err(err).context("impossibile aggiornare akode-package.json; binario ripristinato"); + } + Ok(InstallOutcome::Binary { backup }) +} + +/// Archives may wrap their content in a single top-level directory. +fn archive_root(extract_dir: &Path) -> Result { + let entries: Vec<_> = std::fs::read_dir(extract_dir)?.collect::>()?; + match entries.as_slice() { + [] => bail!("l'archivio della release è vuoto"), + [single] if single.file_type()?.is_dir() => Ok(single.path()), + _ => Ok(extract_dir.to_path_buf()), + } +} + +fn binary_file_name() -> &'static str { + if cfg!(windows) { "akode.exe" } else { "akode" } +} + +fn find_binary(root: &Path) -> Result { + let name = binary_file_name(); + [root.join(name), root.join("bin").join(name)] + .into_iter() + .find(|candidate| candidate.is_file()) + .ok_or_else(|| anyhow!("l'archivio della release non contiene {name}")) +} + +fn backup_path(exe: &Path) -> PathBuf { + let stem = exe + .file_stem() + .and_then(|stem| stem.to_str()) + .unwrap_or("akode"); + exe.with_file_name(format!("{stem}.old")) +} + +/// Puts `new_binary` at `exe`. On Unix the final rename atomically replaces the binary; on +/// Windows a running executable cannot be overwritten, so it is moved aside first. +fn replace_binary(new_binary: &Path, exe: &Path) -> Result { + let file_name = exe + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("akode"); + let staged = exe.with_file_name(format!(".{file_name}.new-{}", std::process::id())); + std::fs::copy(new_binary, &staged) + .with_context(|| format!("impossibile scrivere {}", staged.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755))?; + } + let backup = backup_path(exe); + let result = swap_into_place(&staged, exe, &backup); + if result.is_err() { + let _ = std::fs::remove_file(&staged); + } + result.map(|()| backup) +} + +#[cfg(not(windows))] +fn swap_into_place(staged: &Path, exe: &Path, backup: &Path) -> Result<()> { + if backup.exists() { + std::fs::remove_file(backup)?; + } + std::fs::copy(exe, backup) + .with_context(|| format!("impossibile creare la copia {}", backup.display()))?; + std::fs::rename(staged, exe) + .with_context(|| format!("impossibile sostituire {}", exe.display())) +} + +#[cfg(windows)] +fn swap_into_place(staged: &Path, exe: &Path, backup: &Path) -> Result<()> { + if backup.exists() { + std::fs::remove_file(backup)?; + } + std::fs::rename(exe, backup) + .with_context(|| format!("impossibile spostare {}", exe.display()))?; + if let Err(err) = std::fs::rename(staged, exe) { + restore_binary(backup, exe); + return Err(err).with_context(|| format!("impossibile sostituire {}", exe.display())); + } + Ok(()) +} + +fn restore_binary(backup: &Path, exe: &Path) { + if cfg!(windows) { + let _ = std::fs::rename(backup, exe); + } else { + // Copy to a fresh file and rename: overwriting the binary in place would corrupt a + // running executable (and invalidate its code signature on macOS). + let restored = exe.with_file_name(format!(".akode.restore-{}", std::process::id())); + if std::fs::copy(backup, &restored).is_ok() && std::fs::rename(&restored, exe).is_err() { + let _ = std::fs::remove_file(&restored); + } + } +} + +fn stage_manifest_version( + package_dir: &Path, + version: &Version, + staging: &Path, +) -> Result { + let path = package_dir.join(PACKAGE_MANIFEST_FILE_NAME); + let mut manifest: serde_json::Value = serde_json::from_slice( + &std::fs::read(&path).with_context(|| format!("impossibile leggere {}", path.display()))?, + ) + .with_context(|| format!("{} non è JSON valido", path.display()))?; + let object = manifest + .as_object_mut() + .with_context(|| format!("{} non è un oggetto JSON", path.display()))?; + object.insert( + "version".to_string(), + serde_json::Value::String(version.to_string()), + ); + // Same file system as the package directory, so the later rename is atomic. + let staged = staging.join(PACKAGE_MANIFEST_FILE_NAME); + std::fs::write(&staged, serde_json::to_vec_pretty(&manifest)?)?; + Ok(staged) +} + +fn replace_package_dir(new_package: &Path, package_dir: &Path) -> Result { + let name = package_dir + .file_name() + .and_then(|name| name.to_str()) + .context("cartella del pacchetto non valida")?; + let backup = package_dir.with_file_name(format!("{name}.old")); + if backup.exists() { + std::fs::remove_dir_all(&backup)?; + } + std::fs::rename(package_dir, &backup) + .with_context(|| format!("impossibile spostare {}", package_dir.display()))?; + if let Err(err) = std::fs::rename(new_package, package_dir) { + let _ = std::fs::rename(&backup, package_dir); + return Err(err) + .with_context(|| format!("impossibile sostituire {}", package_dir.display())); + } + Ok(backup) +} + +#[derive(Debug, Serialize, Deserialize)] +struct CheckState { + last_checked_at: DateTime, + #[serde(default)] + latest_version: Option, +} + +/// Startup check: contacts the repository at most once per [`CHECK_INTERVAL`] and returns a +/// newer version to announce, if any. Never installs anything. +pub struct StartupCheck<'a> { + pub akode_home: &'a Path, + pub repo_url: &'a str, + pub enabled: bool, + pub current_version: &'a str, +} + +impl StartupCheck<'_> { + pub async fn run(&self, client: &reqwest::Client, now: DateTime) -> Option { + if !self.enabled { + return None; + } + let state_path = self.akode_home.join(STATE_FILE_NAME); + let previous: Option = std::fs::read(&state_path) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()); + let interval = chrono::Duration::from_std(CHECK_INTERVAL).ok()?; + let latest = match &previous { + Some(state) + if state.last_checked_at <= now && now - state.last_checked_at < interval => + { + state.latest_version.clone() + } + _ => { + let latest = match fetch_latest_release(client, self.repo_url).await { + Ok(release) => release.map(|release| release.version.to_string()), + Err(_) => previous.and_then(|state| state.latest_version), + }; + let state = CheckState { + last_checked_at: now, + latest_version: latest.clone(), + }; + if let Ok(bytes) = serde_json::to_vec(&state) { + let _ = std::fs::create_dir_all(self.akode_home); + let _ = std::fs::write(&state_path, bytes); + } + latest + } + }; + let latest = Version::parse(&latest?).ok()?; + is_newer(self.current_version, &latest).then_some(latest) + } +} + +#[cfg(test)] +#[path = "lib_tests.rs"] +mod tests; diff --git a/akode-rs/update/src/lib_tests.rs b/akode-rs/update/src/lib_tests.rs new file mode 100644 index 00000000..e28354b9 --- /dev/null +++ b/akode-rs/update/src/lib_tests.rs @@ -0,0 +1,472 @@ +use super::*; +use pretty_assertions::assert_eq; +use wiremock::Mock; +use wiremock::MockServer; +use wiremock::ResponseTemplate; +use wiremock::matchers::method; +use wiremock::matchers::path; + +const TARGET: &str = "aarch64-apple-darwin"; +const LATEST_PATH: &str = "/api/v1/repos/andrea/imeai-aKode/releases/latest"; + +fn repo_url(server: &MockServer) -> String { + format!("{}/andrea/imeai-aKode", server.uri()) +} + +fn client() -> reqwest::Client { + http_client(Duration::from_secs(5)).expect("client") +} + +fn tarball(files: &[(&str, &[u8])]) -> Vec { + let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + let mut builder = tar::Builder::new(encoder); + for (name, contents) in files { + let mut header = tar::Header::new_gnu(); + header.set_size(contents.len() as u64); + header.set_mode(0o755); + header.set_cksum(); + builder + .append_data(&mut header, name, *contents) + .expect("append"); + } + builder.into_inner().expect("tar").finish().expect("gzip") +} + +async fn mount_release(server: &MockServer, archive: &[u8], checksum: &str) { + let archive_name = format!("akode-1.2.3-{TARGET}.tar.gz"); + let base = server.uri(); + Mock::given(method("GET")) + .and(path(LATEST_PATH)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "tag_name": "v1.2.3", + "assets": [ + {"name": archive_name, "browser_download_url": format!("{base}/dl/{archive_name}")}, + {"name": format!("{archive_name}.sha256"), "browser_download_url": format!("{base}/dl/{archive_name}.sha256")}, + ], + }))) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path(format!("/dl/{archive_name}"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(archive.to_vec())) + .mount(server) + .await; + Mock::given(method("GET")) + .and(path(format!("/dl/{archive_name}.sha256"))) + .respond_with( + ResponseTemplate::new(200).set_body_string(format!("{checksum} {archive_name}\n")), + ) + .mount(server) + .await; +} + +fn installed_binary(dir: &Path) -> PathBuf { + let exe = dir.join(binary_file_name()); + std::fs::write(&exe, b"old binary").expect("write exe"); + exe +} + +#[test] +fn api_url_is_derived_from_repo_url() { + for (repo, expected) in [ + ( + "https://git.difonzo.net/andrea/imeai-aKode", + "https://git.difonzo.net/api/v1/repos/andrea/imeai-aKode/releases/latest", + ), + ( + "https://git.difonzo.net/andrea/imeai-aKode.git/", + "https://git.difonzo.net/api/v1/repos/andrea/imeai-aKode/releases/latest", + ), + ( + "https://example.com/gitea/andrea/imeai-aKode", + "https://example.com/gitea/api/v1/repos/andrea/imeai-aKode/releases/latest", + ), + ] { + assert_eq!(latest_release_api_url(repo).unwrap().as_str(), expected); + } + assert!(latest_release_api_url("https://git.difonzo.net/andrea").is_err()); + assert!(latest_release_api_url("ftp://git.difonzo.net/andrea/imeai-aKode").is_err()); +} + +#[test] +fn version_comparison() { + let latest = Version::parse("1.2.3").unwrap(); + assert!(is_newer("1.2.2", &latest)); + assert!(is_newer("0.1.0", &latest)); + assert!(is_newer("1.2.3-alpha.1", &latest)); + assert!(!is_newer("1.2.3", &latest)); + assert!(!is_newer("1.3.0", &latest)); + assert!(!is_newer("not-a-version", &latest)); + assert_eq!(parse_version("v1.2.3").unwrap(), latest); +} + +#[test] +fn sha256_file_formats() { + let digest = "a".repeat(64); + assert_eq!(parse_sha256(&digest, "x.tar.gz").unwrap(), digest); + assert_eq!( + parse_sha256(&format!("{digest} *x.tar.gz\n"), "x.tar.gz").unwrap(), + digest + ); + let other = "b".repeat(64); + assert_eq!( + parse_sha256( + &format!("{other} y.tar.gz\n{digest} x.tar.gz\n"), + "x.tar.gz" + ) + .unwrap(), + digest + ); + assert!(parse_sha256("not-a-hash", "x.tar.gz").is_err()); +} + +#[tokio::test] +async fn parses_latest_release() { + let server = MockServer::start().await; + mount_release(&server, b"irrelevant", &"0".repeat(64)).await; + + let release = fetch_latest_release(&client(), &repo_url(&server)) + .await + .unwrap() + .expect("release"); + + assert_eq!(release.version, Version::parse("1.2.3").unwrap()); + assert_eq!(release.tag, "v1.2.3"); + assert_eq!(release.assets.len(), 2); + assert!(matches!( + check(&client(), &repo_url(&server), "1.0.0").await.unwrap(), + CheckResult::Available(_) + )); + assert_eq!( + check(&client(), &repo_url(&server), "1.2.3").await.unwrap(), + CheckResult::UpToDate { + latest: Some(Version::parse("1.2.3").unwrap()) + } + ); +} + +#[tokio::test] +async fn missing_release_means_no_update() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path(LATEST_PATH)) + .respond_with(ResponseTemplate::new(404)) + .mount(&server) + .await; + + assert_eq!( + check(&client(), &repo_url(&server), "0.1.0").await.unwrap(), + CheckResult::UpToDate { latest: None } + ); +} + +#[tokio::test] +async fn installs_verified_archive_and_keeps_backup() { + let server = MockServer::start().await; + let archive = tarball(&[(binary_file_name(), b"new binary")]); + mount_release(&server, &archive, &hex(&Sha256::digest(&archive))).await; + let dir = tempfile::tempdir().unwrap(); + let exe = installed_binary(dir.path()); + let release = fetch_latest_release(&client(), &repo_url(&server)) + .await + .unwrap() + .unwrap(); + + let outcome = install_release( + &client(), + &repo_url(&server), + &release, + TARGET, + &InstallTarget { + exe: exe.clone(), + package_dir: None, + }, + ) + .await + .unwrap(); + + let backup = dir.path().join("akode.old"); + assert_eq!( + outcome, + InstallOutcome::Binary { + backup: backup.clone() + } + ); + assert_eq!(std::fs::read(&exe).unwrap(), b"new binary"); + assert_eq!(std::fs::read(&backup).unwrap(), b"old binary"); + let leftovers: Vec<_> = std::fs::read_dir(dir.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .filter(|name| name.starts_with('.')) + .collect(); + assert!( + leftovers.is_empty(), + "staging files left behind: {leftovers:?}" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&exe).unwrap().permissions().mode() & 0o777, + 0o755 + ); + } +} + +#[tokio::test] +async fn checksum_mismatch_leaves_binary_untouched() { + let server = MockServer::start().await; + let archive = tarball(&[(binary_file_name(), b"tampered binary")]); + mount_release(&server, &archive, &"0".repeat(64)).await; + let dir = tempfile::tempdir().unwrap(); + let exe = installed_binary(dir.path()); + let release = fetch_latest_release(&client(), &repo_url(&server)) + .await + .unwrap() + .unwrap(); + + let err = install_release( + &client(), + &repo_url(&server), + &release, + TARGET, + &InstallTarget { + exe: exe.clone(), + package_dir: None, + }, + ) + .await + .unwrap_err(); + + assert!(err.to_string().contains("SHA-256"), "{err:#}"); + assert_eq!(std::fs::read(&exe).unwrap(), b"old binary"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); +} + +#[tokio::test] +async fn assets_outside_the_repository_are_refused() { + let server = MockServer::start().await; + let dir = tempfile::tempdir().unwrap(); + let exe = installed_binary(dir.path()); + let archive_name = format!("akode-1.2.3-{TARGET}.tar.gz"); + let release = Release { + version: Version::parse("1.2.3").unwrap(), + tag: "v1.2.3".to_string(), + assets: vec![ + ReleaseAsset { + name: archive_name.clone(), + browser_download_url: format!("https://elsewhere.invalid/{archive_name}"), + }, + ReleaseAsset { + name: format!("{archive_name}.sha256"), + browser_download_url: format!("https://elsewhere.invalid/{archive_name}.sha256"), + }, + ], + }; + + let err = install_release( + &client(), + &repo_url(&server), + &release, + TARGET, + &InstallTarget { + exe: exe.clone(), + package_dir: None, + }, + ) + .await + .unwrap_err(); + + assert!(err.to_string().contains("fuori dal repository"), "{err:#}"); + assert_eq!(std::fs::read(&exe).unwrap(), b"old binary"); +} + +#[test] +fn binary_only_archive_updates_package_manifest() { + let dir = tempfile::tempdir().unwrap(); + let package_dir = dir.path().join("package"); + std::fs::create_dir_all(package_dir.join("bin")).unwrap(); + std::fs::write( + package_dir.join(PACKAGE_MANIFEST_FILE_NAME), + r#"{"version":"0.1.0","layoutVersion":1}"#, + ) + .unwrap(); + let exe = installed_binary(&package_dir.join("bin")); + let archive = tarball(&[( + &format!("akode-1.2.3/{}", binary_file_name()), + b"new binary", + )]); + + install_archive( + &archive, + &InstallTarget { + exe: exe.clone(), + package_dir: Some(package_dir.clone()), + }, + &Version::parse("1.2.3").unwrap(), + ) + .unwrap(); + + assert_eq!(std::fs::read(&exe).unwrap(), b"new binary"); + let manifest: serde_json::Value = serde_json::from_slice( + &std::fs::read(package_dir.join(PACKAGE_MANIFEST_FILE_NAME)).unwrap(), + ) + .unwrap(); + assert_eq!( + manifest, + serde_json::json!({"version": "1.2.3", "layoutVersion": 1}) + ); +} + +#[test] +fn package_archive_replaces_package_directory() { + let dir = tempfile::tempdir().unwrap(); + let package_dir = dir.path().join("package"); + std::fs::create_dir_all(package_dir.join("bin")).unwrap(); + std::fs::write( + package_dir.join(PACKAGE_MANIFEST_FILE_NAME), + r#"{"version":"0.1.0"}"#, + ) + .unwrap(); + let exe = installed_binary(&package_dir.join("bin")); + let archive = tarball(&[ + (PACKAGE_MANIFEST_FILE_NAME, br#"{"version":"1.2.3"}"#), + (&format!("bin/{}", binary_file_name()), b"new binary"), + ]); + + let outcome = install_archive( + &archive, + &InstallTarget { + exe: exe.clone(), + package_dir: Some(package_dir.clone()), + }, + &Version::parse("1.2.3").unwrap(), + ) + .unwrap(); + + let backup = dir.path().join("package.old"); + assert_eq!( + outcome, + InstallOutcome::Package { + backup: backup.clone() + } + ); + assert_eq!(std::fs::read(&exe).unwrap(), b"new binary"); + assert_eq!( + std::fs::read(backup.join("bin").join(binary_file_name())).unwrap(), + b"old binary" + ); +} + +#[test] +fn archive_without_binary_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let exe = installed_binary(dir.path()); + let archive = tarball(&[("README.md", b"hello")]); + + assert!( + install_archive( + &archive, + &InstallTarget { + exe: exe.clone(), + package_dir: None, + }, + &Version::parse("1.2.3").unwrap(), + ) + .is_err() + ); + assert_eq!(std::fs::read(&exe).unwrap(), b"old binary"); +} + +#[tokio::test] +async fn startup_check_contacts_repository_once_per_day() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path(LATEST_PATH)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "tag_name": "v1.2.3", + "assets": [], + }))) + .expect(2) + .mount(&server) + .await; + let home = tempfile::tempdir().unwrap(); + let repo = repo_url(&server); + let check = StartupCheck { + akode_home: home.path(), + repo_url: &repo, + enabled: true, + current_version: "0.1.0", + }; + let now = Utc::now(); + let expected = Some(Version::parse("1.2.3").unwrap()); + + assert_eq!(check.run(&client(), now).await, expected); + // Within 24 h the cached result is reused without a request. + assert_eq!( + check + .run(&client(), now + chrono::Duration::hours(23)) + .await, + expected + ); + assert_eq!( + check + .run(&client(), now + chrono::Duration::hours(25)) + .await, + expected + ); + let up_to_date = StartupCheck { + current_version: "1.2.3", + ..check + }; + assert_eq!( + up_to_date + .run(&client(), now + chrono::Duration::hours(26)) + .await, + None + ); +} + +#[tokio::test] +async fn startup_check_records_missing_release() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path(LATEST_PATH)) + .respond_with(ResponseTemplate::new(404)) + .expect(1) + .mount(&server) + .await; + let home = tempfile::tempdir().unwrap(); + let repo = repo_url(&server); + let check = StartupCheck { + akode_home: home.path(), + repo_url: &repo, + enabled: true, + current_version: "0.1.0", + }; + + assert_eq!(check.run(&client(), Utc::now()).await, None); + assert_eq!(check.run(&client(), Utc::now()).await, None); + assert!(home.path().join(STATE_FILE_NAME).is_file()); +} + +#[tokio::test] +async fn startup_check_opt_out_makes_no_request() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&server) + .await; + let home = tempfile::tempdir().unwrap(); + let repo = repo_url(&server); + let check = StartupCheck { + akode_home: home.path(), + repo_url: &repo, + enabled: false, + current_version: "0.1.0", + }; + + assert_eq!(check.run(&client(), Utc::now()).await, None); + assert!(!home.path().join(STATE_FILE_NAME).exists()); +}