Compare commits
2 Commits
ac3f65985d
...
9494b768dd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9494b768dd | ||
|
|
25de1e70dc |
22
akode-rs/Cargo.lock
generated
22
akode-rs/Cargo.lock
generated
@@ -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"
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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()?;
|
||||
|
||||
@@ -75,7 +75,6 @@ use serde::Serialize;
|
||||
use supports_color::Stream;
|
||||
|
||||
mod background;
|
||||
mod desktop;
|
||||
mod disk;
|
||||
mod filesystem_paths;
|
||||
mod git;
|
||||
@@ -92,10 +91,6 @@ mod updates;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows_dev_drive;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "doctor/desktop_tests.rs"]
|
||||
mod desktop_tests;
|
||||
|
||||
use background::background_server_check;
|
||||
use git::git_check;
|
||||
use output::HumanOutputOptions;
|
||||
@@ -567,12 +562,6 @@ async fn build_report(
|
||||
}
|
||||
}
|
||||
|
||||
progress.begin("desktop");
|
||||
if let Some(desktop) = desktop::collect().await {
|
||||
progress.finish("desktop", overall_status(&desktop.checks));
|
||||
checks.extend(desktop.checks);
|
||||
}
|
||||
|
||||
progress.settle();
|
||||
|
||||
report_from_checks(checks)
|
||||
|
||||
@@ -1,314 +0,0 @@
|
||||
use std::cmp::Reverse;
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::FixedOffset;
|
||||
use chrono::Utc;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::DoctorCheck;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos_security;
|
||||
pub(super) mod platform;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
mod windows_security;
|
||||
|
||||
const MAX_DIRECTORY_ENTRIES: usize = 256;
|
||||
const MAX_LOG_FILES: usize = 64;
|
||||
const MAX_SESSION_LOG_FILES: usize = 8;
|
||||
const MAX_LOG_SEGMENT_BYTES: u64 = 10 * 1024 * 1024;
|
||||
const HANDSHAKE_CHECK_ID: &str = "desktop.app_server.handshake";
|
||||
|
||||
pub(super) struct DesktopDiagnostics {
|
||||
pub(super) checks: Vec<DoctorCheck>,
|
||||
}
|
||||
|
||||
struct DesktopLog {
|
||||
path: PathBuf,
|
||||
session_id: String,
|
||||
process_id: u32,
|
||||
modified: SystemTime,
|
||||
}
|
||||
|
||||
struct HandshakeEvent {
|
||||
timestamp: DateTime<FixedOffset>,
|
||||
outcome: HandshakeOutcome,
|
||||
websocket: bool,
|
||||
}
|
||||
|
||||
enum HandshakeOutcome {
|
||||
Success,
|
||||
Failure,
|
||||
}
|
||||
|
||||
enum DesktopLogEvent {
|
||||
ConnectionContext { local_websocket: bool },
|
||||
Handshake(HandshakeEvent),
|
||||
}
|
||||
|
||||
pub(super) async fn collect() -> Option<DesktopDiagnostics> {
|
||||
let application = match platform::installed_app().await {
|
||||
Ok(Some(application)) => application,
|
||||
Ok(None) => return None,
|
||||
Err(_) => {
|
||||
return Some(DesktopDiagnostics {
|
||||
checks: vec![
|
||||
unavailable(
|
||||
"desktop.app.version",
|
||||
"the desktop application installation could not be inspected",
|
||||
),
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
let directory = desktop_log_root(application.identity);
|
||||
let (running, handshake) = match &directory {
|
||||
Some(root) => inspect_desktop_session(
|
||||
&root.join(Utc::now().format("%Y/%m/%d").to_string()),
|
||||
|pid| platform::application_running(&application, pid),
|
||||
),
|
||||
None => (false, stopped_desktop_check()),
|
||||
};
|
||||
let log_directory = directory
|
||||
.as_deref()
|
||||
.map_or_else(|| "unavailable".to_string(), redacted_path);
|
||||
let application_check = platform::desktop_check(
|
||||
"desktop.app.version",
|
||||
CheckStatus::Ok,
|
||||
"the desktop application is installed",
|
||||
)
|
||||
.detail(format!("version: {}", application.version))
|
||||
.detail(format!("running: {running}"))
|
||||
.detail(format!("log directory: {log_directory}"));
|
||||
|
||||
Some(DesktopDiagnostics {
|
||||
checks: vec![
|
||||
application_check,
|
||||
handshake,
|
||||
#[cfg(target_os = "macos")]
|
||||
macos_security::collect(&application.bundle).await,
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_security::collect().await,
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn inspect_desktop_session(
|
||||
directory: &Path,
|
||||
application_running: impl Fn(u32) -> bool,
|
||||
) -> (bool, DoctorCheck) {
|
||||
let logs = discover_desktop_logs(directory);
|
||||
let Some(session) = logs.iter().find(|log| application_running(log.process_id)) else {
|
||||
return (false, stopped_desktop_check());
|
||||
};
|
||||
|
||||
let check = latest_session_handshake(&logs, &session.session_id).map_or_else(
|
||||
|| {
|
||||
platform::desktop_check(
|
||||
HANDSHAKE_CHECK_ID,
|
||||
CheckStatus::Ok,
|
||||
"no desktop app-server handshake was recorded",
|
||||
)
|
||||
},
|
||||
|event| event.outcome.into_check(),
|
||||
);
|
||||
|
||||
(true, check)
|
||||
}
|
||||
|
||||
fn desktop_log_root(identity: &str) -> Option<PathBuf> {
|
||||
let root = match env::consts::OS {
|
||||
"macos" => PathBuf::from(env::var_os("HOME")?)
|
||||
.join("Library/Logs")
|
||||
.join(identity),
|
||||
"windows" => {
|
||||
let local = env::var_os("LOCALAPPDATA").map(PathBuf::from).or_else(|| {
|
||||
env::var_os("USERPROFILE").map(|home| PathBuf::from(home).join("AppData/Local"))
|
||||
})?;
|
||||
local.join("Codex/Logs")
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Some(root)
|
||||
}
|
||||
|
||||
fn discover_desktop_logs(directory: &Path) -> Vec<DesktopLog> {
|
||||
let Ok(entries) = fs::read_dir(directory) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut logs = entries
|
||||
.take(MAX_DIRECTORY_ENTRIES)
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(DesktopLog::from_entry)
|
||||
.collect::<Vec<_>>();
|
||||
logs.sort_unstable_by_key(|log| Reverse(log.modified));
|
||||
logs.truncate(MAX_LOG_FILES);
|
||||
logs
|
||||
}
|
||||
|
||||
fn latest_session_handshake(logs: &[DesktopLog], session_id: &str) -> Option<HandshakeEvent> {
|
||||
let mut latest: Option<HandshakeEvent> = None;
|
||||
|
||||
for log in logs
|
||||
.iter()
|
||||
.filter(|log| log.session_id == session_id)
|
||||
.take(MAX_SESSION_LOG_FILES)
|
||||
{
|
||||
let Ok(contents) = read_log_segment(&log.path) else {
|
||||
continue;
|
||||
};
|
||||
let mut local_websocket = false;
|
||||
|
||||
for line in String::from_utf8_lossy(&contents).lines() {
|
||||
match DesktopLogEvent::parse(line) {
|
||||
Some(DesktopLogEvent::ConnectionContext {
|
||||
local_websocket: local,
|
||||
}) => {
|
||||
local_websocket = local;
|
||||
}
|
||||
Some(DesktopLogEvent::Handshake(event))
|
||||
if (!event.websocket || local_websocket)
|
||||
&& latest
|
||||
.as_ref()
|
||||
.is_none_or(|current| event.timestamp >= current.timestamp) =>
|
||||
{
|
||||
latest = Some(event);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
latest
|
||||
}
|
||||
|
||||
impl DesktopLog {
|
||||
fn from_entry(entry: fs::DirEntry) -> Option<Self> {
|
||||
let metadata = entry.metadata().ok()?;
|
||||
if !metadata.is_file() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let name = entry.file_name();
|
||||
let name = name
|
||||
.to_str()?
|
||||
.strip_prefix("codex-desktop-")?
|
||||
.strip_suffix(".log")?;
|
||||
let (session_and_pid, _) = name.split_once("-t")?;
|
||||
let (session_id, process_id) = session_and_pid.rsplit_once('-')?;
|
||||
|
||||
Some(Self {
|
||||
path: entry.path(),
|
||||
session_id: session_id.to_string(),
|
||||
process_id: process_id.parse().ok().filter(|pid| *pid > 0)?,
|
||||
modified: metadata.modified().ok()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn read_log_segment(path: &Path) -> io::Result<Vec<u8>> {
|
||||
let mut contents = Vec::new();
|
||||
fs::File::open(path)?
|
||||
.take(MAX_LOG_SEGMENT_BYTES)
|
||||
.read_to_end(&mut contents)?;
|
||||
Ok(contents)
|
||||
}
|
||||
|
||||
impl DesktopLogEvent {
|
||||
fn parse(line: &str) -> Option<Self> {
|
||||
let (timestamp, line) = line.split_once(' ')?;
|
||||
let timestamp = DateTime::parse_from_rfc3339(timestamp).ok()?;
|
||||
let (_, message) = line.split_once(" [AppServerConnection] ")?;
|
||||
|
||||
if let Some(fields) = message
|
||||
.strip_prefix("Starting app-server connection ")
|
||||
.or_else(|| message.strip_prefix("app_server_connection.state_changed "))
|
||||
{
|
||||
return Some(Self::ConnectionContext {
|
||||
local_websocket: log_field(fields, "hostId") == Some("local")
|
||||
&& log_field(fields, "transport") == Some("websocket"),
|
||||
});
|
||||
}
|
||||
|
||||
let fields = message.strip_prefix("initialize_handshake_result ")?;
|
||||
let outcome = match log_field(fields, "outcome")? {
|
||||
"success" => HandshakeOutcome::Success,
|
||||
"failure" => HandshakeOutcome::Failure,
|
||||
_ => return None,
|
||||
};
|
||||
let websocket = match log_field(fields, "transportKind")? {
|
||||
"stdio" => false,
|
||||
"websocket" => true,
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Some(Self::Handshake(HandshakeEvent {
|
||||
timestamp,
|
||||
outcome,
|
||||
websocket,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl HandshakeOutcome {
|
||||
fn into_check(self) -> DoctorCheck {
|
||||
let (status, summary) = match self {
|
||||
Self::Success => (
|
||||
CheckStatus::Ok,
|
||||
"the desktop app-server initialized successfully",
|
||||
),
|
||||
Self::Failure => (
|
||||
CheckStatus::Fail,
|
||||
"the desktop app-server failed to initialize",
|
||||
),
|
||||
};
|
||||
|
||||
platform::desktop_check(HANDSHAKE_CHECK_ID, status, summary)
|
||||
}
|
||||
}
|
||||
|
||||
fn log_field<'a>(fields: &'a str, name: &str) -> Option<&'a str> {
|
||||
fields.split_whitespace().rev().find_map(|field| {
|
||||
let (key, value) = field.split_once('=')?;
|
||||
(key == name).then_some(value)
|
||||
})
|
||||
}
|
||||
|
||||
fn stopped_desktop_check() -> DoctorCheck {
|
||||
platform::desktop_check(
|
||||
HANDSHAKE_CHECK_ID,
|
||||
CheckStatus::Ok,
|
||||
"the desktop application is not running",
|
||||
)
|
||||
}
|
||||
|
||||
fn unavailable(id: &'static str, summary: &'static str) -> DoctorCheck {
|
||||
platform::desktop_check(id, CheckStatus::Warning, summary)
|
||||
.remediation("restore desktop diagnostic access and rerun akode doctor")
|
||||
}
|
||||
|
||||
fn redacted_path(path: &Path) -> String {
|
||||
for variable in ["HOME", "USERPROFILE"] {
|
||||
if let Some(home) = env::var_os(variable)
|
||||
&& let Ok(relative) = path.strip_prefix(Path::new(&home))
|
||||
{
|
||||
return Path::new("$HOME").join(relative).display().to_string();
|
||||
}
|
||||
}
|
||||
path.file_name()
|
||||
.unwrap_or(path.as_os_str())
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
use super::super::CheckStatus;
|
||||
use super::super::DoctorCheck;
|
||||
use super::platform::desktop_check;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::process::Output;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_OUTPUT_BYTES: usize = 256 * 1024;
|
||||
const SECURITY_LOG_PREDICATE: &str = concat!(
|
||||
"(process == 'syspolicyd' OR process == 'AppleSystemPolicy' ",
|
||||
"OR process BEGINSWITH 'XProtect' OR subsystem BEGINSWITH 'com.apple.syspolicy' ",
|
||||
"OR subsystem CONTAINS[c] 'XProtect' ",
|
||||
"OR subsystem == 'com.apple.security.assessment') AND ",
|
||||
"(eventMessage CONTAINS[c] 'codex' OR eventMessage CONTAINS[c] 'chatgpt' ",
|
||||
"OR eventMessage CONTAINS[c] '.plugin-appserver' ",
|
||||
"OR eventMessage CONTAINS[c] '100024' OR eventMessage CONTAINS[c] 'EMFILE' ",
|
||||
"OR eventMessage CONTAINS[c] 'ENFILE' ",
|
||||
"OR eventMessage CONTAINS[c] 'too many open files' ",
|
||||
"OR eventMessage CONTAINS[c] 'Unexpected Xprotect assessment')"
|
||||
);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
enum Evidence {
|
||||
Clear,
|
||||
Audit,
|
||||
Exhausted,
|
||||
Blocked,
|
||||
Malware,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
pub(super) async fn collect(bundle: &Path) -> DoctorCheck {
|
||||
let (gatekeeper, events) = tokio::join!(inspect_gatekeeper(bundle), inspect_security_events());
|
||||
enforcement_check(gatekeeper, events)
|
||||
}
|
||||
|
||||
async fn inspect_gatekeeper(bundle: &Path) -> Evidence {
|
||||
let mut command = Command::new("/usr/sbin/spctl");
|
||||
command
|
||||
.args(["--assess", "--type", "execute", "--verbose=2"])
|
||||
.arg(bundle);
|
||||
classify_gatekeeper(run_command(&mut command).await.as_ref())
|
||||
}
|
||||
|
||||
fn classify_gatekeeper(output: Option<&Output>) -> Evidence {
|
||||
let Some(output) = output.filter(|output| !is_truncated(output)) else {
|
||||
return Evidence::Unavailable;
|
||||
};
|
||||
if output.status.success() {
|
||||
return Evidence::Clear;
|
||||
}
|
||||
let error = String::from_utf8_lossy(&output.stderr).to_ascii_lowercase();
|
||||
if error.contains("rejected") || error.contains("no usable signature") {
|
||||
Evidence::Blocked
|
||||
} else {
|
||||
Evidence::Unavailable
|
||||
}
|
||||
}
|
||||
|
||||
async fn inspect_security_events() -> Evidence {
|
||||
let mut command = Command::new("/usr/bin/log");
|
||||
command.args([
|
||||
"show",
|
||||
"--last",
|
||||
"30m",
|
||||
"--info",
|
||||
"--style",
|
||||
"compact",
|
||||
"--predicate",
|
||||
SECURITY_LOG_PREDICATE,
|
||||
]);
|
||||
let Some(output) = run_command(&mut command)
|
||||
.await
|
||||
.filter(|output| output.status.success())
|
||||
else {
|
||||
return Evidence::Unavailable;
|
||||
};
|
||||
let evidence = classify_security_events(&String::from_utf8_lossy(&output.stdout));
|
||||
if is_truncated(&output) && evidence < Evidence::Exhausted {
|
||||
Evidence::Unavailable
|
||||
} else {
|
||||
evidence
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_security_events(output: &str) -> Evidence {
|
||||
let mut evidence = Evidence::Clear;
|
||||
for line in output.lines().map(str::to_ascii_lowercase) {
|
||||
let contains = |values: &[&str]| values.iter().any(|value| line.contains(value));
|
||||
if !contains(&[
|
||||
"com.openai.codex",
|
||||
"codex.app",
|
||||
"chatgpt.app",
|
||||
".plugin-appserver",
|
||||
"akode-command-runner",
|
||||
]) || contains(&["not blocked", "not denied"])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let event = if contains(&["100024", "emfile", "enfile", "too many open files"]) {
|
||||
Evidence::Exhausted
|
||||
} else if contains(&["would block", "would deny"]) {
|
||||
Evidence::Audit
|
||||
} else if contains(&[
|
||||
"xp_malware_detected",
|
||||
"xp_malware_remediated",
|
||||
"malware detected",
|
||||
"malware blocked",
|
||||
"malware removed",
|
||||
"remediat",
|
||||
]) {
|
||||
Evidence::Malware
|
||||
} else if contains(&[
|
||||
"blocked",
|
||||
"denied",
|
||||
"rejected",
|
||||
"notarization failed",
|
||||
"signature invalid",
|
||||
"execution prevented",
|
||||
"unexpected xprotect assessment",
|
||||
"damaged and",
|
||||
]) {
|
||||
Evidence::Blocked
|
||||
} else if contains(&["audit"]) {
|
||||
Evidence::Audit
|
||||
} else {
|
||||
Evidence::Clear
|
||||
};
|
||||
evidence = evidence.max(event);
|
||||
}
|
||||
evidence
|
||||
}
|
||||
|
||||
fn enforcement_check(gatekeeper: Evidence, events: Evidence) -> DoctorCheck {
|
||||
let id = "desktop.security.enforcement";
|
||||
let (status, summary, remedy) = if events == Evidence::Malware {
|
||||
(
|
||||
CheckStatus::Fail,
|
||||
"macos XProtect blocked or remediated the desktop application",
|
||||
"collect the XProtect detection and ask your security administrator to review the official aKode installation",
|
||||
)
|
||||
} else if gatekeeper == Evidence::Blocked {
|
||||
(
|
||||
CheckStatus::Fail,
|
||||
"macos gatekeeper rejected the desktop application",
|
||||
"ask your security administrator to review the application policy",
|
||||
)
|
||||
} else if events == Evidence::Blocked {
|
||||
(
|
||||
CheckStatus::Fail,
|
||||
"a recent macos security event blocked the desktop application",
|
||||
"ask your security administrator to review the matching prevention event",
|
||||
)
|
||||
} else if events == Evidence::Exhausted {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"macos system-policy diagnostics indicate file descriptor exhaustion",
|
||||
"restart your Mac, retry aKode once, and contact support if the problem returns",
|
||||
)
|
||||
} else if events == Evidence::Audit {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"recent desktop security events are audit-only",
|
||||
"ask your security administrator to verify the application policy",
|
||||
)
|
||||
} else if gatekeeper == Evidence::Unavailable {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"the desktop security assessment was unavailable",
|
||||
"check access to macos gatekeeper diagnostics",
|
||||
)
|
||||
} else if events == Evidence::Unavailable {
|
||||
(
|
||||
CheckStatus::Warning,
|
||||
"recent macos security enforcement history was unavailable",
|
||||
"check access to macos unified security logs and rerun akode doctor",
|
||||
)
|
||||
} else {
|
||||
return desktop_check(
|
||||
id,
|
||||
CheckStatus::Ok,
|
||||
"the desktop application passed available macos security assessments",
|
||||
)
|
||||
.detail("gatekeeper: accepted");
|
||||
};
|
||||
desktop_check(id, status, summary).remediation(remedy)
|
||||
}
|
||||
|
||||
fn is_truncated(output: &Output) -> bool {
|
||||
output.stdout.len() > MAX_OUTPUT_BYTES || output.stderr.len() > MAX_OUTPUT_BYTES
|
||||
}
|
||||
|
||||
async fn run_command(command: &mut Command) -> Option<Output> {
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
let mut child = command.spawn().ok()?;
|
||||
let (stdout, stderr) = (child.stdout.take()?, child.stderr.take()?);
|
||||
timeout(PROBE_TIMEOUT, async {
|
||||
let (stdout, stderr, status) =
|
||||
tokio::join!(read_bounded(stdout), read_bounded(stderr), child.wait());
|
||||
Some(Output {
|
||||
status: status.ok()?,
|
||||
stdout: stdout.ok()?,
|
||||
stderr: stderr.ok()?,
|
||||
})
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn read_bounded<R: AsyncRead + Unpin>(mut reader: R) -> io::Result<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
(&mut reader)
|
||||
.take(MAX_OUTPUT_BYTES as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.await?;
|
||||
if bytes.len() > MAX_OUTPUT_BYTES {
|
||||
tokio::io::copy(&mut reader, &mut tokio::io::sink()).await?;
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "macos_security_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,67 +0,0 @@
|
||||
use super::CheckStatus;
|
||||
use super::Evidence;
|
||||
use super::classify_gatekeeper;
|
||||
use super::classify_security_events;
|
||||
use super::enforcement_check;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
use std::process::ExitStatus;
|
||||
use std::process::Output;
|
||||
|
||||
#[test]
|
||||
fn only_matching_enforced_apple_security_events_are_failures() {
|
||||
for (event, expected) in [
|
||||
("denied com.openai.codex", Evidence::Blocked),
|
||||
(
|
||||
"denied /Applications/Codex.app/Contents/MacOS/Codex",
|
||||
Evidence::Blocked,
|
||||
),
|
||||
("malware detected ChatGPT.app", Evidence::Malware),
|
||||
("audit token blocked ChatGPT.app", Evidence::Blocked),
|
||||
(
|
||||
"audit token XP_MALWARE_DETECTED ChatGPT.app",
|
||||
Evidence::Malware,
|
||||
),
|
||||
("XP_MALWARE_REMEDIATED ChatGPT.app", Evidence::Malware),
|
||||
("denied .plugin-appserver", Evidence::Blocked),
|
||||
("audit would block ChatGPT.app", Evidence::Audit),
|
||||
("OSStatus 100024 ChatGPT.app", Evidence::Exhausted),
|
||||
("not blocked ChatGPT.app", Evidence::Clear),
|
||||
("denied EMFILE com.example.other", Evidence::Clear),
|
||||
("EMFILE\nmalware detected ChatGPT.app", Evidence::Malware),
|
||||
] {
|
||||
assert_eq!(classify_security_events(event), expected, "{event}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gatekeeper_failures_require_actionable_security_evidence() {
|
||||
for (message, expected) in [
|
||||
("ChatGPT.app: rejected", Evidence::Blocked),
|
||||
("operation not permitted", Evidence::Unavailable),
|
||||
] {
|
||||
let output = Output {
|
||||
status: ExitStatus::from_raw(1 << 8),
|
||||
stdout: Vec::new(),
|
||||
stderr: message.as_bytes().to_vec(),
|
||||
};
|
||||
assert_eq!(classify_gatekeeper(Some(&output)), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exhaustion_and_unavailable_history_have_actionable_warnings() {
|
||||
for (events, remedy) in [
|
||||
(Evidence::Exhausted, "restart"),
|
||||
(Evidence::Unavailable, "unified security logs"),
|
||||
] {
|
||||
let check = enforcement_check(Evidence::Clear, events);
|
||||
assert_eq!(check.status, CheckStatus::Warning);
|
||||
assert!(
|
||||
check
|
||||
.remediation
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.contains(remedy))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::ffi::CStr;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::ffi::OsStr;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::fs;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::Path;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::PathBuf;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::process::Stdio;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use serde_json::Value;
|
||||
#[cfg(target_os = "macos")]
|
||||
use tokio::process::Command;
|
||||
#[cfg(target_os = "macos")]
|
||||
use tokio::time::timeout;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::FindPackagesByPackageFamily;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::GetPackageFamilyName;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::PACKAGE_FILTER_HEAD;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::System::Threading::OpenProcess;
|
||||
#[cfg(target_os = "windows")]
|
||||
use windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION;
|
||||
|
||||
use super::super::CheckStatus;
|
||||
use super::super::DoctorCheck;
|
||||
|
||||
pub(in crate::doctor) struct InstalledApp {
|
||||
pub(in crate::doctor) identity: &'static str,
|
||||
pub(in crate::doctor) version: String,
|
||||
#[cfg(target_os = "windows")]
|
||||
package_family: &'static str,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) bundle: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(in crate::doctor) struct DiscoveryError;
|
||||
|
||||
pub(super) async fn installed_app() -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
installed_windows_app()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
installed_macos_app().await
|
||||
}
|
||||
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
|
||||
process_executable_path(candidate_pid)
|
||||
.is_some_and(|path| path.starts_with(application.bundle.join("Contents/MacOS")))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn process_executable_path(pid: u32) -> Option<PathBuf> {
|
||||
let pid = i32::try_from(pid).ok()?;
|
||||
let mut buffer = [0_u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
|
||||
let result =
|
||||
unsafe { libc::proc_pidpath(pid, buffer.as_mut_ptr().cast(), buffer.len() as u32) };
|
||||
if result <= 0 {
|
||||
return None;
|
||||
}
|
||||
let executable = CStr::from_bytes_until_nul(&buffer).ok()?;
|
||||
Some(PathBuf::from(OsStr::from_bytes(executable.to_bytes())))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(super) fn application_running(application: &InstalledApp, candidate_pid: u32) -> bool {
|
||||
process_package_family(candidate_pid).as_deref() == Some(application.package_family)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn process_package_family(pid: u32) -> Option<String> {
|
||||
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
|
||||
if handle.is_null() {
|
||||
return None;
|
||||
}
|
||||
let process = unsafe { OwnedHandle::from_raw_handle(handle) };
|
||||
|
||||
let mut family_length = 0;
|
||||
let result = unsafe {
|
||||
GetPackageFamilyName(
|
||||
process.as_raw_handle(),
|
||||
&mut family_length,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result != ERROR_INSUFFICIENT_BUFFER || family_length == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut family = vec![0_u16; family_length as usize];
|
||||
let result = unsafe {
|
||||
GetPackageFamilyName(
|
||||
process.as_raw_handle(),
|
||||
&mut family_length,
|
||||
family.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
if result != ERROR_SUCCESS {
|
||||
return None;
|
||||
}
|
||||
|
||||
let end = family.iter().position(|value| *value == 0)?;
|
||||
String::from_utf16(&family[..end]).ok()
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
|
||||
pub(super) fn application_running(_application: &InstalledApp, _candidate_pid: u32) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn desktop_check(
|
||||
id: impl Into<String>,
|
||||
status: CheckStatus,
|
||||
summary: impl Into<String>,
|
||||
) -> DoctorCheck {
|
||||
DoctorCheck::new(id, "desktop", status, summary)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn installed_windows_app() -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
const PACKAGE_FAMILY: &str = "OpenAI.Codex_2p2nqsd0c76g0";
|
||||
|
||||
let family = PACKAGE_FAMILY
|
||||
.encode_utf16()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let mut count = 0;
|
||||
let mut length = 0;
|
||||
let result = unsafe {
|
||||
FindPackagesByPackageFamily(
|
||||
family.as_ptr(),
|
||||
PACKAGE_FILTER_HEAD,
|
||||
&mut count,
|
||||
std::ptr::null_mut(),
|
||||
&mut length,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result == ERROR_SUCCESS && count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
if result != ERROR_INSUFFICIENT_BUFFER {
|
||||
return Err(DiscoveryError);
|
||||
}
|
||||
|
||||
let mut names = vec![std::ptr::null_mut(); count as usize];
|
||||
let mut buffer = vec![0_u16; length as usize];
|
||||
let result = unsafe {
|
||||
FindPackagesByPackageFamily(
|
||||
family.as_ptr(),
|
||||
PACKAGE_FILTER_HEAD,
|
||||
&mut count,
|
||||
names.as_mut_ptr(),
|
||||
&mut length,
|
||||
buffer.as_mut_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if result != ERROR_SUCCESS {
|
||||
return Err(DiscoveryError);
|
||||
}
|
||||
if count == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let end = buffer
|
||||
.iter()
|
||||
.position(|value| *value == 0)
|
||||
.ok_or(DiscoveryError)?;
|
||||
let package = String::from_utf16(&buffer[..end]).map_err(|_| DiscoveryError)?;
|
||||
let version = package
|
||||
.strip_prefix("OpenAI.Codex_")
|
||||
.and_then(|name| name.split('_').next())
|
||||
.filter(|version| {
|
||||
version
|
||||
.split('.')
|
||||
.all(|part| !part.is_empty() && part.bytes().all(|digit| digit.is_ascii_digit()))
|
||||
})
|
||||
.ok_or(DiscoveryError)?;
|
||||
|
||||
Ok(Some(InstalledApp {
|
||||
identity: "OpenAI.Codex",
|
||||
version: version.to_string(),
|
||||
package_family: PACKAGE_FAMILY,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
async fn installed_macos_app() -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
let applications = std::iter::once(PathBuf::from("/Applications"))
|
||||
.chain(std::env::var_os("HOME").map(|home| PathBuf::from(home).join("Applications")))
|
||||
.flat_map(|directory| {
|
||||
["ChatGPT.app", "Codex.app"]
|
||||
.into_iter()
|
||||
.map(move |application| directory.join(application))
|
||||
});
|
||||
|
||||
for bundle in applications {
|
||||
match fs::metadata(&bundle) {
|
||||
Ok(metadata) if metadata.is_dir() => {}
|
||||
Ok(_) => continue,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(_) => return Err(DiscoveryError),
|
||||
}
|
||||
if let Some(application) = inspect_macos_bundle(&bundle).await? {
|
||||
return Ok(Some(application));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::doctor) async fn inspect_macos_bundle(
|
||||
bundle: &Path,
|
||||
) -> Result<Option<InstalledApp>, DiscoveryError> {
|
||||
let mut command = Command::new("/usr/bin/plutil");
|
||||
command
|
||||
.args(["-convert", "json", "-o", "-"])
|
||||
.arg(bundle.join("Contents/Info.plist"))
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
let output = timeout(Duration::from_secs(5), command.output())
|
||||
.await
|
||||
.map_err(|_| DiscoveryError)?
|
||||
.map_err(|_| DiscoveryError)?;
|
||||
if !output.status.success() || output.stdout.len() > 64 * 1024 {
|
||||
return Err(DiscoveryError);
|
||||
}
|
||||
let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|_| DiscoveryError)?;
|
||||
if metadata.get("CFBundleIdentifier").and_then(Value::as_str) != Some("com.openai.codex") {
|
||||
return Ok(None);
|
||||
}
|
||||
let version = metadata
|
||||
.get("CFBundleShortVersionString")
|
||||
.or_else(|| metadata.get("CFBundleVersion"))
|
||||
.and_then(Value::as_str)
|
||||
.ok_or(DiscoveryError)?;
|
||||
|
||||
Ok(Some(InstalledApp {
|
||||
identity: "com.openai.codex",
|
||||
version: version.to_string(),
|
||||
bundle: bundle.to_path_buf(),
|
||||
}))
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
use std::env;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::super::CheckStatus;
|
||||
use super::super::DoctorCheck;
|
||||
use super::platform::desktop_check;
|
||||
|
||||
const MAX_EVENTS_PER_CHANNEL: usize = 256;
|
||||
const MAX_RENDERED_EVENTS: usize = 16;
|
||||
const MAX_EVENT_OUTPUT_BYTES: usize = 2 * 1024 * 1024;
|
||||
type Channel = (&'static str, &'static str, &'static [u32]);
|
||||
type Evidence = (CheckStatus, String);
|
||||
|
||||
const CHANNELS: [Channel; 5] = [
|
||||
(
|
||||
"microsoft_defender",
|
||||
"Microsoft-Windows-Windows Defender/Operational",
|
||||
&[
|
||||
1006, 1007, 1116, 1117, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128,
|
||||
],
|
||||
),
|
||||
(
|
||||
"applocker",
|
||||
"Microsoft-Windows-AppLocker/EXE and DLL",
|
||||
&[8003, 8004],
|
||||
),
|
||||
(
|
||||
"applocker",
|
||||
"Microsoft-Windows-AppLocker/Packaged app-Execution",
|
||||
&[8021, 8022],
|
||||
),
|
||||
(
|
||||
"applocker",
|
||||
"Microsoft-Windows-AppLocker/MSI and Script",
|
||||
&[8006, 8007],
|
||||
),
|
||||
(
|
||||
"windows_app_control",
|
||||
"Microsoft-Windows-CodeIntegrity/Operational",
|
||||
&[3076, 3077],
|
||||
),
|
||||
];
|
||||
|
||||
pub(super) async fn collect() -> DoctorCheck {
|
||||
let Some(system_root) = env::var_os("SystemRoot") else {
|
||||
return classify(&[]);
|
||||
};
|
||||
let wevtutil = Path::new(&system_root).join("System32/wevtutil.exe");
|
||||
let mut channels = Vec::with_capacity(CHANNELS.len());
|
||||
for pair in CHANNELS.chunks(/*chunk_size*/ 2) {
|
||||
let first = query_channel(&wevtutil, pair[0]);
|
||||
if let Some(second) = pair.get(/*index*/ 1) {
|
||||
let (first, second) = tokio::join!(first, query_channel(&wevtutil, *second));
|
||||
channels.extend([first, second]);
|
||||
} else {
|
||||
channels.push(first.await);
|
||||
}
|
||||
}
|
||||
classify(&channels)
|
||||
}
|
||||
|
||||
async fn query_channel(wevtutil: &Path, channel: Channel) -> Option<Vec<Evidence>> {
|
||||
let events = channel
|
||||
.2
|
||||
.iter()
|
||||
.map(|id| format!("EventID={id}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" or ");
|
||||
let mut child = Command::from(akode_utils_process::background_command(wevtutil))
|
||||
.args(["qe", channel.1])
|
||||
.arg(format!(
|
||||
"/q:*[System[({events}) and TimeCreated[timediff(@SystemTime) <= 604800000]]]"
|
||||
))
|
||||
.arg(format!("/c:{MAX_EVENTS_PER_CHANNEL}"))
|
||||
.args(["/rd:true", "/f:xml"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.ok()?;
|
||||
let mut output = Vec::new();
|
||||
let status = timeout(Duration::from_secs(10), async {
|
||||
let mut reader = child.stdout.take()?.take(MAX_EVENT_OUTPUT_BYTES as u64 + 1);
|
||||
reader.read_to_end(&mut output).await.ok()?;
|
||||
if output.len() > MAX_EVENT_OUTPUT_BYTES {
|
||||
return None;
|
||||
}
|
||||
child.wait().await.ok()
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()?;
|
||||
status
|
||||
.success()
|
||||
.then(|| parse_events(&String::from_utf8_lossy(&output), channel))
|
||||
}
|
||||
|
||||
fn parse_events(xml: &str, (source, _, ids): Channel) -> Vec<Evidence> {
|
||||
xml.split("</Event>")
|
||||
.take(MAX_EVENTS_PER_CHANNEL)
|
||||
.filter_map(|event| {
|
||||
let id = element(event, "EventID")?.parse().ok()?;
|
||||
if !ids.contains(&id) {
|
||||
return None;
|
||||
}
|
||||
let target = event
|
||||
.split("<Data")
|
||||
.skip(/*n*/ 1)
|
||||
.filter_map(|data| data.split_once('>')?.1.split_once("</Data>").map(|v| v.0))
|
||||
.chain(
|
||||
["FilePath", "FileName", "Image", "PackageName", "PackageFamilyName"]
|
||||
.into_iter()
|
||||
.filter_map(|name| element(event, name)),
|
||||
)
|
||||
.find_map(event_target)?;
|
||||
let timestamp = event.split_once("SystemTime=\"")?.1.split_once('"')?.0;
|
||||
let (status, action) = match id {
|
||||
1121 | 1123 | 1126 | 1127 | 8004 | 8007 | 8022 | 3077 => {
|
||||
(CheckStatus::Fail, "blocked")
|
||||
}
|
||||
1122 | 1124 | 1125 | 1128 | 8003 | 8006 | 8021 | 3076 => {
|
||||
(CheckStatus::Warning, "audited")
|
||||
}
|
||||
1006 | 1116 => (CheckStatus::Warning, "detected"),
|
||||
1007 | 1117 => defender_action(event),
|
||||
_ => return None,
|
||||
};
|
||||
Some((
|
||||
status,
|
||||
format!(
|
||||
"source: {source}; event: {id}; target: {target}; action: {action}; time: {timestamp}"
|
||||
),
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn event_target(value: &str) -> Option<&'static str> {
|
||||
let value = value.to_ascii_lowercase();
|
||||
let parts = value.split(['\\', '/']).map(str::trim).collect::<Vec<_>>();
|
||||
let name = *parts.last()?;
|
||||
let package = parts.iter().any(|part| part.starts_with("openai.codex_"));
|
||||
let trusted = package || parts.windows(2).any(|pair| pair == ["openai", "codex"]);
|
||||
match name {
|
||||
"akode-windows-sandbox-setup.exe" => Some("sandbox_setup"),
|
||||
"akode-command-runner.exe" => Some("command_runner"),
|
||||
"akode.exe" => Some("codex"),
|
||||
"codex-desktop.exe" => Some("codex_desktop"),
|
||||
"chatgpt.exe" | "electron.exe" if trusted => Some("codex_desktop"),
|
||||
"rg.exe" if trusted => Some("ripgrep"),
|
||||
_ if package => Some("codex_desktop_package"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn defender_action(event: &str) -> (CheckStatus, &'static str) {
|
||||
let action = [
|
||||
"Action Name",
|
||||
"ActionName",
|
||||
"Action",
|
||||
"Action ID",
|
||||
"ActionID",
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|name| data_value(event, name))
|
||||
.or_else(|| element(event, "ActionName"))
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
match action.as_str() {
|
||||
"quarantine" | "2" => (CheckStatus::Fail, "quarantined"),
|
||||
"clean" | "remove" | "block" | "1" | "3" | "10" => (CheckStatus::Fail, "blocked"),
|
||||
"allow" | "ignore" | "none" | "no action" | "user defined" | "6" | "8" | "9" | "11" => {
|
||||
(CheckStatus::Ok, "allowed")
|
||||
}
|
||||
_ => (CheckStatus::Warning, "detected"),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify(channels: &[Option<Vec<Evidence>>]) -> DoctorCheck {
|
||||
let visible = channels.iter().any(Option::is_some);
|
||||
let mut status = if visible {
|
||||
CheckStatus::Ok
|
||||
} else {
|
||||
CheckStatus::Warning
|
||||
};
|
||||
let mut details = Vec::new();
|
||||
for (event_status, detail) in channels.iter().flatten().flatten() {
|
||||
status = status.max(*event_status);
|
||||
if details.len() < MAX_RENDERED_EVENTS {
|
||||
details.push(detail.clone());
|
||||
}
|
||||
}
|
||||
let summary = match (status, visible) {
|
||||
(CheckStatus::Ok, _) if channels.contains(&None) => "security event coverage is incomplete",
|
||||
(CheckStatus::Ok, _) => "no locally visible recent aKode security enforcement was found",
|
||||
(CheckStatus::Warning, false) => "security event channels could not be inspected",
|
||||
(CheckStatus::Warning, true) => "recent aKode security audit or detection requires review",
|
||||
(CheckStatus::Fail, _) => "endpoint security blocked or quarantined an aKode executable",
|
||||
};
|
||||
let mut check = desktop_check("desktop.security.enforcement", status, summary).details(details);
|
||||
if status != CheckStatus::Ok {
|
||||
check = check.remediation(
|
||||
"ask your organization's security administrator to review endpoint security events and the approved aKode application policy",
|
||||
);
|
||||
}
|
||||
check
|
||||
}
|
||||
|
||||
fn element<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
let body = xml.split_once(&format!("<{name}"))?.1.split_once('>')?.1;
|
||||
Some(body.split_once(&format!("</{name}>"))?.0.trim())
|
||||
}
|
||||
|
||||
fn data_value<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
|
||||
let body = xml
|
||||
.split_once(&format!("Name=\"{name}\""))?
|
||||
.1
|
||||
.split_once('>')?
|
||||
.1;
|
||||
Some(body.split_once("</Data>")?.0.trim())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_security_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,85 +0,0 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::CHANNELS;
|
||||
use super::CheckStatus;
|
||||
use super::MAX_RENDERED_EVENTS;
|
||||
use super::classify;
|
||||
use super::parse_events;
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[tokio::test]
|
||||
async fn an_unavailable_reader_is_not_reported_as_clean() {
|
||||
assert_eq!(super::collect().await.status, CheckStatus::Warning);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_source_distinguishes_audits_from_blocks() {
|
||||
for (channel, audit, block) in [
|
||||
(0, 1122, 1121),
|
||||
(0, 1125, 1126),
|
||||
(1, 8003, 8004),
|
||||
(2, 8021, 8022),
|
||||
(3, 8006, 8007),
|
||||
(4, 3076, 3077),
|
||||
] {
|
||||
for (id, expected) in [(audit, CheckStatus::Warning), (block, CheckStatus::Fail)] {
|
||||
let events = parse_events(&fixture(id, "akode.exe", &[]), CHANNELS[channel]);
|
||||
assert_eq!(events[0].0, expected, "misclassified event {id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defender_distinguishes_detection_and_remediation() {
|
||||
for (id, action, expected) in [
|
||||
(1116, "", CheckStatus::Warning),
|
||||
(1117, "Allow", CheckStatus::Ok),
|
||||
(1117, "Quarantine", CheckStatus::Fail),
|
||||
(1117, "Remove", CheckStatus::Fail),
|
||||
] {
|
||||
let events = parse_events(
|
||||
&fixture(id, "akode.exe", &[("Action Name", action)]),
|
||||
CHANNELS[0],
|
||||
);
|
||||
assert_eq!(classify(&[Some(events)]).status, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_trusted_codex_executables_are_reported() {
|
||||
for (path, expected) in [
|
||||
("akode.exe", true),
|
||||
(r"OpenAI.Codex_2p2nqsd0c76g0\ChatGPT.exe", true),
|
||||
("evil-codex.exe", false),
|
||||
(r"C:\Other\ChatGPT.exe", false),
|
||||
(r"OpenAI.CodexEvil_1\ChatGPT.exe", false),
|
||||
] {
|
||||
let events = parse_events(&fixture(/*id*/ 1121, path, &[]), CHANNELS[0]);
|
||||
assert_eq!(!events.is_empty(), expected, "misclassified {path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evidence_is_bounded_redacted_and_correctly_classified() {
|
||||
assert_eq!(classify(&[None]).status, CheckStatus::Warning);
|
||||
assert_eq!(classify(&[Some(Vec::new()), None]).status, CheckStatus::Ok);
|
||||
let audits = fixture(/*id*/ 1122, "akode.exe", &[]).repeat(MAX_RENDERED_EVENTS);
|
||||
let secret = "private-customer-secret";
|
||||
let block = fixture(/*id*/ 1121, "akode.exe", &[("User", secret)]);
|
||||
let events = parse_events(&format!("{audits}{block}"), CHANNELS[0]);
|
||||
let check = classify(&[Some(events)]);
|
||||
assert_eq!(check.id, "desktop.security.enforcement");
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
assert_eq!(check.details.len(), MAX_RENDERED_EVENTS);
|
||||
assert!(!serde_json::to_string(&check).unwrap().contains(secret));
|
||||
}
|
||||
|
||||
fn fixture(id: u32, path: &str, fields: &[(&str, &str)]) -> String {
|
||||
let data = fields
|
||||
.iter()
|
||||
.map(|(name, value)| format!("<Data Name=\"{name}\">{value}</Data>"))
|
||||
.collect::<String>();
|
||||
format!(
|
||||
"<Event><System><EventID>{id}</EventID><TimeCreated SystemTime=\"2026-01-01T00:00:00Z\"/></System><EventData><Data Name=\"Path\">{path}</Data>{data}</EventData></Event>"
|
||||
)
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::CheckStatus;
|
||||
use super::desktop::inspect_desktop_session;
|
||||
|
||||
const CURRENT_SESSION: &str = "12345678-1234-1234-1234-123456789abc";
|
||||
const CURRENT_PROCESS: u32 = 12345;
|
||||
|
||||
#[test]
|
||||
fn current_desktop_session_reports_the_latest_local_handshake() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
write_log(
|
||||
directory.path(),
|
||||
concat!(
|
||||
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
|
||||
"2026-08-07T12:01:00.000Z info [AppServerConnection] Starting app-server connection hostId=local transport=websocket\n",
|
||||
"2026-08-07T12:02:00.000Z info [AppServerConnection] initialize_handshake_result outcome=success transportKind=websocket\n",
|
||||
"2026-08-07T12:03:00.000Z info [AppServerConnection] app_server_connection.state_changed hostId=remote transport=websocket\n",
|
||||
"2026-08-07T12:04:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=websocket\n",
|
||||
),
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |pid| pid == CURRENT_PROCESS);
|
||||
|
||||
assert!(running);
|
||||
assert_eq!(check.id, "desktop.app_server.handshake");
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(
|
||||
check.summary,
|
||||
"the desktop app-server initialized successfully"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_handshake_does_not_expose_sensitive_log_fields() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
write_log(
|
||||
directory.path(),
|
||||
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result errorMessage=\"desktop-secret outcome=success\" outcome=failure transportKind=stdio\n",
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
|
||||
|
||||
assert!(running);
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
assert_eq!(check.summary, "the desktop app-server failed to initialize");
|
||||
assert!(
|
||||
!serde_json::to_string(&check)
|
||||
.unwrap()
|
||||
.contains("desktop-secret")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_failure_in_the_middle_of_a_log_segment_is_detected() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
let padding = "x".repeat(96 * 1024);
|
||||
write_log(
|
||||
directory.path(),
|
||||
&format!(
|
||||
"{padding}\n2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n{padding}"
|
||||
),
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |_| true);
|
||||
|
||||
assert!(running);
|
||||
assert_eq!(check.status, CheckStatus::Fail);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_desktop_does_not_report_a_failure() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory should be created");
|
||||
write_log(
|
||||
directory.path(),
|
||||
"2026-08-07T12:00:00.000Z error [AppServerConnection] initialize_handshake_result outcome=failure transportKind=stdio\n",
|
||||
);
|
||||
|
||||
let (running, check) = inspect_desktop_session(directory.path(), |_| false);
|
||||
|
||||
assert!(!running);
|
||||
assert_eq!(check.status, CheckStatus::Ok);
|
||||
assert_eq!(check.summary, "the desktop application is not running");
|
||||
}
|
||||
|
||||
fn write_log(directory: &Path, contents: &str) {
|
||||
fs::write(
|
||||
directory.join(format!(
|
||||
"codex-desktop-{CURRENT_SESSION}-{CURRENT_PROCESS}-t0-i0-120000-0.log"
|
||||
)),
|
||||
contents,
|
||||
)
|
||||
.expect("desktop log fixture should be created");
|
||||
}
|
||||
@@ -34,10 +34,6 @@ const GROUPS: &[OutputGroup] = &[
|
||||
title: "Configuration",
|
||||
keys: &["config", "auth", "mcp", "sandbox"],
|
||||
},
|
||||
OutputGroup {
|
||||
title: "Desktop App",
|
||||
keys: &["desktop"],
|
||||
},
|
||||
OutputGroup {
|
||||
title: "Updates",
|
||||
keys: &["updates"],
|
||||
@@ -504,9 +500,6 @@ fn notes_for_report(report: &DoctorReport) -> Vec<DoctorNote> {
|
||||
update_note(check, report)
|
||||
.into_iter()
|
||||
.for_each(|note| notes.push(note));
|
||||
desktop_update_note(check)
|
||||
.into_iter()
|
||||
.for_each(|note| notes.push(note));
|
||||
}
|
||||
if let Some(check) = find_check(report, "state") {
|
||||
rollout_note(check)
|
||||
@@ -556,21 +549,6 @@ fn update_note(check: &DoctorCheck, report: &DoctorReport) -> Option<DoctorNote>
|
||||
})
|
||||
}
|
||||
|
||||
fn desktop_update_note(check: &DoctorCheck) -> Option<DoctorNote> {
|
||||
let status = detail::detail_value(check, "desktop update status")?;
|
||||
let build = detail::detail_value(check, "desktop latest build")?;
|
||||
let summary = match status.as_str() {
|
||||
"ready to install" => format!("build {build} available (ready to install)"),
|
||||
"available" => format!("build {build} available"),
|
||||
_ => return None,
|
||||
};
|
||||
Some(DoctorNote {
|
||||
status: DisplayStatus::Update,
|
||||
name: "desktop".to_string(),
|
||||
summary,
|
||||
})
|
||||
}
|
||||
|
||||
fn rollout_note(check: &DoctorCheck) -> Option<DoctorNote> {
|
||||
let active = detail::detail_value(check, "active rollout files")?;
|
||||
let (files, bytes) = detail::rollout_files_and_bytes(&active)?;
|
||||
@@ -1453,40 +1431,8 @@ Background Server
|
||||
.iter_mut()
|
||||
.find(|detail| detail.starts_with("exclusion targets: "))
|
||||
.expect("endpoint security check should include exclusion targets");
|
||||
*targets = "exclusion targets: verified Codex app and required helpers".into();
|
||||
*targets = "exclusion targets: verified akode binary and required helpers".into();
|
||||
report.checks.push(security);
|
||||
report.checks.extend([
|
||||
DoctorCheck::new(
|
||||
"desktop.app.version",
|
||||
"desktop",
|
||||
CheckStatus::Ok,
|
||||
"the desktop application is installed",
|
||||
)
|
||||
.detail("version: 1.2.3")
|
||||
.detail("running: true")
|
||||
.detail("log directory: $HOME/Library/Logs/com.openai.codex"),
|
||||
DoctorCheck::new(
|
||||
"desktop.app_server.handshake",
|
||||
"desktop",
|
||||
CheckStatus::Ok,
|
||||
"the desktop app-server initialized successfully",
|
||||
),
|
||||
]);
|
||||
let update = report
|
||||
.checks
|
||||
.iter_mut()
|
||||
.find(|check| check.category == "updates")
|
||||
.unwrap();
|
||||
for (status, expected) in [
|
||||
("available", "build 123 available"),
|
||||
("ready to install", "build 123 available (ready to install)"),
|
||||
] {
|
||||
update.details = vec![
|
||||
format!("desktop update status: {status}"),
|
||||
"desktop latest build: 123".to_string(),
|
||||
];
|
||||
assert_eq!(desktop_update_note(update).unwrap().summary, expected);
|
||||
}
|
||||
insta::assert_snapshot!(
|
||||
"doctor_human_report_environment_rows",
|
||||
render_human_report(&report, detailed_no_color_unicode_options())
|
||||
|
||||
@@ -66,11 +66,11 @@ pub(super) fn endpoint_check(inspection: EndpointInspection) -> DoctorCheck {
|
||||
}
|
||||
|
||||
let targets = if cfg!(target_os = "windows") {
|
||||
"signed Codex app; codex.exe; akode-windows-sandbox-setup.exe; akode-command-runner.exe; akode-code-mode-host.exe"
|
||||
"akode.exe; akode-windows-sandbox-setup.exe; akode-command-runner.exe; akode-code-mode-host.exe"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"signing team 2DC432GLL2 plus the installed Codex app identity, signed codex agent, and required helpers"
|
||||
"the akode binary and required helpers"
|
||||
} else {
|
||||
"verified Codex app, codex agent, and required helpers"
|
||||
"verified akode binary and required helpers"
|
||||
};
|
||||
let mut check = DoctorCheck::new(
|
||||
"security.endpoint",
|
||||
|
||||
@@ -5,7 +5,6 @@ expression: "render_human_report(&report, detailed_no_color_unicode_options())"
|
||||
aKode Doctor v0.0.0
|
||||
|
||||
Notes
|
||||
↑ desktop build 123 available (ready to install)
|
||||
⚠ terminal narrow terminal
|
||||
✗ auth token expired - Run `akode login`.
|
||||
✗ network provider is unreachable - A macOS system proxy is configured but unused. If your organization requires it, ask your administrator whether to enable the experimental System proxy setting in `/experimental` or with `akode features enable respect_system_proxy`. Restart aKode after changing this setting.
|
||||
@@ -26,7 +25,7 @@ Environment
|
||||
✓ disk sufficient free disk space (42.0 GiB)
|
||||
⚠ security Microsoft Defender can interfere with aKode. Verify aKode exclusions.
|
||||
endpoint products Microsoft Defender
|
||||
exclusion targets verified Codex app and required helpers
|
||||
exclusion targets verified akode binary and required helpers
|
||||
▸ aKode exclusions not verified (expected aKode application and helper exclusions)
|
||||
→ Microsoft Defender: Add a certificate or executable-path exclusion for aKode and its helpers. If Attack Surface Reduction blocks aKode, add a rule exclusion. If Controlled Folder Access blocks aKode, allow the app.
|
||||
✓ runtime running local build on darwin-arm64
|
||||
@@ -52,17 +51,8 @@ Configuration
|
||||
✗ auth token expired — Run `akode login`.
|
||||
OPENAI_API_KEY present
|
||||
|
||||
Desktop App
|
||||
✓ desktop the desktop application is installed
|
||||
version 1.2.3
|
||||
running true
|
||||
log directory $HOME/Library/Logs/com.openai.codex
|
||||
✓ desktop the desktop app-server initialized successfully
|
||||
|
||||
Updates
|
||||
✓ updates update configuration is locally consistent
|
||||
desktop update status ready to install
|
||||
desktop latest build 123
|
||||
|
||||
Connectivity
|
||||
✓ network network environment readable
|
||||
@@ -74,7 +64,7 @@ Background Server
|
||||
✓ app-server background server is not running
|
||||
|
||||
─────────────────────────────────────────────────────────────
|
||||
16 ok · 6 notes · 3 warn · 2 fail failed
|
||||
14 ok · 5 notes · 3 warn · 2 fail failed
|
||||
|
||||
--summary compact output --all expand truncated lists
|
||||
--json redacted report
|
||||
|
||||
@@ -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(),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,14 +721,14 @@ 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"))?;
|
||||
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())
|
||||
@@ -738,94 +738,9 @@ fn run_update_action(
|
||||
"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.");
|
||||
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]
|
||||
|
||||
90
akode-rs/cli/src/update_cmd.rs
Normal file
90
akode-rs/cli/src/update_cmd.rs
Normal 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 })
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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": [
|
||||
{
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -1556,9 +1556,6 @@ impl App {
|
||||
AppEvent::OpenUrlInBrowser { url } => {
|
||||
self.open_url_in_browser(url);
|
||||
}
|
||||
AppEvent::OpenDesktopThread { thread_id } => {
|
||||
self.open_desktop_thread(thread_id);
|
||||
}
|
||||
AppEvent::PetSelected { pet_id } => {
|
||||
self.handle_pet_selected(tui, pet_id);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Terminal history, desktop handoff, and clear-screen UI helpers for the TUI app.
|
||||
//! Terminal history and clear-screen UI helpers for the TUI app.
|
||||
//!
|
||||
//! This module owns rendering the fresh session header, clearing inline or alternate-screen UI
|
||||
//! state, and resetting transcript-related app state after `/clear` or Ctrl-L. Owned-screen sessions
|
||||
@@ -7,8 +7,6 @@
|
||||
use super::*;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
|
||||
const DESKTOP_THREAD_OPENED_MESSAGE: &str = "Opened this session in the Desktop app.";
|
||||
|
||||
/// Lines of the most recently committed history cell, kept so reflow and restore can be verified.
|
||||
pub(super) struct RenderedHistoryTail {
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
@@ -119,20 +117,6 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open_desktop_thread(&mut self, thread_id: ThreadId) {
|
||||
let url = format!("codex://threads/{thread_id}");
|
||||
if let Err(err) = open_desktop_thread_url(&url) {
|
||||
self.chat_widget
|
||||
.add_error_message(desktop_thread_open_error_message(&err));
|
||||
return;
|
||||
}
|
||||
|
||||
self.chat_widget.add_info_message(
|
||||
DESKTOP_THREAD_OPENED_MESSAGE.to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn clear_ui_header_lines_with_version(
|
||||
&self,
|
||||
width: u16,
|
||||
@@ -259,107 +243,6 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn desktop_thread_open_error_message(err: &str) -> String {
|
||||
format!(
|
||||
"Failed to open this session in the Desktop app: {err}. Install or launch the Desktop app and try again."
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn open_desktop_thread_url(url: &str) -> Result<(), String> {
|
||||
let status = std::process::Command::new("open")
|
||||
.arg(url)
|
||||
.status()
|
||||
.map_err(|err| format!("failed to invoke `open`: {err}"))?;
|
||||
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("`open {url}` exited with {status}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn open_desktop_thread_url(url: &str) -> Result<(), String> {
|
||||
let script = windows_desktop_app_launch_script(url);
|
||||
let output = std::process::Command::new("powershell.exe")
|
||||
.arg("-NoProfile")
|
||||
.arg("-Command")
|
||||
.arg(&script)
|
||||
.output()
|
||||
.map_err(|err| format!("failed to launch the Desktop app through PowerShell: {err}"))?;
|
||||
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
if stderr.is_empty() {
|
||||
Err(format!(
|
||||
"failed to launch the Desktop app through PowerShell with {}",
|
||||
output.status
|
||||
))
|
||||
} else {
|
||||
Err(stderr)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_desktop_app_launch_script(url: &str) -> String {
|
||||
let url = powershell_single_quoted_string(url);
|
||||
format!(
|
||||
r#"
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$url = {url}
|
||||
|
||||
$package = Get-AppxPackage -Name OpenAI.Codex -ErrorAction SilentlyContinue
|
||||
if ($null -eq $package) {{
|
||||
Write-Error 'Desktop app package is not installed'
|
||||
exit 1
|
||||
}}
|
||||
|
||||
$manifest = Get-AppxPackageManifest -Package $package.PackageFullName
|
||||
$application = $manifest.Package.Applications.Application |
|
||||
Where-Object {{
|
||||
@($_.Extensions.Extension) | Where-Object {{
|
||||
$_.Category -eq 'windows.protocol' -and $_.Protocol.Name -eq 'codex'
|
||||
}}
|
||||
}} |
|
||||
Select-Object -First 1
|
||||
if ($null -eq $application -or [string]::IsNullOrWhiteSpace($application.Executable)) {{
|
||||
Write-Error 'Desktop app package does not declare a codex protocol executable'
|
||||
exit 1
|
||||
}}
|
||||
|
||||
# Launch the package-declared protocol executable rather than an internal Electron shim.
|
||||
# Windows can deny direct starts of internal executables under WindowsApps.
|
||||
$exe = Join-Path $package.InstallLocation $application.Executable
|
||||
$appDir = Split-Path -Parent $exe
|
||||
$app = Join-Path $appDir 'resources\app.asar'
|
||||
if (-not (Test-Path $exe)) {{
|
||||
Write-Error "Desktop app executable not found at $exe"
|
||||
exit 1
|
||||
}}
|
||||
if (-not (Test-Path $app)) {{
|
||||
Write-Error "Desktop app bundle not found at $app"
|
||||
exit 1
|
||||
}}
|
||||
|
||||
Start-Process -FilePath $exe -WorkingDirectory $appDir -ArgumentList @('resources\app.asar', $url)
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn powershell_single_quoted_string(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn open_desktop_thread_url(_url: &str) -> Result<(), String> {
|
||||
Err("The Desktop app is only available on macOS and Windows".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "history_ui_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -1,38 +1,11 @@
|
||||
//! Desktop handoff output and clear-screen history reset behavior.
|
||||
//! Clear-screen history reset behavior.
|
||||
|
||||
use super::*;
|
||||
use crate::app::tests::make_test_app_with_channels;
|
||||
use crate::history_cell;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::history_cell::PlainHistoryCell;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn desktop_thread_opened_history_snapshot() {
|
||||
let cell = history_cell::new_info_event(
|
||||
DESKTOP_THREAD_OPENED_MESSAGE.to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
|
||||
insta::assert_snapshot!("desktop_thread_opened_history", render_cell(&cell));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_thread_open_error_history_snapshot() {
|
||||
let cell = history_cell::new_error_event(desktop_thread_open_error_message("launch failed"));
|
||||
|
||||
insta::assert_snapshot!("desktop_thread_open_error_history", render_cell(&cell));
|
||||
}
|
||||
|
||||
fn render_cell(cell: &impl HistoryCell) -> String {
|
||||
let lines = cell.display_lines(/*width*/ 80);
|
||||
lines
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn viewed_image_links_follow_workspace_locality() -> Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
source: tui/src/app/history_ui_tests.rs
|
||||
expression: render_cell(&cell)
|
||||
---
|
||||
■ Failed to open this session in the Desktop app: launch failed. Install or launch the Desktop app and try again.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
source: tui/src/app/history_ui_tests.rs
|
||||
expression: render_cell(&cell)
|
||||
---
|
||||
• Opened this session in the Desktop app.
|
||||
@@ -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 =
|
||||
|
||||
@@ -847,11 +847,6 @@ pub(crate) enum AppEvent {
|
||||
url: String,
|
||||
},
|
||||
|
||||
/// Open the current thread in Codex Desktop.
|
||||
OpenDesktopThread {
|
||||
thread_id: ThreadId,
|
||||
},
|
||||
|
||||
/// Persist a pet selection and reload the ambient pet.
|
||||
PetSelected {
|
||||
pet_id: String,
|
||||
|
||||
@@ -526,7 +526,6 @@ fn parent_owned_command_is_allowed(command: SlashCommand, args: &str) -> bool {
|
||||
| SlashCommand::New
|
||||
| SlashCommand::Clear
|
||||
| SlashCommand::Resume
|
||||
| SlashCommand::App
|
||||
| SlashCommand::Side
|
||||
| SlashCommand::Btw
|
||||
| SlashCommand::Agents
|
||||
|
||||
@@ -510,25 +510,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
#[test]
|
||||
fn app_command_popup_snapshot() {
|
||||
let mut popup = CommandPopup::new(CommandPopupFlags::default(), Vec::new());
|
||||
popup.on_composer_text_change("/app".to_string());
|
||||
|
||||
let width = 72;
|
||||
let area = Rect::new(
|
||||
/*x*/ 0,
|
||||
/*y*/ 0,
|
||||
width,
|
||||
popup.calculate_required_height(width),
|
||||
);
|
||||
let mut buf = Buffer::empty(area);
|
||||
popup.render_ref(area, &mut buf);
|
||||
|
||||
insta::assert_snapshot!("command_popup_app", format!("{buf:?}"));
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
#[test]
|
||||
fn voice_command_popup_snapshot() {
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
---
|
||||
source: tui/src/bottom_pane/command_popup.rs
|
||||
expression: "format!(\"{buf:?}\")"
|
||||
---
|
||||
Buffer {
|
||||
area: Rect { x: 0, y: 0, width: 72, height: 2 },
|
||||
content: [
|
||||
"› /app continue this session in the Desktop app ",
|
||||
" /approve approve one retry of a recent auto-review denial ",
|
||||
],
|
||||
styles: [
|
||||
x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED,
|
||||
x: 12, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: REVERSED,
|
||||
x: 52, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD | REVERSED,
|
||||
x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 3, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
|
||||
x: 6, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
x: 12, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
|
||||
x: 60, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
|
||||
]
|
||||
}
|
||||
@@ -293,16 +293,6 @@ impl ChatWidget {
|
||||
SlashCommand::Worktree => {
|
||||
self.show_managed_worktree_picker();
|
||||
}
|
||||
SlashCommand::App => {
|
||||
let Some(thread_id) = self.thread_id else {
|
||||
self.add_error_message(
|
||||
"Session is still starting; try /app again in a moment.".to_string(),
|
||||
);
|
||||
return;
|
||||
};
|
||||
self.app_event_tx
|
||||
.send(AppEvent::OpenDesktopThread { thread_id });
|
||||
}
|
||||
SlashCommand::Init => {
|
||||
const INIT_PROMPT: &str = include_str!("../../assets/prompt_for_init_command.md");
|
||||
// The transcript and prompt history show what was typed; the model gets the
|
||||
@@ -1250,7 +1240,6 @@ impl ChatWidget {
|
||||
| SlashCommand::Raw
|
||||
| SlashCommand::Vim
|
||||
| SlashCommand::Diff
|
||||
| SlashCommand::App
|
||||
| SlashCommand::Rename
|
||||
| SlashCommand::Voice
|
||||
| SlashCommand::Recap
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/slash_commands.rs
|
||||
expression: "lines_to_single_string(&cells[0])"
|
||||
---
|
||||
■ Session is still starting; try /app again in a moment.
|
||||
@@ -3072,36 +3072,6 @@ async fn slash_fork_with_name_requests_named_fork() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slash_app_requests_desktop_handoff() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
let thread_id = ThreadId::new();
|
||||
chat.thread_id = Some(thread_id);
|
||||
|
||||
chat.dispatch_command(SlashCommand::App);
|
||||
|
||||
assert_matches!(
|
||||
rx.try_recv(),
|
||||
Ok(AppEvent::OpenDesktopThread {
|
||||
thread_id: actual_thread_id,
|
||||
}) if actual_thread_id == thread_id
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slash_app_without_thread_id_shows_starting_error() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
|
||||
chat.dispatch_command(SlashCommand::App);
|
||||
|
||||
let cells = drain_insert_history(&mut rx);
|
||||
assert_eq!(cells.len(), 1, "expected app startup error");
|
||||
assert_chatwidget_snapshot!(
|
||||
"slash_app_without_thread_id_shows_starting_error",
|
||||
lines_to_single_string(&cells[0])
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slash_pwd_and_cwd_alias_display_current_working_directory_from_composer() {
|
||||
let mut output = Vec::new();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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."
|
||||
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),
|
||||
),
|
||||
]
|
||||
} 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)
|
||||
}
|
||||
|
||||
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> {
|
||||
|
||||
@@ -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![
|
||||
|
||||
@@ -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 │
|
||||
╰─────────────────────────────────────────────────╯
|
||||
@@ -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 │
|
||||
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
|
||||
@@ -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 │
|
||||
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
|
||||
@@ -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]
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -35,7 +35,6 @@ pub enum SlashCommand {
|
||||
Resume,
|
||||
Fork,
|
||||
Worktree,
|
||||
App,
|
||||
Init,
|
||||
Compact,
|
||||
Config,
|
||||
@@ -104,7 +103,6 @@ impl SlashCommand {
|
||||
SlashCommand::Clear => "clear the terminal and start a new chat",
|
||||
SlashCommand::Fork => "fork the current chat",
|
||||
SlashCommand::Worktree => "start or continue a conversation in a new worktree",
|
||||
SlashCommand::App => "continue this session in the Desktop app",
|
||||
SlashCommand::Quit | SlashCommand::Exit => "exit aKode",
|
||||
SlashCommand::Copy => "copy the last response or part of it",
|
||||
SlashCommand::Export => "export the conversation as markdown",
|
||||
@@ -282,7 +280,6 @@ impl SlashCommand {
|
||||
| SlashCommand::DebugConfig
|
||||
| SlashCommand::Ps
|
||||
| SlashCommand::Stop
|
||||
| SlashCommand::App
|
||||
| SlashCommand::Goal
|
||||
| SlashCommand::Voice
|
||||
| SlashCommand::Mcp
|
||||
@@ -309,7 +306,6 @@ impl SlashCommand {
|
||||
fn is_visible(self) -> bool {
|
||||
match self {
|
||||
SlashCommand::Copy => !cfg!(target_os = "android"),
|
||||
SlashCommand::App => cfg!(any(target_os = "macos", target_os = "windows")),
|
||||
SlashCommand::Voice => true,
|
||||
SlashCommand::Rollout | SlashCommand::TestApproval => cfg!(debug_assertions),
|
||||
_ => true,
|
||||
@@ -357,7 +353,6 @@ mod tests {
|
||||
assert!(SlashCommand::Raw.available_during_task());
|
||||
assert!(SlashCommand::Raw.available_in_side_conversation());
|
||||
assert!(SlashCommand::Raw.supports_inline_args());
|
||||
assert!(SlashCommand::App.available_during_task());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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.
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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"))
|
||||
);
|
||||
}
|
||||
6
akode-rs/update/BUILD.bazel
Normal file
6
akode-rs/update/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "update",
|
||||
crate_name = "akode_update",
|
||||
)
|
||||
31
akode-rs/update/Cargo.toml
Normal file
31
akode-rs/update/Cargo.toml
Normal 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
601
akode-rs/update/src/lib.rs
Normal 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;
|
||||
472
akode-rs/update/src/lib_tests.rs
Normal file
472
akode-rs/update/src/lib_tests.rs
Normal 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());
|
||||
}
|
||||
Reference in New Issue
Block a user