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

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(())
}