diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 28d2bedc..77d816a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,6 +90,10 @@ jobs: - run: npm run build:desktop - run: cargo fmt --manifest-path src-tauri/Cargo.toml -- --check - run: cargo test --manifest-path src-tauri/Cargo.toml + - name: Verify native close-to-tray and explicit Quit + run: | + cargo build --manifest-path src-tauri/Cargo.toml --example close-to-tray + python3 scripts/test-close-to-tray.py src-tauri/target/debug/examples/close-to-tray - name: Install disposable native VS Code test dependency run: | curl --fail --location --retry 3 https://update.code.visualstudio.com/latest/darwin-arm64/stable -o "$RUNNER_TEMP/vscode.zip" diff --git a/tauri/scripts/test-close-to-tray.py b/tauri/scripts/test-close-to-tray.py new file mode 100644 index 00000000..d53579e9 --- /dev/null +++ b/tauri/scripts/test-close-to-tray.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +"""Prove the old event handler fails and the fixed native lifecycle passes.""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +binary = str(Path(sys.argv[1]).resolve()) +with tempfile.TemporaryDirectory(prefix="multi-codex-tray-") as temporary: + env = dict(os.environ, HOME=temporary, XDG_DATA_HOME=temporary) + before = subprocess.run( + [binary, "--without-exit-guard"], env=env, capture_output=True, text=True, timeout=45 + ) + assert before.returncode != 0, "Regression check did not detect the missing exit guard" + assert "automatic last-window exit stopped the tray process" in before.stderr, before.stderr + print("Confirmed old handler fails: automatic last-window exit stopped the tray process") + subprocess.run([binary], env=env, check=True, timeout=45) diff --git a/tauri/src-tauri/examples/close-to-tray.rs b/tauri/src-tauri/examples/close-to-tray.rs new file mode 100644 index 00000000..cfe15f46 --- /dev/null +++ b/tauri/src-tauri/examples/close-to-tray.rs @@ -0,0 +1,122 @@ +//! Native event-loop regression check, run on macOS CI with disposable state. +#[path = "../src/lifecycle.rs"] +mod lifecycle; + +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tauri::Manager; + +#[derive(Default)] +struct Evidence { + hidden: bool, + reopened: bool, + automatic_exit: bool, + explicit_quit: bool, + completed: bool, +} + +fn main() { + let without_guard = std::env::args().any(|arg| arg == "--without-exit-guard"); + let evidence = Arc::new(Mutex::new(Evidence::default())); + let observed = Arc::clone(&evidence); + let app = tauri::Builder::default() + .on_window_event(lifecycle::on_window_event) + .setup(|app| { + tauri::WebviewWindowBuilder::new(app, "main", tauri::WebviewUrl::default()) + .title("Multi Codex close-to-tray regression") + .build()?; + tauri::tray::TrayIconBuilder::with_id("accounts") + .icon(tauri::image::Image::from_bytes(include_bytes!( + "../icons/menu-bar.png" + ))?) + .icon_as_template(cfg!(target_os = "macos")) + .build(app)?; + Ok(()) + }) + .build(tauri::test::mock_context(tauri::test::noop_assets())) + .expect("build native lifecycle fixture"); + let started = Instant::now(); + let mut phase = 0; + let mut automatic_exit_at = None; + let code = app.run_return(move |app, event| { + if !without_guard { + lifecycle::on_run_event(&event); + } + match event { + tauri::RunEvent::Ready => { + app.get_webview_window("main").unwrap().close().unwrap(); + } + tauri::RunEvent::ExitRequested { code: None, .. } => { + observed.lock().unwrap().automatic_exit = true; + automatic_exit_at = Some(Instant::now()); + // Wake a later iteration so a pending exit cannot accidentally + // pass on the final MainEventsCleared before LoopDestroyed. + let handle = app.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(250)); + let _ = handle.run_on_main_thread(|| {}); + }); + } + tauri::RunEvent::ExitRequested { code: Some(0), .. } => { + observed.lock().unwrap().explicit_quit = true; + } + tauri::RunEvent::MainEventsCleared => { + assert!( + started.elapsed() < Duration::from_secs(20), + "lifecycle check timed out" + ); + assert!( + app.tray_by_id("accounts").is_some(), + "account tray was removed" + ); + match phase { + 0 => { + let window = app + .get_webview_window("main") + .expect("close destroyed main window"); + if !window.is_visible().unwrap() { + observed.lock().unwrap().hidden = true; + window.show().unwrap(); + phase = 1; + } + } + 1 => { + let window = app.get_webview_window("main").unwrap(); + if window.is_visible().unwrap() { + observed.lock().unwrap().reopened = true; + // Exercise the separate last-window ExitRequested path, + // which a CloseRequested listener cannot intercept. + window.destroy().unwrap(); + phase = 2; + } + } + 2 if automatic_exit_at + .is_some_and(|at| at.elapsed() >= Duration::from_millis(200)) => + { + observed.lock().unwrap().completed = true; + phase = 3; + app.exit(0); + } + _ => {} + } + } + _ => {} + } + }); + let evidence = evidence.lock().unwrap(); + assert!(evidence.hidden, "close did not hide the main window"); + assert!(evidence.reopened, "hidden main window did not reopen"); + assert!( + evidence.automatic_exit, + "last-window exit path was not exercised" + ); + assert!( + evidence.completed, + "automatic last-window exit stopped the tray process" + ); + assert!(evidence.explicit_quit, "explicit Quit was blocked"); + assert_eq!(code, 0); + println!( + "PASS: close hides, reopen works, tray survives last-window exit, explicit Quit exits" + ); +} diff --git a/tauri/src-tauri/src/lib.rs b/tauri/src-tauri/src/lib.rs index ef25094a..c2afcfec 100644 --- a/tauri/src-tauri/src/lib.rs +++ b/tauri/src-tauri/src/lib.rs @@ -1,3 +1,5 @@ +mod lifecycle; + #[cfg(all(test, target_os = "macos"))] #[path = "../../../cli/crates/core/src/macos_navigation.rs"] mod macos_navigation; @@ -1005,15 +1007,7 @@ pub fn run() { }); Ok(()) }) - .on_window_event(|window, event| { - #[cfg(any(target_os = "macos", target_os = "linux"))] - if window.label() == "main" { - if let tauri::WindowEvent::CloseRequested { api, .. } = event { - api.prevent_close(); - let _ = window.hide(); - } - } - }) + .on_window_event(lifecycle::on_window_event) .invoke_handler(tauri::generate_handler![ hud::hud_snapshot, hud::hud_save_settings, @@ -1079,6 +1073,7 @@ pub fn run() { .build(tauri::generate_context!()) .expect("error while building Multi Codex"); app.run(|_app, _event| { + lifecycle::on_run_event(&_event); if matches!(_event, tauri::RunEvent::Exit) { hud_platform::cleanup(); } diff --git a/tauri/src-tauri/src/lifecycle.rs b/tauri/src-tauri/src/lifecycle.rs new file mode 100644 index 00000000..209bf62d --- /dev/null +++ b/tauri/src-tauri/src/lifecycle.rs @@ -0,0 +1,26 @@ +//! Keep the account tray alive independently of the launcher window. + +pub fn on_window_event(window: &tauri::Window, event: &tauri::WindowEvent) { + #[cfg(any(target_os = "macos", target_os = "linux"))] + if window.label() == "main" { + if let tauri::WindowEvent::CloseRequested { api, .. } = event { + api.prevent_close(); + if let Err(error) = window.hide() { + eprintln!("Multi Codex could not hide its window: {error}"); + } + } + } +} + +pub fn on_run_event(event: &tauri::RunEvent) { + // Closing the last native window can request process exit separately from + // CloseRequested. The tray must survive that request. Explicit Quit and + // updater restarts carry an exit code and must still be allowed through. + #[cfg(any(target_os = "macos", target_os = "linux"))] + if let tauri::RunEvent::ExitRequested { + code: None, api, .. + } = event + { + api.prevent_exit(); + } +}