From 0ed7592131f00d06a00bb713070b242b3f48838e Mon Sep 17 00:00:00 2001 From: kev1n77 <59403997+kev1n77@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:25:07 +0800 Subject: [PATCH 1/3] feat(desktop): support verified in-app updates on macOS, Windows and Linux --- scripts/desktop-nsh-package-common.mjs | 9 +- scripts/desktop-release-assets.mjs | 8 +- scripts/generate-tauri-latest-json.mjs | 19 +- scripts/package-desktop-nsh-linux.mjs | 7 +- scripts/package-desktop-nsh-windows.mjs | 6 +- scripts/tauri-release-manifest.test.mjs | 24 +- scripts/verify-tauri-latest-json.mjs | 14 +- src/apps/desktop/README.md | 6 +- src/apps/desktop/src/api/update_api.rs | 2 +- src/apps/desktop/src/backend_protocol/mod.rs | 1 + .../backend_protocol/native_commands/mod.rs | 1 + .../native_commands/update.rs | 395 ++++++++++++++---- src/apps/desktop/src/native_host.rs | 1 + .../src/update_maintenance/linux_update.sh | 37 ++ .../desktop/src/update_maintenance/mod.rs | 116 ++++- .../src/update_maintenance/portable.rs | 281 +++++++++++++ .../desktop/src/update_maintenance/windows.rs | 89 ++++ .../src/update_maintenance/windows_update.ps1 | 76 ++++ src/nsh-ui/App.test.tsx | 97 +++++ src/nsh-ui/App.tsx | 149 +++++-- src/nsh-ui/src/locales/en-US.ts | 3 +- src/nsh-ui/src/locales/zh-CN.ts | 3 +- src/nsh-ui/src/locales/zh-TW.ts | 3 +- 23 files changed, 1202 insertions(+), 145 deletions(-) create mode 100644 src/apps/desktop/src/update_maintenance/linux_update.sh create mode 100644 src/apps/desktop/src/update_maintenance/portable.rs create mode 100644 src/apps/desktop/src/update_maintenance/windows.rs create mode 100644 src/apps/desktop/src/update_maintenance/windows_update.ps1 diff --git a/scripts/desktop-nsh-package-common.mjs b/scripts/desktop-nsh-package-common.mjs index 2473be3e96..fa4c1ec195 100644 --- a/scripts/desktop-nsh-package-common.mjs +++ b/scripts/desktop-nsh-package-common.mjs @@ -599,10 +599,10 @@ export function requireFiles(files) { } /** - * Records how a package directory was built next to it (not inside it): - * `.package.json`. + * Writes the build receipt next to the package. Portable desktop updates also + * need the receipt inside the signed archive to identify the installation. */ -export function writePackageInfo(packageDir, { profile, target, identity, version, executable }) { +export function writePackageInfo(packageDir, { profile, target, identity, version, executable, inBundle = false }) { const info = { schemaVersion: 1, profile, @@ -615,6 +615,9 @@ export function writePackageInfo(packageDir, { profile, target, identity, versio assemblyDigest: identity.assemblyDigest, }; writeFileSync(`${packageDir}.package.json`, `${JSON.stringify(info, null, 2)}\n`); + if (inBundle) { + writeFileSync(join(packageDir, "openbitfun-package.json"), `${JSON.stringify(info, null, 2)}\n`); + } return info; } diff --git a/scripts/desktop-release-assets.mjs b/scripts/desktop-release-assets.mjs index f224804ab5..00ad9bc9a1 100644 --- a/scripts/desktop-release-assets.mjs +++ b/scripts/desktop-release-assets.mjs @@ -13,12 +13,8 @@ // macOS manual installer (`manual_installers["darwin-"]`). // OpenBitFun-nsh__-windows.zip (+ .sig) // OpenBitFun-nsh__-linux.tar.gz (+ .sig) -// Windows and Linux manual downloads (`manual_installers["windows-*"]`, -// `manual_installers["linux-*"]`). There is no native installer or -// in-place updater for them yet, so `platforms` never carries a -// `windows-*` or `linux-*` key: an older Tauri package under a newer -// manifest version would make an installed Tauri app reinstall it in a -// loop, while a missing key makes it report that no package exists. +// Windows and Linux portable downloads. An updater manifest can also +// list these archives under native `*-nsh` platform keys. import { basename } from 'node:path'; const NATIVE_UPDATER = /^OpenBitFun-nsh_(.+)_(aarch64|x86_64)\.app\.tar\.gz$/; diff --git a/scripts/generate-tauri-latest-json.mjs b/scripts/generate-tauri-latest-json.mjs index cb7f5aca3f..ee1b228580 100644 --- a/scripts/generate-tauri-latest-json.mjs +++ b/scripts/generate-tauri-latest-json.mjs @@ -6,7 +6,8 @@ // platforms["darwin--nsh"] the native updater archive + signature // platforms["darwin-"] the SAME archive + signature: the bridge an // installed Tauri build updates through -// no windows-* / linux-* platform keys (no native in-place updater yet) +// Windows/Linux native entries are emitted when requested with +// --required-platforms and point to the signed portable archives. // manual_installers["darwin-"] the DMG // manual_installers["windows-x86_64"] the native Windows zip // manual_installers["linux-"] the native Linux tarball @@ -70,16 +71,10 @@ if (Object.keys(platforms).length === 0) { fail('No signed native updater archives were found. Expected OpenBitFun-nsh__.app.tar.gz with its .sig.'); } -const missingPlatforms = requiredPlatforms.filter((platform) => !platforms[platform]); -if (missingPlatforms.length > 0) { - fail(`Missing required updater platforms: ${missingPlatforms.join(', ')}`); -} - const manifest = { version, notes: notesFile && existsSync(notesFile) ? readFileSync(notesFile, 'utf8').trim() : '', pub_date: new Date().toISOString(), - platforms: Object.fromEntries(Object.entries(platforms).sort(([a], [b]) => a.localeCompare(b))), }; // What a person downloads and installs by hand: the macOS DMG (the updater @@ -105,6 +100,10 @@ if (installerAssetsDir) { } const url = releaseUrl(basename(file)); manualInstallers[asset.platform] = { url, signature_url: `${url}.sig` }; + const nativeKey = `${asset.platform}-nsh`; + if (/^(windows|linux)-/.test(asset.platform) && requiredPlatforms.includes(nativeKey)) { + platforms[nativeKey] = { url, signature: readFileSync(signaturePath, 'utf8').trim() }; + } } } @@ -113,6 +112,12 @@ if (missingManual.length > 0) { fail(`Missing required manual installers: ${missingManual.join(', ')}`); } +const missingPlatforms = requiredPlatforms.filter((platform) => !platforms[platform]); +if (missingPlatforms.length > 0) { + fail(`Missing required updater platforms: ${missingPlatforms.join(', ')}`); +} +manifest.platforms = Object.fromEntries(Object.entries(platforms).sort(([a], [b]) => a.localeCompare(b))); + if (Object.keys(manualInstallers).length > 0) { manifest.manual_installers = Object.fromEntries( Object.entries(manualInstallers).sort(([a], [b]) => a.localeCompare(b)), diff --git a/scripts/package-desktop-nsh-linux.mjs b/scripts/package-desktop-nsh-linux.mjs index 92860cc625..f061dfb7ca 100644 --- a/scripts/package-desktop-nsh-linux.mjs +++ b/scripts/package-desktop-nsh-linux.mjs @@ -17,9 +17,8 @@ // Usage: node scripts/package-desktop-nsh-linux.mjs [--profile release|release-fast] // [--target x86_64-unknown-linux-gnu] [--skip-build] [--product-config ] // Build dependencies: GTK 4, libadwaita and WebKitGTK 6 development packages -// (see the `desktop-nsh-linux` CI job). AppImage/deb packaging and in-place -// updates are a later step: the native updater refuses to install on Linux -// and points to the download page instead. +// (see the `desktop-nsh-linux` CI job). The native updater replaces this +// portable package in a writable installation directory. import { chmodSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -103,7 +102,7 @@ profile ${identity.productId}-nsh /opt/${identity.productId}/openbitfun-nsh flag `); const arch = (options.target ?? process.arch).includes("aarch64") || process.arch === "arm64" ? "aarch64" : "x86_64"; -writePackageInfo(app, { ...options, identity, version: pkg.version, executable: "openbitfun-nsh" }); +writePackageInfo(app, { ...options, identity, version: pkg.version, inBundle: true, executable: "openbitfun-nsh" }); const archive = join(outDir, `${appName}-nsh_${pkg.version}_${arch}-linux.tar.gz`); rmSync(archive, { force: true }); run("tar", ["-czf", archive, "-C", join(outDir, "linux"), appName]); diff --git a/scripts/package-desktop-nsh-windows.mjs b/scripts/package-desktop-nsh-windows.mjs index 4d3ff63383..61d19deb1a 100644 --- a/scripts/package-desktop-nsh-windows.mjs +++ b/scripts/package-desktop-nsh-windows.mjs @@ -23,9 +23,7 @@ // [--target x86_64-pc-windows-msvc] [--skip-build] [--no-installer] // [--product-config ] // Requires Rust 1.97 or newer for the NSH crates and -// the WebView2 runtime on the machine that runs the app. In-place updates of this -// layout are a later step: the native updater refuses to install on Windows and -// points to the download page instead. +// the WebView2 runtime on the machine that runs the app. import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; @@ -92,7 +90,7 @@ copyResources( ); const arch = (options.target ?? process.arch).includes("aarch64") || process.arch === "arm64" ? "arm64" : "x64"; -writePackageInfo(app, { ...options, identity, version: pkg.version, executable }); +writePackageInfo(app, { ...options, identity, version: pkg.version, inBundle: true, executable }); const archive = join(outDir, `${appName}-nsh_${pkg.version}_${arch}-windows.zip`); rmSync(archive, { force: true }); if (process.platform === "win32") { diff --git a/scripts/tauri-release-manifest.test.mjs b/scripts/tauri-release-manifest.test.mjs index 50d8bff443..832e86a23c 100644 --- a/scripts/tauri-release-manifest.test.mjs +++ b/scripts/tauri-release-manifest.test.mjs @@ -131,7 +131,7 @@ test('native release manifest bridges installed Tauri builds to the native macOS assert.equal(verified.status, 0, verified.stderr); }); -test('Windows and Linux never get updater keys, and a diverging bridge is rejected', (t) => { +test('Stable rejects Windows and Linux updater keys and a diverging bridge', (t) => { const release = nativeRelease(t); assert.equal(collect(release).status, 0); assert.equal(generate(release).status, 0); @@ -153,6 +153,28 @@ test('Windows and Linux never get updater keys, and a diverging bridge is reject assert.notEqual(verify(release.out).status, 0); }); +test('requested Windows and Linux native keys use the signed portable downloads', (t) => { + const version = '2.0.0'; + const release = nativeRelease(t, version); + assert.equal(collect(release, version).status, 0); + const portable = ['windows-x86_64', 'linux-x86_64', 'linux-aarch64']; + const keys = [...NATIVE_UPDATER_PLATFORMS.split(','), ...portable.map(platform => `${platform}-nsh`)].join(','); + const generated = generate(release, version, ['--required-platforms', keys]); + assert.equal(generated.status, 0, generated.stderr); + const manifest = JSON.parse(fs.readFileSync(release.out, 'utf8')); + for (const platform of portable) { + const update = manifest.platforms[`${platform}-nsh`]; + assert.equal(update.url, manifest.manual_installers[platform].url); + assert.equal(update.signature, `signature of ${path.basename(update.url)}`); + assert.equal(manifest.platforms[platform], undefined); + } + const verified = run('scripts/verify-tauri-latest-json.mjs', [ + '--manifest', release.out, '--version', version, '--required-platforms', keys, + '--forbidden-platform-prefixes', '', + ]); + assert.equal(verified.status, 0, verified.stderr); +}); + test('native updater collection rejects archives either updater would refuse', (t) => { const release = nativeRelease(t); const archive = path.join(release.assets, 'macos-x64', 'bundle', 'macos', 'OpenBitFun-nsh_1.2.3_x86_64.app.tar.gz'); diff --git a/scripts/verify-tauri-latest-json.mjs b/scripts/verify-tauri-latest-json.mjs index 71e10325a1..e134907afa 100644 --- a/scripts/verify-tauri-latest-json.mjs +++ b/scripts/verify-tauri-latest-json.mjs @@ -9,8 +9,7 @@ const requiredManualPlatforms = parseListArg(args['required-manual-platforms'] | // `darwin-` keys that must carry exactly the native `darwin--nsh` // archive and signature: the update bridge for installed Tauri builds. const bridgePlatforms = parseListArg(args['bridge-platforms'] || ''); -// Platform key prefixes the manifest must not carry (`windows-,linux-`: no native -// in-place updater yet, and an older Tauri package would reinstall in a loop). +// Releases can omit portable updates while the installer archives are present. const forbiddenPlatformPrefixes = parseListArg(args['forbidden-platform-prefixes'] || ''); const checkUrls = ['1', 'true', 'yes'].includes(String(args['check-urls'] || '').toLowerCase()); @@ -56,9 +55,18 @@ for (const platform of Object.keys(manifest.platforms)) { if (prefix) { fail(`Platform ${platform} is not allowed in this manifest (forbidden prefix ${prefix})`); } + if (/^(windows|linux)-/.test(platform) && !/^(windows|linux)-(aarch64|x86_64)-nsh$/.test(platform)) { + fail(`Portable updater ${platform} must use a native platform key`); + } } const manualInstallers = manifest.manual_installers || {}; +for (const [platform, entry] of Object.entries(manifest.platforms)) { + if (/^(windows|linux)-/.test(platform) && + manualInstallers[platform.slice(0, -4)]?.url !== entry.url) { + fail(`Portable updater ${platform} does not match its installer URL`); + } +} const missingManual = requiredManualPlatforms.filter((platform) => !manualInstallers[platform]); if (missingManual.length > 0) { fail(`Missing required manual installers: ${missingManual.join(', ')}`); @@ -114,7 +122,7 @@ function parseArgs(rawArgs) { } const key = arg.slice(2); const value = rawArgs[i + 1]; - if (!value || value.startsWith('--')) { + if (value === undefined || value.startsWith('--')) { fail(`Missing value for --${key}`); } parsed[key] = value; diff --git a/src/apps/desktop/README.md b/src/apps/desktop/README.md index 6e8fa9b1ac..f8dc3da15e 100644 --- a/src/apps/desktop/README.md +++ b/src/apps/desktop/README.md @@ -684,8 +684,10 @@ If installation fails, the pending update remains available to retry. Use On macOS the update replaces the application bundle in place (asking for an administrator password when the bundle's folder is not writable) and restarts. -Windows and Linux builds report that in-place installation is not available yet; -download the new package from openbitfun.com. +On Windows and Linux, extract the full portable package into a user-writable +directory to enable in-place updates when the feed offers a native update for +the platform. The app stages and verifies the archive before offering a restart. +Linux requires a filesystem that supports atomic directory exchange. Installed builds of the earlier Tauri-based desktop update into the native app on macOS through their usual update flow: the release lists the native package under diff --git a/src/apps/desktop/src/api/update_api.rs b/src/apps/desktop/src/api/update_api.rs index cc20db1be4..7e02ea0f07 100644 --- a/src/apps/desktop/src/api/update_api.rs +++ b/src/apps/desktop/src/api/update_api.rs @@ -7,7 +7,7 @@ use std::{io::Write, path::Path, sync::OnceLock}; pub(crate) const PROGRESS_EVENT: &str = "openbitfun-update-progress"; const RECORD_NAME: &str = "pending.json"; -const RECEIPT_NAME: &str = "install-result.json"; +pub(crate) const RECEIPT_NAME: &str = "install-result.json"; // Serialize downloads and installs at the host, including calls from multiple windows. pub(crate) static UPDATE: OnceLock> = OnceLock::new(); diff --git a/src/apps/desktop/src/backend_protocol/mod.rs b/src/apps/desktop/src/backend_protocol/mod.rs index fe795c556f..d31b986e08 100644 --- a/src/apps/desktop/src/backend_protocol/mod.rs +++ b/src/apps/desktop/src/backend_protocol/mod.rs @@ -22,6 +22,7 @@ mod dispatch_generated; mod events; pub mod ffi; mod native_commands; +pub(crate) use native_commands::start_automatic_updates; pub mod ws; use std::future::Future; diff --git a/src/apps/desktop/src/backend_protocol/native_commands/mod.rs b/src/apps/desktop/src/backend_protocol/native_commands/mod.rs index 85f15db7d5..f32dba9fcc 100644 --- a/src/apps/desktop/src/backend_protocol/native_commands/mod.rs +++ b/src/apps/desktop/src/backend_protocol/native_commands/mod.rs @@ -35,6 +35,7 @@ pub(super) use pet::{ hide_agent_companion_desktop_pet, resize_agent_companion_desktop_pet, show_agent_companion_desktop_pet, }; +pub(crate) use update::start_automatic_updates; pub(super) use update::{ check_for_updates, download_update, get_pending_update, install_pending_update, }; diff --git a/src/apps/desktop/src/backend_protocol/native_commands/update.rs b/src/apps/desktop/src/backend_protocol/native_commands/update.rs index 197edf99b8..df2a32d1a3 100644 --- a/src/apps/desktop/src/backend_protocol/native_commands/update.rs +++ b/src/apps/desktop/src/backend_protocol/native_commands/update.rs @@ -10,11 +10,9 @@ //! The native bundle is its own installation format: it reads the manifest's //! `--nsh` platform entry (for example `darwin-aarch64-nsh`), keeps //! its cache apart from the Tauri build's (`app-updates-nsh`), and only an -//! archive whose bundle carries the running executable (`openbitfun-nsh`) -//! can replace it. Release artifact (see -//! `scripts/package-desktop-nsh-macos.mjs --updater-archive`): -//! `OpenBitFun-nsh__.app.tar.gz` plus its minisign signature, -//! listed as `platforms["darwin--nsh"] = { url, signature }`. +//! archive that carries the native runner and UI can replace it. The feed can +//! serve a signed macOS bundle, Windows portable ZIP and Linux portable +//! tarball under their respective native platform keys. use std::path::PathBuf; use std::sync::Arc; @@ -31,7 +29,65 @@ use crate::api::update_api::{ use crate::host::NativeHost; /// `package_kind` of a staged native bundle. -const NATIVE_PACKAGE_KIND: &str = "nsh-app"; +fn package_kind() -> &'static str { + match std::env::consts::OS { + "windows" => "nsh-zip", + "linux" => "nsh-tar", + _ => "nsh-app", + } +} + +fn local_update_supported() -> bool { + cfg!(any(target_os = "macos", windows, target_os = "linux")) +} + +pub(crate) fn start_automatic_updates(host: &Arc) { + if !local_update_supported() || release_pubkey().is_none() { + return; + } + let host = Arc::downgrade(host); + tokio::spawn(async move { + use std::time::Duration; + let mut delay = Duration::from_secs(20); + loop { + tokio::time::sleep(delay).await; + let Some(host) = host.upgrade() else { return }; + if !host.shell().attached() { + delay = Duration::from_secs(60); + continue; + } + delay = match check_and_stage_automatic_update(&host).await { + Ok(true) => Duration::from_secs(6 * 60 * 60), + Ok(false) => Duration::from_secs(60), + Err(error) => { + log::warn!("Automatic desktop update check failed: {error}"); + Duration::from_secs(30 * 60) + } + }; + } + }); +} + +async fn check_and_stage_automatic_update(host: &NativeHost) -> Result { + let state = host.command_state::("automatic update")?; + let enabled: bool = state + .config_service + .get_config(Some("app.auto_update")) + .await + .map_err(|error| error.to_string())?; + if !enabled { + return Ok(false); + } + let release = latest_release(&http_client()?).await?; + let Some(release) = release.filter(|release| release.platform.is_some()) else { + return Ok(true); + }; + let request = update_api::DownloadUpdateRequest { + expected_version: Some(release.version.to_string()), + }; + download(host, request, Some(release)).await?; + Ok(true) +} /// The release key the build was signed for. Packaging passes the public key /// the Tauri build injects into its updater config (`TAURI_UPDATER_PUBKEY`). @@ -74,13 +130,14 @@ fn current_version() -> Result { } fn cache_dir() -> Result { + let cache_name = "app-updates-nsh"; if crate::e2e_storage_guard_enabled() { return Ok(openbitfun_core::infrastructure::get_path_manager_arc() .user_data_dir() - .join("app-updates-nsh")); + .join(cache_name)); } dirs::cache_dir() - .map(|dir| dir.join("com.openbitfun.desktop").join("app-updates-nsh")) + .map(|dir| dir.join("com.openbitfun.desktop").join(cache_name)) .ok_or_else(|| "The cache directory of this user is unavailable".to_string()) } @@ -230,8 +287,21 @@ pub(in crate::backend_protocol) fn get_pending_update( host: &Arc, args: Value, ) -> DispatchFuture<'_> { - let _ = (host, args); + let _ = host; Box::pin(async move { + #[derive(Default, Deserialize)] + #[serde(rename_all = "camelCase")] + struct StatusRequest { + #[serde(default)] + include_download: bool, + } + let request: StatusRequest = arg_or_default(&args, "request", "get_pending_update")?; + if request.include_download { + let active = download_progress().clone(); + if active.is_some() { + return Ok(json!({ "pending": null, "download": active })); + } + } let dir = cache_dir()?; let current = current_version()?; let pending = tokio::task::spawn_blocking(move || { @@ -239,56 +309,190 @@ pub(in crate::backend_protocol) fn get_pending_update( &dir, ¤t, &update_api::platform(), - NATIVE_PACKAGE_KIND, + package_kind(), )? .map(|record| update_api::pending_response(&dir, record)) .transpose() }) .await .map_err(|error| error.to_string())??; - serde_json::to_value(pending).map_err(|error| error.to_string()) + if request.include_download { + Ok(json!({ "pending": pending, "download": null })) + } else { + serde_json::to_value(pending).map_err(|error| error.to_string()) + } }) } const MAX_ARCHIVE_BYTES: u64 = 512 * 1024 * 1024; const PROGRESS_EMIT_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100); -const UNSUPPORTED_IN_PLACE_UPDATE: &str = "Installing updates in place is available for the native desktop on macOS only; download the new version from openbitfun.com"; +const UNSUPPORTED_IN_PLACE_UPDATE: &str = "This installation does not support in-place updates; download the new version from GitHub Releases"; + +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct DownloadProgress { + version: String, + phase: DownloadPhase, + downloaded: u64, + total: Option, + fraction: Option, +} + +#[derive(Clone, Copy, Serialize)] +#[serde(rename_all = "camelCase")] +enum DownloadPhase { + Downloading, + Verifying, +} + +fn download_progress() -> std::sync::MutexGuard<'static, Option> { + static PROGRESS: std::sync::Mutex> = std::sync::Mutex::new(None); + PROGRESS.lock().unwrap_or_else(|error| error.into_inner()) +} + +struct DownloadActivity<'a> { + host: &'a NativeHost, + version: String, +} + +impl DownloadActivity<'_> { + fn report(&self, phase: DownloadPhase, downloaded: u64, total: Option) { + let progress = DownloadProgress { + version: self.version.clone(), + phase, + downloaded, + total, + fraction: total + .filter(|total| *total > 0) + .map(|total| downloaded.min(total) as f64 / total as f64), + }; + *download_progress() = Some(progress.clone()); + let _ = self.host.emit(PROGRESS_EVENT, progress); + } +} + +impl Drop for DownloadActivity<'_> { + fn drop(&mut self) { + *download_progress() = None; + } +} async fn download( host: &NativeHost, request: update_api::DownloadUpdateRequest, + checked: Option, ) -> Result { - if cfg!(not(target_os = "macos")) { + let current = current_version()?; + if !local_update_supported() { return Err(UNSUPPORTED_IN_PLACE_UPDATE.to_string()); } let pubkey = release_pubkey().ok_or_else(|| NO_RELEASE_KEY.to_string())?; - let _operation = UPDATE - .get_or_init(Default::default) - .try_lock() - .map_err(|_| "An update operation is already in progress".to_string())?; + let automatic = checked.is_some(); + let _operation = UPDATE.get_or_init(Default::default).lock().await; + let dir = cache_dir()?; + // A second request may have waited for the first download to finish. + // Reuse the staged version even if the feed advances or goes offline. + let expected = checked + .as_ref() + .map(|release| release.version.clone()) + .or_else(|| { + request + .expected_version + .as_deref() + .and_then(|value| semver::Version::parse(value).ok()) + }); + let cached = tokio::task::spawn_blocking({ + let dir = dir.clone(); + move || { + let record = update_api::read_record_for_kind( + &dir, + ¤t, + &update_api::platform(), + package_kind(), + )?; + if let Some(record) = &record { + if !automatic { + update_api::verify_package_file( + &dir.join(record.package_name()?), + record, + pubkey, + )?; + } + } + Ok::<_, String>(record) + } + }) + .await + .map_err(|error| error.to_string())?; + // An automatic check preserves an unreadable record. A manual retry can + // replace it after verifying a fresh download. + let cached = if automatic { + cached? + } else { + cached.ok().flatten() + }; + if let (Some(record), Some(expected)) = (&cached, &expected) { + if staged_version_satisfies(record, expected) { + return Ok(record.response()); + } + } + let release = match checked { + Some(release) => release, + None => latest_release(&http_client()?) + .await? + .ok_or_else(|| "No update available".to_string())?, + }; + let version = release.version.to_string(); + request.validate_version(&version)?; + if let Some(record) = cached { + if staged_version_satisfies(&record, &release.version) { + return Ok(record.response()); + } + } + let platform = release.platform.ok_or_else(|| { + format!("Version {version} has no package for this installation format yet") + })?; + let activity = DownloadActivity { host, version }; + activity.report(DownloadPhase::Downloading, 0, None); + let result = stage_download(&activity, platform, dir, pubkey).await; + let version = activity.version.clone(); + drop(activity); + match &result { + Ok(pending) => { + let _ = host.emit("openbitfun-update-ready", pending); + } + Err(error) => { + let _ = host.emit( + "openbitfun-update-failed", + json!({ "version": version, "error": error }), + ); + } + } + result +} + +fn staged_version_satisfies(record: &PendingUpdateRecord, expected: &semver::Version) -> bool { + semver::Version::parse(&record.version).is_ok_and(|pending| pending >= *expected) +} + +async fn stage_download( + activity: &DownloadActivity<'_>, + platform: ManifestPlatform, + dir: PathBuf, + pubkey: &str, +) -> Result { let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); *CANCEL_DOWNLOAD .get_or_init(Default::default) .lock() .map_err(|_| "Download cancellation state is unavailable".to_string())? = Some(cancel_tx); let cancellation = DownloadCancellation; - let dir = cache_dir()?; let transfer_dir = dir.clone(); let transfer = async { use futures::StreamExt; use tokio::io::AsyncWriteExt; let client = http_client()?; - let release = latest_release(&client) - .await? - .ok_or_else(|| "No update available".to_string())?; - let platform = release.platform.clone().ok_or_else(|| { - format!( - "Version {} has no package for this installation format yet", - release.version - ) - })?; - request.validate_version(&release.version.to_string())?; let response = client .get(&platform.url) .send() @@ -304,6 +508,7 @@ async fn download( )); } } + activity.report(DownloadPhase::Downloading, 0, total); // Stream directly to a temporary file inside the update cache directory // so large archives never sit in RAM. let temp_file = tokio::task::spawn_blocking(move || { @@ -340,10 +545,7 @@ async fn download( .map_err(|error| format!("Failed to write update archive: {error}"))?; if last_emit.elapsed() >= PROGRESS_EMIT_INTERVAL { last_emit = std::time::Instant::now(); - let _ = host.emit( - PROGRESS_EVENT, - json!({ "downloaded": downloaded, "total": total }), - ); + activity.report(DownloadPhase::Downloading, downloaded, total); } } writer @@ -351,34 +553,33 @@ async fn download( .await .map_err(|error| format!("Failed to flush update archive: {error}"))?; drop(writer); - let _ = host.emit( - PROGRESS_EVENT, - json!({ "downloaded": downloaded, "total": total }), - ); + activity.report(DownloadPhase::Verifying, downloaded, total); let sha256 = format!("{:x}", hasher.finalize()); - Ok::<_, String>((release, platform, temp_file, sha256)) + Ok::<_, String>((temp_file, sha256)) }; - let (release, platform, temp_file, sha256) = tokio::select! { + let (temp_file, sha256) = tokio::select! { result = transfer => result?, _ = cancel_rx => return Err("Update download canceled".into()), }; // Finalization cannot be canceled midway through committing pending.json. drop(cancellation); let record = PendingUpdateRecord { - version: release.version.to_string(), + version: activity.version.clone(), platform: update_api::platform(), signature: platform.signature, sha256, - package_kind: Some(NATIVE_PACKAGE_KIND.to_string()), + package_kind: Some(package_kind().to_string()), }; let pubkey = pubkey.to_string(); tokio::task::spawn_blocking(move || { // Verify before anything is committed: a bad signature leaves no record. update_api::verify_package_file(temp_file.path(), &record, &pubkey)?; - let reader = std::io::BufReader::new( - std::fs::File::open(temp_file.path()).map_err(|error| error.to_string())?, - ); - validate_native_archive_reader(reader)?; + #[cfg(target_os = "macos")] + validate_native_archive_reader(std::io::BufReader::new( + temp_file.reopen().map_err(|error| error.to_string())?, + ))?; + #[cfg(any(windows, target_os = "linux"))] + crate::update_maintenance::validate_portable_update(temp_file.path())?; update_api::commit_package_file(&dir, &record, temp_file)?; Ok::<_, String>(record.response()) }) @@ -393,6 +594,7 @@ fn validate_native_archive(bytes: &[u8]) -> Result<(), String> { validate_native_archive_reader(bytes) } +#[cfg(any(target_os = "macos", test))] fn validate_native_archive_reader(reader: R) -> Result<(), String> { let runner = std::env::current_exe() .ok() @@ -461,68 +663,74 @@ pub(in crate::backend_protocol) fn download_update( Box::pin(async move { let request: update_api::DownloadUpdateRequest = arg_or_default(&args, "request", "download_update")?; - let response = download(host, request).await?; + let response = download(host, request, None).await?; serde_json::to_value(response).map_err(|error| error.to_string()) }) } async fn install(host: &NativeHost, version: String) -> Result<(), String> { - if cfg!(not(target_os = "macos")) { + let current = current_version()?; + if !local_update_supported() { return Err(UNSUPPORTED_IN_PLACE_UPDATE.to_string()); } + let operation = if cfg!(target_os = "macos") { + "app.restart" + } else { + "app.quit" + }; + if !host.shell().offers(operation) { + return Err("The attached desktop shell cannot restart for an update".into()); + } let pubkey = release_pubkey().ok_or_else(|| NO_RELEASE_KEY.to_string())?; let _operation = UPDATE .get_or_init(Default::default) .try_lock() .map_err(|_| "An update operation is already in progress".to_string())?; let dir = cache_dir()?; - let current = current_version()?; - let pubkey = pubkey.to_string(); - let package_path = tokio::task::spawn_blocking(move || { + #[cfg_attr(target_os = "macos", allow(unused_variables))] + let handoff = tokio::task::spawn_blocking(move || { let record = update_api::read_record_for_kind( &dir, ¤t, &update_api::platform(), - NATIVE_PACKAGE_KIND, + package_kind(), )? .ok_or_else(|| "No downloaded update is available".to_string())?; if record.version != version { - return Err( - "The downloaded update has changed; reopen About before installing".to_string(), - ); + return Err("The downloaded update has changed; reopen About before installing".into()); + } + let path = dir.join(record.package_name()?); + update_api::verify_package_file(&path, &record, pubkey)?; + #[cfg(target_os = "macos")] + { + crate::update_maintenance::install_native_app_bundle_file(&path)?; + Ok::<(), String>(()) + } + #[cfg(any(windows, target_os = "linux"))] + { + crate::update_maintenance::handoff_portable_update( + &path, + &version, + &dir.join(update_api::RECEIPT_NAME), + ) } - let package_path = dir.join(record.package_name()?); - update_api::verify_package_file(&package_path, &record, &pubkey)?; - Ok::<_, String>(package_path) }) .await .map_err(|error| error.to_string())??; - // Unpack and validate once directly from the verified package file on disk. - install_bundle_file(package_path).await?; - // The shell restarts the app: the new bundle starts once this run exited. - log::info!("Native desktop update installed; restarting"); - host.shell_request( - "app.restart", - Value::Null, - crate::host::shell::SHELL_REQUEST_TIMEOUT, - ) - .await - .map(|_| ()) -} - -#[cfg(target_os = "macos")] -async fn install_bundle_file(path: std::path::PathBuf) -> Result<(), String> { - tokio::task::spawn_blocking(move || { - crate::update_maintenance::install_native_app_bundle_file(&path) - }) - .await - .map_err(|error| error.to_string())? -} - -#[cfg(not(target_os = "macos"))] -async fn install_bundle_file(path: std::path::PathBuf) -> Result<(), String> { - let _ = path; - Err(UNSUPPORTED_IN_PLACE_UPDATE.to_string()) + let result = host + .shell_request( + operation, + Value::Null, + crate::host::shell::SHELL_REQUEST_TIMEOUT, + ) + .await; + #[cfg(any(windows, target_os = "linux"))] + if let Err(error) = &result { + if let Err(recovery) = handoff.cancel() { + return Err(format!("{error}; {recovery}")); + } + } + result.map(|_| ()) } pub(in crate::backend_protocol) fn install_pending_update( @@ -552,6 +760,25 @@ mod tests { .unwrap() } + #[test] + fn portable_updates_follow_semver_across_release_types() { + let current = semver::Version::parse("2.0.0-rc.1").unwrap(); + let platforms = json!({ + "windows-x86_64-nsh": { "url": "https://example.test/update.zip", "signature": "s" }, + }); + let check = |version| { + release_from_manifest( + manifest(version, platforms.clone()), + ¤t, + "windows-x86_64-nsh", + ) + }; + assert!(check("2.0.0-rc.2").unwrap().unwrap().platform.is_some()); + assert!(check("2.0.0").unwrap().unwrap().platform.is_some()); + assert!(check("2.0.0-rc.1").unwrap().is_none()); + assert!(check("1.99.0").unwrap().is_none()); + } + #[test] fn only_the_native_platform_entry_of_a_newer_release_is_offered() { let current = semver::Version::parse("1.0.0").unwrap(); @@ -661,7 +888,7 @@ mod tests { platform: update_api::platform(), signature: "sig".into(), sha256: format!("{:x}", Sha256::digest(bytes)), - package_kind: Some(NATIVE_PACKAGE_KIND.into()), + package_kind: Some(package_kind().into()), }; update_api::save_package(dir.path(), &record, bytes).unwrap(); let current = semver::Version::parse("1.0.0").unwrap(); @@ -669,7 +896,7 @@ mod tests { dir.path(), ¤t, &update_api::platform(), - NATIVE_PACKAGE_KIND + package_kind() ) .unwrap() .is_some()); diff --git a/src/apps/desktop/src/native_host.rs b/src/apps/desktop/src/native_host.rs index fb38f711ea..00319c6ac8 100644 --- a/src/apps/desktop/src/native_host.rs +++ b/src/apps/desktop/src/native_host.rs @@ -171,6 +171,7 @@ pub async fn start_native_backend(host: Arc) -> Result/dev/null; do + [ "$attempt" -lt 60 ] || exit 1 + attempt=$((attempt + 1)) + sleep 1 +done + +"$@" & +app="$!" +sleep 2 +if kill -0 "$app" 2>/dev/null || wait "$app"; then + rm -rf -- "$stage" + exit 0 +fi + +# The primary publication was atomic. If the new process fails immediately, +# preserve both bundles unless the original can be restored and restarted. +if mv -T -- "$target" "$stage/failed"; then + if mv -T -- "$stage/OpenBitFun" "$target"; then + temporary="$receipt.$$.tmp" + printf '{"version":"%s","success":false,"error":"The update failed to start. The previous version was restored."}\n' "$version" > "$temporary" && + mv -f -- "$temporary" "$receipt" + rm -rf -- "$stage" + exec "$@" + fi + mv -T -- "$stage/failed" "$target" +fi +exit 1 diff --git a/src/apps/desktop/src/update_maintenance/mod.rs b/src/apps/desktop/src/update_maintenance/mod.rs index 92eba30418..4a7437c9a1 100644 --- a/src/apps/desktop/src/update_maintenance/mod.rs +++ b/src/apps/desktop/src/update_maintenance/mod.rs @@ -1,14 +1,17 @@ //! Publication of a verified native desktop update package. //! //! The native updater (`backend_protocol/native_commands/update.rs`) owns -//! discovery, download and minisign verification; this module owns the macOS -//! bundle replacement, including the administrator authorization fallback. -//! Windows and Linux have no in-place install yet: the updater reports it. +//! discovery, download and minisign verification; this module publishes the +//! verified native bundle on the local installation. #[cfg(target_os = "macos")] mod macos; +#[cfg(any(target_os = "linux", windows, test))] +mod portable; #[cfg(any(target_os = "macos", test))] mod publication; +#[cfg(windows)] +mod windows; /// Replaces the running native (NSH) desktop bundle with the verified /// `.app.tar.gz` of a newer one from a file on disk (single unpack pass). @@ -18,3 +21,110 @@ mod publication; pub(crate) fn install_native_app_bundle_file(path: &std::path::Path) -> Result<(), String> { macos::install_file(path).map_err(|error| error.to_string()) } + +#[cfg(any(target_os = "linux", windows))] +pub(crate) fn validate_portable_update(path: &std::path::Path) -> Result<(), String> { + portable::verify_layout(path, portable_format(), None).map_err(|error| error.to_string()) +} + +#[cfg(any(target_os = "linux", windows))] +fn portable_format() -> portable::Format { + if cfg!(windows) { + portable::Format::Zip + } else { + portable::Format::TarGz + } +} + +#[cfg(any(target_os = "linux", windows))] +pub(crate) struct PortableHandoff { + child: std::process::Child, + stage: std::path::PathBuf, + #[cfg(target_os = "linux")] + target: std::path::PathBuf, + _lock: std::fs::File, +} + +#[cfg(any(target_os = "linux", windows))] +impl PortableHandoff { + pub(crate) fn cancel(mut self) -> Result<(), String> { + let _ = self.child.kill(); + let _ = self.child.wait(); + #[cfg(target_os = "linux")] + exchange_bundles(&self.target, &self.stage.join("OpenBitFun")).map_err(|error| { + format!( + "Update rollback failed: {error}. The previous bundle is at {}", + self.stage.join("OpenBitFun").display() + ) + })?; + std::fs::remove_dir_all(&self.stage).map_err(|error| error.to_string()) + } +} + +#[cfg(target_os = "linux")] +pub(crate) fn handoff_portable_update( + path: &std::path::Path, + version: &str, + receipt: &std::path::Path, +) -> Result { + use openbitfun_services_core::process_manager::create_detached_command; + + let (stage, lock, target, staged) = + portable::stage(path, portable_format(), version).map_err(|error| error.to_string())?; + let parent = target.parent().ok_or("Missing installation parent")?; + let mut child = create_detached_command("/bin/sh") + .args(["-c", include_str!("linux_update.sh"), "openbitfun-update"]) + .arg(std::process::id().to_string()) + .arg(stage.path()) + .arg(&target) + .arg(receipt) + .arg(version) + .arg(target.join("openbitfun-nsh")) + .args(std::env::args_os().skip(1)) + .current_dir(parent) + .spawn() + .map_err(|error| error.to_string())?; + if let Err(error) = exchange_bundles(&target, &staged) { + let _ = child.kill(); + let _ = child.wait(); + return Err(error.to_string()); + } + Ok(PortableHandoff { + child, + stage: stage.keep(), + target, + _lock: lock, + }) +} + +#[cfg(target_os = "linux")] +fn exchange_bundles(target: &std::path::Path, staged: &std::path::Path) -> std::io::Result<()> { + use std::os::unix::ffi::OsStrExt; + let target = std::ffi::CString::new(target.as_os_str().as_bytes())?; + let staged = std::ffi::CString::new(staged.as_os_str().as_bytes())?; + // The paths are valid C strings, and both directories were created on the + // same filesystem. If exchange fails, the original install remains usable. + let result = unsafe { + libc::renameat2( + libc::AT_FDCWD, + target.as_ptr(), + libc::AT_FDCWD, + staged.as_ptr(), + libc::RENAME_EXCHANGE, + ) + }; + if result == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + +#[cfg(windows)] +pub(crate) fn handoff_portable_update( + path: &std::path::Path, + version: &str, + receipt: &std::path::Path, +) -> Result { + windows::handoff(path, version, receipt).map_err(|error| error.to_string()) +} diff --git a/src/apps/desktop/src/update_maintenance/portable.rs b/src/apps/desktop/src/update_maintenance/portable.rs new file mode 100644 index 0000000000..0d32a34263 --- /dev/null +++ b/src/apps/desktop/src/update_maintenance/portable.rs @@ -0,0 +1,281 @@ +//! Verified portable NSH packages update the whole app directory together. +use std::ffi::OsStr; +use std::fs::{self, File}; +use std::io::{self, BufReader}; +use std::path::{Component, Path, PathBuf}; + +const ROOT: &str = "OpenBitFun"; +const MAX_UNPACKED_BYTES: u64 = 4 * 1024 * 1024 * 1024; + +#[derive(Clone, Copy)] +pub(super) enum Format { + Zip, + TarGz, +} + +impl Format { + fn required(self) -> [&'static str; 5] { + let (runner, backend) = match self { + Self::Zip => ("openbitfun-desktop.exe", "openbitfun_desktop_lib.dll"), + Self::TarGz => ("openbitfun-nsh", "libopenbitfun_desktop_lib.so"), + }; + [ + runner, + backend, + "nsh/app.json", + "nsh/bundle.nshc", + "openbitfun-package.json", + ] + } +} + +fn package_path(path: &Path) -> io::Result { + let mut parts = path.components(); + if parts.next() != Some(Component::Normal(OsStr::new(ROOT))) { + return Err(invalid("Expected one OpenBitFun package directory")); + } + let mut relative = PathBuf::new(); + for component in parts { + let Component::Normal(name) = component else { + return Err(invalid("Invalid path in native update package")); + }; + if name.to_string_lossy().contains([':', '\\']) { + return Err(invalid("Invalid path in native update package")); + } + relative.push(name); + } + Ok(relative) +} + +fn invalid(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +pub(super) fn verify_layout( + archive: &Path, + format: Format, + destination: Option<&Path>, +) -> io::Result<()> { + let mut size = 0u64; + let mut files = std::collections::HashSet::new(); + let mut inspect = |path: &Path, is_file: bool, entry_size: u64| -> io::Result<()> { + let relative = package_path(path)?; + if is_file && (relative.as_os_str().is_empty() || !files.insert(relative)) { + return Err(invalid( + "Duplicate or invalid file in native update package", + )); + } + size = size.saturating_add(entry_size); + if size > MAX_UNPACKED_BYTES { + return Err(invalid("Native update exceeds its unpacked size limit")); + } + Ok(()) + }; + + match format { + Format::Zip => { + let mut zip = zip::ZipArchive::new(File::open(archive)?)?; + for index in 0..zip.len() { + let mut entry = zip.by_index(index)?; + let path = entry + .enclosed_name() + .ok_or_else(|| invalid("Invalid ZIP path in native update"))? + .to_owned(); + if entry.is_symlink() { + return Err(invalid("Links are not supported in native ZIP updates")); + } + inspect(&path, !entry.is_dir(), entry.size())?; + if let Some(destination) = destination { + let target = destination.join(path); + if entry.is_dir() { + fs::create_dir_all(&target)?; + } else { + if let Some(parent) = target.parent() { + fs::create_dir_all(parent)?; + } + let mut file = File::create_new(&target)?; + io::copy(&mut entry, &mut file)?; + } + } + } + } + Format::TarGz => { + let reader = BufReader::new(File::open(archive)?); + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(reader)); + for entry in tar.entries()? { + let mut entry = entry?; + let kind = entry.header().entry_type(); + if !kind.is_file() && !kind.is_dir() { + return Err(invalid( + "Links and special files are not supported in native tar updates", + )); + } + inspect(&entry.path()?, kind.is_file(), entry.size())?; + if let Some(destination) = destination { + if !entry.unpack_in(destination)? { + return Err(invalid("Native tar update escaped the staging directory")); + } + } + } + } + } + if format + .required() + .iter() + .any(|name| !files.contains(Path::new(name))) + { + return Err(invalid( + "Native update is missing its runner, backend or UI bundle", + )); + } + Ok(()) +} + +#[cfg(any(target_os = "linux", windows))] +pub(super) fn stage( + archive: &Path, + format: Format, + version: &str, +) -> io::Result<(tempfile::TempDir, File, PathBuf, PathBuf)> { + let runner = std::env::current_exe()?; + let target = runner + .parent() + .ok_or_else(|| invalid("Native installation path is unavailable"))?; + if runner.file_name() != Some(OsStr::new(format.required()[0])) + || format + .required() + .iter() + .any(|name| !target.join(name).is_file()) + { + return Err(invalid( + "This installation is not an OpenBitFun portable bundle", + )); + } + #[cfg(windows)] + for entry in fs::read_dir(target)? { + let filename = entry?.file_name().to_string_lossy().to_ascii_lowercase(); + if filename.starts_with("unins") && filename.ends_with(".dat") { + return Err(invalid( + "This application is managed by its setup program; use the installer to update it", + )); + } + } + let data_dir = openbitfun_core::infrastructure::get_path_manager_arc().user_data_dir(); + if data_dir.starts_with(target) + || data_dir + .canonicalize() + .is_ok_and(|path| path.starts_with(target)) + { + return Err(invalid("Move the application data outside the portable application directory before installing an update")); + } + let parent = target + .parent() + .ok_or_else(|| invalid("Native installation parent is unavailable"))?; + let name = target + .file_name() + .ok_or_else(|| invalid("Native installation directory name is unavailable"))?; + let lock = fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(parent.join(format!(".{}.update.lock", name.to_string_lossy())))?; + lock.try_lock() + .map_err(|_| io::Error::other("Another application update is running"))?; + let stage = tempfile::Builder::new() + .prefix(".openbitfun-update-") + .tempdir_in(parent)?; + verify_layout(archive, format, Some(stage.path()))?; + let staged = stage.path().join(ROOT); + #[derive(serde::Deserialize)] + #[serde(rename_all = "camelCase")] + struct PackageInfo { + bundle_id: String, + version: String, + } + let read_info = |root: &Path| -> io::Result { + Ok(serde_json::from_slice(&fs::read( + root.join("openbitfun-package.json"), + )?)?) + }; + let installed = read_info(target)?; + let update = read_info(&staged)?; + if installed.bundle_id.is_empty() || installed.bundle_id != update.bundle_id { + return Err(invalid("Update package belongs to a different application")); + } + if installed.version != crate::VERSION || update.version != version { + return Err(invalid( + "Native package version does not match the update request", + )); + } + Ok((stage, lock, target.into(), staged)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn portable_paths_are_confined_to_one_product_tree() { + assert_eq!( + package_path(Path::new("OpenBitFun/nsh/bundle.nshc")).unwrap(), + Path::new("nsh/bundle.nshc") + ); + for path in ["elsewhere/x", "OpenBitFun/../x", "OpenBitFun/file:stream"] { + assert!(package_path(Path::new(path)).is_err(), "{path}"); + } + } + + #[test] + fn windows_zip_requires_the_native_backend_and_ui() { + use std::io::Write; + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("update.zip"); + let mut zip = zip::ZipWriter::new(File::create(&file).unwrap()); + for entry in Format::Zip.required() { + zip.start_file( + format!("{ROOT}/{entry}"), + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + zip.write_all(b"package payload").unwrap(); + } + zip.finish().unwrap(); + let unpack = dir.path().join("unpack"); + verify_layout(&file, Format::Zip, Some(&unpack)).unwrap(); + assert!(unpack.join(ROOT).join("nsh/bundle.nshc").is_file()); + assert!(verify_layout(&file, Format::TarGz, None).is_err()); + } + + #[test] + fn linux_tar_preserves_runner_permissions() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("update.tar.gz"); + let encoder = flate2::write::GzEncoder::new( + File::create(&file).unwrap(), + flate2::Compression::fast(), + ); + let mut tar = tar::Builder::new(encoder); + for entry in Format::TarGz.required() { + let mut header = tar::Header::new_gnu(); + header.set_size(1); + header.set_mode(0o755); + header.set_cksum(); + tar.append_data(&mut header, format!("{ROOT}/{entry}"), &b"x"[..]) + .unwrap(); + } + tar.into_inner().unwrap().finish().unwrap(); + let unpack = dir.path().join("unpack"); + fs::create_dir(&unpack).unwrap(); + verify_layout(&file, Format::TarGz, Some(&unpack)).unwrap(); + let runner = unpack.join(ROOT).join("openbitfun-nsh"); + assert!(runner.is_file()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_ne!( + fs::metadata(&runner).unwrap().permissions().mode() & 0o100, + 0 + ); + } + } +} diff --git a/src/apps/desktop/src/update_maintenance/windows.rs b/src/apps/desktop/src/update_maintenance/windows.rs new file mode 100644 index 0000000000..4004ea6005 --- /dev/null +++ b/src/apps/desktop/src/update_maintenance/windows.rs @@ -0,0 +1,89 @@ +//! Windows locks the running bundle. A detached helper waits for clean exit, +//! publishes the already verified bundle, and relaunches as the same user. +use std::io; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use openbitfun_services_core::process_manager::create_detached_command; + +use super::{ + portable::{self, Format}, + PortableHandoff, +}; + +pub(super) fn handoff( + archive: &Path, + version: &str, + receipt: &Path, +) -> io::Result { + use base64::Engine; + let (stage, lock, target, _) = portable::stage(archive, Format::Zip, version)?; + let ready = stage.path().join("ready"); + let system_root = std::env::var_os("SystemRoot") + .map(PathBuf::from) + .ok_or_else(|| io::Error::other("Windows system directory is unavailable"))?; + let powershell = system_root.join("System32/WindowsPowerShell/v1.0/powershell.exe"); + let script: Vec = include_str!("windows_update.ps1") + .encode_utf16() + .flat_map(u16::to_le_bytes) + .collect(); + let encoded = base64::engine::general_purpose::STANDARD.encode(script); + let arguments = std::env::args_os() + .skip(1) + .map(|argument| quote_argument(&argument.to_string_lossy())) + .collect::>() + .join(" "); + let mut child = create_detached_command(powershell) + .args(["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded]) + .current_dir( + &target + .parent() + .ok_or_else(|| io::Error::other("Missing install parent"))?, + ) + .env("OBF_UPDATE_PARENT", std::process::id().to_string()) + .env("OBF_UPDATE_STAGE", stage.path()) + .env("OBF_UPDATE_TARGET", &target) + .env("OBF_UPDATE_RECEIPT", receipt) + .env("OBF_UPDATE_VERSION", version) + .env("OBF_UPDATE_CURRENT", crate::VERSION) + .env("OBF_UPDATE_ARGUMENTS", arguments) + .spawn()?; + let deadline = Instant::now() + Duration::from_secs(5); + loop { + if ready.is_file() { + return Ok(PortableHandoff { + child, + stage: stage.keep(), + _lock: lock, + }); + } + if child.try_wait()?.is_some() || Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return Err(io::Error::other( + "The Windows update helper could not start", + )); + } + std::thread::sleep(Duration::from_millis(25)); + } +} + +fn quote_argument(argument: &str) -> String { + let mut quoted = String::from("\""); + let mut slashes = 0; + for character in argument.chars() { + if character == '\\' { + slashes += 1; + continue; + } + if character == '"' { + quoted.extend(std::iter::repeat_n('\\', slashes + 1)); + } + quoted.extend(std::iter::repeat_n('\\', slashes)); + quoted.push(character); + slashes = 0; + } + quoted.extend(std::iter::repeat_n('\\', slashes * 2)); + quoted.push('"'); + quoted +} diff --git a/src/apps/desktop/src/update_maintenance/windows_update.ps1 b/src/apps/desktop/src/update_maintenance/windows_update.ps1 new file mode 100644 index 0000000000..b2c3fccb13 --- /dev/null +++ b/src/apps/desktop/src/update_maintenance/windows_update.ps1 @@ -0,0 +1,76 @@ +$ErrorActionPreference = 'Stop' +$stage = $env:OBF_UPDATE_STAGE +$target = $env:OBF_UPDATE_TARGET +$backup = Join-Path $stage 'previous' +$staged = Join-Path $stage 'OpenBitFun' +$receipt = $env:OBF_UPDATE_RECEIPT +$restartArguments = $env:OBF_UPDATE_ARGUMENTS +$result = @{version = $env:OBF_UPDATE_VERSION; success = $false; error = $null} +$parent = Get-Process -Id ([int]$env:OBF_UPDATE_PARENT) +# Acquire the process handle before asking the application to exit. +$null = $parent.Handle +[System.IO.File]::WriteAllText((Join-Path $stage 'ready'), 'ready') +$lock = $null +try { + if (-not $parent.WaitForExit(60000)) { + throw 'The application did not exit. The update can be retried.' + } + $lockPath = Join-Path ([System.IO.Path]::GetDirectoryName($target)) ( + '.' + [System.IO.Path]::GetFileName($target) + '.update.lock') + $lock = [System.IO.File]::Open($lockPath, 'OpenOrCreate', 'ReadWrite', 'None') + $installed = Get-Content -LiteralPath (Join-Path $target 'openbitfun-package.json') -Raw | ConvertFrom-Json + if ($installed.version -ne $env:OBF_UPDATE_CURRENT) { + throw 'The installed version changed before the update could be applied.' + } + [System.IO.Directory]::Move($target, $backup) + try { + [System.IO.Directory]::Move($staged, $target) + $launch = @{ + FilePath = (Join-Path $target 'openbitfun-desktop.exe') + WorkingDirectory = $target + } + if ($restartArguments) { $launch.ArgumentList = $restartArguments } + $app = Start-Process @launch -PassThru + if ($app.WaitForExit(2000) -and $app.ExitCode -ne 0) { + throw "The updated application exited with code $($app.ExitCode)." + } + $result.success = $true + } catch { + if ([System.IO.Directory]::Exists($target)) { + [System.IO.Directory]::Move($target, $staged) + } + [System.IO.Directory]::Move($backup, $target) + throw + } +} catch { + $result.error = $_.Exception.Message + if ([System.IO.Directory]::Exists($backup)) { + $result.error += "; recovery copy retained at $backup" + } +} finally { + if ($lock) { $lock.Dispose() } + $receiptTemp = $receipt + '.' + $PID + '.tmp' + try { + [System.IO.File]::WriteAllText($receiptTemp, ($result | ConvertTo-Json -Compress), + (New-Object System.Text.UTF8Encoding($false))) + if ([System.IO.File]::Exists($receipt)) { + [System.IO.File]::Replace($receiptTemp, $receipt, $null) + } else { + [System.IO.File]::Move($receiptTemp, $receipt) + } + } catch { + # A missing receipt must not prevent a recovered app from relaunching. + } finally { + if ($result.success -or -not [System.IO.Directory]::Exists($backup)) { + Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue + } + } +} +if (-not $result.success -and $parent.HasExited -and -not [System.IO.Directory]::Exists($backup)) { + $runner = Join-Path $target 'openbitfun-desktop.exe' + if ([System.IO.File]::Exists($runner)) { + $launch = @{FilePath = $runner; WorkingDirectory = $target} + if ($restartArguments) { $launch.ArgumentList = $restartArguments } + Start-Process @launch + } +} diff --git a/src/nsh-ui/App.test.tsx b/src/nsh-ui/App.test.tsx index 02cd4c7732..5acc79e30b 100644 --- a/src/nsh-ui/App.test.tsx +++ b/src/nsh-ui/App.test.tsx @@ -4379,6 +4379,103 @@ test("the account menu checks for updates, offers the download and then the rest await app.waitFor("Restart to update"); }); +test("an automatic update shows download progress and offers restart without a second download", async () => { + const backend = createBackend(); + const native = nativeWindowHandlers(backend, "windows"); + let version: string | null = null; + let statusReads = 0; + let manualDownloads = 0; + let finishCheck: (() => void) | undefined; + const target = "2.0.1"; + const app = await open("./App.tsx", { + ...DESKTOP, + host: { handlers: { + ...native.handlers, + "openbitfun.invoke": (data: unknown) => { + const args = (data ?? {}) as { action?: string }; + if (args.action === "get_pending_update") { + statusReads++; + return { ok: true, value: version ? { version } : null }; + } + if (args.action === "check_for_updates") { + return new Promise(resolve => { + finishCheck = () => resolve({ ok: true, value: { updateAvailable: true, latestVersion: target } }); + }); + } + if (args.action === "download_update") manualDownloads++; + return backend.handlers["openbitfun.invoke"](data); + }, + } }, + }); + await app.waitFor("label:account-row"); + await app.waitUntil(() => statusReads > 0); + await app.press("label:account-row"); + const checking = app.press("Check for updates"); + await app.waitUntil(() => Boolean(finishCheck)); + const started = app.host.send("openbitfun.event", { + event: "openbitfun-update-progress", + payload: { version: target, phase: "downloading", fraction: null }, + }); + await app.waitFor("id:app-update-progress"); + finishCheck?.(); + await Promise.all([checking, started]); + await app.press("label:account-row"); + await app.waitFor("Downloading update…"); + expect(app.shows("Check for updates")).toBe(false); + expect(app.shows("Download update 2.0.1")).toBe(false); + await app.host.send("openbitfun.event", { + event: "openbitfun-update-progress", + payload: { version: target, phase: "downloading", fraction: 0.42 }, + }); + await app.waitFor("42%"); + await app.host.send("openbitfun.event", { + event: "openbitfun-update-progress", + payload: { version: target, phase: "verifying", fraction: 1 }, + }); + await app.waitFor("Verifying update…"); + expect(manualDownloads).toBe(0); + version = target; + await app.host.send("openbitfun.event", { + event: "openbitfun-update-ready", + payload: { version: "2.0.9" }, + }); + await app.waitFor("Update 2.0.1 is ready to install"); + await app.waitFor("id:app-update-progress", { state: "gone" }); + await app.press("label:Update 2.0.1 is ready to install >> id:toast-dismiss"); + await app.waitFor("label:account-update-ready"); + await app.press("label:account-row"); + await app.waitFor("Restart to update"); +}); + +test("the local updater restores an in-flight download and offers retry on failure", async () => { + const backend = createBackend(); + const native = nativeWindowHandlers(backend, "linux"); + const version = "2.0.1"; + const app = await open("./App.tsx", { + ...DESKTOP, + host: { handlers: { + ...native.handlers, + "openbitfun.invoke": (data: unknown) => { + const args = (data ?? {}) as { action?: string; request?: { includeDownload?: boolean } }; + if (args.action === "get_pending_update") { + expect(args.request?.includeDownload).toBe(true); + return { ok: true, value: { pending: null, download: { version, phase: "downloading", fraction: 0.25 } } }; + } + return backend.handlers["openbitfun.invoke"](data); + }, + } }, + }); + await app.waitFor("25%"); + await app.press("label:account-row"); + await app.waitFor("Downloading update… 25%"); + await app.host.send("openbitfun.event", { + event: "openbitfun-update-failed", + payload: { version, error: "Connection closed" }, + }); + await app.waitFor("Download update 2.0.1"); + await app.waitFor("id:app-update-progress", { state: "gone" }); +}); + test("global search opens an indexed settings section inside its page", async () => { const backend = createBackend(); const app = await open("./App.tsx", { ...DESKTOP, host: { handlers: backend.handlers } }); diff --git a/src/nsh-ui/App.tsx b/src/nsh-ui/App.tsx index 3a537ca5c6..c63190d22f 100644 --- a/src/nsh-ui/App.tsx +++ b/src/nsh-ui/App.tsx @@ -80,7 +80,7 @@ import { } from "./src/controller/controllerStore"; import { ControllerShell } from "./src/controller/ControllerShell"; import { loadLocalDeviceId, localDeviceId } from "./src/devicePrefsStore"; -import { basename } from "./src/format"; +import { basename, formatPercent } from "./src/format"; import { isAuthRequiredError, localizeHostError, @@ -1035,6 +1035,9 @@ function AccountRow() { > {accountLabel()} + + + ("idle"); const updateVersion = signal(""); -let updateStateRead = false; +const updateFraction = signal(null); +let updateRevision = 0; + +function isUpdateDownloading(): boolean { + return updatePhase() === "downloading" || updatePhase() === "verifying"; +} + +function updateProgressLabel(): string { + if (updatePhase() === "verifying") return tr("shell.updates.verifying"); + const label = tr("shell.updates.downloading"); + const percent = formatPercent(updateFraction()); + return percent ? `${label} ${percent}` : label; +} -async function readPendingUpdate(): Promise { - if (updateStateRead || !inAppUpdatesAvailable()) return; - updateStateRead = true; +function AppUpdateProgress() { + const width = space.xl + space.lg; + return ( + } + style={{ flexShrink: 0, width, alignItems: "center", gap: space.hair }} + > + + {formatPercent(updateFraction()) || "…"} + + + + + + + + ); +} + +function applyUpdateDownload(download: UpdateDownload): void { + // The legacy progress payload has only byte counts. Its command response + // still completes a manual update on an older desktop backend. + if (!download?.version || updatePhase() === "installing") return; + updateRevision++; + updateVersion.set(download.version); + updateFraction.set(download.fraction); + updatePhase.set(download.phase); +} + +function showReadyUpdate(pending: PendingAppUpdate | null, notify: boolean): void { + if (!pending?.version || updatePhase() === "installing") return; + const changed = pending.version !== updateVersion() || updatePhase() !== "ready"; + updateVersion.set(pending.version); + updatePhase.set("ready"); + if (pending.installError) { + pushToast(tr("shell.updates.failed", { error: errorText(pending.installError) }), "error"); + } else if (notify && changed) { + pushToast(tr("shell.updates.readyVersion", { version: pending.version }), "info"); + } +} + +async function readPendingUpdate(notify = false): Promise { + if (!inAppUpdatesAvailable()) return; + const revision = ++updateRevision; try { - const pending = await invokeCommand<{ version?: string } | null>("get_pending_update", {}); - if (pending?.version) { - updateVersion.set(pending.version); - updatePhase.set("ready"); + const status = await invokeCommand("get_pending_update", { + includeDownload: true, + }); + if (revision !== updateRevision) return; + if (status && "download" in status) { + if (status.download) applyUpdateDownload(status.download); + else if (status.pending) showReadyUpdate(status.pending, notify); + else if (isUpdateDownloading()) updatePhase.set("available"); + } else { + showReadyUpdate(status, notify); } } catch (error) { console.warn("Failed to read pending update", error); @@ -1296,9 +1365,10 @@ async function readPendingUpdate(): Promise { } async function checkForAppUpdates(): Promise { - if (updatePhase() === "checking" || updatePhase() === "downloading" || updatePhase() === "installing") { + if (updatePhase() === "checking" || isUpdateDownloading() || updatePhase() === "installing") { return; } + updateRevision++; const previous = updatePhase(); updatePhase.set("checking"); try { @@ -1307,6 +1377,7 @@ async function checkForAppUpdates(): Promise { currentVersion?: string; latestVersion?: string | null; }>("check_for_updates", {}); + if (updatePhase() !== "checking") return; if (result?.updateAvailable && result.latestVersion) { if (previous === "ready" && updateVersion() === result.latestVersion) { updatePhase.set("ready"); @@ -1321,6 +1392,7 @@ async function checkForAppUpdates(): Promise { pushToast(tr("shell.updates.upToDate", { version: result?.currentVersion ?? "" }), "success"); } } catch (error) { + if (updatePhase() !== "checking") return; updatePhase.set(previous === "ready" ? "ready" : "idle"); pushToast(tr("shell.updates.failed", { error: errorText(error) }), "error"); } @@ -1329,23 +1401,31 @@ async function checkForAppUpdates(): Promise { async function downloadAppUpdate(): Promise { const expected = updateVersion(); if (!expected || updatePhase() !== "available") return; + updateRevision++; + updateFraction.set(null); updatePhase.set("downloading"); try { - const pending = await invokeCommand<{ version?: string; installError?: string }>("download_update", { + const pending = await invokeCommand("download_update", { expectedVersion: expected, }); - updateVersion.set(pending?.version || expected); - updatePhase.set("ready"); - pushToast(tr("shell.updates.readyVersion", { version: updateVersion() }), "success"); + if (isUpdateDownloading() && updateVersion() !== expected && updateVersion() !== pending?.version) return; + showReadyUpdate(pending?.version ? pending : { version: expected }, true); } catch (error) { - updatePhase.set("available"); - pushToast(tr("shell.updates.failed", { error: errorText(error) }), "error"); + showUpdateDownloadFailure(expected, error); } } +function showUpdateDownloadFailure(version: string, error: unknown): void { + if (!isUpdateDownloading() || updateVersion() !== version) return; + updateRevision++; + updatePhase.set("available"); + pushToast(tr("shell.updates.failed", { error: errorText(error) }), "error"); +} + async function installAppUpdate(): Promise { const version = updateVersion(); if (!version || updatePhase() !== "ready") return; + updateRevision++; updatePhase.set("installing"); try { await invokeCommand("install_pending_update", { version }); @@ -1378,7 +1458,8 @@ function updateMenuItem(): DropdownMenuItem { onSelect: () => void downloadAppUpdate(), }; case "downloading": - return { id: "footer-updates", label: tr("shell.updates.downloading"), icon: "download", disabled: true }; + case "verifying": + return { id: "footer-updates", label: updateProgressLabel(), icon: "download", disabled: true }; case "ready": return { id: "footer-updates", @@ -3353,6 +3434,14 @@ function FleetUpdateNotice() { ); } +function AppUpdateProgressNotice() { + return ( + + + + ); +} + /** The connected device or fleet now ships a newer web UI bundle; reload on the user's cue. */ function WebUiUpdateNotice() { const label = () => { @@ -3382,12 +3471,23 @@ function StudioApp() { untracked(() => syncGlobalNativeTheme(family)); }); // Fast local-only reads first (zero network RTT): theme, font, content width, layout, window chrome. - bindWindowShell(() => { - let current = true; - cleanup(() => { current = false; }); - void initWindowChrome().then(() => { - if (current && nativeWindow()) void readPendingUpdate(); - }); + bindWindowShell(() => { void initWindowChrome(); }); + effect(() => { + if (!inAppUpdatesAvailable()) return; + const localUpdateEvent = (origin: string) => !origin || origin === entryDeviceId(); + cleanup(listenEvent("openbitfun-update-progress", (download, meta) => { + if (localUpdateEvent(meta.origin)) applyUpdateDownload(download); + })); + cleanup(listenEvent<{ version: string; error: string }>("openbitfun-update-failed", (failure, meta) => { + if (failure && localUpdateEvent(meta.origin)) showUpdateDownloadFailure(failure.version, failure.error); + })); + cleanup(listenEvent("openbitfun-update-ready", (_, meta) => { + if (localUpdateEvent(meta.origin)) void readPendingUpdate(true); + })); + cleanup(listenEvent("backend://events-dropped", (_, meta) => { + if (localUpdateEvent(meta.origin)) void readPendingUpdate(); + })); + untracked(() => { void readPendingUpdate(); }); }); const localAppearanceReady = loadAppearance(); void loadLocalFontPreference(); @@ -3811,6 +3911,7 @@ function StudioApp() { + diff --git a/src/nsh-ui/src/locales/en-US.ts b/src/nsh-ui/src/locales/en-US.ts index 63348f45bf..5265391f5f 100644 --- a/src/nsh-ui/src/locales/en-US.ts +++ b/src/nsh-ui/src/locales/en-US.ts @@ -1554,7 +1554,7 @@ export const enUSMessages = { "settings.field.notifyPermissionRequest": "Notify on permission requests", "settings.field.notifyPermissionRequestDesc": "Notify when a tool run needs your approval", "settings.field.autoUpdate": "Check for updates automatically", - "settings.field.autoUpdateDesc": "Automatically check for newer builds", + "settings.field.autoUpdateDesc": "Check for updates and download them in the background on this desktop.", "settings.field.telemetry": "Send usage telemetry", "settings.field.telemetryDesc": "Share anonymous usage metrics to improve stability", "settings.field.confirmOnExit": "Confirm before quitting", @@ -3120,6 +3120,7 @@ export const enUSMessages = { "shell.updates.available": "Update {{version}} available", "shell.updates.download": "Download update {{version}}", "shell.updates.downloading": "Downloading update…", + "shell.updates.verifying": "Verifying update…", "shell.updates.readyVersion": "Update {{version}} is ready to install", "shell.updates.install": "Restart to install {{version}}", "shell.updates.installing": "Installing update…", diff --git a/src/nsh-ui/src/locales/zh-CN.ts b/src/nsh-ui/src/locales/zh-CN.ts index 716991a19c..15073fee67 100644 --- a/src/nsh-ui/src/locales/zh-CN.ts +++ b/src/nsh-ui/src/locales/zh-CN.ts @@ -1553,7 +1553,7 @@ export const zhCNMessages: Record = { "settings.field.notifyPermissionRequest": "权限审批请求通知", "settings.field.notifyPermissionRequestDesc": "工具调用需要人工确认时发送提醒", "settings.field.autoUpdate": "自动检查更新", - "settings.field.autoUpdateDesc": "启动时自动检测可用新版本", + "settings.field.autoUpdateDesc": "自动检查此桌面的更新,并在后台下载。", "settings.field.telemetry": "发送匿名使用统计", "settings.field.telemetryDesc": "分享匿名运行指标以帮助改进产品稳定性", "settings.field.confirmOnExit": "退出前确认", @@ -3119,6 +3119,7 @@ export const zhCNMessages: Record = { "shell.updates.available": "有可用更新 {{version}}", "shell.updates.download": "下载更新 {{version}}", "shell.updates.downloading": "正在下载更新…", + "shell.updates.verifying": "正在验证更新…", "shell.updates.readyVersion": "更新 {{version}} 已可安装", "shell.updates.install": "重启以安装 {{version}}", "shell.updates.installing": "正在安装更新…", diff --git a/src/nsh-ui/src/locales/zh-TW.ts b/src/nsh-ui/src/locales/zh-TW.ts index 111840ea3d..a5375acb34 100644 --- a/src/nsh-ui/src/locales/zh-TW.ts +++ b/src/nsh-ui/src/locales/zh-TW.ts @@ -1553,7 +1553,7 @@ export const zhTWMessages: Record = { "settings.field.notifyPermissionRequest": "權限審核請求通知", "settings.field.notifyPermissionRequestDesc": "工具執行需要人工確認時發送提醒", "settings.field.autoUpdate": "自動檢查更新", - "settings.field.autoUpdateDesc": "啟動時自動檢查可用新版本", + "settings.field.autoUpdateDesc": "自動檢查此桌面的更新,並在背景下載。", "settings.field.telemetry": "傳送匿名使用統計", "settings.field.telemetryDesc": "分享匿名執行指標以協助改進產品穩定性", "settings.field.confirmOnExit": "結束前確認", @@ -3119,6 +3119,7 @@ export const zhTWMessages: Record = { "shell.updates.available": "有可用更新 {{version}}", "shell.updates.download": "下載更新 {{version}}", "shell.updates.downloading": "正在下載更新…", + "shell.updates.verifying": "正在驗證更新…", "shell.updates.readyVersion": "更新 {{version}} 已可安裝", "shell.updates.install": "重新啟動以安裝 {{version}}", "shell.updates.installing": "正在安裝更新…", From 24c1f3b3142686c2cda05792daa2046c7d412717 Mon Sep 17 00:00:00 2001 From: kev1n77 <59403997+kev1n77@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:28:49 +0800 Subject: [PATCH 2/3] fix(build): defer renderer dependencies until asset compilation --- scripts/sync-nsh-vendor-assets.mjs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/sync-nsh-vendor-assets.mjs b/scripts/sync-nsh-vendor-assets.mjs index 2778c9f931..e27141e8cd 100644 --- a/scripts/sync-nsh-vendor-assets.mjs +++ b/scripts/sync-nsh-vendor-assets.mjs @@ -16,8 +16,6 @@ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { spawnSync } from 'node:child_process'; -import { buildSync } from 'esbuild'; -import { compileString } from 'sass'; import { createRequire } from 'node:module'; import { dirname, join, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -32,6 +30,7 @@ export const VENDOR_TARGETS = [ /** The pinned PDF.js dependency and its renderer are compiled as a classic script. */ export function preparePdfRendererAsset({ check = false } = {}) { + const { buildSync } = require('esbuild'); const distribution = dirname(require.resolve('pdfjs-dist/package.json')); const directories = ['cmaps', 'standard_fonts', 'wasm']; const licenses = [join(distribution, 'LICENSE')]; @@ -79,6 +78,8 @@ export function preparePdfRendererAsset({ check = false } = {}) { /** Compiles the built-in chart renderer and its pinned dependencies for the isolated document. */ export function prepareFigureRendererAsset({ check = false } = {}) { + const { buildSync } = require('esbuild'); + const { compileString } = require('sass'); const chartDir = dirname(require.resolve('echarts/package.json')); const chartRequire = createRequire(join(chartDir, 'package.json')); const reactDomDir = dirname(require.resolve('react-dom/package.json')); From 327060e6b478a0616d397592c7e6367b45c3f8e7 Mon Sep 17 00:00:00 2001 From: kev1n77 <59403997+kev1n77@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:30:30 +0800 Subject: [PATCH 3/3] fix(build): stamp Windows development icons in clean checkouts --- scripts/desktop-nsh-package-common.mjs | 1 + scripts/desktop-nsh-package-common.test.mjs | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/scripts/desktop-nsh-package-common.mjs b/scripts/desktop-nsh-package-common.mjs index fa4c1ec195..c225b75275 100644 --- a/scripts/desktop-nsh-package-common.mjs +++ b/scripts/desktop-nsh-package-common.mjs @@ -352,6 +352,7 @@ export function stampDevAppIdentity(appDir, rootDir = root, platform = process.p const winIcon = join(rootDir, "src", "apps", "desktop", "icons", "openbitfun-app-icon.ico"); const destIcon = join(appDir, "icon.ico"); if (existsSync(winIcon)) { + mkdirSync(appDir, { recursive: true }); copyFileSync(winIcon, destIcon); } } diff --git a/scripts/desktop-nsh-package-common.test.mjs b/scripts/desktop-nsh-package-common.test.mjs index f69a3dc6f7..2cff8e67ca 100644 --- a/scripts/desktop-nsh-package-common.test.mjs +++ b/scripts/desktop-nsh-package-common.test.mjs @@ -22,6 +22,7 @@ import { runnerTargetDir, shouldParallelizeCargo, stageRunnerBinary, + stampDevAppIdentity, writeWebBundleManifest, } from './desktop-nsh-package-common.mjs'; import { desktopDevServerArgs } from './desktop-nsh-dev.mjs'; @@ -159,6 +160,17 @@ test('products without declared icons use the committed OpenBitFun icons', () => assert.equal(productIcon({ icons: { macos: '/brand/app.icns' } }, 'macos'), '/brand/app.icns'); }); +test('Windows development identity can be stamped in a clean checkout', (t) => { + const work = mkdtempSync(join(tmpdir(), 'openbitfun-windows-dev-icon-')); + t.after(() => rmSync(work, { recursive: true, force: true })); + const icons = join(work, 'src', 'apps', 'desktop', 'icons'); + mkdirSync(icons, { recursive: true }); + writeFileSync(join(icons, 'openbitfun-app-icon.ico'), 'icon fixture'); + const appDir = join(work, 'target', 'desktop-nsh', 'nsh'); + stampDevAppIdentity(appDir, work, 'win32'); + assert.equal(readFileSync(join(appDir, 'icon.ico'), 'utf8'), 'icon fixture'); +}); + test('the packaged web bundle carries its ui-bundle.json, over the untouched files and the product id', () => { const site = mkdtempSync(join(tmpdir(), 'nsh-web-')); writeFileSync(join(site, 'index.html'), '');