Rimosso il sistema di aggiornamento upstream: nessun update verso terzi (B)
Parte "sicurezza" di 9494b768 (senza il nuovo `akode update`, che e' una funzione di aKode):
- via il sottocomando `update`, il prompt di aggiornamento, il riquadro "Update available",
la cache delle versioni e le azioni npm/pnpm/bun/brew/installer che eseguivano
curl https://chatgpt.com/codex/install.sh (e il .ps1) o installavano @openai/codex;
- UpdateAction resta con la sola sostituzione del pacchetto del daemon locale;
- test rimossi solo perche' il codice che verificavano non c'e' piu'
(risoluzione Windows del comando di update, parsing di `update`, update dei pacchetti
fuori dal progetto).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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()?;
|
||||
|
||||
@@ -60,7 +60,6 @@ mod sandbox_setup;
|
||||
mod sandbox_uninstall;
|
||||
mod state_db_recovery;
|
||||
#[cfg(not(windows))]
|
||||
mod wsl_paths;
|
||||
|
||||
use crate::mcp_cmd::McpCli;
|
||||
use crate::plugin_cmd::PluginCli;
|
||||
@@ -155,9 +154,6 @@ enum Subcommand {
|
||||
/// Generate shell completion scripts.
|
||||
Completion(CompletionCommand),
|
||||
|
||||
/// Update aKode to the latest version.
|
||||
Update,
|
||||
|
||||
/// Diagnose local aKode installation, config, auth, and runtime health.
|
||||
Doctor(DoctorCommand),
|
||||
|
||||
@@ -714,106 +710,21 @@ fn run_update_action(
|
||||
action: UpdateAction,
|
||||
cli_executable: Option<&std::path::Path>,
|
||||
) -> anyhow::Result<()> {
|
||||
if let UpdateAction::Daemon(source) = action {
|
||||
let executable = cli_executable
|
||||
.ok_or_else(|| anyhow::anyhow!("Cannot locate the launching aKode CLI"))?;
|
||||
println!("Updating the local background server...");
|
||||
let status = std::process::Command::new(executable)
|
||||
.args(source.command_args())
|
||||
.status()?;
|
||||
anyhow::ensure!(
|
||||
status.success(),
|
||||
"Daemon update failed with status {status}"
|
||||
);
|
||||
println!("Relaunch aKode to reconnect.");
|
||||
return Ok(());
|
||||
}
|
||||
println!();
|
||||
let cmd_str = action.command_str();
|
||||
println!("Updating aKode via `{cmd_str}`...");
|
||||
let status = {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let (cmd, args) = action.command_args();
|
||||
let cmd = if action == UpdateAction::StandaloneWindows {
|
||||
// These args contain PowerShell metacharacters, so do not let
|
||||
// PATHEXT select a batch shim for this action.
|
||||
"powershell.exe"
|
||||
} else {
|
||||
cmd
|
||||
};
|
||||
let path_env =
|
||||
std::env::var_os("PATH").ok_or_else(|| anyhow::anyhow!("PATH is not set"))?;
|
||||
let command_path = resolve_windows_update_command_from_path(cmd, &path_env)?;
|
||||
// Do not let a project-local command or package-manager config
|
||||
// influence the updater after the user accepts the update prompt.
|
||||
let update_cwd = tempfile::tempdir()?;
|
||||
// Resolve through PATH without consulting the project cwd. When
|
||||
// this returns a .cmd/.bat shim, std::process::Command routes the
|
||||
// absolute path through the system command processor.
|
||||
std::process::Command::new(command_path)
|
||||
.args(args)
|
||||
.current_dir(update_cwd.path())
|
||||
.status()?
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let (cmd, args) = action.command_args();
|
||||
let command_path = crate::wsl_paths::normalize_for_wsl(cmd);
|
||||
let normalized_args: Vec<String> = args
|
||||
.iter()
|
||||
.map(crate::wsl_paths::normalize_for_wsl)
|
||||
.collect();
|
||||
std::process::Command::new(&command_path)
|
||||
.args(&normalized_args)
|
||||
// Package managers search parent directories for project config and hooks.
|
||||
.current_dir("/")
|
||||
.status()?
|
||||
}
|
||||
};
|
||||
if !status.success() {
|
||||
anyhow::bail!("`{cmd_str}` failed with status {status}");
|
||||
}
|
||||
println!("\n🎉 Update ran successfully! Please restart aKode.");
|
||||
let UpdateAction::Daemon(source) = action;
|
||||
let executable =
|
||||
cli_executable.ok_or_else(|| anyhow::anyhow!("Cannot locate the launching aKode CLI"))?;
|
||||
println!("Updating the local background server...");
|
||||
let status = std::process::Command::new(executable)
|
||||
.args(source.command_args())
|
||||
.status()?;
|
||||
anyhow::ensure!(
|
||||
status.success(),
|
||||
"Daemon update failed with status {status}"
|
||||
);
|
||||
println!("Relaunch aKode to reconnect.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn resolve_windows_update_command_from_path(
|
||||
command: &str,
|
||||
path_env: &std::ffi::OsStr,
|
||||
) -> anyhow::Result<PathBuf> {
|
||||
let path_env =
|
||||
std::env::join_paths(std::env::split_paths(path_env).filter(|path| path.is_absolute()))?;
|
||||
if path_env.is_empty() {
|
||||
anyhow::bail!(
|
||||
"Could not find an absolute update command `{command}` on PATH. Please update manually: https://developers.openai.com/akode/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/akode/cli/"
|
||||
);
|
||||
};
|
||||
run_update_action(action, /*cli_executable*/ None)
|
||||
}
|
||||
}
|
||||
|
||||
fn run_execpolicycheck(cmd: ExecPolicyCheckCommand) -> anyhow::Result<()> {
|
||||
cmd.run()
|
||||
}
|
||||
@@ -1550,14 +1461,6 @@ async fn dispatch_cli(
|
||||
)?;
|
||||
print_completion(completion_cli);
|
||||
}
|
||||
Some(Subcommand::Update) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
"update",
|
||||
)?;
|
||||
run_update_command()?;
|
||||
}
|
||||
Some(Subcommand::Doctor(doctor_cli)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
@@ -2166,7 +2069,6 @@ fn unsupported_subcommand_name_for_strict_config(
|
||||
Some(Subcommand::Login(_)) => Some("login"),
|
||||
Some(Subcommand::Logout(_)) => Some("logout"),
|
||||
Some(Subcommand::Completion(_)) => Some("completion"),
|
||||
Some(Subcommand::Update) => Some("update"),
|
||||
Some(Subcommand::Sandbox(_)) => Some("sandbox"),
|
||||
Some(Subcommand::Debug(_)) => Some("debug"),
|
||||
Some(Subcommand::Execpolicy(_)) => Some("execpolicy"),
|
||||
@@ -2588,52 +2490,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/akode/cli/"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn updater_http_client_factory_honors_respect_system_proxy() {
|
||||
let akode_home = tempfile::tempdir().expect("temporary aKode home");
|
||||
@@ -3373,12 +3229,6 @@ enabled = true
|
||||
assert!(matches!(cli.subcommand, Some(Subcommand::Plugin(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_parses_as_update_subcommand() {
|
||||
let cli = MultitoolCli::try_parse_from(["akode", "update"]).expect("parse");
|
||||
assert!(matches!(cli.subcommand, Some(Subcommand::Update)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_merges_scoped_tui_flags() {
|
||||
let (target, interactive, remote) = finalize_archive_from_args(
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -46,8 +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;
|
||||
use crate::key_hint::KeyBindingListExt;
|
||||
|
||||
@@ -121,13 +121,6 @@ async fn non_startup_history_dismisses_logo_until_a_new_thread() -> Result<()> {
|
||||
},
|
||||
)),
|
||||
);
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::UpdateAvailableHistoryCell::new(
|
||||
"99.0.0".into(),
|
||||
/*update_action*/ None,
|
||||
)),
|
||||
);
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::SessionNoticeCell(
|
||||
|
||||
@@ -964,9 +964,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);
|
||||
let mut app = Self {
|
||||
@@ -1243,25 +1240,6 @@ 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)]
|
||||
let pre_loop_exit_reason: Option<ExitReason> = None;
|
||||
|
||||
let mut backends =
|
||||
|
||||
@@ -18,9 +18,6 @@ pub(crate) fn is_startup_cell(cell: &dyn HistoryCell) -> bool {
|
||||
|| cell.as_any().is::<history_cell::SessionInfoCell>()
|
||||
|| cell.as_any().is::<history_cell::StartupWarningsCell>()
|
||||
|| cell.as_any().is::<history_cell::DeprecationNoticeCell>()
|
||||
|| cell
|
||||
.as_any()
|
||||
.is::<history_cell::UpdateAvailableHistoryCell>()
|
||||
|| cell.as_any().is::<history_cell::SessionNoticeCell>()
|
||||
|| cell
|
||||
.as_any()
|
||||
|
||||
@@ -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,90 +9,6 @@ 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))]
|
||||
#[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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for UpdateAvailableHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
use ratatui_macros::line;
|
||||
use ratatui_macros::text;
|
||||
let update_instruction = if let Some(update_action) = self.update_action {
|
||||
line![
|
||||
"Run ",
|
||||
update_action.command_str().fg(accent_color()),
|
||||
" to update."
|
||||
]
|
||||
} else {
|
||||
line![
|
||||
"See ",
|
||||
"https://github.com/openai/codex"
|
||||
.fg(accent_color())
|
||||
.underlined(),
|
||||
" for installation options."
|
||||
]
|
||||
};
|
||||
|
||||
let content = text![
|
||||
line![
|
||||
"✨\u{200A}".bold().fg(accent_color()),
|
||||
"Update available!".bold().fg(accent_color()),
|
||||
" ",
|
||||
format!("{AKODE_CLI_VERSION} -> {}", self.latest_version).bold(),
|
||||
],
|
||||
update_instruction,
|
||||
"",
|
||||
"See full release notes:",
|
||||
"https://github.com/openai/codex/releases/latest"
|
||||
.fg(accent_color())
|
||||
.underlined(),
|
||||
];
|
||||
|
||||
let inner_width = content
|
||||
.width()
|
||||
.min(usize::from(width.saturating_sub(4)))
|
||||
.max(1);
|
||||
let lines = adaptive_wrap_lines(content.lines, RtOptions::new(inner_width));
|
||||
with_border_with_inner_width(lines, inner_width)
|
||||
}
|
||||
|
||||
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"),
|
||||
]
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
crate::terminal_hyperlinks::annotate_web_urls(self.display_lines(width))
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
}
|
||||
}
|
||||
pub(crate) fn new_warning_event(message: String) -> WarningHistoryCell {
|
||||
let style = crate::style::status_style(crate::style::StatusTone::Attention);
|
||||
WarningHistoryCell {
|
||||
|
||||
@@ -6,40 +6,6 @@ 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.0.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.0.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.0.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 │
|
||||
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
|
||||
@@ -1377,33 +1377,6 @@ fn web_search_history_cell_snapshot() {
|
||||
insta::assert_snapshot!(rendered);
|
||||
}
|
||||
|
||||
#[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");
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_search_history_cell_without_detail_snapshot() {
|
||||
let cell = new_web_search_call("call-1".to_string(), String::new(), WebSearchAction::Other);
|
||||
|
||||
@@ -237,13 +237,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;
|
||||
@@ -1205,30 +1199,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);
|
||||
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
---
|
||||
source: tui/src/update_prompt.rs
|
||||
expression: rendered
|
||||
---
|
||||
|
||||
Update available · 0.0.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.0.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"))
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user