Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(desktop): prepare Runtime during Windows installation and hide consoles (#3097)

Max6a827e3540a4
diff --git a/core/process_isolation.py b/core/process_isolation.py
index 52da750fe..fe8cebd23 100644
--- a/core/process_isolation.py
+++ b/core/process_isolation.py
@@ -248,11 +248,16 @@ def isolated_subprocess_kwargs(*, console: bool = True) -> dict[str, Any]:
``console=False`` is for a console program that only ever runs in the
background. On Windows it then gets no console window, which a parent with
no console of its own -- the desktop app starts the service that way --
- would otherwise open for it.
+ would otherwise open for it. Desktop-managed processes always use this
+ policy, including callers that leave ``console`` at its CLI default.
"""
if os.name == "nt":
flags = subprocess.CREATE_NEW_PROCESS_GROUP
- if not console:
+ desktop_managed = any(
+ os.environ.get(name, "").strip().lower() in {"1", "true", "yes", "on"}
+ for name in ("AVIBE_DESKTOP_SHELL", "AVIBE_DESKTOP_MANAGED_RUNTIME")
+ )
+ if not console or desktop_managed:
flags |= subprocess.CREATE_NO_WINDOW
return {"creationflags": flags}
return {"start_new_session": True}
@@ -552,11 +557,6 @@ def _terminate_windows_process_tree(
expected_identity: PersistedProcessIdentity,
terminate_timeout: float,
) -> bool:
- control_signal = getattr(signal, "CTRL_BREAK_EVENT", None)
- if control_signal is None:
- logger.error("Refusing to terminate %s because Windows process-group signaling is unavailable", label)
- return False
-
try:
process, live_identity = _open_process_identity(expected_identity.pid)
except psutil.NoSuchProcess:
@@ -571,13 +571,18 @@ def _terminate_windows_process_tree(
return False
victims = _windows_process_tree(process)
- try:
- process.send_signal(control_signal)
- except psutil.NoSuchProcess:
- return True
- except (psutil.Error, OSError):
- logger.debug("Failed to signal the Windows process group for %s", label, exc_info=True)
- return False
+ control_signal = getattr(signal, "CTRL_BREAK_EVENT", None)
+ if control_signal is not None:
+ try:
+ process.send_signal(control_signal)
+ except psutil.NoSuchProcess:
+ # The captured descendants can still be alive after their leader exits.
+ pass
+ except (psutil.Error, OSError):
+ # Windowless desktop children do not share a console with this
+ # process. A failed console signal does not revoke the verified
+ # identity: continue to the bounded, PID-reuse-safe psutil cleanup.
+ logger.debug("Could not send a console signal to %s; checking its process tree", label, exc_info=True)
_gone, alive = psutil.wait_procs(victims, timeout=terminate_timeout)
if not alive:
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
index f28561970..1ee2145aa 100644
--- a/desktop/Cargo.lock
+++ b/desktop/Cargo.lock
@@ -234,6 +234,7 @@ dependencies = [
"async-trait",
"avibe-runtime-host",
"block2",
+ "dirs 6.0.0",
"flate2",
"objc2",
"objc2-app-kit",
diff --git a/desktop/README.md b/desktop/README.md
index 81b308cf0..d9241ff25 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -115,8 +115,19 @@ put `$AVIBE_DESKTOP_RUNTIME_ROOT/bin` first after your PATH changes when that
variable is set. Codex's caller-context `BASH_ENV` injection does not run in zsh
and is not a fallback for this case.
-The first launch verifies the embedded Runtime archive and installs it
-atomically below the operating system's application-data directory. Installs
+Windows NSIS installation eagerly prepares the embedded Runtime after copying
+the app, including during silent `/UPDATE` transactions. The installed executable's
+`--prepare-runtime` mode verifies and extracts the archive before any GUI or
+single-instance initialization, into the same `%LOCALAPPDATA%\bot.avibe.desktop\runtime`
+tree used by the shell. Preparation failure fails installation; unattended
+installations return a nonzero exit without a dialog so the updater can report
+failure and roll back the app.
+
+First launch retains the lazy integrity and repair fallback for legacy installs,
+interrupted installations, and missing or damaged Runtime slots. macOS DMG,
+non-NSIS, and development paths remain lazy. Whenever preparation is necessary,
+the bootstrap page says that it is preparing the Runtime and that first-time
+preparation can take a few minutes. Installs
are versioned and content-addressed, so application updates never replace files
used by a running Runtime. The extracted tree is hashed before its slot is
published. A later launch reuses it after checking its file set, sizes, and
diff --git a/desktop/runtime-host/src/bootstrap.rs b/desktop/runtime-host/src/bootstrap.rs
index 4dfe9b998..623c4f7fc 100644
--- a/desktop/runtime-host/src/bootstrap.rs
+++ b/desktop/runtime-host/src/bootstrap.rs
@@ -395,6 +395,7 @@ impl RuntimeHost {
/// Runs the state machine once and returns its terminal status.
pub async fn bootstrap(&self, sink: &dyn StatusSink, trigger: BootstrapTrigger) -> BootstrapStatus {
let run = self.launched_runtime().begin_run();
+ publish(sink, BootstrapStatus::preparing());
let (origin, resolved_launcher) = match self.resolve_origin().await {
Ok(resolved) => resolved,
Err(error) => {
diff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rs
index 68ad77815..f88bb731d 100644
--- a/desktop/runtime-host/src/lib.rs
+++ b/desktop/runtime-host/src/lib.rs
@@ -53,7 +53,9 @@ pub use origin::{
is_shell_ui_url, wait_for_shell_ui_url, LoopbackOrigin, OriginError, ShellUiUrlWaitError, DEV_SERVER_PORT,
SHELL_UI_URL_TIMEOUT,
};
-pub use private_runtime::{PrivateRuntimeBundle, PrivateRuntimeError, RuntimeBundleManifest};
+pub use private_runtime::{
+ prepare_installed_runtime, PrivateRuntimeBundle, PrivateRuntimeError, RuntimeBundleManifest,
+};
pub use status::{BootstrapNotice, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus};
/// The host the shipped desktop shell uses: real HTTP probing, the installed
diff --git a/desktop/runtime-host/src/private_runtime.rs b/desktop/runtime-host/src/private_runtime.rs
index 9072c485d..60acb97db 100644
--- a/desktop/runtime-host/src/private_runtime.rs
+++ b/desktop/runtime-host/src/private_runtime.rs
@@ -2,8 +2,8 @@
//!
//! Product packages carry one target-specific ZIP plus an embedded manifest.
//! Production trust comes from the desktop application's code signature; the
-//! first launch then verifies the archive before extracting it into a versioned
-//! user-data directory. The application bundle is never mutated, and an update
+//! installer or first launch verifies the archive before extracting it into a
+//! versioned user-data directory. The application bundle is never mutated, and an update
//! can install a successor without replacing files used by a running daemon.
use std::ffi::OsStr;
@@ -130,6 +130,30 @@ pub struct PrivateRuntimeBundle {
trees_root: PathBuf,
}
+/// Prepare the Windows installer's adjacent bundle in the shell's app-data root.
+///
+/// Both paths come from the installed executable and OS directory lookup, never
+/// command-line arguments. This shares the lazy launcher's verification and slot
+/// lifecycle, but never prunes superseded slots or starts a Runtime.
+pub fn prepare_installed_runtime(
+ executable: &Path,
+ app_local_data_dir: &Path,
+) -> Result<InstalledPrivateRuntime, PrivateRuntimeError> {
+ let resource_dir = executable.parent().filter(|path| path.is_absolute()).ok_or_else(|| {
+ PrivateRuntimeError::Install(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "invalid executable directory",
+ ))
+ })?;
+ if !app_local_data_dir.is_absolute() {
+ return Err(PrivateRuntimeError::Install(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "invalid application data directory",
+ )));
+ }
+ PrivateRuntimeBundle::new(resource_dir.join("runtime"), app_local_data_dir.join("runtime")).prepare()
+}
+
impl PrivateRuntimeBundle {
pub fn new(bundle_dir: PathBuf, install_root: PathBuf) -> Self {
let trees_root = TREES_DIR_NAME.map_or_else(|| install_root.clone(), |name| install_root.join(name));
@@ -891,6 +915,58 @@ mod tests {
manifest
}
+ #[test]
+ fn installer_preparation_and_lazy_launch_share_the_same_verified_slot() {
+ let root = scratch("installer-prepare");
+ let manifest = write_bundle(&root, None);
+ let installation = root.join("Program Files").join("Avibe 测试");
+ fs::create_dir_all(&installation).unwrap();
+ fs::rename(root.join("bundle"), installation.join("runtime")).unwrap();
+ let app_data = root.join("Local App Data").join("bot.avibe.desktop");
+ let executable = installation.join("avibe-desktop.exe");
+ let predecessor = app_data.join("runtime").join("old-version").join("old-digest");
+ fs::create_dir_all(&predecessor).unwrap();
+ fs::write(predecessor.join("running"), b"keep this Runtime").unwrap();
+
+ let prepared = prepare_installed_runtime(&executable, &app_data).unwrap();
+ assert!(!prepared.reused);
+ assert!(prepared.root.starts_with(app_data.join("runtime")));
+ assert!(prepared.root.ends_with(&manifest.archive_sha256[..16]));
+ assert!(!prepared.root.starts_with(&installation));
+
+ let again = prepare_installed_runtime(&executable, &app_data).unwrap();
+ let lazy = PrivateRuntimeBundle::new(installation.join("runtime"), app_data.join("runtime"))
+ .prepare()
+ .unwrap();
+ assert!(again.reused && lazy.reused);
+ assert_eq!(prepared.root, again.root);
+ assert_eq!(prepared.root, lazy.root);
+ assert_eq!(fs::read(predecessor.join("running")).unwrap(), b"keep this Runtime");
+ fs::remove_dir_all(root).unwrap();
+ }
+
+ #[test]
+ fn installer_preparation_fails_closed_on_invalid_paths_or_bundle() {
+ let root = scratch("installer-failure");
+ let app_data = root.join("local-data");
+ let executable = root.join("app").join("avibe-desktop.exe");
+ assert!(prepare_installed_runtime(Path::new("relative.exe"), &app_data).is_err());
+ assert!(prepare_installed_runtime(&executable, Path::new("relative")).is_err());
+ assert!(matches!(
+ prepare_installed_runtime(&executable, &app_data),
+ Err(PrivateRuntimeError::ManifestUnavailable(_))
+ ));
+ write_bundle(&root, None);
+ fs::create_dir_all(executable.parent().unwrap()).unwrap();
+ fs::rename(root.join("bundle"), root.join("app/runtime")).unwrap();
+ fs::write(root.join("app/runtime/runtime.zip"), b"corrupt archive").unwrap();
+ assert!(matches!(
+ prepare_installed_runtime(&executable, &app_data),
+ Err(PrivateRuntimeError::ArchiveVerification)
+ ));
+ fs::remove_dir_all(root).unwrap();
+ }
+
#[test]
fn tree_verification_keeps_the_frozen_v1_digest_and_rejects_equal_size_tampering() {
let root = scratch("frozen-tree-digest");
diff --git a/desktop/runtime-host/src/status.rs b/desktop/runtime-host/src/status.rs
index 22d5437b3..0a1f4f485 100644
--- a/desktop/runtime-host/src/status.rs
+++ b/desktop/runtime-host/src/status.rs
@@ -32,6 +32,7 @@ impl BootstrapPhase {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BootstrapNoticeCode {
+ Preparing,
Probing,
Adopted,
Starting,
@@ -89,6 +90,17 @@ pub struct BootstrapStatus {
}
impl BootstrapStatus {
+ /// Runtime preparation precedes discovery of a validated origin.
+ pub fn preparing() -> Self {
+ Self {
+ phase: BootstrapPhase::Probing,
+ origin: String::new(),
+ attempt: 0,
+ notice: BootstrapNotice::new(BootstrapNoticeCode::Preparing),
+ retryable: false,
+ }
+ }
+
pub fn probing(origin: &LoopbackOrigin, attempt: u32) -> Self {
Self {
phase: BootstrapPhase::Probing,
@@ -199,9 +211,26 @@ mod tests {
assert_eq!(status.notice.code, BootstrapNoticeCode::InvalidOrigin);
}
+ #[test]
+ fn preparation_has_no_endpoint_or_probe_attempt_and_is_not_terminal() {
+ let status = BootstrapStatus::preparing();
+ assert!(!status.phase.is_terminal());
+ assert_eq!(
+ serde_json::to_value(status).unwrap(),
+ serde_json::json!({
+ "phase": "probing",
+ "origin": "",
+ "attempt": 0,
+ "notice": { "code": "preparing" },
+ "retryable": false,
+ })
+ );
+ }
+
#[test]
fn every_notice_code_uses_its_contract_spelling() {
let cases = [
+ (BootstrapNoticeCode::Preparing, "preparing"),
(BootstrapNoticeCode::Probing, "probing"),
(BootstrapNoticeCode::Adopted, "adopted"),
(BootstrapNoticeCode::Starting, "starting"),
diff --git a/desktop/runtime-host/tests/bootstrap.rs b/desktop/runtime-host/tests/bootstrap.rs
index 01d0479c8..b991ad5ca 100644
--- a/desktop/runtime-host/tests/bootstrap.rs
+++ b/desktop/runtime-host/tests/bootstrap.rs
@@ -384,6 +384,54 @@ async fn boot(host: &RuntimeHost, trigger: BootstrapTrigger) -> BootstrapStatus
host.bootstrap(&Recorder::default(), trigger).await
}
+#[tokio::test]
+async fn preparation_is_visible_before_resolution_and_probing_waits_for_it() {
+ struct HeldLauncher {
+ recorder: Arc<Recorder>,
+ entered: Notify,
+ release: Mutex<std::sync::mpsc::Receiver<()>>,
+ }
+
+ impl RuntimeLauncher for HeldLauncher {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ // Check at entry, rather than after resolve has had time to run.
+ assert_eq!(self.recorder.statuses(), vec![BootstrapStatus::preparing()]);
+ self.entered.notify_one();
+ self.release
+ .lock()
+ .unwrap()
+ .recv_timeout(Duration::from_secs(5))
+ .expect("test releases resolution");
+ FakeLauncher::working().resolve()
+ }
+ }
+
+ let recorder = Arc::new(Recorder::default());
+ let (release, receiver) = std::sync::mpsc::channel();
+ let launcher = Arc::new(HeldLauncher {
+ recorder: recorder.clone(),
+ entered: Notify::new(),
+ release: Mutex::new(receiver),
+ });
+ let probe = FakeProbe::healthy_from(1);
+ let host = RuntimeHost::new(probe.clone(), launcher.clone(), fast_settings());
+ let recording = recorder.clone();
+ let run = tokio::spawn(async move { host.bootstrap(recording.as_ref(), Launch).await });
+ tokio::time::timeout(Duration::from_secs(5), launcher.entered.notified())
+ .await
+ .expect("resolution entered");
+
+ let held_statuses = recorder.statuses();
+ let held_probe_calls = probe.calls();
+ release.send(()).unwrap();
+ let terminal = run.await.unwrap();
+
+ assert_eq!(held_statuses, vec![BootstrapStatus::preparing()]);
+ assert_eq!(held_probe_calls, 0, "no endpoint probes while preparation is blocked");
+ assert_eq!(terminal.phase, BootstrapPhase::Ready);
+ assert_eq!(recorder.statuses()[1], BootstrapStatus::probing(&origin(), 1));
+}
+
#[tokio::test(start_paused = true)]
async fn a_cold_link_is_consumed_only_after_ready_navigation_commits_and_never_replayed() {
let launcher = FakeLauncher::working();
@@ -467,7 +515,10 @@ async fn an_already_running_runtime_is_adopted_without_starting_anything() {
assert_eq!(status.attempt, 1);
assert_eq!(launcher.calls(), 0, "an adopted Runtime must never be re-started");
assert_eq!(probe.calls(), 1);
- assert_eq!(recorder.phases(), vec![BootstrapPhase::Probing, BootstrapPhase::Ready]);
+ assert_eq!(
+ recorder.phases(),
+ vec![BootstrapPhase::Probing, BootstrapPhase::Probing, BootstrapPhase::Ready]
+ );
assert!(!host.has_launched());
assert!(!host.has_owned_runtime(), "an untagged Runtime is never this app's");
assert!(launcher.verbs().is_empty(), "an untagged Runtime is never stopped");
@@ -719,6 +770,7 @@ async fn an_absent_runtime_is_started_and_adopted_once_it_answers() {
assert_eq!(
recorder.phases(),
vec![
+ BootstrapPhase::Probing,
BootstrapPhase::Probing,
BootstrapPhase::Starting,
BootstrapPhase::Starting,
@@ -1496,7 +1548,7 @@ async fn a_non_loopback_origin_fails_immediately_and_is_not_retryable() {
assert_eq!(status.attempt, 0);
assert_eq!(probe.calls(), 0, "a rejected origin is never contacted");
assert_eq!(launcher.calls(), 0);
- assert_eq!(recorder.phases(), vec![BootstrapPhase::Failed]);
+ assert_eq!(recorder.phases(), vec![BootstrapPhase::Probing, BootstrapPhase::Failed]);
// The rejected value is unvalidated input on its way to a WebView, so it is
// dropped and represented only by a typed notice.
assert!(status.origin.is_empty(), "got {:?}", status.origin);
@@ -1522,7 +1574,10 @@ async fn an_override_origin_is_adopted_only_and_never_starts_the_default_runtime
assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeNotFound);
assert_eq!(probe.calls(), 1, "the override origin is probed directly");
assert_eq!(launcher.calls(), 0, "override mode must not launch the default Runtime");
- assert_eq!(recorder.phases(), vec![BootstrapPhase::Probing, BootstrapPhase::Failed]);
+ assert_eq!(
+ recorder.phases(),
+ vec![BootstrapPhase::Probing, BootstrapPhase::Probing, BootstrapPhase::Failed]
+ );
}
#[tokio::test(start_paused = true)]
diff --git a/desktop/scripts/verify-i18n.mjs b/desktop/scripts/verify-i18n.mjs
index bfe9e2ec8..de2fb82d0 100644
--- a/desktop/scripts/verify-i18n.mjs
+++ b/desktop/scripts/verify-i18n.mjs
@@ -5,6 +5,7 @@ const expectedNoticeCodes = [
'adopted',
'invalid_origin',
'launcher_exited',
+ 'preparing',
'probing',
'ready',
'ready_timeout',
diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml
index 26ffb214c..f0a54b1d4 100644
--- a/desktop/src-tauri/Cargo.toml
+++ b/desktop/src-tauri/Cargo.toml
@@ -52,6 +52,8 @@ async-trait.workspace = true
tauri = { version = "2", features = ["tray-icon", "macos-private-api", "test"] }
[target.'cfg(windows)'.dependencies]
+# Match Tauri's Known Folder lookup without initializing the GUI.
+dirs = "6"
# The pet's drag: the primary button's state and a one-step window frame.
windows-sys = { version = "0.61", features = [
"Win32_UI_Input_KeyboardAndMouse",
diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs
index c1a0b22f3..c803d4c9c 100644
--- a/desktop/src-tauri/src/main.rs
+++ b/desktop/src-tauri/src/main.rs
@@ -2,6 +2,13 @@
// alongside it on Windows.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+#[cfg(any(windows, test))]
+mod prepare_runtime;
+
fn main() {
+ #[cfg(windows)]
+ if let Some(code) = prepare_runtime::run() {
+ std::process::exit(code);
+ }
avibe_desktop_lib::run()
}
diff --git a/desktop/src-tauri/src/prepare_runtime.rs b/desktop/src-tauri/src/prepare_runtime.rs
new file mode 100644
index 000000000..066b0996b
--- /dev/null
+++ b/desktop/src-tauri/src/prepare_runtime.rs
@@ -0,0 +1,87 @@
+//! Installer-only preparation before Tauri, its window, or single-instance IPC.
+
+use std::ffi::OsString;
+use std::path::{Path, PathBuf};
+
+const PREPARE_ARGUMENT: &str = "--prepare-runtime";
+
+fn dispatch(args: impl IntoIterator<Item = OsString>, prepare: impl FnOnce() -> bool) -> Option<i32> {
+ let args: Vec<_> = args.into_iter().collect();
+ if !args.iter().any(|arg| arg == PREPARE_ARGUMENT) {
+ return None;
+ }
+ if args.len() != 1 {
+ return Some(2);
+ }
+ Some(if prepare() { 0 } else { 1 })
+}
+
+fn app_local_data_dir(local_data: &Path) -> Result<PathBuf, serde_json::Error> {
+ #[derive(serde::Deserialize)]
+ struct Identity {
+ identifier: String,
+ }
+ // Use the same identifier as the normal shell, without creating a Tauri app.
+ let identity: Identity = serde_json::from_str(include_str!("../tauri.conf.json"))?;
+ Ok(local_data.join(identity.identifier))
+}
+
+#[cfg(windows)]
+pub fn run() -> Option<i32> {
+ dispatch(std::env::args_os().skip(1), || {
+ let Ok(executable) = std::env::current_exe() else {
+ return false;
+ };
+ // This is Tauri's own Windows app_local_data_dir lookup: Known Folder
+ // LocalAppData plus the configured identifier, independent of cwd/env.
+ let Some(local_data) = dirs::data_local_dir() else {
+ return false;
+ };
+ let Ok(app_data) = app_local_data_dir(&local_data) else {
+ return false;
+ };
+ // NSIS owns localized progress/failure copy; no raw paths escape here.
+ avibe_runtime_host::prepare_installed_runtime(&executable, &app_data).is_ok()
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn args(values: &[&str]) -> Vec<OsString> {
+ values.iter().map(OsString::from).collect()
+ }
+
+ #[test]
+ fn ordinary_launches_leave_preparation_to_the_shell() {
+ for values in [vec![], vec!["avibe://show/session"], vec!["--other-flag"]] {
+ assert_eq!(dispatch(args(&values), || panic!("must launch the GUI")), None);
+ }
+ }
+
+ #[test]
+ fn helper_reports_success_or_failure_without_falling_through_to_the_gui() {
+ assert_eq!(dispatch(args(&[PREPARE_ARGUMENT]), || true), Some(0));
+ assert_eq!(dispatch(args(&[PREPARE_ARGUMENT]), || false), Some(1));
+ for values in [
+ vec![PREPARE_ARGUMENT, "/UPDATE"],
+ vec!["--install-root", "elsewhere", PREPARE_ARGUMENT],
+ vec![PREPARE_ARGUMENT, PREPARE_ARGUMENT],
+ ] {
+ assert_eq!(dispatch(args(&values), || panic!("unexpected argument")), Some(2));
+ }
+ }
+
+ #[test]
+ fn app_data_uses_the_shell_identifier_under_the_os_local_data_root() {
+ let temporary = tempfile::tempdir().unwrap();
+ let local = temporary.path().join("Local App Data 测试");
+ let config: serde_json::Value = serde_json::from_str(include_str!("../tauri.conf.json")).unwrap();
+ assert!(config["app"].get("appDirectoriesOverride").is_none());
+ assert_eq!(
+ app_local_data_dir(&local).unwrap(),
+ local.join(config["identifier"].as_str().unwrap())
+ );
+ }
+}
diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json
index b95b5cd76..49855fe90 100644
--- a/desktop/src-tauri/tauri.conf.json
+++ b/desktop/src-tauri/tauri.conf.json
@@ -60,6 +60,12 @@
"resources": {
"resources/runtime/": "runtime/"
},
+ "windows": {
+ "nsis": {
+ "installerHooks": "./windows/hooks.nsh",
+ "languages": ["English", "SimpChinese"]
+ }
+ },
"macOS": {
"hardenedRuntime": true,
"entitlements": "Entitlements.plist"
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
index 61b89080d..db4a8b0ce 100644
--- a/desktop/src-tauri/tests/shell_boundaries.rs
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -50,10 +50,62 @@ fn shipping_text(source: &str) -> String {
#[test]
fn source_checks_read_a_windows_checkout_as_the_same_text() {
- let checkout = read_to_string(&crate_dir().join("src/lib.rs")).replace("\r\n", "\n");
- let windows = checkout.replace('\n', "\r\n");
- assert_eq!(shipping_text(&windows), shipping_text(&checkout));
- assert!(!shipping_source("src/lib.rs").contains('\r'));
+ for relative in ["src/lib.rs", "windows/hooks.nsh"] {
+ let checkout = read_to_string(&crate_dir().join(relative)).replace("\r\n", "\n");
+ let windows = checkout.replace('\n', "\r\n");
+ assert_eq!(shipping_text(&windows), shipping_text(&checkout));
+ assert!(!shipping_source(relative).contains('\r'));
+ }
+}
+
+#[test]
+fn installer_preparation_exits_before_the_gui_and_preserves_normal_startup() {
+ let entrypoint = shipping_source("src/main.rs");
+ assert!(entrypoint.contains("windows_subsystem = \"windows\""));
+ assert!(entrypoint.contains("#[cfg(windows)]\n if let Some(code) = prepare_runtime::run()"));
+ let helper = entrypoint.find("prepare_runtime::run()").unwrap();
+ let exit = entrypoint.find("std::process::exit(code)").unwrap();
+ let gui = entrypoint.find("avibe_desktop_lib::run()").unwrap();
+ assert!(helper < exit && exit < gui);
+
+ let preparation = shipping_source("src/prepare_runtime.rs");
+ assert!(preparation.contains("std::env::current_exe()"));
+ assert!(preparation.contains("dirs::data_local_dir()"));
+ assert!(preparation.contains("avibe_runtime_host::prepare_installed_runtime(&executable, &app_data)"));
+ assert!(!preparation.contains("tauri::Builder") && !preparation.contains("avibe_desktop_lib::run"));
+ let launcher = shipping_source("../runtime-host/src/launcher.rs");
+ assert!(
+ launcher.contains("self.bundle.prepare()"),
+ "lazy integrity and repair must remain available"
+ );
+}
+
+#[test]
+fn nsis_prepares_after_copy_and_fails_without_dialogs_in_unattended_modes() {
+ let config = config();
+ let nsis = &config["bundle"]["windows"]["nsis"];
+ assert_eq!(nsis["installerHooks"], "./windows/hooks.nsh");
+ assert_eq!(nsis["languages"], serde_json::json!(["English", "SimpChinese"]));
+ let hook = shipping_source(nsis["installerHooks"].as_str().unwrap());
+ assert!(hook.contains("!macro NSIS_HOOK_POSTINSTALL"));
+ assert!(hook.contains(r#"ExecWait '"$INSTDIR\${MAINBINARYNAME}.exe" --prepare-runtime' $0"#));
+ assert!(hook.contains("ClearErrors") && hook.contains("${If} ${Errors}"));
+ assert!(hook.contains("${If} $0 != 0"));
+ let dialog = hook.find("MessageBox").unwrap();
+ for condition in [
+ "${IfNot} ${Silent}",
+ "${AndIf} $UpdateMode != 1",
+ "${AndIf} $PassiveMode != 1",
+ ] {
+ assert!(hook.find(condition).unwrap() < dialog);
+ }
+ assert!(hook.contains("SetErrorLevel 1\n Abort"));
+ assert!(!hook.contains("ExecShell") && !hook.contains(" /UPDATE"));
+ for key in ["AvibeRuntimePreparing", "AvibeRuntimePrepareFailed"] {
+ for language in [1033, 2052] {
+ assert!(hook.contains(&format!("LangString {key} {language} ")));
+ }
+ }
}
#[test]
diff --git a/desktop/src-tauri/windows/hooks.nsh b/desktop/src-tauri/windows/hooks.nsh
new file mode 100644
index 000000000..28f3e7c63
--- /dev/null
+++ b/desktop/src-tauri/windows/hooks.nsh
@@ -0,0 +1,32 @@
+; Tauri includes hooks before MUI_LANGUAGE, so use the stable Windows language
+; IDs here. Both languages are enabled in tauri.conf.json.
+!include LogicLib.nsh
+LangString AvibeRuntimePreparing 1033 "Preparing Avibe Runtime..."
+LangString AvibeRuntimePreparing 2052 "正在准备 Avibe Runtime..."
+LangString AvibeRuntimePrepareFailed 1033 "Avibe Runtime could not be prepared. Please run the installer again."
+LangString AvibeRuntimePrepareFailed 2052 "无法准备 Avibe Runtime。请重新运行安装程序。"
+
+!macro NSIS_HOOK_POSTINSTALL
+ Push $0
+ DetailPrint "$(AvibeRuntimePreparing)"
+ ; Keep the executable's path out of the progress text.
+ SetDetailsPrint none
+ ClearErrors
+ ExecWait '"$INSTDIR\${MAINBINARYNAME}.exe" --prepare-runtime' $0
+ SetDetailsPrint lastused
+ ${If} ${Errors}
+ StrCpy $0 1
+ ${EndIf}
+ ${If} $0 != 0
+ DetailPrint "$(AvibeRuntimePrepareFailed)"
+ ${IfNot} ${Silent}
+ ${AndIf} $UpdateMode != 1
+ ${AndIf} $PassiveMode != 1
+ MessageBox MB_OK|MB_ICONSTOP "$(AvibeRuntimePrepareFailed)"
+ ${EndIf}
+ Pop $0
+ SetErrorLevel 1
+ Abort
+ ${EndIf}
+ Pop $0
+!macroend
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index f0e5209ef..671ceb202 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -12,6 +12,7 @@ import './styles.css'
*/
type BootstrapPhase = 'probing' | 'starting' | 'ready' | 'failed'
type NoticeCode =
+ | 'preparing'
| 'probing'
| 'adopted'
| 'starting'
@@ -54,6 +55,7 @@ declare const __DESKTOP_BOOTSTRAP_CATALOGS__: Record<'en' | 'zh', BootstrapCatal
const STATUS_EVENT = 'bootstrap-status'
const NOTICE_CODES: ReadonlySet<string> = new Set<NoticeCode>([
+ 'preparing',
'probing',
'adopted',
'starting',
@@ -82,7 +84,7 @@ const locale = selectLocale(navigator.languages)
const catalog = __DESKTOP_BOOTSTRAP_CATALOGS__[locale]
root.lang = locale
-messageEl.textContent = catalog.notices.probing
+messageEl.textContent = catalog.notices.preparing
retryEl.textContent = catalog.retry
helpEl.textContent = catalog.installationHelp
diff --git a/docs/plans/2026-10-31-windows-first-run.md b/docs/plans/2026-10-31-windows-first-run.md
new file mode 100644
index 000000000..b6b265fb8
--- /dev/null
+++ b/docs/plans/2026-10-31-windows-first-run.md
@@ -0,0 +1,59 @@
+# Windows first-run feedback and background processes
+
+## Change contract
+
+Before Runtime resolution (including bundled archive extraction and verification),
+bootstrap publishes the localized `preparing` notice. Its phase remains `probing`,
+its origin is empty, its attempt is zero, and it is not retryable. The bootstrap
+page initially renders the same notice. Only completed resolution permits the
+`probing` notice and endpoint probes. Progress remains indeterminate.
+
+On Windows, either truthy desktop environment marker (`AVIBE_DESKTOP_SHELL` or
+`AVIBE_DESKTOP_MANAGED_RUNTIME`) makes isolated children windowless. Without
+either marker, callers retain the existing console default. Explicit background
+spawns (owned Runtime children, their log sinks, and desktop backend installers)
+request no console even when desktop environment markers are absent. POSIX
+session isolation and the Rust launcher's detached lifecycle remain unchanged.
+Persisted Windows worker recovery still verifies the worker marker before
+touching its process tree. An unavailable or failed console signal must not
+prevent bounded forced cleanup of that verified tree, including descendants
+captured before the leader exited.
+
+Windows NSIS installs eagerly prepare the adjacent bundled Runtime after copying
+the app. The executable handles the exact `--prepare-runtime` command before
+Tauri initialization and rejects extra helper arguments. It obtains LocalAppData
+through the same `dirs` Known Folder lookup as Tauri, uses the identifier from
+`tauri.conf.json`, and delegates installation to `PrivateRuntimeBundle::prepare`.
+`dirs` is already in Tauri's dependency graph and is explicitly declared as a
+Windows dependency for this GUI-free lookup.
+
+The post-install hook waits for preparation and fails installation on a launch
+error or nonzero exit. Silent, passive, and `/UPDATE` modes never show the hook's
+failure dialog. Preparation does not prune old slots or start the shell. The
+normal lazy path remains the integrity/repair fallback; macOS DMG and non-NSIS
+paths remain lazy.
+
+## Validation
+
+- Hold launcher resolution at a test-controlled barrier: preparation must
+ already be visible, and no endpoint probe may occur until release.
+- Check the serialized status and both bundled locale catalogs.
+- Exercise the Windows creation-flag policy with isolated environment fixtures,
+ plus the existing Windows `GetConsoleWindow` probe.
+- Exercise the owned-process spawn boundary without creating a real service;
+ every child it creates must request windowless isolation.
+- Exercise persisted worker cleanup without a shared console: verified trees
+ are reaped, while a changed identity blocks signaling and forced termination.
+- Run focused Rust/Python tests, Ruff, desktop i18n/build and UI build gates.
+- Verify installer argument dispatch and root derivation, installation/reuse
+ through the existing bundle implementation, failure propagation, and retention
+ of a predecessor slot in hermetic directories. Verify NSIS hook wiring and
+ unattended failure branches with the existing shell-boundary tests.
+- On the next Windows rc, verify the preparation sentence during first-run
+ repair, eager extraction in the NSIS installer, and zero extra Python console
+ windows after the workbench appears, including while a backend CLI installs.
+ Exercise a failed silent `/UPDATE` to confirm the existing updater handles
+ the nonzero installer exit.
+
+Wizard/onboarding behavior, extraction percentages, signing,
+and release publication are outside this change.
diff --git a/tests/test_process_isolation.py b/tests/test_process_isolation.py
index 6444318d6..61ad9c0f9 100644
--- a/tests/test_process_isolation.py
+++ b/tests/test_process_isolation.py
@@ -14,7 +14,7 @@ from types import SimpleNamespace
import psutil
import pytest
-from core import watch_worker
+from core import process_isolation, watch_worker
from core.process_isolation import (
KILL_SIGNAL,
PROCESS_IDENTITY_ENV,
@@ -91,6 +91,29 @@ def test_background_console_program_opens_no_console_window() -> None:
assert result.stdout.strip() == "0"
[email protected]("marker", ["AVIBE_DESKTOP_SHELL", "AVIBE_DESKTOP_MANAGED_RUNTIME"])
[email protected]("value", [None, "", "0", "false", "off", "1", "true", "yes", "on", " TRUE "])
[email protected]("console", [True, False])
+def test_windows_console_policy_preserves_cli_default_and_hides_desktop_children(
+ monkeypatch: pytest.MonkeyPatch, marker: str, value: str | None, console: bool
+) -> None:
+ desktop_env = {}
+ if value is not None:
+ desktop_env[marker] = value
+ # Replace only this module's os reference: changing os.name globally can
+ # make pathlib and pytest select Windows implementations on a POSIX host.
+ monkeypatch.setattr(process_isolation, "os", SimpleNamespace(name="nt", environ=desktop_env))
+ monkeypatch.setattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x200, raising=False)
+ monkeypatch.setattr(subprocess, "CREATE_NO_WINDOW", 0x08000000, raising=False)
+
+ kwargs = isolated_subprocess_kwargs() if console else isolated_subprocess_kwargs(console=False)
+
+ flags = kwargs["creationflags"]
+ assert flags & subprocess.CREATE_NEW_PROCESS_GROUP
+ desktop_managed = value is not None and value.strip().lower() in {"1", "true", "yes", "on"}
+ assert bool(flags & subprocess.CREATE_NO_WINDOW) == (desktop_managed or not console)
+
+
def test_process_identity_reads_inherited_worker_marker(monkeypatch: pytest.MonkeyPatch) -> None:
process = SimpleNamespace(
create_time=lambda: 123.0,
@@ -350,6 +373,71 @@ def test_terminate_process_tree_by_pid_refuses_current_process(monkeypatch: pyte
)
[email protected]("console_signal", ["unavailable", "not_attached", "leader_exited", "ignored"])
[email protected]("terminate_works", [True, False])
+def test_windows_recovery_reaps_verified_descendants_without_a_console(
+ monkeypatch: pytest.MonkeyPatch, console_signal: str, terminate_works: bool
+) -> None:
+ class Process:
+ def __init__(self, pid):
+ self.pid = pid
+ self.alive = True
+
+ def children(self, *, recursive):
+ assert recursive
+ return [child]
+
+ def send_signal(self, _signal):
+ if console_signal == "not_attached":
+ raise OSError("no shared console")
+ if console_signal == "leader_exited":
+ self.alive = False
+ raise psutil.NoSuchProcess(self.pid)
+
+ def terminate(self):
+ if terminate_works:
+ self.alive = False
+
+ def kill(self):
+ self.alive = False
+
+ leader = Process(12345)
+ child = Process(12346)
+ monkeypatch.setattr(process_isolation, "os", SimpleNamespace(name="nt", getpid=lambda: 99999))
+ monkeypatch.setattr(process_isolation, "_open_process_identity", lambda _pid: (leader, _live_identity()))
+ monkeypatch.setattr(signal, "CTRL_BREAK_EVENT", None if console_signal == "unavailable" else 1, raising=False)
+ monkeypatch.setattr(
+ psutil, "wait_procs",
+ lambda victims, *, timeout: ([p for p in victims if not p.alive], [p for p in victims if p.alive]),
+ )
+
+ assert terminate_process_tree_by_pid(
+ leader.pid, logging.getLogger(__name__), "stale windowless worker",
+ expected_identity=_persisted_identity(), terminate_timeout=0,
+ )
+ assert not leader.alive
+ assert not child.alive, "a console failure or an exited leader must not leave descendants alive"
+
+
+def test_windows_recovery_cannot_force_terminate_a_worker_whose_marker_changed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(process_isolation, "os", SimpleNamespace(name="nt", getpid=lambda: 99999))
+ identities = iter([_live_identity(), _live_identity(worker_fingerprint=fingerprint_process_marker("replacement"))])
+ monkeypatch.setattr(
+ process_isolation, "_open_process_identity",
+ lambda _pid: (SimpleNamespace(pid=12345), next(identities)),
+ )
+ monkeypatch.setattr(
+ process_isolation, "_windows_process_tree",
+ lambda _process: pytest.fail("a changed marker must stop recovery before any signaling"),
+ )
+
+ assert not terminate_process_tree_by_pid(
+ 12345, logging.getLogger(__name__), "changed worker", expected_identity=_persisted_identity(),
+ )
+
+
def test_terminate_process_tree_by_pid_refuses_service_process_group(monkeypatch: pytest.MonkeyPatch) -> None:
if os.name == "nt":
pytest.skip("process group guard is POSIX-specific")
diff --git a/tests/test_runtime_spawn_ownership.py b/tests/test_runtime_spawn_ownership.py
index f529acaae..fb6c56044 100644
--- a/tests/test_runtime_spawn_ownership.py
+++ b/tests/test_runtime_spawn_ownership.py
@@ -10,17 +10,44 @@ reaped -- not on a mock having been called.
from __future__ import annotations
import errno
+import io
import subprocess
import sys
from pathlib import Path
+from types import SimpleNamespace
import pytest
+from core import process_isolation
from vibe import runtime
MARKER = "avibe-spawn-ownership-probe"
+def test_background_spawn_and_all_its_helpers_are_windowless_without_desktop_markers(monkeypatch, tmp_path):
+ """The owning spawn boundary applies its policy to the entire child tree."""
+ monkeypatch.setattr(process_isolation, "os", SimpleNamespace(name="nt", environ={}))
+ monkeypatch.setattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x200, raising=False)
+ monkeypatch.setattr(subprocess, "CREATE_NO_WINDOW", 0x08000000, raising=False)
+ monkeypatch.setattr(runtime.paths, "get_runtime_dir", lambda: tmp_path / "runtime")
+ monkeypatch.setattr(runtime, "get_working_dir", lambda: tmp_path)
+ spawned = []
+
+ def popen(args, **kwargs):
+ child = SimpleNamespace(stdin=io.BytesIO())
+ spawned.append((child, kwargs))
+ return child
+
+ monkeypatch.setattr(runtime.subprocess, "Popen", popen)
+ child = runtime._spawn_owned_process(["fixture-runtime"], "stdout.log", "stderr.log", {})
+
+ assert len(spawned) > 1, "exercise both the owned child and its helpers"
+ assert child is spawned[-1][0]
+ for _, kwargs in spawned:
+ assert kwargs["creationflags"] & subprocess.CREATE_NO_WINDOW
+ assert kwargs["creationflags"] & subprocess.CREATE_NEW_PROCESS_GROUP
+
+
class _Spawned(list):
"""The probe children, plus the log sinks started for them."""
diff --git a/tests/test_service_logging_handlers.py b/tests/test_service_logging_handlers.py
index 32478b31b..f1d23a167 100644
--- a/tests/test_service_logging_handlers.py
+++ b/tests/test_service_logging_handlers.py
@@ -98,7 +98,7 @@ def test_spawn_background_detaches_stdin(monkeypatch, tmp_path):
sink_paths: list[Path] = []
monkeypatch.setattr(runtime.paths, "get_runtime_dir", lambda: tmp_path)
- monkeypatch.setattr(runtime, "isolated_subprocess_kwargs", lambda: {"creationflags": 0x200})
+ monkeypatch.setattr(runtime, "isolated_subprocess_kwargs", lambda *, console=True: {"creationflags": 0x200})
class FakeSink:
def __init__(self, path: Path):
@@ -141,7 +141,7 @@ def test_runtime_log_sink_uses_platform_isolation(monkeypatch, tmp_path):
captured["kwargs"] = kwargs
monkeypatch.setattr(runtime.subprocess, "Popen", FakePopen)
- monkeypatch.setattr(runtime, "isolated_subprocess_kwargs", lambda: {"creationflags": 0x200})
+ monkeypatch.setattr(runtime, "isolated_subprocess_kwargs", lambda *, console=True: {"creationflags": 0x200})
runtime._spawn_runtime_log_sink(tmp_path / "runtime.log")
@@ -154,7 +154,7 @@ def test_generic_background_spawn_uses_platform_isolation(monkeypatch, tmp_path)
sink_paths: list[Path] = []
monkeypatch.setattr(runtime.paths, "get_runtime_dir", lambda: tmp_path)
- monkeypatch.setattr(runtime, "isolated_subprocess_kwargs", lambda: {"creationflags": 0x200})
+ monkeypatch.setattr(runtime, "isolated_subprocess_kwargs", lambda *, console=True: {"creationflags": 0x200})
class FakeSink:
def __init__(self, path: Path):
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 9f08e386a..e39c2923d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -6,6 +6,7 @@
"shellUnavailable": "The Avibe desktop shell stopped responding. Quit and open Avibe again.",
"genericFailure": "Avibe could not connect to its Runtime.",
"notices": {
+ "preparing": "Preparing the Avibe Runtime… This can take a few minutes the first time.",
"probing": "Looking for a running Avibe Runtime…",
"adopted": "Connected to the Avibe Runtime already running on this machine.",
"starting": "Starting the Avibe Runtime…",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c23c92bf6..ec45d1710 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -6,6 +6,7 @@
"shellUnavailable": "Avibe 桌面端已停止响应,请退出后重新打开。",
"genericFailure": "Avibe 无法连接到 Runtime。",
"notices": {
+ "preparing": "正在准备 Avibe Runtime… 首次启动可能需要几分钟。",
"probing": "正在查找运行中的 Avibe Runtime…",
"adopted": "已连接到本机正在运行的 Avibe Runtime。",
"starting": "正在启动 Avibe Runtime…",
diff --git a/vibe/desktop_backends.py b/vibe/desktop_backends.py
index 35c977451..5f5905cc8 100644
--- a/vibe/desktop_backends.py
+++ b/vibe/desktop_backends.py
@@ -612,7 +612,7 @@ def _spawn_owned_installer(
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
- **isolated_subprocess_kwargs(),
+ **isolated_subprocess_kwargs(console=False),
)
identity = capture_spawned_process_identity(process.pid, marker)
owned = _OwnedInstaller(process, worker_fingerprint, identity)
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 99aae44b4..8235a0906 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -1255,7 +1255,7 @@ def _spawn_runtime_log_sink(path: Path) -> subprocess.Popen:
stderr=subprocess.DEVNULL,
cwd=str(get_working_dir()),
close_fds=True,
- **isolated_subprocess_kwargs(),
+ **isolated_subprocess_kwargs(console=False),
)
@@ -1372,7 +1372,7 @@ def _spawn_owned_process(
cwd=str(get_working_dir()),
close_fds=True,
env=independent_process_env(env),
- **isolated_subprocess_kwargs(),
+ **isolated_subprocess_kwargs(console=False),
)
# Closing can fail too, so it happens inside this region and before the
# handover: once the caller owns the child, nothing here can raise.