feat(gui): preflight NSH downloads and install Nix runtimes

This commit is contained in:
Kevin Yue committed 2026-11-02 11:42:55 +08:00
1 parent dcc74d805b
commit d825e2b9c8
11 files changed
+369 -22

No files matched your search

+50 -13
View File
@@ -181,6 +181,18 @@ impl<'a> GuiLauncher<'a> {
let variant = selection.variant;
let candidate = Self::new(self.version, self.credential.clone(), variant).envs(self.envs.clone());
let program = candidate.find_compatible_program(cancellation).await?;
if program.is_none() && variant == crate::gui::GuiVariant::Nsh {
use crate::service::transport::DESKTOP_GUI_INSTALLER;
service_input.write_all(&[DESKTOP_GUI_INSTALLER]).await?;
let supplies_runtime = match service_output.read_u8().await? {
0 => false,
1 => true,
_ => anyhow::bail!("Invalid GUI installer capability response"),
};
if !supplies_runtime {
super::nsh_runtime::check()?;
}
}
if program.is_none() && !selection.allow_download {
gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::DownloadRequired)).await?;
return Ok(None);
@@ -486,11 +498,21 @@ mod tests {
#[test]
#[cfg(target_os = "linux")]
fn supervisor_switch_success_and_failure_preserve_child_ownership() {
for scenario in ["success", "failure", "missing", "incompatible"] {
for scenario in [
"success",
"failure",
"missing",
"incompatible",
"runtime-too-old",
"runtime-too-old-confirmed",
] {
let directory = TempDir::new().unwrap();
let executable = std::env::current_exe().unwrap();
// An old host GTK must block generic downloads, but not package-managed downloads.
let gtk = super::super::nsh_runtime::tests::gtk_fixture(directory.path(), 12);
fs::rename(gtk, directory.path().join("libgtk-4.so.1")).unwrap();
for name in ["gpgui", "gpgui-nsh"] {
if scenario == "missing" && name == "gpgui-nsh" {
if (scenario == "missing" || scenario.starts_with("runtime-too-old")) && name == "gpgui-nsh" {
continue;
}
let version = if scenario == "incompatible" && name == "gpgui-nsh" {
@@ -515,6 +537,7 @@ mod tests {
.env("GP_SWITCH_SCENARIO", scenario)
.env("GP_SWITCH_DIRECTORY", directory.path())
.env("GP_GUI_BINARY", directory.path().join("gpgui"))
.env("LD_LIBRARY_PATH", directory.path())
.env("XDG_CONFIG_HOME", directory.path().join("config"))
.output()
.unwrap();
@@ -629,12 +652,15 @@ mod tests {
#[ignore = "subprocess supervisor fixture with isolated GUI paths and preferences"]
#[cfg(target_os = "linux")]
async fn supervisor_fixture() {
use crate::service::transport::{DESKTOP_SWITCH_BEGIN, DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_COMMIT};
use crate::service::transport::{
DESKTOP_GUI_INSTALLER, DESKTOP_SWITCH_BEGIN, DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_COMMIT,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
let scenario = std::env::var("GP_SWITCH_SCENARIO").unwrap();
let success = scenario == "success";
let download_required = matches!(scenario.as_str(), "missing" | "incompatible");
let runtime_too_old = scenario.starts_with("runtime-too-old");
let listener = super::super::gui_switch::SwitchListener::new().unwrap();
let (mut service_input, mut control) = tokio::io::duplex(64);
let (mut service_output, mut credentials) = tokio::io::duplex(2048);
@@ -643,6 +669,9 @@ mod tests {
loop {
let message = control.read_u8().await.unwrap();
match message {
DESKTOP_GUI_INSTALLER => {
credentials.write_all(&[u8::from(!runtime_too_old)]).await.unwrap();
}
DESKTOP_SWITCH_BEGIN => {
fs::write(&service_marker, "").unwrap();
let credential = SessionCredential::generate(Uuid::new_v4(), VERSION).unwrap();
@@ -676,23 +705,21 @@ mod tests {
&listener.path(),
crate::gui::GuiSwitchRequest {
variant: crate::gui::GuiVariant::Nsh,
allow_download: false,
allow_download: scenario == "runtime-too-old-confirmed",
},
)
.await;
if download_required {
if runtime_too_old {
let error = result.unwrap_err().to_string();
anyhow::ensure!(
error.contains("4.14") && error.contains("4.12.1"),
"Unexpected runtime error: {error}"
);
} else if download_required {
anyhow::ensure!(
result? == crate::gui::GuiSwitchOutcome::DownloadRequired,
"Missing download confirmation"
);
anyhow::ensure!(
!directory.join("service-switch-started").exists(),
"Download check changed the service session"
);
anyhow::ensure!(
!directory.join("gpgui-nsh-started").exists(),
"Download check launched the replacement"
);
} else {
anyhow::ensure!(result.is_ok() == success, "Unexpected switch result: {result:?}");
if success {
@@ -702,6 +729,16 @@ mod tests {
);
}
}
if download_required || runtime_too_old {
anyhow::ensure!(
!directory.join("service-switch-started").exists(),
"Download check changed the service session"
);
anyhow::ensure!(
!directory.join("gpgui-nsh-started").exists(),
"Download check launched the replacement"
);
}
anyhow::ensure!(
!directory.join("gpgui-exited").exists(),
"Current GUI exited before acknowledgement"
+2
View File
@@ -11,6 +11,8 @@ pub mod desktop_launcher;
pub mod gui_launcher;
#[cfg(target_os = "linux")]
pub mod gui_switch;
#[cfg(any(target_os = "linux", test))]
mod nsh_runtime;
pub mod users;
pub mod collection;
+105
View File
@@ -0,0 +1,105 @@
//! Checks the generic Linux NSH runtime before offering a download.
//! Runs in the desktop supervisor, which does not load either GUI's GTK runtime.
use std::{ffi::OsStr, os::raw::c_uint};
use anyhow::{Context, ensure};
use libloading::{
Library,
os::unix::{RTLD_LOCAL, RTLD_NOW},
};
// Match nsh-platform-linux's gtk4/v4_14 feature when changing the NSH build.
const MIN_GTK_MINOR: u32 = 14;
#[cfg(target_os = "linux")]
pub(super) fn check() -> anyhow::Result<()> {
check_gtk(OsStr::new("libgtk-4.so.1"))?;
load_library(OsStr::new("libgnutls.so.30"), "GnuTLS 3")?;
load_library(OsStr::new("libdbus-1.so.3"), "D-Bus")?;
Ok(())
}
fn load_library(path: &OsStr, name: &str) -> anyhow::Result<Library> {
// Resolve symbols now as well as transitive dependencies, without initializing GTK.
let library = unsafe { libloading::os::unix::Library::open(Some(path), RTLD_LOCAL | RTLD_NOW) };
library.map(Into::into).map_err(|error| {
log::warn!("Native Shell runtime check failed for {name}: {error}");
anyhow::anyhow!("Native Shell could not load {name}. Install its runtime libraries and try again.")
})
}
fn check_gtk(path: &OsStr) -> anyhow::Result<()> {
let library = load_library(path, "GTK 4.14 or later")?;
type Version = unsafe extern "C" fn() -> c_uint;
// These public GTK getters take no arguments and do not initialize a display.
let (major, minor, micro) = unsafe {
let major = library.get::<Version>(b"gtk_get_major_version\0");
let minor = library.get::<Version>(b"gtk_get_minor_version\0");
let micro = library.get::<Version>(b"gtk_get_micro_version\0");
let message = "Native Shell requires GTK 4.14 or later. Update GTK 4 and try again.";
(
major.context(message)?(),
minor.context(message)?(),
micro.context(message)?(),
)
};
ensure!(
major == 4 && minor >= MIN_GTK_MINOR,
"Native Shell requires GTK 4.14 or later. This system has GTK {major}.{minor}.{micro}."
);
Ok(())
}
#[cfg(test)]
pub(super) mod tests {
use super::*;
use std::{fs, process::Command};
pub(in crate::process) fn gtk_fixture(directory: &std::path::Path, minor: u32) -> std::path::PathBuf {
let source = directory.join(format!("gtk-{minor}.c"));
let library = directory.join(format!("gtk-{minor}.so"));
fs::write(
&source,
format!(
"unsigned gtk_get_major_version(void) {{ return 4; }}\n\
unsigned gtk_get_minor_version(void) {{ return {minor}; }}\n\
unsigned gtk_get_micro_version(void) {{ return 1; }}\n"
),
)
.unwrap();
assert!(
Command::new("cc")
.args(["-shared", "-fPIC"])
.arg(source)
.arg("-o")
.arg(&library)
.status()
.unwrap()
.success()
);
library
}
#[test]
fn loads_runtime_version_without_development_metadata_or_a_display() {
let directory = tempfile::tempdir().unwrap();
let old = gtk_fixture(directory.path(), 12);
let supported = gtk_fixture(directory.path(), 14);
let newer = gtk_fixture(directory.path(), 20);
let error = check_gtk(old.as_os_str()).unwrap_err().to_string();
assert!(error.contains("4.14"), "{error}");
assert!(error.contains("4.12.1"), "{error}");
check_gtk(supported.as_os_str()).unwrap();
check_gtk(newer.as_os_str()).unwrap();
}
#[test]
fn missing_runtime_reports_an_actionable_error() {
let directory = tempfile::tempdir().unwrap();
let error = check_gtk(directory.path().join("missing.so").as_os_str())
.unwrap_err()
.to_string();
assert!(error.contains("GTK 4.14 or later"), "{error}");
assert!(error.contains("Install"), "{error}");
}
}
@@ -24,3 +24,5 @@ pub const DESKTOP_RENDERING_RETRY: u8 = 1;
pub const DESKTOP_SWITCH_BEGIN: u8 = 2;
pub const DESKTOP_SWITCH_COMMIT: u8 = 3;
pub const DESKTOP_SWITCH_CANCEL: u8 = 4;
/// Query whether the service package can install GUI runtime dependencies; replies with 0 or 1.
pub const DESKTOP_GUI_INSTALLER: u8 = 5;