Skip to content
Open
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
70 changes: 70 additions & 0 deletions .github/workflows/desktop-window-lifecycle.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
name: Windows Desktop Window Lifecycle

on:
push:
paths:
- 'apps/desktop/src-tauri/**'
- '.github/workflows/desktop-window-lifecycle.yml'
pull_request:
paths:
- 'apps/desktop/src-tauri/**'
- '.github/workflows/desktop-window-lifecycle.yml'
workflow_dispatch:

permissions:
contents: read

jobs:
windows:
runs-on: windows-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: Swatinem/rust-cache@v2
with:
workspaces: apps/desktop/src-tauri
- name: Prepare Compile-Only Resources
shell: pwsh
run: |
# Tests and the unbundled executable need no downloaded Node, Control,
# Engine or frontend. Only this disposable build checkout is changed.
$configPath = 'apps/desktop/src-tauri/tauri.conf.json'
$config = Get-Content -Raw -LiteralPath $configPath | ConvertFrom-Json -AsHashtable
$config.build.frontendDist = 'ci-placeholder'
$config.bundle.resources = @{}
$config.bundle.active = $false
New-Item -ItemType Directory -Path 'apps/desktop/src-tauri/ci-placeholder' -Force | Out-Null
Set-Content -LiteralPath 'apps/desktop/src-tauri/ci-placeholder/index.html' -Value '<!doctype html><title>Compile Only</title>'
$config | ConvertTo-Json -Depth 30 | Set-Content -LiteralPath $configPath
- name: Test Native Windows Lifecycle
shell: pwsh
working-directory: apps/desktop/src-tauri
run: |
cargo test --locked -- --test-threads=1
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Build Unbundled Native Shell
shell: pwsh
working-directory: apps/desktop/src-tauri
run: |
cargo build --locked --release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Record Native Artifact Provenance
shell: pwsh
run: |
$exe = 'apps/desktop/src-tauri/target/release/strata-desktop.exe'
New-Item -ItemType Directory -Path 'window-lifecycle-artifact' | Out-Null
Copy-Item -LiteralPath $exe -Destination 'window-lifecycle-artifact/strata-desktop.exe'
@{
schema = 1
sourceCommit = $env:GITHUB_SHA
sourceRepository = $env:GITHUB_REPOSITORY
sha256 = (Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()
bytes = (Get-Item -LiteralPath $exe).Length
compileOnlyResources = $true
} | ConvertTo-Json | Set-Content -LiteralPath 'window-lifecycle-artifact/provenance.json'
- uses: actions/upload-artifact@v4
with:
name: windows-window-lifecycle
path: window-lifecycle-artifact/
if-no-files-found: error
retention-days: 14
2 changes: 1 addition & 1 deletion apps/desktop/src-tauri/src/desktoplog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ mod tests {
let path = write_startup_failure(&dir, "the app stopped unexpectedly: boom (at main.rs:1, thread main)", Some(Path::new("/x/desktop-1.log"))).unwrap();
assert!(path.file_name().unwrap().to_string_lossy().starts_with("desktop-crash-"));
let text = std::fs::read_to_string(&path).unwrap();
for needle in ["boom", "main.rs:1", "/x/desktop-1.log", "0.2.0", "System:", "Meaning:"] {
for needle in ["boom", "main.rs:1", "/x/desktop-1.log", env!("CARGO_PKG_VERSION"), "System:", "Meaning:"] {
assert!(text.contains(needle), "{needle}");
}
let _ = std::fs::remove_dir_all(&dir);
Expand Down
16 changes: 16 additions & 0 deletions apps/desktop/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ use tauri::{Manager, WebviewUrl, WebviewWindowBuilder};
mod updater;
mod desktoplog;
mod shell;
#[cfg(windows)]
mod window_lifecycle;
#[cfg(target_os = "linux")]
mod supervisor;

Expand Down Expand Up @@ -882,6 +884,8 @@ fn run_embedded() {
tauri::Builder::default()
// First, as the plugin requires: a second launch ends here after telling the running app to show itself.
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
#[cfg(windows)]
if window_lifecycle::second_launch(app, &_args) { return; }
if let Some(window) = app.get_webview_window("main") {
let _ = window.unminimize();
let _ = window.show();
Expand All @@ -900,6 +904,16 @@ fn run_embedded() {
panic!("STRATA_DESKTOP_TEST_PANIC is set: the app panics on purpose");
}
let handle = app.handle().clone();
#[cfg(windows)]
{
// A cold explicit Quit starts neither the Host nor a window.
if window_lifecycle::quit_requested(&std::env::args().collect::<Vec<_>>()) {
handle.exit(0);
return Ok(());
}
handle.manage(window_lifecycle::Policy::from_environment());
handle.state::<window_lifecycle::Policy>().watch_owner(handle.clone());
}
// A setup error would become a panic inside Tauri ("Failed to setup app"), and with panic = "abort" a crash with no message.
// A failed start is reported (log, crash file, message box) and ends the app here instead.
let port = match start_host(&handle) {
Expand All @@ -917,6 +931,8 @@ fn run_embedded() {
Ok(())
})
.on_window_event(|window, event| {
#[cfg(windows)]
if window_lifecycle::close(window, event) { return; }
// "Minimise to tray" (Settings, off by default): closing the main window hides it and keeps Strata running in the tray; Quit in the
// tray menu ends it (#3477). If no tray could be made the window closes as before.
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
Expand Down
159 changes: 159 additions & 0 deletions apps/desktop/src-tauri/src/window_lifecycle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
//! Opt-in Windows window lifetime. No engine, UI or updater ownership changes.
use std::sync::Arc;
use tauri::Manager;

#[cfg(windows)]
mod owner {
use std::{ffi::c_void, path::PathBuf};
type Handle = *mut c_void;
#[link(name = "kernel32")]
extern "system" {
fn OpenProcess(access: u32, inherit: i32, pid: u32) -> Handle;
fn QueryFullProcessImageNameW(process: Handle, flags: u32, image: *mut u16, size: *mut u32) -> i32;
fn WaitForSingleObject(handle: Handle, timeout: u32) -> u32;
fn CloseHandle(handle: Handle) -> i32;
}
pub struct Owner(Handle);
unsafe impl Send for Owner {}
unsafe impl Sync for Owner {}
impl Owner {
pub fn open(pid: u32, image: &str) -> Option<Self> {
if pid == 0 || !PathBuf::from(image).is_absolute() { return None; }
let handle = unsafe { OpenProcess(0x0010_0000 | 0x1000, 0, pid) };
if handle.is_null() { return None; }
let owner = Self(handle);
let mut buffer = vec![0u16; 32768];
let mut size = buffer.len() as u32;
if unsafe { QueryFullProcessImageNameW(handle, 0, buffer.as_mut_ptr(), &mut size) } == 0 {
return None;
}
let actual = String::from_utf16_lossy(&buffer[..size as usize]);
if !actual.eq_ignore_ascii_case(image) || !owner.alive() { return None; }
Some(owner)
}
pub fn alive(&self) -> bool { unsafe { WaitForSingleObject(self.0, 0) == 258 } }
pub fn wait(&self) { unsafe { WaitForSingleObject(self.0, u32::MAX); } }
}
impl Drop for Owner { fn drop(&mut self) { unsafe { CloseHandle(self.0); } } }
}

pub struct Policy {
#[cfg(windows)]
owner: Option<Arc<owner::Owner>>,
}

impl Policy {
pub fn from_environment() -> Self {
#[cfg(windows)]
{
let enabled = std::env::var("STRATA_CLOSE_TO_TRAY").ok().as_deref() == Some("1");
let pid = std::env::var("STRATA_TRAY_PID").ok().and_then(|v| v.parse().ok());
let image = std::env::var("STRATA_TRAY_IMAGE").ok();
let owner = if enabled {
pid.zip(image).and_then(|(pid, image)| owner::Owner::open(pid, &image)).map(Arc::new)
} else { None };
Self { owner }
}
#[cfg(not(windows))]
Self {}
}

pub fn can_hide(&self) -> bool {
#[cfg(windows)]
{ self.owner.as_ref().map(|owner| owner.alive()).unwrap_or(false) }
#[cfg(not(windows))]
{ false }
}

pub fn watch_owner(&self, app: tauri::AppHandle) {
#[cfg(windows)]
if let Some(owner) = self.owner.clone() {
// Hold this exact process handle: PID reuse cannot change the owner.
std::thread::spawn(move || { owner.wait(); app.exit(0); });
}
}
}

pub fn quit_requested(args: &[String]) -> bool {
args.iter().any(|arg| arg == "--quit")
}

pub fn second_launch(app: &tauri::AppHandle, args: &[String]) -> bool {
if quit_requested(args) {
app.exit(0); // Explicit quit uses the original clean Host shutdown.
return true;
}
false // Keep the existing single-instance restore path in main.rs.
}

pub fn close(window: &tauri::Window, event: &tauri::WindowEvent) -> bool {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
if window.label() == "main" && window.app_handle().state::<Policy>().can_hide() {
// Only prevent destruction after hide succeeds. Without a live Tray,
// normal close remains available and cannot strand an invisible App.
if window.hide().is_ok() { api.prevent_close(); return true; }
}
}
false
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn explicit_quit_does_not_match_other_arguments() {
let args = |values: &[&str]| values.iter().map(|value| value.to_string()).collect::<Vec<_>>();
assert!(quit_requested(&args(&["strata-desktop", "--quit"])));
assert!(!quit_requested(&args(&["strata-desktop", "--quit-later"])));
assert!(!quit_requested(&args(&["strata-desktop", "a--quit.exe"])));
assert!(!quit_requested(&[]));
}

#[cfg(windows)]
#[test]
fn owner_requires_the_exact_live_executable() {
let image = crate::plain_path(std::env::current_exe().unwrap()).to_string_lossy().into_owned();
let pid = std::process::id();
let owner = owner::Owner::open(pid, &image).expect("the current test process");
assert!(owner.alive());
assert!(owner::Owner::open(pid, &format!("{image}.other")).is_none());
assert!(owner::Owner::open(pid, "relative.exe").is_none());
assert!(owner::Owner::open(0, &image).is_none());
}

#[cfg(windows)]
#[test]
fn a_held_owner_stops_enabling_hide_when_that_process_exits() {
use std::os::windows::process::CommandExt;
use std::process::{Command, Stdio};
let image = std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap())
.join("System32").join("ping.exe");
let mut child = Command::new(&image).args(["-n", "60", "127.0.0.1"])
.creation_flags(0x0800_0000).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())
.spawn().expect("a disposable owner with no console window");
let opened = owner::Owner::open(child.id(), &image.to_string_lossy());
// Always end the disposable process, including if the identity assertion fails.
let was_alive = opened.as_ref().map(|owner| owner.alive()).unwrap_or(false);
let _ = child.kill();
child.wait().unwrap();
let owner = opened.expect("the exact disposable process");
owner.wait();
let policy = Policy { owner: Some(Arc::new(owner)) };
assert!(was_alive);
assert!(!policy.can_hide(), "a dead owner cannot strand an invisible App");
}

#[test]
fn missing_or_unverified_tray_never_enables_hide() {
std::env::remove_var("STRATA_CLOSE_TO_TRAY");
assert!(!Policy::from_environment().can_hide());
std::env::set_var("STRATA_CLOSE_TO_TRAY", "1");
std::env::set_var("STRATA_TRAY_PID", "0");
std::env::set_var("STRATA_TRAY_IMAGE", "relative.exe");
assert!(!Policy::from_environment().can_hide());
std::env::remove_var("STRATA_CLOSE_TO_TRAY");
std::env::remove_var("STRATA_TRAY_PID");
std::env::remove_var("STRATA_TRAY_IMAGE");
}
}
29 changes: 29 additions & 0 deletions docs/CLOSING.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,35 @@ in that order instead of the engine dying under a request.
`strata_control/procs.py` is the identity rule behind every "is this still the process I started": PID **and** start time
**and** command line, checked again at the moment of each signal. A PID alone is never signalled.

## Optional Windows Close To Tray

The default X still closes the App. A Windows Tray companion may opt into hiding
the main window instead by supplying all three environment values when it launches
the App:

```text
STRATA_CLOSE_TO_TRAY=1
STRATA_TRAY_PID=<the live companion process ID>
STRATA_TRAY_IMAGE=<the companion's absolute executable path>
```

The companion must provide a visible way to open and exit the App. The shell
checks the process image, holds that exact process handle and watches its exit.
A missing, inaccessible, exited or mismatched owner keeps normal X behavior.
With a live verified owner, X hides only the main window and keeps the same Host
alive. It does not detach an Engine or change its normal idle-unload setting.
Launching the App again uses the existing single-instance restore path.

`strata-desktop.exe --quit` is an explicit Windows exit, including while hidden.
A cold `--quit` starts neither a Host nor a window. When the verified Tray owner
exits, the App exits through the existing Host cleanup path. Updater exit, crash
containment, the Windows Job and Linux/macOS behavior are unchanged. This adds no
Tray icon, startup entry, launcher, HTTP endpoint or frontend permission.

The [acceptance record](windows-close-to-tray/README.md) records this candidate's
native X, same-window Tray Reopen and hidden-window Web inference separately from
the earlier deployed Extension reference.

## Leftovers, and how they are found

Every engine, image encoder and server Strata starts writes a small private record (`<state>/procs/<pid>.json`: PID, start
Expand Down
Loading
Loading