aKode: comando akode update e avviso di nuova versione

- Nuovo crate akode-update: legge l'ultima release dal repository Gitea
  configurato ([update] repo_url, predefinito git.difonzo.net/andrea/aKode;
  404 = nessun aggiornamento), confronta la semver, scarica
  akode-<versione>-<target>.tar.gz solo dallo stesso host, verifica lo
  SHA-256 e sostituisce il binario in modo atomico tenendo akode.old
  (nel layout a pacchetto aggiorna anche akode-package.json o l'intero
  pacchetto).
- `akode update [--check]` con messaggi in italiano; mai installazioni
  automatiche.
- TUI: controllo in background all'avvio al massimo ogni 24 h
  (update-check.json in AKODE_HOME), avviso su una riga, disattivabile con
  [update] check_on_startup = false.
- Rimossi il prompt di aggiornamento e le azioni npm/brew/installer di
  OpenAI ormai inutilizzati; il doctor mostra sorgente e ultimo controllo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 14:56:25 +01:00
parent 25de1e70dc
commit 9494b768dd
37 changed files with 1485 additions and 1209 deletions

22
akode-rs/Cargo.lock generated
View File

@@ -734,6 +734,7 @@ dependencies = [
"akode-terminal-detection",
"akode-thread-store",
"akode-tui",
"akode-update",
"akode-utils-absolute-path",
"akode-utils-cargo-bin",
"akode-utils-cli",
@@ -2997,6 +2998,7 @@ dependencies = [
"akode-state",
"akode-terminal-detection",
"akode-uds",
"akode-update",
"akode-utils-absolute-path",
"akode-utils-approval-presets",
"akode-utils-cargo-bin",
@@ -3100,6 +3102,26 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "akode-update"
version = "0.1.0"
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.1.0"

View File

@@ -22,6 +22,7 @@ members = [
"feedback",
"features",
"install-context",
"update",
"code-mode",
"code-mode-host",
"code-mode-protocol",
@@ -228,6 +229,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" }

View File

@@ -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-model-provider-info = { workspace = true }
akode-memories-write = { workspace = true }

View File

@@ -5,36 +5,6 @@ use akode_tui::DaemonUpdateSource;
use pretty_assertions::assert_eq;
use std::os::unix::fs::PermissionsExt;
#[test]
fn package_update_runs_outside_the_project() -> anyhow::Result<()> {
const CHILD: &str = "AKODE_TEST_PACKAGE_UPDATE_CHILD";
if std::env::var_os(CHILD).is_some() {
return run_update_action(UpdateAction::PnpmGlobalLatest, /*cli_executable*/ None);
}
let project = tempfile::tempdir()?;
let bin = tempfile::tempdir()?;
akode_utils_cargo_bin::write_executable(
&bin.path().join("pnpm"),
"#!/bin/sh\npwd -P > \"$0.cwd\"\n",
)?;
assert_cmd::Command::new(std::env::current_exe()?)
.args([
"--exact",
"daemon_update_tests::package_update_runs_outside_the_project",
])
.current_dir(project.path())
.env("TMPDIR", project.path())
.env("PATH", bin.path())
.env(CHILD, "1")
.assert()
.success();
let cwd = std::fs::read_to_string(bin.path().join("pnpm.cwd"))?;
assert!(!std::path::Path::new(cwd.trim_end()).starts_with(project.path().canonicalize()?));
Ok(())
}
#[test]
fn daemon_handoff_uses_selected_executable_and_propagates_failure() -> anyhow::Result<()> {
let dir = tempfile::tempdir()?;

View File

@@ -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<String>, 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::<VersionInfo>(&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<String>, state_file: &Path) {
match std::fs::read_to_string(state_file) {
Ok(contents) => match serde_json::from_str::<CheckState>(&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<String>,
#[serde(default)]
dismissed_version: Option<String>,
latest_version: Option<String>,
}
#[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(),
]
);
}
}

View File

@@ -62,7 +62,7 @@ mod sandbox_setup;
mod sandbox_uninstall;
mod state_db_recovery;
#[cfg(not(windows))]
mod wsl_paths;
mod update_cmd;
use crate::mcp_cmd::McpCli;
use crate::plugin_cmd::PluginCli;
@@ -158,8 +158,8 @@ enum Subcommand {
/// Generate shell completion scripts.
Completion(CompletionCommand),
/// Update aKode to the latest version.
Update,
/// 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),
@@ -721,111 +721,26 @@ 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>,
) -> anyhow::Result<()> {
if let UpdateAction::Daemon(source) = action {
let executable = cli_executable
.ok_or_else(|| anyhow::anyhow!("Cannot locate the launching aKode CLI"))?;
println!("Updating the local background server...");
let status = std::process::Command::new(executable)
.args(source.command_args())
.status()?;
anyhow::ensure!(
status.success(),
"Daemon update failed with status {status}"
);
println!("Relaunch aKode to reconnect.");
return Ok(());
}
println!();
let cmd_str = action.command_str();
println!("Updating aKode via `{cmd_str}`...");
let status = {
#[cfg(windows)]
{
let (cmd, args) = action.command_args();
let cmd = if action == UpdateAction::StandaloneWindows {
// These args contain PowerShell metacharacters, so do not let
// PATHEXT select a batch shim for this action.
"powershell.exe"
} else {
cmd
};
let path_env =
std::env::var_os("PATH").ok_or_else(|| anyhow::anyhow!("PATH is not set"))?;
let command_path = resolve_windows_update_command_from_path(cmd, &path_env)?;
// Do not let a project-local command or package-manager config
// influence the updater after the user accepts the update prompt.
let update_cwd = tempfile::tempdir()?;
// Resolve through PATH without consulting the project cwd. When
// this returns a .cmd/.bat shim, std::process::Command routes the
// absolute path through the system command processor.
std::process::Command::new(command_path)
.args(args)
.current_dir(update_cwd.path())
.status()?
}
#[cfg(not(windows))]
{
let (cmd, args) = action.command_args();
let command_path = crate::wsl_paths::normalize_for_wsl(cmd);
let normalized_args: Vec<String> = args
.iter()
.map(crate::wsl_paths::normalize_for_wsl)
.collect();
std::process::Command::new(&command_path)
.args(&normalized_args)
// Package managers search parent directories for project config and hooks.
.current_dir("/")
.status()?
}
};
if !status.success() {
anyhow::bail!("`{cmd_str}` failed with status {status}");
}
println!("\n🎉 Update ran successfully! Please restart aKode.");
let UpdateAction::Daemon(source) = action;
let executable =
cli_executable.ok_or_else(|| anyhow::anyhow!("Cannot locate the launching aKode CLI"))?;
println!("Updating the local background server...");
let status = std::process::Command::new(executable)
.args(source.command_args())
.status()?;
anyhow::ensure!(
status.success(),
"Daemon update failed with status {status}"
);
println!("Relaunch aKode to reconnect.");
Ok(())
}
#[cfg(windows)]
fn resolve_windows_update_command_from_path(
command: &str,
path_env: &std::ffi::OsStr,
) -> anyhow::Result<PathBuf> {
let path_env =
std::env::join_paths(std::env::split_paths(path_env).filter(|path| path.is_absolute()))?;
if path_env.is_empty() {
anyhow::bail!(
"Could not find an absolute update command `{command}` on PATH. Please update manually: https://developers.openai.com/codex/cli/"
);
}
which::which_in_global(command, Some(&path_env))?
.next()
.ok_or_else(|| anyhow::anyhow!("could not find update command `{command}` on PATH"))
}
fn run_update_command() -> anyhow::Result<()> {
#[cfg(debug_assertions)]
{
anyhow::bail!(
"`akode update` is not available in debug builds. Install a release build of aKode to use this command."
);
}
#[cfg(not(debug_assertions))]
{
let Some(action) = akode_tui::get_update_action() else {
anyhow::bail!(
"Could not detect the aKode installation method. Please update manually: https://developers.openai.com/codex/cli/"
);
};
run_update_action(action, /*cli_executable*/ None)
}
}
fn run_execpolicycheck(cmd: ExecPolicyCheckCommand) -> anyhow::Result<()> {
cmd.run()
}
@@ -1579,13 +1494,16 @@ async fn dispatch_cli(
)?;
print_completion(completion_cli);
}
Some(Subcommand::Update) => {
Some(Subcommand::Update(update_cli)) => {
reject_remote_mode_for_subcommand(
root_remote.as_deref(),
root_remote_auth_token_env.as_deref(),
"update",
)?;
run_update_command()?;
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(
@@ -2195,7 +2113,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::Update(_)) => Some("update"),
Some(Subcommand::Sandbox(_)) => Some("sandbox"),
Some(Subcommand::Debug(_)) => Some("debug"),
Some(Subcommand::Execpolicy(_)) => Some("execpolicy"),
@@ -2617,52 +2535,6 @@ mod tests {
assert!(size < 64 * 1024, "interactive TUI future is {size} bytes");
}
#[cfg(windows)]
#[test]
fn windows_update_command_resolution_ignores_relative_path_entries() {
let cwd = std::env::current_dir().expect("current directory");
let decoy_dir = tempfile::tempdir_in(&cwd).expect("relative decoy directory");
let trusted_dir = tempfile::tempdir().expect("trusted PATH directory");
let relative_decoy_dir = decoy_dir
.path()
.strip_prefix(&cwd)
.expect("decoy directory should be relative to cwd");
for command in ["npm.cmd", "pnpm.cmd", "bun.exe"] {
std::fs::write(decoy_dir.path().join(command), "decoy")
.expect("write cwd-relative decoy");
std::fs::write(trusted_dir.path().join(command), "trusted")
.expect("write trusted PATH command");
let path_env = std::env::join_paths([relative_decoy_dir, trusted_dir.path()])
.expect("join synthetic PATH");
let resolved = resolve_windows_update_command_from_path(command, &path_env)
.expect("resolve update command");
assert_eq!(resolved, trusted_dir.path().join(command));
}
let cwd_decoy = tempfile::Builder::new()
.suffix(".cmd")
.tempfile_in(&cwd)
.expect("cwd-local decoy");
let command = cwd_decoy
.path()
.file_name()
.and_then(|name| name.to_str())
.expect("decoy filename");
let relative_only_path_env = std::env::join_paths(["."]).expect("join relative-only PATH");
let err = resolve_windows_update_command_from_path(command, &relative_only_path_env)
.expect_err("relative-only PATH should not resolve a cwd command");
assert_eq!(
err.to_string(),
format!(
"Could not find an absolute update command `{command}` on PATH. Please update manually: https://developers.openai.com/codex/cli/"
)
);
}
#[tokio::test]
async fn updater_http_client_factory_honors_respect_system_proxy() {
let codex_home = tempfile::tempdir().expect("temporary Codex home");
@@ -3405,7 +3277,19 @@ enabled = true
#[test]
fn update_parses_as_update_subcommand() {
let cli = MultitoolCli::try_parse_from(["akode", "update"]).expect("parse");
assert!(matches!(cli.subcommand, Some(Subcommand::Update)));
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]

View File

@@ -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<InstallTarget> {
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 })
}

View File

@@ -1,59 +0,0 @@
use std::ffi::OsStr;
/// Returns true if the current process is running under WSL.
pub use akode_utils_path::is_wsl;
/// Convert a Windows absolute path (`C:\foo\bar` or `C:/foo/bar`) to a WSL mount path (`/mnt/c/foo/bar`).
/// Returns `None` if the input does not look like a Windows drive path.
pub fn win_path_to_wsl(path: &str) -> Option<String> {
let bytes = path.as_bytes();
if bytes.len() < 3
|| bytes[1] != b':'
|| !(bytes[2] == b'\\' || bytes[2] == b'/')
|| !bytes[0].is_ascii_alphabetic()
{
return None;
}
let drive = (bytes[0] as char).to_ascii_lowercase();
let tail = path[3..].replace('\\', "/");
if tail.is_empty() {
return Some(format!("/mnt/{drive}"));
}
Some(format!("/mnt/{drive}/{tail}"))
}
/// If under WSL and given a Windows-style path, return the equivalent `/mnt/<drive>/…` path.
/// Otherwise returns the input unchanged.
pub fn normalize_for_wsl<P: AsRef<OsStr>>(path: P) -> String {
let value = path.as_ref().to_string_lossy().to_string();
if !is_wsl() {
return value;
}
if let Some(mapped) = win_path_to_wsl(&value) {
return mapped;
}
value
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn win_to_wsl_basic() {
assert_eq!(
win_path_to_wsl(r"C:\Temp\codex.zip").as_deref(),
Some("/mnt/c/Temp/codex.zip")
);
assert_eq!(
win_path_to_wsl("D:/Work/codex.tgz").as_deref(),
Some("/mnt/d/Work/codex.tgz")
);
assert!(win_path_to_wsl("/home/user/codex").is_none());
}
#[test]
fn normalize_is_noop_on_unix_paths() {
assert_eq!(normalize_for_wsl("/home/u/x"), "/home/u/x");
}
}

View File

@@ -2,23 +2,62 @@ 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;
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
const LATEST_PATH: &str = "/api/v1/repos/andrea/aKode/releases/latest";
fn akode_update(akode_home: &Path, server: &MockServer) -> Result<assert_cmd::Command> {
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
cmd.env("AKODE_HOME", codex_home);
cmd.env("AKODE_HOME", akode_home).args([
"-c",
&format!("update.repo_url=\"{}/andrea/aKode\"", server.uri()),
"update",
]);
Ok(cmd)
}
#[cfg(debug_assertions)]
#[tokio::test]
async fn update_does_not_start_interactive_prompt() -> Result<()> {
let codex_home = TempDir::new()?;
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()?;
codex_command(codex_home.path())?
.arg("update")
akode_update(akode_home.path(), &server)?
.assert()
.failure()
.stderr(contains("`akode update` is not available in debug builds"));
.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(())
}

View File

@@ -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;
@@ -547,6 +548,9 @@ pub struct ConfigToml {
/// Defaults to `true`.
pub feedback: Option<FeedbackConfigToml>,
/// Release source and startup check for `akode update`.
pub update: Option<UpdateConfigToml>,
/// Settings for app-specific controls.
#[serde(default)]
pub apps: Option<AppsConfigToml>,

View File

@@ -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/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<String>,
/// When `false`, the TUI never checks for a newer release on startup. Defaults to `true`.
pub check_on_startup: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct FeedbackConfigToml {

View File

@@ -7246,6 +7246,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": {
@@ -8767,6 +8782,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": [
{

View File

@@ -1271,6 +1271,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.
@@ -4823,6 +4830,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()

View File

@@ -399,6 +399,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(),

View File

@@ -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 }

View File

@@ -46,7 +46,6 @@ use crate::external_editor;
use crate::file_search::FileSearchManager;
use crate::history_cell;
use crate::history_cell::HistoryCell;
#[cfg(not(debug_assertions))]
use crate::history_cell::UpdateAvailableHistoryCell;
use crate::hooks_rpc::HookTrustUpdate;
use crate::key_hint::KeyBinding;

View File

@@ -128,7 +128,6 @@ async fn non_startup_history_dismisses_logo_until_a_new_thread() -> Result<()> {
&mut tui,
Box::new(history_cell::UpdateAvailableHistoryCell::new(
"99.0.0".into(),
/*update_action*/ None,
)),
);
app.insert_history_cell(

View File

@@ -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,8 +997,6 @@ See the aKode keymap documentation for supported actions and examples."
)
});
let runtime_keymap = startup_try!(runtime_keymap);
#[cfg(not(debug_assertions))]
let upgrade_version = crate::updates::get_upgrade_version(&config);
let agents_overview =
agents_overview::AgentsOverviewState::new(local_settings.tui.agents_overview_grouping);
@@ -1243,25 +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;
#[cfg(not(debug_assertions))]
let pre_loop_exit_reason = if let Some(latest_version) = upgrade_version {
let control = Box::pin(app.handle_event(
tui,
&mut app_server,
AppEvent::InsertHistoryCell(Box::new(UpdateAvailableHistoryCell::new(
latest_version,
crate::update_action::get_update_action(),
))),
))
.await;
match startup_try!(control) {
AppRunControl::Continue => None,
AppRunControl::Exit(exit_reason) => Some(exit_reason),
}
} else {
None
};
#[cfg(debug_assertions)]
spawn_startup_update_check(&app.app_event_tx, &app.config);
let pre_loop_exit_reason: Option<ExitReason> = None;
let mut backends =

View File

@@ -44,7 +44,6 @@ use crate::test_support::test_path_buf;
use crate::text_formatting::truncate_text;
use crate::tooltips;
use crate::ui_consts::LIVE_PREFIX_COLS;
use crate::update_action::UpdateAction;
use crate::version::AKODE_CLI_VERSION;
use crate::wrapping::RtOptions;
use crate::wrapping::adaptive_wrap_line;

View File

@@ -9,80 +9,39 @@ use crate::wrapping::adaptive_wrap_line_to_width;
#[cfg_attr(not(test), allow(dead_code))]
const RECAP_HEADING: &str = "Conversation recap";
#[cfg_attr(debug_assertions, allow(dead_code))]
/// One-line startup notice for a newer aKode release (`akode update` installs it).
#[derive(Debug)]
pub(crate) struct UpdateAvailableHistoryCell {
latest_version: String,
update_action: Option<UpdateAction>,
}
#[cfg_attr(debug_assertions, allow(dead_code))]
impl UpdateAvailableHistoryCell {
pub(crate) fn new(latest_version: String, update_action: Option<UpdateAction>) -> Self {
Self {
latest_version,
update_action,
}
pub(crate) fn new(latest_version: String) -> Self {
Self { latest_version }
}
}
impl HistoryCell for UpdateAvailableHistoryCell {
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
use ratatui_macros::line;
use ratatui_macros::text;
let update_instruction = if let Some(update_action) = self.update_action {
line![
"Run ",
update_action.command_str().fg(accent_color()),
" to update."
]
} else {
line![
"See ",
"https://github.com/openai/codex"
.fg(accent_color())
.underlined(),
" for installation options."
]
};
let content = text![
line![
"✨\u{200A}".bold().fg(accent_color()),
"Update available!".bold().fg(accent_color()),
" ",
format!("{AKODE_CLI_VERSION} -> {}", self.latest_version).bold(),
],
update_instruction,
"",
"See full release notes:",
"https://github.com/openai/codex/releases/latest"
.fg(accent_color())
.underlined(),
];
let inner_width = content
.width()
.min(usize::from(width.saturating_sub(4)))
.max(1);
let lines = adaptive_wrap_lines(content.lines, RtOptions::new(inner_width));
with_border_with_inner_width(lines, inner_width)
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<Line<'static>> {
let update_instruction = if let Some(update_action) = self.update_action {
format!("Run {} to update.", update_action.command_str())
} else {
"See https://github.com/openai/codex for installation options.".to_string()
};
vec![
Line::from("Update available!"),
Line::from(format!("{AKODE_CLI_VERSION} -> {}", self.latest_version)),
Line::from(update_instruction),
Line::from(""),
Line::from("See full release notes:"),
Line::from("https://github.com/openai/codex/releases/latest"),
]
vec![Line::from(format!(
"È disponibile aKode {} — esegui \"akode update\"",
self.latest_version
))]
}
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {

View File

@@ -2,45 +2,10 @@
use super::*;
use crate::branding;
use crate::line_truncation::line_width;
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
use crate::style::accent_color;
use crate::width::display_width;
/// Render `lines` inside a border whose inner width is at least `inner_width`.
///
/// This is useful when callers have already clamped their content to a
/// specific width and want the border math centralized here instead of
/// duplicating padding logic in the TUI widgets themselves.
pub(crate) fn with_border_with_inner_width(
lines: Vec<Line<'static>>,
inner_width: usize,
) -> Vec<Line<'static>> {
let max_line_width = lines.iter().map(line_width).max().unwrap_or(0);
let content_width = inner_width.max(max_line_width);
let mut out = Vec::with_capacity(lines.len() + 2);
let border_inner_width = content_width + 2;
out.push(vec![format!("╭{}╮", "─".repeat(border_inner_width)).dim()].into());
for line in lines.into_iter() {
let used_width = line_width(&line);
let span_count = line.spans.len();
let mut spans: Vec<Span<'static>> = Vec::with_capacity(span_count + 4);
spans.push(Span::from("│ ").dim());
spans.extend(line);
if used_width < content_width {
spans.push(Span::from(" ".repeat(content_width - used_width)).dim());
}
spans.push(Span::from(" │").dim());
out.push(Line::from(spans));
}
out.push(vec![format!("╰{}╯", "─".repeat(border_inner_width)).dim()].into());
out
}
/// Brand title shared by the session header and the status card; each owns its own indentation.
pub(crate) fn codex_title(version: &str) -> Vec<Span<'static>> {
vec![

View File

@@ -1,11 +0,0 @@
---
source: tui/src/history_cell/tests.rs
expression: rendered
---
╭─────────────────────────────────────────────────╮
│ ✨ Update available! 0.1.0 -> 9.9.9 │
│ Run pnpm add -g @openai/codex to update. │
│ │
│ See full release notes: │
│ https://github.com/openai/codex/releases/latest │
╰─────────────────────────────────────────────────╯

View File

@@ -1,12 +0,0 @@
---
source: tui/src/history_cell/tests.rs
expression: rendered
---
╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✨ Update available! 0.1.0 -> 9.9.9 │
│ Run sh -c 's=$(curl -fsSL https://chatgpt.com/codex/install.sh) && AKODE_NON_INTERACTIVE=1 eval "$s"' to │
│ update. │
│ │
│ See full release notes: │
│ https://github.com/openai/codex/releases/latest │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

View File

@@ -1,12 +0,0 @@
---
source: tui/src/history_cell/tests.rs
expression: rendered
---
╭────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✨ Update available! 0.1.0 -> 9.9.9 │
│ Run powershell -ExecutionPolicy Bypass -c '$env:AKODE_NON_INTERACTIVE=1; irm │
│ https://chatgpt.com/codex/install.ps1 | iex' to update. │
│ │
│ See full release notes: │
│ https://github.com/openai/codex/releases/latest │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

View File

@@ -1378,30 +1378,17 @@ fn web_search_history_cell_snapshot() {
}
#[test]
fn standalone_unix_update_available_history_cell_snapshot() {
let cell =
UpdateAvailableHistoryCell::new("9.9.9".to_string(), Some(UpdateAction::StandaloneUnix));
let rendered = render_lines(&cell.display_lines(/*width*/ 110)).join("\n");
fn update_available_history_cell_is_one_italian_line() {
let cell = UpdateAvailableHistoryCell::new("9.9.9".to_string());
insta::assert_snapshot!(rendered);
}
#[test]
fn standalone_windows_update_available_history_cell_snapshot() {
let cell =
UpdateAvailableHistoryCell::new("9.9.9".to_string(), Some(UpdateAction::StandaloneWindows));
let rendered = render_lines(&cell.display_lines(/*width*/ 110)).join("\n");
insta::assert_snapshot!(rendered);
}
#[test]
fn pnpm_update_available_history_cell_snapshot() {
let cell =
UpdateAvailableHistoryCell::new("9.9.9".to_string(), Some(UpdateAction::PnpmGlobalLatest));
let rendered = render_lines(&cell.display_lines(/*width*/ 110)).join("\n");
insta::assert_snapshot!(rendered);
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]

View File

@@ -239,13 +239,7 @@ pub(crate) mod update_action;
mod worktree_startup;
pub use update_action::DaemonUpdateSource;
pub use update_action::UpdateAction;
#[cfg(not(debug_assertions))]
pub use update_action::get_update_action;
mod update_prompt;
mod update_versions;
mod updates;
#[cfg(any(not(debug_assertions), test))]
mod updates_cache;
mod user_prompt;
mod version;
mod vim_search;
@@ -1207,30 +1201,6 @@ async fn run_ratatui_app(
}));
let (mut tui, mut terminal_restore_guard, mut startup_draft) = startup_draft.into_parts();
#[cfg(not(debug_assertions))]
{
use crate::update_prompt::UpdatePromptOutcome;
let skip_update_prompt = cli.prompt.as_ref().is_some_and(|prompt| !prompt.is_empty());
if !skip_update_prompt {
startup_draft.flush_pending_events(&mut tui).await?;
match update_prompt::run_update_prompt_if_needed(&mut tui, &initial_config).await? {
UpdatePromptOutcome::Continue => {}
UpdatePromptOutcome::RunUpdate(action) => {
terminal_restore_guard.restore()?;
return Ok(AppExitInfo {
token_usage: crate::token_usage::TokenUsage::default(),
thread_id: None,
resume_hint: None,
disconnect_info: None,
update_action: Some(action),
exit_reason: ExitReason::UserRequested,
});
}
}
}
}
// Initialize high-fidelity session event logging if enabled.
session_log::maybe_init(&initial_config);

View File

@@ -1,15 +0,0 @@
---
source: tui/src/update_prompt.rs
expression: rendered
---
Update available · 0.1.0
→ 9.9.9
Release notes:
https://github.com/opena
i/codex/releases/latest
↑
› 3. Skip until next version
enter continue · esc
skip

View File

@@ -1,13 +0,0 @@
---
source: tui/src/update_prompt.rs
expression: terminal.backend()
---
Update available · 0.1.0 → 9.9.9
Release notes: https://github.com/openai/codex/releases/latest
› 1. Update now (runs `npm install -g @openai/codex`)
2. Skip
3. Skip until next version
enter continue · esc skip

View File

@@ -1,192 +1,11 @@
#[cfg(any(not(debug_assertions), test))]
use akode_install_context::InstallContext;
#[cfg(any(not(debug_assertions), test))]
use akode_install_context::InstallMethod;
#[cfg(any(not(debug_assertions), test))]
use akode_install_context::StandalonePlatform;
/// Update action the CLI should perform after the TUI exits.
///
/// aKode updates itself with `akode update`; the only action requested from the TUI is the
/// daemon package replacement chosen in the daemon menu.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpdateAction {
/// Replace the local daemon after restoring the terminal.
Daemon(DaemonUpdateSource),
/// Update via `npm install -g @openai/codex@latest`.
NpmGlobalLatest,
/// Update via `bun install -g @openai/codex@latest`.
BunGlobalLatest,
/// Update via `vp install -g @openai/codex@latest`.
VitePlusGlobalLatest,
/// Update via `pnpm add -g @openai/codex@latest`.
PnpmGlobalLatest,
/// Update via `brew upgrade codex`.
BrewUpgrade,
/// Update via the standalone Unix installer.
StandaloneUnix,
/// Update via `$env:AKODE_NON_INTERACTIVE=1; irm https://chatgpt.com/codex/install.ps1 | iex`.
StandaloneWindows,
}
impl UpdateAction {
#[cfg(any(not(debug_assertions), test))]
pub(crate) fn from_install_context(context: &InstallContext) -> Option<Self> {
match &context.method {
InstallMethod::Npm => Some(UpdateAction::NpmGlobalLatest),
InstallMethod::Bun => Some(UpdateAction::BunGlobalLatest),
InstallMethod::VitePlus => Some(UpdateAction::VitePlusGlobalLatest),
InstallMethod::Pnpm => Some(UpdateAction::PnpmGlobalLatest),
InstallMethod::Brew => Some(UpdateAction::BrewUpgrade),
InstallMethod::Standalone { platform, .. } => Some(match platform {
StandalonePlatform::Unix => UpdateAction::StandaloneUnix,
StandalonePlatform::Windows => UpdateAction::StandaloneWindows,
}),
InstallMethod::Other => None,
}
}
/// Returns the list of command-line arguments for invoking the update.
pub fn command_args(self) -> (&'static str, &'static [&'static str]) {
match self {
UpdateAction::Daemon(source) => ("codex", source.command_args()),
UpdateAction::NpmGlobalLatest => ("npm", &["install", "-g", "@openai/codex"]),
UpdateAction::BunGlobalLatest => ("bun", &["install", "-g", "@openai/codex"]),
UpdateAction::VitePlusGlobalLatest => ("vp", &["install", "-g", "@openai/codex"]),
UpdateAction::PnpmGlobalLatest => ("pnpm", &["add", "-g", "@openai/codex"]),
UpdateAction::BrewUpgrade => ("brew", &["upgrade", "--cask", "codex"]),
UpdateAction::StandaloneUnix => (
"sh",
&[
"-c",
r#"s=$(curl -fsSL https://chatgpt.com/codex/install.sh) && AKODE_NON_INTERACTIVE=1 eval "$s""#,
],
),
UpdateAction::StandaloneWindows => (
"powershell",
&[
"-ExecutionPolicy",
"Bypass",
"-c",
"$env:AKODE_NON_INTERACTIVE=1; irm https://chatgpt.com/codex/install.ps1 | iex",
],
),
}
}
/// Returns string representation of the command-line arguments for invoking the update.
pub fn command_str(self) -> String {
let (command, args) = self.command_args();
shlex::try_join(std::iter::once(command).chain(args.iter().copied()))
.unwrap_or_else(|_| format!("{command} {}", args.join(" ")))
}
}
#[cfg(not(debug_assertions))]
pub fn get_update_action() -> Option<UpdateAction> {
UpdateAction::from_install_context(InstallContext::current())
}
#[cfg(test)]
mod tests {
use super::*;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
#[test]
fn maps_install_context_to_update_action() {
let native_release_dir =
AbsolutePathBuf::from_absolute_path(std::env::temp_dir().join("native-release"))
.expect("temp dir path should be absolute");
assert_eq!(
UpdateAction::from_install_context(&InstallContext {
method: InstallMethod::Other,
package_layout: None,
}),
None
);
assert_eq!(
UpdateAction::from_install_context(&InstallContext {
method: InstallMethod::Npm,
package_layout: None,
}),
Some(UpdateAction::NpmGlobalLatest)
);
assert_eq!(
UpdateAction::from_install_context(&InstallContext {
method: InstallMethod::Bun,
package_layout: None,
}),
Some(UpdateAction::BunGlobalLatest)
);
assert_eq!(
UpdateAction::from_install_context(&InstallContext {
method: InstallMethod::Pnpm,
package_layout: None,
}),
Some(UpdateAction::PnpmGlobalLatest)
);
assert_eq!(
UpdateAction::from_install_context(&InstallContext {
method: InstallMethod::Brew,
package_layout: None,
}),
Some(UpdateAction::BrewUpgrade)
);
assert_eq!(
UpdateAction::from_install_context(&InstallContext {
method: InstallMethod::Standalone {
platform: StandalonePlatform::Unix,
release_dir: native_release_dir.clone(),
resources_dir: Some(native_release_dir.join("akode-resources")),
},
package_layout: None,
}),
Some(UpdateAction::StandaloneUnix)
);
assert_eq!(
UpdateAction::from_install_context(&InstallContext {
method: InstallMethod::Standalone {
platform: StandalonePlatform::Windows,
release_dir: native_release_dir.clone(),
resources_dir: Some(native_release_dir.join("akode-resources")),
},
package_layout: None,
}),
Some(UpdateAction::StandaloneWindows)
);
}
#[test]
fn standalone_windows_update_command_reruns_latest_installer() {
assert_eq!(
UpdateAction::StandaloneWindows.command_args(),
(
"powershell",
&[
"-ExecutionPolicy",
"Bypass",
"-c",
"$env:AKODE_NON_INTERACTIVE=1; irm https://chatgpt.com/codex/install.ps1 | iex"
][..],
)
);
}
#[cfg(unix)]
#[test]
fn standalone_unix_update_fails_when_installer_download_fails() {
let (command, args) = UpdateAction::StandaloneUnix.command_args();
let offline_command = args[1].replace("https://chatgpt.com", "file:///dev/null");
assert_ne!(offline_command, args[1], "installer URL must be replaced");
let output = std::process::Command::new(command)
.args([args[0], &offline_command])
.env_clear()
.env("HOME", "/dev/null")
.env("PATH", "/usr/bin:/bin")
.output()
.expect("run standalone Unix update command");
assert!(!output.status.success(), "{output:?}");
}
}
/// Package source explicitly selected by the user in the daemon menu.

View File

@@ -1,367 +0,0 @@
//! Shared picker presentation for the installed CLI's update choices.
//! Update discovery and execution remain disabled in debug builds.
#![cfg(any(not(debug_assertions), test))]
use crate::bottom_pane::picker_option_list;
use crate::bottom_pane::render_menu_surface;
use crate::key_hint;
#[cfg(not(debug_assertions))]
use crate::legacy_core::config::Config;
use crate::render::Insets;
use crate::render::renderable::FlexRenderable;
use crate::render::renderable::Renderable;
use crate::render::renderable::RenderableExt as _;
use crate::render::renderable::RenderableItem;
use crate::tui::FrameRequester;
#[cfg(not(debug_assertions))]
use crate::tui::Tui;
#[cfg(not(debug_assertions))]
use crate::tui::TuiEvent;
use crate::update_action::UpdateAction;
#[cfg(not(debug_assertions))]
use crate::updates;
#[cfg(not(debug_assertions))]
use color_eyre::Result;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyEventKind;
use crossterm::event::KeyModifiers;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::prelude::Widget;
use ratatui::style::Stylize as _;
use ratatui::text::Line;
use ratatui::widgets::Clear;
use ratatui::widgets::Paragraph;
use ratatui::widgets::WidgetRef;
use ratatui::widgets::Wrap;
#[cfg(not(debug_assertions))]
use tokio_stream::StreamExt;
const RELEASE_NOTES_URL: &str = "https://github.com/openai/codex/releases/latest";
#[cfg(not(debug_assertions))]
pub(crate) enum UpdatePromptOutcome {
Continue,
RunUpdate(UpdateAction),
}
#[cfg(not(debug_assertions))]
pub(crate) async fn run_update_prompt_if_needed(
tui: &mut Tui,
config: &Config,
) -> Result<UpdatePromptOutcome> {
let Some(latest_version) = updates::get_upgrade_version_for_popup(config) else {
return Ok(UpdatePromptOutcome::Continue);
};
let Some(update_action) = crate::update_action::get_update_action() else {
return Ok(UpdatePromptOutcome::Continue);
};
let mut screen =
UpdatePromptScreen::new(tui.frame_requester(), latest_version.clone(), update_action);
tui.draw(u16::MAX, |frame| {
frame.render_widget_ref(&screen, frame.area());
})?;
tui.discard_pending_input_before_interactive_screen()?;
let events = tui.event_stream();
tokio::pin!(events);
while !screen.is_done() {
if let Some(event) = events.next().await {
tui.screen_size_for_event(&event)?;
match event {
TuiEvent::Key(key_event) => screen.handle_key(key_event),
TuiEvent::Paste(_) | TuiEvent::FocusLost | TuiEvent::Mouse(_) => {}
TuiEvent::Draw | TuiEvent::Resume | TuiEvent::Resize(_) | TuiEvent::FocusGained => {
tui.draw(u16::MAX, |frame| {
frame.render_widget_ref(&screen, frame.area());
})?;
}
}
} else {
break;
}
}
match screen.selection() {
Some(UpdateSelection::UpdateNow) => {
tui.terminal.clear()?;
Ok(UpdatePromptOutcome::RunUpdate(update_action))
}
Some(UpdateSelection::NotNow) | None => Ok(UpdatePromptOutcome::Continue),
Some(UpdateSelection::DontRemind) => {
if let Err(err) = updates::dismiss_version(config, screen.latest_version()).await {
tracing::error!("Failed to persist update dismissal: {err}");
}
Ok(UpdatePromptOutcome::Continue)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum UpdateSelection {
UpdateNow,
NotNow,
DontRemind,
}
struct UpdatePromptScreen {
request_frame: FrameRequester,
latest_version: String,
current_version: String,
update_action: UpdateAction,
highlighted: UpdateSelection,
selection: Option<UpdateSelection>,
}
impl UpdatePromptScreen {
fn new(
request_frame: FrameRequester,
latest_version: String,
update_action: UpdateAction,
) -> Self {
Self {
request_frame,
latest_version,
current_version: env!("CARGO_PKG_VERSION").to_string(),
update_action,
highlighted: UpdateSelection::UpdateNow,
selection: None,
}
}
fn handle_key(&mut self, key_event: KeyEvent) {
if key_event.kind == KeyEventKind::Release {
return;
}
if key_event.modifiers.contains(KeyModifiers::CONTROL)
&& matches!(key_event.code, KeyCode::Char('c') | KeyCode::Char('d'))
{
self.select(UpdateSelection::NotNow);
return;
}
match key_event.code {
KeyCode::Up | KeyCode::Char('k') => self.set_highlight(self.highlighted.prev()),
KeyCode::Down | KeyCode::Char('j') => self.set_highlight(self.highlighted.next()),
KeyCode::Char('1') => self.select(UpdateSelection::UpdateNow),
KeyCode::Char('2') => self.select(UpdateSelection::NotNow),
KeyCode::Char('3') => self.select(UpdateSelection::DontRemind),
KeyCode::Enter => self.select(self.highlighted),
KeyCode::Esc => self.select(UpdateSelection::NotNow),
_ => {}
}
}
fn set_highlight(&mut self, highlight: UpdateSelection) {
if self.highlighted != highlight {
self.highlighted = highlight;
self.request_frame.schedule_frame();
}
}
fn select(&mut self, selection: UpdateSelection) {
self.highlighted = selection;
self.selection = Some(selection);
self.request_frame.schedule_frame();
}
fn is_done(&self) -> bool {
self.selection.is_some()
}
fn selection(&self) -> Option<UpdateSelection> {
self.selection
}
#[cfg(not(debug_assertions))]
fn latest_version(&self) -> &str {
self.latest_version.as_str()
}
}
impl UpdateSelection {
fn next(self) -> Self {
match self {
UpdateSelection::UpdateNow => UpdateSelection::NotNow,
UpdateSelection::NotNow => UpdateSelection::DontRemind,
UpdateSelection::DontRemind => UpdateSelection::UpdateNow,
}
}
fn prev(self) -> Self {
match self {
UpdateSelection::UpdateNow => UpdateSelection::DontRemind,
UpdateSelection::NotNow => UpdateSelection::UpdateNow,
UpdateSelection::DontRemind => UpdateSelection::NotNow,
}
}
}
impl WidgetRef for &UpdatePromptScreen {
fn render_ref(&self, area: Rect, buf: &mut Buffer) {
Clear.render(area, buf);
let mut column = FlexRenderable::new();
let update_command = self.update_action.command_str();
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
column.push(
/*flex*/ 0,
Paragraph::new(Line::from(vec![
"Update available".bold(),
" · ".dim(),
format!(
"{current} → {latest}",
current = self.current_version,
latest = self.latest_version
)
.dim(),
]))
.wrap(Wrap { trim: false })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
);
column.push(
/*flex*/ 1,
Paragraph::new(Line::from(vec![
"Release notes: ".dim(),
RELEASE_NOTES_URL.dim().underlined(),
]))
.wrap(Wrap { trim: false })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
);
let selected_index = match self.highlighted {
UpdateSelection::UpdateNow => 0,
UpdateSelection::NotNow => 1,
UpdateSelection::DontRemind => 2,
};
column.push(
/*flex*/ 1,
picker_option_list(
vec![
format!("Update now (runs `{update_command}`)"),
"Skip".to_string(),
"Skip until next version".to_string(),
],
selected_index,
),
);
column.push(
/*flex*/ 0,
Paragraph::new(Line::from(vec![
key_hint::plain(KeyCode::Enter).into(),
" continue · ".dim(),
key_hint::plain(KeyCode::Esc).into(),
" skip".dim(),
]))
.wrap(Wrap { trim: false })
.inset(Insets::vh(/*v*/ 0, /*h*/ 2)),
);
column.push(/*flex*/ 1, RenderableItem::Borrowed(&""));
let panel = Rect {
height: column.desired_height(area.width).min(area.height),
..area
};
render_menu_surface(panel, buf);
column.render(panel, buf);
crate::terminal_hyperlinks::mark_underlined_hyperlink(buf, area, RELEASE_NOTES_URL);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_backend::VT100Backend;
use crate::tui::FrameRequester;
use crossterm::event::KeyCode;
use crossterm::event::KeyEvent;
use crossterm::event::KeyModifiers;
use pretty_assertions::assert_eq;
use ratatui::Terminal;
use ratatui::widgets::FrameExt;
fn new_prompt() -> UpdatePromptScreen {
UpdatePromptScreen::new(
FrameRequester::test_dummy(),
"9.9.9".into(),
UpdateAction::NpmGlobalLatest,
)
}
#[test]
fn update_prompt_snapshot() {
let screen = new_prompt();
let mut terminal =
Terminal::new(VT100Backend::new(/*width*/ 80, /*height*/ 12)).expect("terminal");
terminal
.draw(|frame| frame.render_widget_ref(&screen, frame.area()))
.expect("render update prompt");
insta::assert_snapshot!("update_prompt_modal", terminal.backend());
}
#[test]
fn update_prompt_confirm_selects_update() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(screen.is_done());
assert_eq!(screen.selection(), Some(UpdateSelection::UpdateNow));
}
#[test]
fn update_prompt_dismiss_option_leaves_prompt_in_normal_state() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
screen.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(screen.is_done());
assert_eq!(screen.selection(), Some(UpdateSelection::NotNow));
}
#[test]
fn update_prompt_dont_remind_selects_dismissal() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
screen.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(screen.is_done());
assert_eq!(screen.selection(), Some(UpdateSelection::DontRemind));
}
#[test]
fn update_prompt_ctrl_c_skips_update() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
assert!(screen.is_done());
assert_eq!(screen.selection(), Some(UpdateSelection::NotNow));
}
#[test]
fn update_prompt_navigation_wraps_between_entries() {
let mut screen = new_prompt();
screen.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
assert_eq!(screen.highlighted, UpdateSelection::DontRemind);
screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
assert_eq!(screen.highlighted, UpdateSelection::UpdateNow);
}
#[test]
fn long_update_command_keeps_selected_skip_visible_in_a_short_viewport() {
let mut screen = new_prompt();
screen.update_action = UpdateAction::StandaloneWindows;
screen.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
let (width, height) = (28, 12);
let mut terminal = Terminal::new(VT100Backend::new(width, height)).expect("terminal");
terminal
.draw(|frame| frame.render_widget_ref(&screen, frame.area()))
.expect("render resized update picker");
let rendered = terminal.backend().to_string();
assert!(rendered.contains("› 3. Skip until next version"));
let words = rendered.split_whitespace().collect::<Vec<_>>().join(" ");
assert!(words.contains("enter continue · esc skip"));
assert_eq!(screen.selection(), None);
insta::assert_snapshot!(format!("update_picker_selected_{width}x{height}"), rendered);
screen.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert_eq!(screen.selection(), Some(UpdateSelection::NotNow));
}
}

View File

@@ -1,19 +0,0 @@
#![cfg(not(debug_assertions))]
use crate::legacy_core::config::Config;
pub(crate) use crate::updates_cache::dismiss_version;
pub fn get_upgrade_version(config: &Config) -> Option<String> {
// aKode: no remote update checks (upstream queried GitHub, npm and Homebrew).
let _ = config;
None
}
/// 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> {
// aKode: no remote update checks.
let _ = config;
None
}

View File

@@ -1,52 +0,0 @@
use crate::legacy_core::config::Config;
use chrono::DateTime;
use chrono::Utc;
use serde::Deserialize;
use serde::Serialize;
use std::path::Path;
use std::path::PathBuf;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub(crate) struct VersionInfo {
pub(crate) latest_version: String,
// ISO-8601 timestamp (RFC3339)
pub(crate) last_checked_at: DateTime<Utc>,
#[serde(default)]
pub(crate) dismissed_version: Option<String>,
}
const VERSION_FILENAME: &str = "version.json";
pub(crate) fn version_filepath(config: &Config) -> PathBuf {
config.codex_home.join(VERSION_FILENAME).into_path_buf()
}
pub(crate) fn read_version_info(version_file: &Path) -> anyhow::Result<VersionInfo> {
let contents = std::fs::read_to_string(version_file)?;
Ok(serde_json::from_str(&contents)?)
}
/// Persist a dismissal for the current latest version so we don't show
/// the update popup again for this version.
pub(crate) async fn dismiss_version(config: &Config, version: &str) -> anyhow::Result<()> {
let version_file = version_filepath(config);
let mut info = match read_version_info(&version_file) {
Ok(info) => info,
Err(_) => VersionInfo {
latest_version: version.to_string(),
last_checked_at: DateTime::<Utc>::UNIX_EPOCH,
dismissed_version: None,
},
};
info.dismissed_version = Some(version.to_string());
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(())
}
#[cfg(test)]
#[path = "updates_cache_tests.rs"]
mod tests;

View File

@@ -1,29 +0,0 @@
use super::*;
use crate::legacy_core::config::ConfigBuilder;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
#[tokio::test]
async fn dismiss_version_creates_cache_file_when_missing() {
let codex_home = tempdir().expect("temp codex home");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("load config");
let version_file = version_filepath(&config);
dismiss_version(&config, "999.0.0")
.await
.expect("dismiss version");
let info = read_version_info(&version_file).expect("read version info");
assert_eq!(info.last_checked_at, DateTime::<Utc>::UNIX_EPOCH);
assert_eq!(
(
info.latest_version.as_str(),
info.dismissed_version.as_deref()
),
("999.0.0", Some("999.0.0"))
);
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "update",
crate_name = "akode_update",
)

View File

@@ -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 }

601
akode-rs/update/src/lib.rs Normal file
View File

@@ -0,0 +1,601 @@
//! 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<ReleaseAsset>,
}
#[derive(Deserialize)]
struct GiteaRelease {
tag_name: String,
#[serde(default)]
assets: Vec<ReleaseAsset>,
}
/// 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<Version>,
},
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<PathBuf>,
}
/// 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<reqwest::Client> {
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<reqwest::Url> {
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<reqwest::Url> {
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<Option<Release>> {
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<Version> {
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<CheckResult> {
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<Vec<u8>> {
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<Vec<u8>> {
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 `<hex>` or `sha256sum` output (`<hex> <file>`), possibly listing several files.
fn parse_sha256(text: &str, archive_name: &str) -> Result<String> {
let lines: Vec<Vec<&str>> = text
.lines()
.map(|line| line.split_whitespace().collect::<Vec<_>>())
.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<InstallOutcome> {
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<InstallOutcome> {
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<PathBuf> {
let entries: Vec<_> = std::fs::read_dir(extract_dir)?.collect::<std::io::Result<_>>()?;
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<PathBuf> {
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<PathBuf> {
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 {
let _ = std::fs::copy(backup, exe);
}
}
fn stage_manifest_version(
package_dir: &Path,
version: &Version,
staging: &Path,
) -> Result<PathBuf> {
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<PathBuf> {
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<Utc>,
#[serde(default)]
latest_version: Option<String>,
}
/// 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<Utc>) -> Option<Version> {
if !self.enabled {
return None;
}
let state_path = self.akode_home.join(STATE_FILE_NAME);
let previous: Option<CheckState> = 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;

View File

@@ -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/aKode/releases/latest";
fn repo_url(server: &MockServer) -> String {
format!("{}/andrea/aKode", server.uri())
}
fn client() -> reqwest::Client {
http_client(Duration::from_secs(5)).expect("client")
}
fn tarball(files: &[(&str, &[u8])]) -> Vec<u8> {
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/aKode",
"https://git.difonzo.net/api/v1/repos/andrea/aKode/releases/latest",
),
(
"https://git.difonzo.net/andrea/aKode.git/",
"https://git.difonzo.net/api/v1/repos/andrea/aKode/releases/latest",
),
(
"https://example.com/gitea/andrea/aKode",
"https://example.com/gitea/api/v1/repos/andrea/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/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());
}