Apply the update through « Redémarrer » or at the next launch (#59)

The settings show « Redémarrer » next to « Mise à jour prête ». It
verifies the kept package of the chosen channel again, hands exactly
that file to Velopack with `Update.exe apply --waitPid <pid> --package
<file>`, then quits as « Quitter » does (WM_QUIT, never hidden in the
notification area). Velopack 1.2.161 reads the file in place, waits for
the app to exit, replaces current\ and opens the new version once, or
the old one again after a failure.

After « Quitter », the next launch does the same before loading the
app, offline too, but only in the single instance: a shortcut launched
while the app runs still just brings its window back (#50).

An attempt record, <channel>-<version>.attempt next to the package
folder, holds the installer's process id. A launch that finds it never
retries on its own: it waits for a running installer (a close second
launch, or the old version reopened after a failure), then either
leaves the app to the new version or opens the current one with a
one-time notice. « Redémarrer » retries; a newer release starts fresh.
The record survives a new download of the same version, since Velopack
deletes a package it cannot open.

Velopack's swap has no rollback between its two renames; this residual
risk is recorded in ADR-0005 and docs/paquets-windows.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-20 14:02:57 +01:00
1 parent 8e12abf7f4
commit ab3c6964a5
10 files changed
+549 -47

No files matched your search

+17 -8
View File
@@ -12,7 +12,7 @@ mod title_bar;
mod tray;
mod worker;
use std::{borrow::Cow, rc::Rc, sync::Arc};
use std::{borrow::Cow, ops::ControlFlow, rc::Rc, sync::Arc};
use arena_tracker_core::{
Config, DataDragon, LeagueClient, Preferences, RiotApi, Tracker, data_dir, default_seasons,
@@ -157,7 +157,7 @@ impl Render for RootView {
let on_page = self.screen == Screen::Page;
let settings = settings_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)));
// The settings show the ready version; #59 turns this into « Redémarrer ».
// The settings show the ready version next to « Redémarrer ».
let update = self.form.read(cx).update_ready().then(|| {
update_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)))
@@ -288,6 +288,10 @@ fn main() {
else {
return;
};
// Only the single instance gets here: a launch relayed to a running one installs nothing.
let ControlFlow::Continue(update_notice) = release::update_at_launch() else {
return;
};
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
app.run(move |cx| {
gpui_kit::init(cx);
@@ -308,12 +312,17 @@ fn main() {
..Default::default()
};
match startup() {
Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| {
single_instance::accept_relaunches(window);
cx.new(|cx| RootView::new(setup, window, cx))
})
.map(drop),
Err((lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| {
Ok(mut setup) => {
setup.notice = (update_notice.into_iter().chain(setup.notice))
.reduce(|update, seasons| format!("{update}\n{seasons}"));
gpui_kit::open_window(options, cx, |window, cx| {
single_instance::accept_relaunches(window);
cx.new(|cx| RootView::new(setup, window, cx))
})
.map(drop)
}
Err((mut lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| {
lines.extend(update_notice);
single_instance::accept_relaunches(window);
apply_theme(preferences.theme, window, cx);
window
+145 -10
View File
@@ -1,7 +1,21 @@
use std::io;
use std::ops::ControlFlow;
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use arena_tracker_core::UpdateChannel;
use arena_tracker_core::{Config, Preferences, UpdateChannel, data_dir};
use base64::prelude::{BASE64_STANDARD, Engine};
use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
use windows::Win32::System::Threading::{
CREATE_NO_WINDOW, GetExitCodeProcess, OpenProcess, PROCESS_NAME_WIN32,
PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, QueryFullProcessImageNameW,
WaitForSingleObject,
};
use windows::core::PWSTR;
use crate::single_instance::owned;
/// This executable's release version; `None` for a development build, which never updates.
pub const VERSION: Option<&str> = option_env!("ARENA_RELEASE_VERSION");
@@ -9,6 +23,9 @@ const CHANNEL: Option<&str> = option_env!("ARENA_RELEASE_CHANNEL");
const PUBLIC_KEY: Option<&str> = option_env!("ARENA_RELEASE_PUBLIC_KEY");
/// Public: read without a Gitea account or token.
const RELEASES: &str = "https://gitea.nessar.fr/api/v1/repos/nessar/arena-tracker/releases";
/// Velopack 1.2.161 waits up to 60 s for the app to exit, 15 s for each hook and about 40 s
/// for the folder swap: an installer still running after this counts as failed.
const INSTALLER_WAIT_MS: u32 = 180_000;
/// The Windows installer invokes these fast callbacks and waits for the process to exit.
/// The SDK's ordinary startup path opens cached packages even with auto-apply disabled.
@@ -55,23 +72,141 @@ fn verify_release(dir: &Path) -> Result<(), String> {
Ok(())
}
/// The channel followed until the player chooses one: the installed version's, Stable for a
/// The saved choice, or until the player chooses, the installed version's channel: Stable for a
/// development build.
pub fn installed_channel() -> UpdateChannel {
if CHANNEL == Some("beta") {
pub fn channel(preferences: Preferences) -> UpdateChannel {
(preferences.update_channel).unwrap_or(if CHANNEL == Some("beta") {
UpdateChannel::Beta
} else {
UpdateChannel::Stable
}
})
}
/// Keeps the newest release of `channel` downloaded and authenticated in
/// `%LOCALAPPDATA%\arena-tracker\updates`, outside the installation, and returns its version.
/// A failed check only means no update is ready; the next launch checks again.
pub fn download_update(channel: UpdateChannel) -> Option<String> {
let (version, key) = (VERSION?, BASE64_STANDARD.decode(PUBLIC_KEY?).ok()?);
/// What every update step needs: the folder of kept updates,
/// `%LOCALAPPDATA%\arena-tracker\updates`, outside the installation and Velopack's cache; the
/// public key; the installed version. `None` for a development build.
fn update_context() -> Option<(PathBuf, Vec<u8>, &'static str)> {
let dir = PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("arena-tracker/updates");
Some((dir, BASE64_STANDARD.decode(PUBLIC_KEY?).ok()?, VERSION?))
}
/// Keeps the newest release of `channel` downloaded and authenticated in the updates folder and
/// returns its version. A failed check only means no update is ready; the next launch checks
/// again.
pub fn download_update(channel: UpdateChannel) -> Option<String> {
let (dir, key, version) = update_context()?;
arena_tracker_core::download_update(RELEASES, &dir, &key, channel, version)
.ok()
.flatten()
}
/// Before the app loads, in the single instance only: hands the kept update of the chosen
/// channel to Update.exe once. `Break`: Update.exe replaces this version and opens the app.
/// `Continue`: load the app, with the notice to show if there is one.
pub fn update_at_launch() -> ControlFlow<(), Option<String>> {
let Some((dir, key, version)) = update_context() else {
return ControlFlow::Continue(None);
};
// Without a readable configuration the chosen channel is unknown; the app then says why.
// shortcut: startup() reads config.toml again, a few hundred bytes; pass it along if that
// file ever grows.
let config =
data_dir().and_then(|data| Config::load_or_default(&data.join("config.toml")).ok());
let Some(config) = config else {
return ControlFlow::Continue(None);
};
let channel = channel(config.preferences);
arena_tracker_core::update_at_launch(
&dir,
&key,
channel,
version,
start_installer,
installer_exit,
)
.map_continue(|error| error.map(|error| error.to_string()))
}
/// « Redémarrer »: hands the kept update of `channel` to Update.exe; the app must then quit.
/// Hashes the package on the calling thread: a few tens of milliseconds for a full package.
pub fn restart_to_update(channel: UpdateChannel) -> Result<(), String> {
let (dir, key, version) = update_context().ok_or("Cette version ne se met pas à jour.")?;
arena_tracker_core::restart_to_update(&dir, &key, channel, version, start_installer)
.map_err(|e| e.to_string())
}
/// Update.exe at the installation's root, next to `current\arena-tracker.exe`.
fn installer() -> io::Result<PathBuf> {
let exe = std::env::current_exe()?;
let root = exe.parent().and_then(Path::parent);
Ok(root.ok_or(io::ErrorKind::NotFound)?.join("Update.exe"))
}
/// Starts Velopack's installer on an authenticated package, which it reads in place: it waits
/// for this process to exit, replaces `current\` and opens the app once, this version again if
/// it fails (ADR-0005, `docs/paquets-windows.md`).
fn start_installer(package: &Path) -> io::Result<u32> {
let child = Command::new(installer()?)
.args([
"apply",
"--waitPid",
&std::process::id().to_string(),
"--package",
])
.arg(package)
.creation_flags(CREATE_NO_WINDOW.0)
.spawn()?;
Ok(child.id())
}
/// The exit code of the installer an earlier launch started as `pid`, once it ends. A launch
/// waiting here runs from the installation, so Velopack stops it before replacing `current\`.
fn installer_exit(pid: u32) -> Option<u32> {
process_exit(pid, &installer().ok()?)
}
/// Waits for process `pid` and returns its exit code; `None` when no such process runs from
/// `image` (the id may belong to another program by now), or when it still runs after the wait.
// shortcut: compares path spellings, as current_exe() gives them to both launches; compare file
// identities if an 8.3 or `\\?\` spelling ever shows up there.
fn process_exit(pid: u32, image: &Path) -> Option<u32> {
let access = PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE;
let process = owned(unsafe { OpenProcess(access, false, pid) }.ok()?);
let handle = HANDLE(process.as_raw_handle());
let mut name = [0u16; 1024];
let mut len = name.len() as u32;
let name_ptr = PWSTR(name.as_mut_ptr());
unsafe { QueryFullProcessImageNameW(handle, PROCESS_NAME_WIN32, name_ptr, &mut len) }.ok()?;
let name = String::from_utf16_lossy(&name[..len as usize]);
if !name.eq_ignore_ascii_case(&image.to_string_lossy())
|| unsafe { WaitForSingleObject(handle, INSTALLER_WAIT_MS) } != WAIT_OBJECT_0
{
return None;
}
let mut code = 0;
unsafe { GetExitCodeProcess(handle, &mut code) }.ok()?;
Some(code)
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use std::process::Command;
use super::process_exit;
#[test]
fn the_installers_exit_code_is_read_only_from_its_own_image() {
let windows = PathBuf::from(std::env::var_os("SystemRoot").unwrap());
let cmd = windows.join("System32").join("cmd.exe");
// Kept until the end: its open handle stops the id from going to another process.
let child = Command::new(&cmd).args(["/c", "exit 3"]).spawn().unwrap();
assert_eq!(
process_exit(child.id(), Path::new("C:\\Other\\Update.exe")),
None
);
// SystemRoot and the process image differ in case.
assert_eq!(process_exit(child.id(), &cmd), Some(3));
drop(child);
}
}
+50 -15
View File
@@ -13,7 +13,7 @@ use gpui_kit::component::switch::Switch;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme, ThemeMode};
use gpui_kit::*;
use crate::release;
use crate::release::{self, channel};
use crate::tray::{Tray, UNAVAILABLE};
use crate::worker::{RefreshGate, UpdateChecked, spawn_update_check};
@@ -96,18 +96,13 @@ pub enum KeyEvent {
UpdateReady,
}
/// The saved choice, or the installed version's channel until the player chooses.
fn channel(preferences: Preferences) -> UpdateChannel {
(preferences.update_channel).unwrap_or_else(release::installed_channel)
}
pub struct KeyForm {
store: KeyStore,
input: Entity<InputState>,
/// The first-launch prompt (no key and nothing stored yet) has no way back.
first_launch: bool,
error: Option<String>,
preference_error: Option<&'static str>,
preference_error: Option<SharedString>,
tray: Option<Rc<Tray>>,
/// The tray reports here that it showed its one-time notice.
notice_shown: Sender<()>,
@@ -202,6 +197,11 @@ impl KeyForm {
self.ready.is_some()
}
/// Not while a check runs: it may replace the folder of the package being handed over.
fn can_restart(&self) -> bool {
self.update_ready() && !self.update_checks.running()
}
/// Checks the chosen channel in the background, after the running check if there is one.
fn check_updates(&mut self) {
if release::VERSION.is_some() && self.update_checks.request() {
@@ -221,6 +221,8 @@ impl KeyForm {
.map(|version| format!("Mise à jour prête : version {version}").into());
self.set_ready(ready, cx);
}
// « Redémarrer » waits for the end of the check.
cx.notify();
}
fn set_ready(&mut self, ready: Option<SharedString>, cx: &mut Context<Self>) {
@@ -260,13 +262,13 @@ impl KeyForm {
let notice = (!self.store.config.tray_notice_shown).then(|| self.notice_shown.clone());
self.tray = Tray::install(window, notice, cx);
if self.tray.is_none() {
self.preference_error = Some(UNAVAILABLE);
self.preference_error = Some(UNAVAILABLE.into());
cx.notify();
return;
}
}
self.preference_error = if self.store.save_preferences(preferences).is_err() {
Some("Impossible d’enregistrer les préférences.")
Some("Impossible d’enregistrer les préférences.".into())
} else {
apply_theme(preferences.theme, window, cx);
if channel(preferences) != channel(previous) {
@@ -353,14 +355,42 @@ impl KeyForm {
.children(
self.update_status()
.map(|status| div().text_color(muted).child(status)),
),
)
.children(self.can_restart().then(|| {
div().h_flex().child(
Button::new("restart")
.label("Redémarrer")
.on_click(cx.listener(|this, _, _, cx| this.restart(cx))),
)
})),
)
.children(
self.preference_error
.map(|error| div().text_color(danger).child(error)),
(self.preference_error.clone()).map(|error| div().text_color(danger).child(error)),
)
}
/// Hands the ready update to the installer, then quits as « Quitter » does: never hidden in
/// the notification area, the single instance is free when the new version opens.
fn restart(&mut self, cx: &mut Context<Self>) {
// A second click queued before the quit must not start a second installer.
if !self.can_restart() {
return;
}
match release::restart_to_update(channel(self.store.config.preferences)) {
Ok(()) => {
self.set_ready(None, cx);
cx.quit();
}
Err(error) => {
self.preference_error = Some(error.into());
// Checked again, and downloaded again if the kept package was altered.
self.set_ready(None, cx);
self.check_updates();
cx.notify();
}
}
}
fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let placeholder = if self.store.has_key() {
PLACEHOLDER_SAVED
@@ -467,9 +497,7 @@ mod tests {
use crate::worker::UpdateChecked;
#[gpui::test]
fn the_chosen_channel_is_saved_and_only_its_check_makes_an_update_ready(
cx: &mut TestAppContext,
) {
fn the_chosen_channel_is_saved_and_only_its_check_offers_a_restart(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let dir = std::env::temp_dir().join(format!("arena-channel-{}", std::process::id()));
let path = dir.join("config.toml");
@@ -525,6 +553,13 @@ mod tests {
);
});
cx.update(|window, cx| window.draw(cx).clear(cx));
form.update(cx, |form, cx| {
// A development build has no installer: « Redémarrer » says so and the app stays.
form.restart(cx);
assert!(!form.update_ready());
let error = form.preference_error.as_deref();
assert_eq!(error, Some("Cette version ne se met pas à jour."));
});
choose(UpdateChannel::Stable, cx);
assert!(!form.read_with(cx, |form, _| form.update_ready()));
+1 -1
View File
@@ -60,7 +60,7 @@ pub struct Primary {
pub starting: HeldMutex,
}
fn owned(handle: HANDLE) -> OwnedHandle {
pub(crate) fn owned(handle: HANDLE) -> OwnedHandle {
unsafe { OwnedHandle::from_raw_handle(handle.0) }
}