From 64b5b8734618eaae39f657ba94178feea47a2cd3 Mon Sep 17 00:00:00 2001 From: meetsu <96637888+klNuno@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:23:10 +0100 Subject: [PATCH 1/6] fix(egui): wake the UI when a store write ends; pump test frames on repaint requests The frame that reports a finished store write asked for no frame after it. The write's store could hold a newer write already due, which the timed repaint had left out while the store was writing, and a backup's drain had already run earlier in that frame: both waited for an unrelated deadline or the next input. pump_saves now asks for one more frame when a write ends. The backup and native tests bounded their waits by wall clock with the frames counted in, so one slow debug frame on a loaded runner failed a wait that was only slow, and a frame drawn every millisecond hid lost wakeups. The new pump draws a frame only when the app asks for one, through the context's repaint observer, and bounds only the idle time between frames. --- crates/accshift-egui/src/app/saves.rs | 9 ++ crates/accshift-egui/src/app/tests.rs | 1 + .../src/app/tests/backup_restore.rs | 127 +++++++++++++----- .../src/app/tests/native_regressions.rs | 21 +-- crates/accshift-egui/src/app/tests/pump.rs | 121 +++++++++++++++++ 5 files changed, 234 insertions(+), 45 deletions(-) create mode 100644 crates/accshift-egui/src/app/tests/pump.rs diff --git a/crates/accshift-egui/src/app/saves.rs b/crates/accshift-egui/src/app/saves.rs index f55abe9b..3c026a3d 100644 --- a/crates/accshift-egui/src/app/saves.rs +++ b/crates/accshift-egui/src/app/saves.rs @@ -92,6 +92,7 @@ impl AppModel { .run(move |backend| backend.save_client_storage_store(store_id, &save.value)); self.saves.push((store_id, pending)); } + let mut reported = false; self.saves.retain_mut(|(id, pending)| { let result = match pending.poll() { Poll::Waiting => return true, @@ -103,7 +104,15 @@ impl AppModel { self.backup.save_failed(error); } b.stores.finish_save(id, &result); + reported = true; false }); + // The job's wake brought this frame and is spent. A write that ends + // frees its store, whose next write the timed repaint above left + // out and may be due already, and a backup's drain ran earlier in + // this frame: without one more frame both wait for the next input. + if reported { + ctx.request_repaint(); + } } } diff --git a/crates/accshift-egui/src/app/tests.rs b/crates/accshift-egui/src/app/tests.rs index 20628c3d..fc506d5d 100644 --- a/crates/accshift-egui/src/app/tests.rs +++ b/crates/accshift-egui/src/app/tests.rs @@ -14,6 +14,7 @@ use super::*; mod backup_restore; mod early_boot; mod native_regressions; +mod pump; mod real_unreadable; mod shortcuts; mod updates; diff --git a/crates/accshift-egui/src/app/tests/backup_restore.rs b/crates/accshift-egui/src/app/tests/backup_restore.rs index f8e9094c..0c781917 100644 --- a/crates/accshift-egui/src/app/tests/backup_restore.rs +++ b/crates/accshift-egui/src/app/tests/backup_restore.rs @@ -4,6 +4,7 @@ //! closing under it. An export waits behind the same boundary. use super::super::settings_panel::SettingsAction; +use super::pump; use super::*; use accshift_app::i18n::{translate, Locale}; use serde_json::json; @@ -68,13 +69,35 @@ fn frame(app: &mut AppModel, ctx: &Context) { output.textures_delta.clear(); } +/// Frames until `condition` holds: [`pump::until`]. +#[track_caller] fn pump_until(app: &mut AppModel, ctx: &Context, condition: impl Fn(&AppModel) -> bool) { - let deadline = Instant::now() + std::time::Duration::from_secs(3); - while !condition(app) { - assert!(Instant::now() < deadline, "the condition never held"); - frame(app, ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump::until(app, ctx, frame, condition); +} + +#[test] +fn a_slow_frame_is_not_a_hang() { + // Regression (SLOW_FRAME): the wait's deadline counted the frames + // themselves. On a loaded runner one debug frame outlasted it, and a + // condition two frames away "never held" though nothing was stuck. + let ctx = Context::default(); + let (mut app, mock) = restore_app(&ctx); + // The panel's mount job cannot land before the first frame polls it. + assert!(mock.hold("steam_has_api_key")); + app.toggle_settings_panel(); + let limit = std::time::Duration::from_millis(50); + pump::within( + &mut app, + &ctx, + limit, + |app, ctx| { + frame(app, ctx); + mock.release("steam_has_api_key"); + // The frame outlasts the limit; the job lands meanwhile. + std::thread::sleep(limit * 3); + }, + |a| a.settings_panel.as_ref().is_some_and(|p| p.hydrated), + ); } fn note(app: &AppModel) -> String { @@ -156,6 +179,62 @@ fn a_restore_waits_for_a_running_save_and_holds_new_writes() { assert!(app.backup.card.notice.contains("pre-restore-1")); } +/// Well inside the next deadline the app asks a frame for on its own (a +/// toast's expiry, seconds away), so a wait that needs a frame nobody asked +/// for does not hold within it. +const NO_TIMER: std::time::Duration = std::time::Duration::from_millis(500); +/// Long enough for a released mocked call to deliver its result and wake +/// the app, and for a note's debounce to run out. Too short only lets the +/// regressions below pass without their fix, never fail with it. +const LANDED: std::time::Duration = std::time::Duration::from_millis(200); + +#[test] +fn a_write_ending_under_the_boundary_wakes_the_restore() { + // Regression (DRAIN_WAKE): the frame that reports a write runs the + // boundary's drain before it, and asked for no frame after: the restore + // waited for an unrelated deadline or the next mouse move. + let ctx = Context::default(); + let (mut app, mock) = restore_app(&ctx); + frame(&mut app, &ctx); + assert!(mock.hold(SAVE)); + set_note(&mut app, "typed before"); + pump_until(&mut app, &ctx, |_| mock.waiting(SAVE) == 1); + app.start_backup_restore("C:/b.json".into(), String::new()); + assert!(mock.hold("backup_restore")); + mock.release(SAVE); + // The write's result and its wake are in before the next frame, which + // then has nothing left to wake it. + std::thread::sleep(LANDED); + pump::within(&mut app, &ctx, NO_TIMER, frame, |_| { + mock.waiting("backup_restore") == 1 + }); + mock.release("backup_restore"); + pump_until(&mut app, &ctx, |a| !a.backup.holds_writes()); +} + +#[test] +fn a_note_typed_while_its_store_writes_is_written_when_that_write_ends() { + // Regression (DRAIN_WAKE): a write due while its store still wrote was + // left out of the timed repaint, and the frame that reported the write + // asked for none: it waited for an unrelated deadline or the next input. + let ctx = Context::default(); + let (mut app, mock) = restore_app(&ctx); + frame(&mut app, &ctx); + assert!(mock.hold(SAVE)); + set_note(&mut app, "first"); + pump_until(&mut app, &ctx, |_| mock.waiting(SAVE) == 1); + set_note(&mut app, "second"); + mock.release(SAVE); + // Past the second note's debounce too: only the frame that reports the + // first write can start the second. + std::thread::sleep(LANDED); + pump::within(&mut app, &ctx, NO_TIMER, frame, |_| mock.seen(SAVE) == 2); + pump_until(&mut app, &ctx, |a| { + !a.booted().unwrap().stores.storage().has_unsaved() + }); + assert_eq!(note(&app), "second"); +} + #[test] fn restored_settings_keep_the_restored_platform_they_enable() { let ctx = Context::default(); @@ -353,11 +432,7 @@ fn a_picker_that_fails_says_why() { app.import_backup(); } pump_until(&mut app, &ctx, |_| mock.seen(command) == 1); - let deadline = Instant::now() + std::time::Duration::from_secs(3); - while !app.backup.card.error && Instant::now() < deadline { - frame(&mut app, &ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump_until(&mut app, &ctx, |a| a.backup.card.error); assert!( app.backup.card.error && app.backup.card.notice.contains(odd), "PICKER_ERROR: {command} said {:?}", @@ -770,12 +845,12 @@ fn a_restore_whose_theme_cannot_be_read_keeps_it_selected_until_it_loads() { assert!(mock.fail("list_custom_themes", None)); focus(&mut app, &ctx, false); focus(&mut app, &ctx, true); - let deadline = Instant::now() + std::time::Duration::from_secs(3); - while app.booted().unwrap().registry.document("mine").is_none() { - assert!(Instant::now() < deadline, "the theme never loaded"); - focus(&mut app, &ctx, true); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump::until( + &mut app, + &ctx, + |app, ctx| focus(app, ctx, true), + |a| a.booted().unwrap().registry.document("mine").is_some(), + ); let b = app.booted().unwrap(); assert_eq!(b.stores.settings().theme_id, "mine"); assert_ne!(b.theme.vars.bg_card, before, "the theme does not draw"); @@ -807,15 +882,7 @@ fn theme_restore_app( fn refocus_until(app: &mut AppModel, ctx: &Context, loaded: impl Fn(&AppModel) -> bool) { focus(app, ctx, false); focus(app, ctx, true); - let deadline = Instant::now() + std::time::Duration::from_secs(3); - while !loaded(app) { - assert!( - Instant::now() < deadline, - "the themes were not read again on the next focus" - ); - focus(app, ctx, true); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump::until(app, ctx, |app, ctx| focus(app, ctx, true), loaded); } #[test] @@ -1260,11 +1327,11 @@ fn a_panel_edit_made_during_the_restore_never_lands_over_it() { mock.release("backup_restore"); pump_until(&mut app, &ctx, |a| !a.backup.holds_writes()); assert!(!app.backup.card.error, "{}", app.backup.card.notice); - // Past the panel's save debounce. - let until = Instant::now() + std::time::Duration::from_millis(400); - while Instant::now() < until { + // Until the panel has no save left to run: one still queued runs at + // its deadline, which the app asks a frame for. + pump_until(&mut app, &ctx, |a| a.settings_panel_deadline().is_none()); + for _ in 0..3 { frame(&mut app, &ctx); - std::thread::sleep(std::time::Duration::from_millis(5)); } let panel = app.settings_panel.as_ref().unwrap().draft.language; let stored = app.booted().unwrap().stores.settings().language; diff --git a/crates/accshift-egui/src/app/tests/native_regressions.rs b/crates/accshift-egui/src/app/tests/native_regressions.rs index b3af6edf..4d0b8566 100644 --- a/crates/accshift-egui/src/app/tests/native_regressions.rs +++ b/crates/accshift-egui/src/app/tests/native_regressions.rs @@ -1,3 +1,4 @@ +use super::pump; use super::*; use egui::{pos2, vec2, Id, RawInput, Rect, Sense, ViewportId}; use serde_json::json; @@ -110,26 +111,16 @@ fn frame(app: &mut AppModel, ctx: &Context, focused: bool, minimized: bool) { output.textures_delta.clear(); } +/// Focused frames until `condition` holds: [`pump::until`]. +#[track_caller] fn pump_until(app: &mut AppModel, ctx: &Context, condition: impl Fn(&AppModel) -> bool) { - let deadline = Instant::now() + std::time::Duration::from_secs(10); - while !condition(app) { - assert!( - Instant::now() < deadline, - "condition did not become true within 10 s" - ); - frame(app, ctx, true, false); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump::until(app, ctx, |app, ctx| frame(app, ctx, true, false), condition); } /// Frames until no external refresh runs, accounts it reloads included. +#[track_caller] fn wait_refresh_over(app: &mut AppModel, ctx: &Context) { - let deadline = Instant::now() + std::time::Duration::from_secs(10); - while app.external_refresh.running() { - assert!(Instant::now() < deadline, "the refresh never ended"); - frame(app, ctx, true, false); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump_until(app, ctx, |a| !a.external_refresh.running()); } #[test] diff --git a/crates/accshift-egui/src/app/tests/pump.rs b/crates/accshift-egui/src/app/tests/pump.rs new file mode 100644 index 00000000..f5305454 --- /dev/null +++ b/crates/accshift-egui/src/app/tests/pump.rs @@ -0,0 +1,121 @@ +//! Frames on the mock backend until a condition holds, each one drawn when +//! the app asks for it, as the window's event loop would. +//! +//! Only the idle wait between frames is bounded, never a frame: a debug +//! frame on a loaded runner can take seconds (the first ones rasterize +//! their glyphs), and a deadline that counted the frames failed waits that +//! were only slow, two frames away from holding. + +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use egui::Context; + +use super::AppModel; + +/// How long the app may sit idle, the condition false and no frame asked +/// for, before the wait counts as a hang. +const IDLE_LIMIT: Duration = Duration::from_secs(3); +/// A backstop for an app that asks for a frame after every frame. +const MAX_FRAMES: u32 = 2_000; +/// How often an idle wait reads the condition again, for a state no frame +/// reports (a mocked call reaching its hold). +const IDLE_POLL: Duration = Duration::from_millis(1); + +/// The next frame the app asked for since the last one began, as the +/// context's repaint observer sees it: a job whose result landed asks for +/// one through the pool's wake, a debounce for one at its deadline. +#[derive(Default)] +struct Wakes { + due: Mutex>, + asked: Condvar, +} + +impl Wakes { + /// Watches every repaint request `ctx` gets from now on. + fn observe(ctx: &Context) -> Arc { + let wakes = Arc::new(Self::default()); + let seen = Arc::clone(&wakes); + ctx.set_repaint_observer(move |info| { + let Some(at) = Instant::now().checked_add(info.delay) else { + return; + }; + let mut due = seen.due.lock().unwrap_or_else(|p| p.into_inner()); + if due.is_none_or(|due| at < due) { + *due = Some(at); + seen.asked.notify_all(); + } + }); + wakes + } + + fn clear(&self) { + *self.due.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + + /// Waits at most `limit` for a frame the app asked for to come due; + /// true when one did. + fn wait_due(&self, limit: Duration) -> bool { + let due = self.due.lock().unwrap_or_else(|p| p.into_inner()); + let now = Instant::now(); + let wait = match *due { + Some(at) if at <= now => return true, + Some(at) => (at - now).min(limit), + None => limit, + }; + let (due, _) = self + .asked + .wait_timeout(due, wait) + .unwrap_or_else(|p| p.into_inner()); + due.is_some_and(|at| at <= Instant::now()) + } +} + +/// Draws frames with `draw` until `condition` holds. +#[track_caller] +pub(super) fn until( + app: &mut AppModel, + ctx: &Context, + draw: impl FnMut(&mut AppModel, &Context), + condition: impl Fn(&AppModel) -> bool, +) { + within(app, ctx, IDLE_LIMIT, draw, condition); +} + +/// [`until`], idle for at most `idle_limit` in all. +#[track_caller] +pub(super) fn within( + app: &mut AppModel, + ctx: &Context, + idle_limit: Duration, + mut draw: impl FnMut(&mut AppModel, &Context), + condition: impl Fn(&AppModel) -> bool, +) { + let wakes = Wakes::observe(ctx); + let mut idle = Duration::ZERO; + let mut frames = 0; + while !condition(app) { + assert!( + frames < MAX_FRAMES, + "the condition never held: {frames} frames drawn" + ); + wakes.clear(); + draw(app, ctx); + frames += 1; + loop { + if condition(app) { + return; + } + assert!( + idle < idle_limit, + "the condition never held: the app sat idle {idle:?} with no frame to draw" + ); + let waited = Instant::now(); + let due = wakes.wait_due(IDLE_POLL); + idle += waited.elapsed(); + if due { + break; + } + } + } +} From 1c00099c668adc3e91b19bb648e7c02b933b7f31 Mon Sep 17 00:00:00 2001 From: meetsu <96637888+klNuno@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:42:28 +0100 Subject: [PATCH 2/6] fix(egui): run the close sequence on SIGHUP too SIGHUP kept its default action, which ends the process before the pending store writes are flushed (a closed terminal, a session that hangs up). It now wakes the loop like SIGTERM and SIGINT. A signal the parent left ignored (nohup) stays ignored. Tests drive the installed handler end to end: the signal wakes the loop, the close runs and the pending write is on disk. --- crates/accshift-egui/Cargo.toml | 2 +- crates/accshift-egui/src/lib.rs | 71 ++++++++++++ crates/accshift-egui/src/window/mod.rs | 3 +- crates/accshift-egui/src/window/signal.rs | 126 +++++++++++++++------- 4 files changed, 159 insertions(+), 43 deletions(-) diff --git a/crates/accshift-egui/Cargo.toml b/crates/accshift-egui/Cargo.toml index 63ec5f44..dda61891 100644 --- a/crates/accshift-egui/Cargo.toml +++ b/crates/accshift-egui/Cargo.toml @@ -71,7 +71,7 @@ image-webp = "0.2" [target.'cfg(not(windows))'.dependencies] egui = { version = "0.37", features = ["default_fonts"] } -# Unix termination signals (window/signal.rs): SIGTERM and SIGINT run the same +# Unix termination signals (window/signal.rs): SIGTERM, SIGINT and SIGHUP run the same # orderly shutdown as a normal quit. `libc` is already in the workspace graph. [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/accshift-egui/src/lib.rs b/crates/accshift-egui/src/lib.rs index 6a42a3e7..1a2dbe75 100644 --- a/crates/accshift-egui/src/lib.rs +++ b/crates/accshift-egui/src/lib.rs @@ -647,5 +647,76 @@ mod tests { drop(shell); let _ = std::fs::remove_dir_all(&dir.0); } + + /// The runner's path for a Unix termination signal, end to end: the + /// installed handler wakes the loop (here a channel stands for the + /// event loop proxy), which runs [`Shell::close`]. A store write still + /// pending lands on disk. + #[cfg(unix)] + fn a_signal_flushes_a_pending_write(sig: libc::c_int, tag: &str) { + use accshift_app::backend::Backend; + use accshift_app::storage::CLIENT_STORE_SETTINGS; + use std::time::Duration; + + let _lock = crate::window::signal::test_lock(sig); + let dir = scratch(tag); + let backend = Arc::new(RealBackend::with_context(dir.clone())); + let ctx = egui::Context::default(); + let mut app = crate::AppModel::real(&ctx, backend.clone(), None, None); + app.wait_boot(&ctx).expect("boot on scratch dir"); + backend.boot_state().mark_completed(); + { + let booted = app.booted_mut().expect("booted"); + let mut next = booted.stores.settings().clone(); + next.close_to_tray = true; + booted.stores.save_settings(&next); + } + let mut shell = Shell::new(Screen::App(Box::new(app)), None) + .with_window(Host::new(backend.clone(), 0)); + + let (quit_tx, quit_rx) = std::sync::mpsc::channel(); + let guard = crate::window::signal::install(move || { + let _ = quit_tx.send(()); + }) + .expect("signal handler installed"); + assert_eq!(unsafe { libc::raise(sig) }, 0); + quit_rx + .recv_timeout(Duration::from_secs(5)) + .expect("the handler woke the loop"); + // A close request now quits instead of hiding to the tray. + assert!(crate::window::session_ending()); + let mut hidden = 0; + shell.close(Some(geometry(1040.0)), || hidden += 1); + drop(guard); + + assert_eq!(hidden, 1); + let snapshot = backend + .load_client_storage_snapshot() + .expect("snapshot on disk"); + assert_eq!( + snapshot + .stores + .get(CLIENT_STORE_SETTINGS) + .and_then(|v| v.get("closeToTray")) + .and_then(|v| v.as_bool()), + Some(true), + "the write pending at the signal must be on disk" + ); + drop(shell); + } + + #[cfg(unix)] + #[test] + fn sigterm_flushes_a_pending_write_to_disk() { + a_signal_flushes_a_pending_write(libc::SIGTERM, "sigterm-flush"); + } + + // Regression: `SIGHUP` (a closed terminal, a session hanging up) kept + // its default action and ended the process with the write unsaved. + #[cfg(unix)] + #[test] + fn sighup_flushes_a_pending_write_to_disk() { + a_signal_flushes_a_pending_write(libc::SIGHUP, "sighup-flush"); + } } } diff --git a/crates/accshift-egui/src/window/mod.rs b/crates/accshift-egui/src/window/mod.rs index ab61a37a..e65552db 100644 --- a/crates/accshift-egui/src/window/mod.rs +++ b/crates/accshift-egui/src/window/mod.rs @@ -145,7 +145,8 @@ pub fn restore_position(window: &egui_winit::winit::window::Window, saved: &conf } /// The OS is ending the session (Windows `WM_ENDSESSION`, or Unix -/// `SIGTERM`/`SIGINT`): a close request quits instead of hiding to the tray. +/// `SIGTERM`/`SIGINT`/`SIGHUP`): a close request quits instead of hiding to +/// the tray. pub fn session_ending() -> bool { #[cfg(windows)] return frame::session_ending(); diff --git a/crates/accshift-egui/src/window/signal.rs b/crates/accshift-egui/src/window/signal.rs index 54728380..0b52419a 100644 --- a/crates/accshift-egui/src/window/signal.rs +++ b/crates/accshift-egui/src/window/signal.rs @@ -1,4 +1,5 @@ -//! Unix `SIGTERM` and `SIGINT` handling: turns a termination signal into a +//! Unix `SIGTERM`, `SIGINT` and `SIGHUP` handling: turns a termination +//! signal (a session logout, `kill`, Ctrl+C, a closed terminal) into a //! wake on the winit event loop so the app runs its normal close sequence //! (window geometry, pending store writes, telemetry session end, single //! instance release) before exiting. @@ -83,10 +84,25 @@ mod imp { } } + /// The signals that run the close sequence. `SIGHUP` too: its default + /// action ends the process on the spot, so a closed terminal or a session + /// that hangs up would lose the pending writes. A signal the parent left + /// ignored (`nohup`, a background job's `SIGINT`) stays ignored. + const SIGNALS: [libc::c_int; 3] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP]; + + /// Puts back the dispositions `install` replaced, last first. + fn restore(previous: &[(libc::c_int, libc::sigaction)]) { + for (sig, prev) in previous.iter().rev() { + // SAFETY: `prev` is the disposition `sigaction` returned for `sig`. + unsafe { + let _ = libc::sigaction(*sig, prev, std::ptr::null_mut()); + } + } + } + pub struct Guard { write_fd: libc::c_int, - prev_term: libc::sigaction, - prev_int: libc::sigaction, + previous: Vec<(libc::c_int, libc::sigaction)>, thread: Option>, } @@ -94,10 +110,7 @@ mod imp { fn drop(&mut self) { // Restore previous dispositions before closing the pipe so no // later signal invokes `handle_signal` against a closed fd. - unsafe { - let _ = libc::sigaction(libc::SIGTERM, &self.prev_term, std::ptr::null_mut()); - let _ = libc::sigaction(libc::SIGINT, &self.prev_int, std::ptr::null_mut()); - } + restore(&self.previous); SIGNAL_WRITE_FD.retire(); // Closing the write end wakes the watcher thread with EOF. unsafe { @@ -149,28 +162,24 @@ mod imp { libc::sigemptyset(&mut action.sa_mask); } - let mut prev_term: libc::sigaction = unsafe { std::mem::zeroed() }; - let mut prev_int: libc::sigaction = unsafe { std::mem::zeroed() }; - let term_ok = unsafe { libc::sigaction(libc::SIGTERM, &action, &mut prev_term) } == 0; - if !term_ok { - SIGNAL_WRITE_FD.retire(); - unsafe { - let _ = libc::close(read_fd); - let _ = libc::close(write_fd); - } - return None; - } - let int_ok = unsafe { libc::sigaction(libc::SIGINT, &action, &mut prev_int) } == 0; - if !int_ok { - unsafe { - let _ = libc::sigaction(libc::SIGTERM, &prev_term, std::ptr::null_mut()); + let mut previous = Vec::with_capacity(SIGNALS.len()); + for sig in SIGNALS { + let mut prev: libc::sigaction = unsafe { std::mem::zeroed() }; + // SAFETY: a null action only reads the current disposition. + let read = unsafe { libc::sigaction(sig, std::ptr::null(), &mut prev) } == 0; + if read && prev.sa_sigaction == libc::SIG_IGN { + continue; } - SIGNAL_WRITE_FD.retire(); - unsafe { - let _ = libc::close(read_fd); - let _ = libc::close(write_fd); + if unsafe { libc::sigaction(sig, &action, &mut prev) } != 0 { + restore(&previous); + SIGNAL_WRITE_FD.retire(); + unsafe { + let _ = libc::close(read_fd); + let _ = libc::close(write_fd); + } + return None; } - return None; + previous.push((sig, prev)); } let thread = match std::thread::Builder::new() @@ -202,10 +211,7 @@ mod imp { }) { Ok(thread) => thread, Err(_) => { - unsafe { - let _ = libc::sigaction(libc::SIGTERM, &prev_term, std::ptr::null_mut()); - let _ = libc::sigaction(libc::SIGINT, &prev_int, std::ptr::null_mut()); - } + restore(&previous); SIGNAL_WRITE_FD.retire(); unsafe { let _ = libc::close(read_fd); @@ -217,8 +223,7 @@ mod imp { Some(Guard { write_fd, - prev_term, - prev_int, + previous, thread: Some(thread), }) } @@ -239,6 +244,20 @@ mod imp { pub use imp::{install, received, Guard}; +/// Serializes the tests that install the handler: the dispositions and the +/// pipe slot are process-wide. Also puts `sig` back to its default action, so +/// a test run that inherited it ignored still sees the handler take it. +#[cfg(all(test, unix))] +pub(crate) fn test_lock(sig: libc::c_int) -> std::sync::MutexGuard<'static, ()> { + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: `SIG_DFL` is a valid disposition for any catchable signal. + unsafe { + libc::signal(sig, libc::SIG_DFL); + } + guard +} + #[cfg(test)] mod tests { use super::*; @@ -295,16 +314,11 @@ mod tests { #[cfg(unix)] mod unix_tests { use super::*; - use std::sync::{mpsc, Mutex, OnceLock}; + use std::sync::mpsc; use std::time::Duration; - fn signal_test_lock() -> &'static Mutex<()> { - static LOCK: OnceLock> = OnceLock::new(); - LOCK.get_or_init(|| Mutex::new(())) - } - fn assert_signal_triggers_quit(sig: libc::c_int) { - let _lock = signal_test_lock().lock().unwrap_or_else(|e| e.into_inner()); + let _lock = test_lock(sig); let (tx, rx) = mpsc::channel(); let guard = install(move || { let _ = tx.send(()); @@ -329,9 +343,39 @@ mod tests { assert_signal_triggers_quit(libc::SIGINT); } + // Regression: `SIGHUP` kept its default action, which ends the + // process before the close sequence flushes the pending writes. + #[test] + fn sighup_triggers_orderly_quit_callback() { + assert_signal_triggers_quit(libc::SIGHUP); + } + + #[test] + fn a_signal_the_parent_left_ignored_stays_ignored() { + let _lock = test_lock(libc::SIGHUP); + unsafe { + libc::signal(libc::SIGHUP, libc::SIG_IGN); + } + let (tx, rx) = mpsc::channel(); + let guard = install(move || { + let _ = tx.send(()); + }) + .expect("signal handler installed"); + assert_eq!(unsafe { libc::raise(libc::SIGHUP) }, 0); + assert!(rx.recv_timeout(Duration::from_millis(300)).is_err()); + assert!(!received()); + drop(guard); + let mut now: libc::sigaction = unsafe { std::mem::zeroed() }; + unsafe { + libc::sigaction(libc::SIGHUP, std::ptr::null(), &mut now); + libc::signal(libc::SIGHUP, libc::SIG_DFL); + } + assert_eq!(now.sa_sigaction, libc::SIG_IGN); + } + #[test] fn dropping_guard_without_signal_exits_watcher_cleanly() { - let _lock = signal_test_lock().lock().unwrap_or_else(|e| e.into_inner()); + let _lock = test_lock(libc::SIGTERM); let (tx, rx) = mpsc::channel(); let guard = install(move || { let _ = tx.send(()); From 4910b3cf30a2ea2d65b1504113fd5e83bc90d301 Mon Sep 17 00:00:00 2001 From: meetsu <96637888+klNuno@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:44:33 +0100 Subject: [PATCH 3/6] test(battle-net): a local config without the owed list still loads The owed SavedAccountNames list has lived in the local config since #135. Cover the file a user updating from 2.0.0 or 2.0.1 holds: it has other local fields and no owed list, loads as an empty list, and keeps its fields once the first list is written. --- .../src/platforms/battle_net/tests.rs | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/accshift-core/src/platforms/battle_net/tests.rs b/crates/accshift-core/src/platforms/battle_net/tests.rs index caf51418..bcbb717f 100644 --- a/crates/accshift-core/src/platforms/battle_net/tests.rs +++ b/crates/accshift-core/src/platforms/battle_net/tests.rs @@ -663,3 +663,40 @@ fn a_setup_that_fails_after_quitting_the_launcher_starts_it_again() { assert_eq!(result, Ok(7)); assert!(!restarted); } + +#[test] +fn a_local_config_without_owed_names_still_loads() { + let _guard = crate::config::config_io_test_mutex() + .lock() + .unwrap_or_else(|e| e.into_inner()); + let root = std::env::temp_dir().join(format!( + "accshift-battlenet-owed-legacy-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&root); + let ctx = TestCtx { root: root.clone() }; + // A local file as 2.0.1 leaves it with nothing owed (the field is skipped + // when empty) or as 2.0.0 left it, before the field existed. + let local = crate::storage::local_config_path(&ctx).unwrap(); + std::fs::create_dir_all(local.parent().unwrap()).unwrap(); + std::fs::write( + &local, + r#"{"steam":{"path_override":""},"battleNet":{"path_override":"D:/Games/Battle.net"}}"#, + ) + .unwrap(); + + let config = crate::config::load_config(&ctx); + assert_eq!(config.battle_net.path_override, "D:/Games/Battle.net"); + assert!(config.battle_net.owed_saved_accounts.is_empty()); + let (merged, owed) = with_owed_saved_accounts(&ctx, vec!["new@example.com".to_string()]); + assert!(owed.is_empty()); + assert_eq!(merged, vec!["new@example.com".to_string()]); + + // The first owed list lands beside the fields already there. + owe_saved_accounts(&ctx, &["old@example.com".to_string()]); + let config = crate::config::load_config(&ctx); + assert_eq!(config.battle_net.path_override, "D:/Games/Battle.net"); + assert_eq!(config.battle_net.owed_saved_accounts, ["old@example.com"]); + let _ = std::fs::remove_dir_all(&root); +} From a88d22c50ed6ab9d38930385fe539397355c83e0 Mon Sep 17 00:00:00 2001 From: meetsu <96637888+klNuno@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:31:03 +0100 Subject: [PATCH 4/6] fix(egui): keep honouring an ignored SIGHUP only, SIGINT and SIGTERM always close --- crates/accshift-egui/src/window/signal.rs | 27 ++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/accshift-egui/src/window/signal.rs b/crates/accshift-egui/src/window/signal.rs index 0b52419a..e780d2bf 100644 --- a/crates/accshift-egui/src/window/signal.rs +++ b/crates/accshift-egui/src/window/signal.rs @@ -167,7 +167,10 @@ mod imp { let mut prev: libc::sigaction = unsafe { std::mem::zeroed() }; // SAFETY: a null action only reads the current disposition. let read = unsafe { libc::sigaction(sig, std::ptr::null(), &mut prev) } == 0; - if read && prev.sa_sigaction == libc::SIG_IGN { + // `nohup` leaves SIGHUP ignored and expects it to stay so. SIGINT + // and SIGTERM always close cleanly, even when a shell without job + // control started the app in the background with them ignored. + if sig == libc::SIGHUP && read && prev.sa_sigaction == libc::SIG_IGN { continue; } if unsafe { libc::sigaction(sig, &action, &mut prev) } != 0 { @@ -373,6 +376,28 @@ mod tests { assert_eq!(now.sa_sigaction, libc::SIG_IGN); } + // A shell without job control starts background jobs with SIGINT + // ignored: `kill -INT` must still close the app cleanly. + #[test] + fn an_ignored_sigint_still_triggers_orderly_quit() { + let _lock = test_lock(libc::SIGINT); + unsafe { + libc::signal(libc::SIGINT, libc::SIG_IGN); + } + let (tx, rx) = mpsc::channel(); + let guard = install(move || { + let _ = tx.send(()); + }) + .expect("signal handler installed"); + assert_eq!(unsafe { libc::raise(libc::SIGINT) }, 0); + rx.recv_timeout(Duration::from_secs(2)) + .expect("signal callback fired"); + drop(guard); + unsafe { + libc::signal(libc::SIGINT, libc::SIG_DFL); + } + } + #[test] fn dropping_guard_without_signal_exits_watcher_cleanly() { let _lock = test_lock(libc::SIGTERM); From f34e7b2c15d8a74007a9e96766c190ef98ab05ab Mon Sep 17 00:00:00 2001 From: meetsu <96637888+klNuno@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:03:56 +0100 Subject: [PATCH 5/6] test(egui): drive the wake regressions by an answer already in, release holds on unwind The slow-frame regression asks for its next frame itself, so a late job never counts as idle. The two wake regressions answer the note write in place of the mock before the frame, instead of sleeping for the worker. Their holds go through HeldCommands, now shared, so a failed assertion releases them instead of hanging Jobs::drop. --- crates/accshift-egui/src/app/tests.rs | 1 + .../src/app/tests/backup_restore.rs | 51 ++++++++++++------- crates/accshift-egui/src/app/tests/held.rs | 41 +++++++++++++++ .../src/app/tests/native_regressions.rs | 37 +------------- 4 files changed, 75 insertions(+), 55 deletions(-) create mode 100644 crates/accshift-egui/src/app/tests/held.rs diff --git a/crates/accshift-egui/src/app/tests.rs b/crates/accshift-egui/src/app/tests.rs index fc506d5d..8ce35a57 100644 --- a/crates/accshift-egui/src/app/tests.rs +++ b/crates/accshift-egui/src/app/tests.rs @@ -13,6 +13,7 @@ use super::*; mod backup_restore; mod early_boot; +mod held; mod native_regressions; mod pump; mod real_unreadable; diff --git a/crates/accshift-egui/src/app/tests/backup_restore.rs b/crates/accshift-egui/src/app/tests/backup_restore.rs index 0c781917..c48d8a4a 100644 --- a/crates/accshift-egui/src/app/tests/backup_restore.rs +++ b/crates/accshift-egui/src/app/tests/backup_restore.rs @@ -4,6 +4,7 @@ //! closing under it. An export waits behind the same boundary. use super::super::settings_panel::SettingsAction; +use super::held::HeldCommands; use super::pump; use super::*; use accshift_app::i18n::{translate, Locale}; @@ -82,8 +83,9 @@ fn a_slow_frame_is_not_a_hang() { // condition two frames away "never held" though nothing was stuck. let ctx = Context::default(); let (mut app, mock) = restore_app(&ctx); + let mut held = HeldCommands::new(&mock); // The panel's mount job cannot land before the first frame polls it. - assert!(mock.hold("steam_has_api_key")); + held.hold("steam_has_api_key"); app.toggle_settings_panel(); let limit = std::time::Duration::from_millis(50); pump::within( @@ -92,9 +94,11 @@ fn a_slow_frame_is_not_a_hang() { limit, |app, ctx| { frame(app, ctx); - mock.release("steam_has_api_key"); - // The frame outlasts the limit; the job lands meanwhile. + held.release("steam_has_api_key"); + // The frame outlasts the limit, and asks for the next one itself: + // however late the job lands, no wait for it counts as idle. std::thread::sleep(limit * 3); + ctx.request_repaint(); }, |a| a.settings_panel.as_ref().is_some_and(|p| p.hydrated), ); @@ -183,10 +187,23 @@ fn a_restore_waits_for_a_running_save_and_holds_new_writes() { /// toast's expiry, seconds away), so a wait that needs a frame nobody asked /// for does not hold within it. const NO_TIMER: std::time::Duration = std::time::Duration::from_millis(500); -/// Long enough for a released mocked call to deliver its result and wake -/// the app, and for a note's debounce to run out. Too short only lets the -/// regressions below pass without their fix, never fail with it. -const LANDED: std::time::Duration = std::time::Duration::from_millis(200); + +/// Answers the note write in flight in place of the mock, whose held call is +/// then released: the answer is in before the next frame and no wake came +/// with it, as when the job's wake brought a frame drawn before this one. +fn answer_note_write(app: &mut AppModel, held: &mut HeldCommands) { + let (_, pending) = app + .saves + .iter_mut() + .find(|(store, _)| *store == "client.account-card-notes") + .expect("no note write in flight"); + let (answer, answered) = std::sync::mpsc::channel(); + answer.send(Ok(None)).unwrap(); + // The held call's own Pending is dropped before its release: its + // answer then has no one to go to, and its job wakes nothing. + *pending = Pending::from_receiver(answered); + held.release(SAVE); +} #[test] fn a_write_ending_under_the_boundary_wakes_the_restore() { @@ -195,20 +212,18 @@ fn a_write_ending_under_the_boundary_wakes_the_restore() { // waited for an unrelated deadline or the next mouse move. let ctx = Context::default(); let (mut app, mock) = restore_app(&ctx); + let mut held = HeldCommands::new(&mock); frame(&mut app, &ctx); - assert!(mock.hold(SAVE)); + held.hold(SAVE); set_note(&mut app, "typed before"); pump_until(&mut app, &ctx, |_| mock.waiting(SAVE) == 1); app.start_backup_restore("C:/b.json".into(), String::new()); - assert!(mock.hold("backup_restore")); - mock.release(SAVE); - // The write's result and its wake are in before the next frame, which - // then has nothing left to wake it. - std::thread::sleep(LANDED); + held.hold("backup_restore"); + answer_note_write(&mut app, &mut held); pump::within(&mut app, &ctx, NO_TIMER, frame, |_| { mock.waiting("backup_restore") == 1 }); - mock.release("backup_restore"); + held.release("backup_restore"); pump_until(&mut app, &ctx, |a| !a.backup.holds_writes()); } @@ -219,15 +234,13 @@ fn a_note_typed_while_its_store_writes_is_written_when_that_write_ends() { // asked for none: it waited for an unrelated deadline or the next input. let ctx = Context::default(); let (mut app, mock) = restore_app(&ctx); + let mut held = HeldCommands::new(&mock); frame(&mut app, &ctx); - assert!(mock.hold(SAVE)); + held.hold(SAVE); set_note(&mut app, "first"); pump_until(&mut app, &ctx, |_| mock.waiting(SAVE) == 1); set_note(&mut app, "second"); - mock.release(SAVE); - // Past the second note's debounce too: only the frame that reports the - // first write can start the second. - std::thread::sleep(LANDED); + answer_note_write(&mut app, &mut held); pump::within(&mut app, &ctx, NO_TIMER, frame, |_| mock.seen(SAVE) == 2); pump_until(&mut app, &ctx, |a| { !a.booted().unwrap().stores.storage().has_unsaved() diff --git a/crates/accshift-egui/src/app/tests/held.rs b/crates/accshift-egui/src/app/tests/held.rs new file mode 100644 index 00000000..e016259a --- /dev/null +++ b/crates/accshift-egui/src/app/tests/held.rs @@ -0,0 +1,41 @@ +//! A guard for commands a test holds at the mock. + +use std::sync::Arc; + +use accshift_app::mock::MockBackend; + +/// Commands held at the mock for one test, released when it drops. A failed +/// assertion then unwinds through the release: otherwise a worker stays parked +/// at the hold and `Jobs::drop`, joining it, hangs the suite. +pub(super) struct HeldCommands { + mock: Arc, + commands: Vec<&'static str>, +} + +impl HeldCommands { + /// Declare it after the app so it drops first. + pub(super) fn new(mock: &Arc) -> Self { + Self { + mock: mock.clone(), + commands: Vec::new(), + } + } + + pub(super) fn hold(&mut self, command: &'static str) { + self.commands.push(command); + assert!(self.mock.hold(command), "{command} could not be held"); + } + + pub(super) fn release(&mut self, command: &str) { + self.commands.retain(|held| *held != command); + self.mock.release(command); + } +} + +impl Drop for HeldCommands { + fn drop(&mut self) { + for command in self.commands.drain(..) { + self.mock.release(command); + } + } +} diff --git a/crates/accshift-egui/src/app/tests/native_regressions.rs b/crates/accshift-egui/src/app/tests/native_regressions.rs index 4d0b8566..e0348105 100644 --- a/crates/accshift-egui/src/app/tests/native_regressions.rs +++ b/crates/accshift-egui/src/app/tests/native_regressions.rs @@ -1,3 +1,4 @@ +use super::held::HeldCommands; use super::pump; use super::*; use egui::{pos2, vec2, Id, RawInput, Rect, Sense, ViewportId}; @@ -145,42 +146,6 @@ fn native_external_storage_on_focus_refreshes_stores_and_accounts() { assert_eq!(b.accounts.loading.loader.current_account(), "external"); } -/// Commands held at the mock for one test, released when it drops. A failed -/// assertion then unwinds through the release: otherwise a worker stays parked -/// at the hold and `Jobs::drop`, joining it, hangs the suite. -struct HeldCommands { - mock: Arc, - commands: Vec<&'static str>, -} - -impl HeldCommands { - /// Declare it after the app so it drops first. - fn new(mock: &Arc) -> Self { - Self { - mock: mock.clone(), - commands: Vec::new(), - } - } - - fn hold(&mut self, command: &'static str) { - self.commands.push(command); - assert!(self.mock.hold(command), "{command} could not be held"); - } - - fn release(&mut self, command: &str) { - self.commands.retain(|held| *held != command); - self.mock.release(command); - } -} - -impl Drop for HeldCommands { - fn drop(&mut self) { - for command in self.commands.drain(..) { - self.mock.release(command); - } - } -} - /// Waits until a call of `command` sits at its hold in the mock. fn wait_held(mock: &MockBackend, command: &str) { let deadline = Instant::now() + std::time::Duration::from_secs(10); From 4cdaa42b3c60577b2b0e020da12d8ae4ca9ec559 Mon Sep 17 00:00:00 2001 From: meetsu <96637888+klNuno@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:05:53 +0100 Subject: [PATCH 6/6] docs(egui): clarify ignored SIGHUP handling --- crates/accshift-egui/src/window/signal.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/accshift-egui/src/window/signal.rs b/crates/accshift-egui/src/window/signal.rs index e780d2bf..32e62b5e 100644 --- a/crates/accshift-egui/src/window/signal.rs +++ b/crates/accshift-egui/src/window/signal.rs @@ -86,8 +86,8 @@ mod imp { /// The signals that run the close sequence. `SIGHUP` too: its default /// action ends the process on the spot, so a closed terminal or a session - /// that hangs up would lose the pending writes. A signal the parent left - /// ignored (`nohup`, a background job's `SIGINT`) stays ignored. + /// that hangs up would lose the pending writes. An ignored `SIGHUP` + /// stays ignored so `nohup` keeps working. const SIGNALS: [libc::c_int; 3] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP]; /// Puts back the dispositions `install` replaced, last first.