desktop: Write pending changes before the window closes

Views can hold back writes to batch them, which would be lost if the
window closed in the meantime. The first close is held until registered
views have flushed, writing locally without announcing, with a 5 second
fallback. On macOS, Quit goes through the same path instead of
terminating the app directly.
This commit is contained in:
Rūdolfs Ošiņš
2026-11-06 18:21:33 +01:00
parent e29def0dda
commit 244e2dc44c
4 changed files with 126 additions and 3 deletions
@@ -14,6 +14,7 @@
"core:resources:default",
"core:tray:default",
"core:webview:default",
"core:window:allow-close",
"core:window:allow-set-badge-count",
"core:window:allow-start-dragging",
"core:window:default",
+84 -3
View File
@@ -1,7 +1,12 @@
mod commands;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use radicle_types::AppState;
use tauri::Manager;
#[cfg(target_os = "macos")]
use tauri::menu::{Menu, MenuItem, MenuItemKind};
use tauri::{Emitter, Manager};
use tauri_plugin_log::{Target, TargetKind};
use commands::{auth, cob, diff, identity, inbox, profile, repo, startup, thread};
@@ -52,7 +57,7 @@ pub fn run() {
.build(),
);
builder
let builder = builder
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_clipboard_manager::init())
@@ -61,7 +66,18 @@ pub fn run() {
.setup(|app| {
register_rad_scheme(app);
Ok(())
})
});
// Tauri only installs a default menu on macOS, so only there is one
// replaced.
#[cfg(target_os = "macos")]
let builder = builder.menu(app_menu).on_menu_event(|app, event| {
if event.id() == QUIT {
quit(app);
}
});
builder
.on_window_event(flush_before_close)
.invoke_handler(tauri::generate_handler![
auth::authenticate,
auth::init,
@@ -151,6 +167,71 @@ pub fn run() {
.expect("error while running tauri application");
}
#[cfg(target_os = "macos")]
const QUIT: &str = "quit";
// The default menu's Quit terminates the app without closing its window, which
// would skip the flush below, so it's replaced by one that closes the window.
#[cfg(target_os = "macos")]
fn app_menu<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<Menu<R>> {
let menu = Menu::default(app)?;
for item in menu.items()? {
let MenuItemKind::Submenu(submenu) = item else {
continue;
};
for (index, entry) in submenu.items()?.into_iter().enumerate() {
let MenuItemKind::Predefined(predefined) = entry else {
continue;
};
let text = predefined.text()?;
if !text.trim_start_matches('&').starts_with("Quit") {
continue;
}
submenu.remove(&predefined)?;
let item = MenuItem::with_id(app, QUIT, text, true, Some("CmdOrCtrl+Q"))?;
submenu.insert(&item, index)?;
}
}
Ok(menu)
}
#[cfg(target_os = "macos")]
fn quit<R: tauri::Runtime>(app: &tauri::AppHandle<R>) {
match app.get_webview_window("main") {
Some(window) => {
if let Err(e) = window.close() {
log::warn!("Unable to close the main window: {e}");
app.exit(0);
}
}
None => app.exit(0),
}
}
// The frontend holds back some writes, such as board changes, to batch them.
// The first close asks it to flush and close the window itself, which it does
// as soon as the flush is through; if it doesn't within five seconds, the
// window closes anyway.
fn flush_before_close(window: &tauri::Window, event: &tauri::WindowEvent) {
static CLOSING: AtomicBool = AtomicBool::new(false);
let tauri::WindowEvent::CloseRequested { api, .. } = event else {
return;
};
if CLOSING.swap(true, Ordering::SeqCst) {
return;
}
api.prevent_close();
if let Err(e) = window.emit("close-requested", ()) {
log::warn!("Unable to ask the frontend to flush before closing: {e}");
}
let window = window.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_secs(5));
let _ = window.close();
});
}
// Installers register the scheme; an AppImage has to do it at runtime. It
// must never keep the app from starting, nor take the scheme from another
// handler, such as an installed package or one the user chose.
+39
View File
@@ -0,0 +1,39 @@
import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
import once from "lodash/once";
// A flush writes what a view holds back; `announce` is whether the writes
// are announced to the network as well.
type Flush = (announce: boolean) => Promise<void>;
const flushes = new Set<Flush>();
// Closing writes locally only: the commits and signed refs land, and peers
// learn of them with the next announcement for the repository or when the
// node restarts.
async function flushAll() {
await Promise.allSettled([...flushes].map(flush => flush(false)));
}
// The backend holds the first close of the window until the frontend has
// written what it was holding back, and closing the window once that's done
// lets it go right away. The test backend has no window, so the page flushes
// as it goes away or is hidden instead.
export const listenForClose = once(async () => {
if (!window.__TAURI_INTERNALS__) {
window.addEventListener("pagehide", () => void flushAll());
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") void flushAll();
});
return;
}
await listen("close-requested", async () => {
await flushAll();
await getCurrentWindow().close();
});
});
export function flushBeforeClose(flush: Flush): () => void {
flushes.add(flush);
return () => flushes.delete(flush);
}
+2
View File
@@ -2,6 +2,7 @@ import "overlayscrollbars/overlayscrollbars.css";
import { mount } from "svelte";
import App from "./App.svelte";
import { listenForClose } from "./lib/closeFlush";
import { disableDropNavigation } from "./lib/disableDropNavigation";
import { disableNativeContextMenu } from "./lib/disableNativeContextMenu";
@@ -9,5 +10,6 @@ const app = mount(App, { target: document.body });
disableNativeContextMenu();
disableDropNavigation();
void listenForClose();
export default app;