aKode: comando akode update e avviso di nuova versione

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

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

View File

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

View File

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

View File

@@ -18,6 +18,39 @@ use crate::session_start::complete_session_start;
use crate::unarchive_prompt::run_unarchive_prompt;
use color_eyre::eyre::ContextCompat;
/// Checks the configured release repository in the background (at most once per day) and
/// announces a newer aKode release with a one-line notice. Never blocks startup and never
/// installs anything.
fn spawn_startup_update_check(app_event_tx: &AppEventSender, config: &Config) {
if !config.update_check_on_startup {
return;
}
let app_event_tx = app_event_tx.clone();
let akode_home = config.codex_home.to_path_buf();
let repo_url = config.update_repo_url.clone();
tokio::spawn(async move {
let Ok(client) = akode_update::http_client(akode_update::STARTUP_CHECK_TIMEOUT) else {
return;
};
let check = akode_update::StartupCheck {
akode_home: &akode_home,
repo_url: &repo_url,
enabled: true,
current_version: env!("CARGO_PKG_VERSION"),
};
let latest = tokio::time::timeout(
akode_update::STARTUP_CHECK_TIMEOUT,
check.run(&client, chrono::Utc::now()),
)
.await;
if let Ok(Some(latest)) = latest {
app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
UpdateAvailableHistoryCell::new(latest.to_string()),
)));
}
});
}
fn spawn_startup_thread_start(
app_server: &AppServerSession,
local_settings: crate::local_settings::LocalSettings,
@@ -964,8 +997,6 @@ See the aKode keymap documentation for supported actions and examples."
)
});
let runtime_keymap = startup_try!(runtime_keymap);
#[cfg(not(debug_assertions))]
let upgrade_version = crate::updates::get_upgrade_version(&config);
let agents_overview =
agents_overview::AgentsOverviewState::new(local_settings.tui.agents_overview_grouping);
@@ -1243,25 +1274,7 @@ See the aKode keymap documentation for supported actions and examples."
let mut waiting_for_initial_session_configured = wait_for_initial_session_configured;
let mut waiting_for_initial_session_header = true;
#[cfg(not(debug_assertions))]
let pre_loop_exit_reason = if let Some(latest_version) = upgrade_version {
let control = Box::pin(app.handle_event(
tui,
&mut app_server,
AppEvent::InsertHistoryCell(Box::new(UpdateAvailableHistoryCell::new(
latest_version,
crate::update_action::get_update_action(),
))),
))
.await;
match startup_try!(control) {
AppRunControl::Continue => None,
AppRunControl::Exit(exit_reason) => Some(exit_reason),
}
} else {
None
};
#[cfg(debug_assertions)]
spawn_startup_update_check(&app.app_event_tx, &app.config);
let pre_loop_exit_reason: Option<ExitReason> = None;
let mut backends =

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1378,30 +1378,17 @@ fn web_search_history_cell_snapshot() {
}
#[test]
fn standalone_unix_update_available_history_cell_snapshot() {
let cell =
UpdateAvailableHistoryCell::new("9.9.9".to_string(), Some(UpdateAction::StandaloneUnix));
let rendered = render_lines(&cell.display_lines(/*width*/ 110)).join("\n");
fn update_available_history_cell_is_one_italian_line() {
let cell = UpdateAvailableHistoryCell::new("9.9.9".to_string());
insta::assert_snapshot!(rendered);
}
#[test]
fn standalone_windows_update_available_history_cell_snapshot() {
let cell =
UpdateAvailableHistoryCell::new("9.9.9".to_string(), Some(UpdateAction::StandaloneWindows));
let rendered = render_lines(&cell.display_lines(/*width*/ 110)).join("\n");
insta::assert_snapshot!(rendered);
}
#[test]
fn pnpm_update_available_history_cell_snapshot() {
let cell =
UpdateAvailableHistoryCell::new("9.9.9".to_string(), Some(UpdateAction::PnpmGlobalLatest));
let rendered = render_lines(&cell.display_lines(/*width*/ 110)).join("\n");
insta::assert_snapshot!(rendered);
assert_eq!(
render_lines(&cell.display_lines(/*width*/ 110)),
vec!["È disponibile aKode 9.9.9 — esegui \"akode update\"".to_string()]
);
assert_eq!(
render_lines(&cell.raw_lines()),
vec!["È disponibile aKode 9.9.9 — esegui \"akode update\"".to_string()]
);
}
#[test]

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,19 +0,0 @@
#![cfg(not(debug_assertions))]
use crate::legacy_core::config::Config;
pub(crate) use crate::updates_cache::dismiss_version;
pub fn get_upgrade_version(config: &Config) -> Option<String> {
// aKode: no remote update checks (upstream queried GitHub, npm and Homebrew).
let _ = config;
None
}
/// Returns the latest version to show in a popup, if it should be shown.
/// This respects the user's dismissal choice for the current latest version.
pub fn get_upgrade_version_for_popup(config: &Config) -> Option<String> {
// aKode: no remote update checks.
let _ = config;
None
}

View File

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

View File

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