Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
18 changes: 18 additions & 0 deletions tauri/scripts/test-close-to-tray.py
Original file line number Diff line number Diff line change
@@ -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)
122 changes: 122 additions & 0 deletions tauri/src-tauri/examples/close-to-tray.rs
Original file line number Diff line number Diff line change
@@ -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"
);
}
13 changes: 4 additions & 9 deletions tauri/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
mod lifecycle;

#[cfg(all(test, target_os = "macos"))]
#[path = "../../../cli/crates/core/src/macos_navigation.rs"]
mod macos_navigation;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();
}
Expand Down
26 changes: 26 additions & 0 deletions tauri/src-tauri/src/lifecycle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! Keep the account tray alive independently of the launcher window.

pub fn on_window_event<R: tauri::Runtime>(window: &tauri::Window<R>, 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();
}
}
Loading