Import AITURK IDE 1.0.0-beta.1 from Hermes 63279301; preserve MIT license
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
[package]
|
||||
name = "hermes-bootstrap"
|
||||
version = "0.0.1"
|
||||
description = "Hermes Setup — signed installer that drives scripts/install.ps1"
|
||||
authors = ["Nous Research <info@nousresearch.com>"]
|
||||
edition = "2021"
|
||||
rust-version = "1.77"
|
||||
|
||||
# Rename the output binary so the distributed artifact is literally
|
||||
# `Hermes-Setup.exe` on disk — not `hermes-bootstrap.exe`. Grandma sees
|
||||
# what we hand her, period. Tauri honors [[bin]] over [package].name
|
||||
# for the produced executable name.
|
||||
[[bin]]
|
||||
name = "Hermes-Setup"
|
||||
path = "src/main.rs"
|
||||
|
||||
# The library target name MUST match the `withGlobalTauri` binding name that
|
||||
# tauri.conf.json's `app.windows[].label` references. We don't ship a separate
|
||||
# lib for now; everything is in src/.
|
||||
[lib]
|
||||
name = "hermes_bootstrap_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
# Tauri runtime + plugins
|
||||
tauri = { version = "2", features = [] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-process = "2"
|
||||
tauri-plugin-shell = "2"
|
||||
|
||||
# Async + IO
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
futures = "0.3"
|
||||
|
||||
# Serialization
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
||||
# HTTP — rustls so we don't need OpenSSL on the build box
|
||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream"] }
|
||||
|
||||
# Logging — emitted to a file under HERMES_HOME/logs/ and (optionally) the
|
||||
# webview console via Tauri's event channel.
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
||||
tracing-appender = "0.2"
|
||||
|
||||
# Paths + utils
|
||||
dirs = "5"
|
||||
which = "6"
|
||||
anyhow = "1"
|
||||
thiserror = "1"
|
||||
once_cell = "1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
# Process control on Windows (CREATE_NO_WINDOW etc.)
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.59", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Diagnostics_ToolHelp",
|
||||
"Win32_System_Threading",
|
||||
"Win32_System_Console",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
|
||||
# Signal-0 liveness probe for the update-lock marker owner (update.rs).
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[profile.release]
|
||||
# A 5-10MB signed installer is the goal. LTO + size-opt + single codegen unit.
|
||||
panic = "abort"
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
opt-level = "s"
|
||||
strip = true
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSAudioCaptureUsageDescription</key>
|
||||
<string>Hermes launches the desktop app, which uses audio capture for voice conversations.</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>Hermes launches the desktop app, which uses the microphone for voice input and voice conversations.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,190 @@
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
// -----------------------------------------------------------------
|
||||
// Bake the install.ps1 pin into the binary at compile time.
|
||||
//
|
||||
// BUILD_PIN_COMMIT and BUILD_PIN_BRANCH are read by bootstrap.rs's
|
||||
// `option_env!()` macro to default the install-script reference.
|
||||
// Precedence (matches install.ps1's own arg precedence): commit > branch.
|
||||
//
|
||||
// The COMMIT pin is opt-in. By default a dev build pins ONLY the branch,
|
||||
// so the produced installer follows that branch's HEAD at install time
|
||||
// (tolerant of fast-forwards/new commits, and never references a SHA the
|
||||
// local checkout hasn't pushed). Set HERMES_BUILD_PIN_COMMIT to bake an
|
||||
// immutable commit pin for reproducible/release installers.
|
||||
//
|
||||
// Commit pin resolution:
|
||||
// - HERMES_BUILD_PIN_COMMIT, if set and non-empty. Accepts a SHA, tag,
|
||||
// or branch name; resolved to an immutable SHA via `git rev-parse`
|
||||
// when possible, else used verbatim if it already looks like a SHA.
|
||||
// - Otherwise: NO commit pin (branch-follow is the default).
|
||||
//
|
||||
// Branch pin resolution:
|
||||
// 1. HERMES_BUILD_PIN_BRANCH, if set and non-empty.
|
||||
// 2. `git rev-parse --abbrev-ref HEAD` of the checkout this build.rs
|
||||
// lives in — the current branch. (None on a detached HEAD.)
|
||||
// 3. Last-resort fallback handled below: if neither commit nor branch
|
||||
// resolves, warn — the binary needs a runtime arg or dev-repo env.
|
||||
//
|
||||
// Build script reruns on git HEAD change so a new commit triggers
|
||||
// a rebuild without `cargo clean`.
|
||||
// -----------------------------------------------------------------
|
||||
|
||||
let commit = resolve_commit_pin();
|
||||
let branch = resolve_branch_pin();
|
||||
|
||||
if let Some(c) = &commit {
|
||||
println!("cargo:rustc-env=BUILD_PIN_COMMIT={c}");
|
||||
println!(
|
||||
"cargo:warning=hermes-bootstrap: pinning to commit {}",
|
||||
short(c)
|
||||
);
|
||||
}
|
||||
if let Some(b) = &branch {
|
||||
println!("cargo:rustc-env=BUILD_PIN_BRANCH={b}");
|
||||
match &commit {
|
||||
Some(_) => println!("cargo:warning=hermes-bootstrap: pinning to branch {b}"),
|
||||
None => println!(
|
||||
"cargo:warning=hermes-bootstrap: following branch {b} HEAD (no commit pin; \
|
||||
set HERMES_BUILD_PIN_COMMIT for an immutable pin)"
|
||||
),
|
||||
}
|
||||
}
|
||||
if commit.is_none() && branch.is_none() {
|
||||
// Fail loudly rather than silently produce a binary that errors
|
||||
// at runtime with "no install-script pin supplied". A build that
|
||||
// can't resolve a pin almost certainly indicates a misconfigured
|
||||
// build environment.
|
||||
println!(
|
||||
"cargo:warning=hermes-bootstrap: no pin resolved at build time; binary will fail at runtime without HERMES_SETUP_DEV_REPO_ROOT or runtime args"
|
||||
);
|
||||
}
|
||||
|
||||
// Rerun build.rs when HEAD moves. With branch-follow as the default the
|
||||
// baked commit no longer changes per-commit, but a branch *switch* changes
|
||||
// the detected branch name, so we still re-trigger. When an explicit
|
||||
// HERMES_BUILD_PIN_COMMIT resolves a moving ref (tag/branch) to a SHA, a
|
||||
// HEAD move can also change that resolution. .git/HEAD changes on every
|
||||
// commit / branch switch / rebase.
|
||||
let git_dir = locate_git_dir();
|
||||
if let Some(gd) = &git_dir {
|
||||
println!("cargo:rerun-if-changed={}/HEAD", gd.display());
|
||||
// .git/HEAD often points at a ref (e.g. `ref: refs/heads/bb/gui`);
|
||||
// also watch the ref itself so a new commit on the same branch
|
||||
// re-triggers.
|
||||
if let Ok(head) = std::fs::read_to_string(gd.join("HEAD")) {
|
||||
if let Some(rest) = head.trim().strip_prefix("ref: ") {
|
||||
println!("cargo:rerun-if-changed={}/{}", gd.display(), rest);
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("cargo:rerun-if-env-changed=HERMES_BUILD_PIN_COMMIT");
|
||||
println!("cargo:rerun-if-env-changed=HERMES_BUILD_PIN_BRANCH");
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Tauri windows manifest. See hermes-setup.manifest for rationale —
|
||||
// declares level="asInvoker" so Windows's installer-detection
|
||||
// heuristic doesn't refuse to launch us without UAC elevation.
|
||||
// -----------------------------------------------------------------
|
||||
#[cfg(target_os = "windows")]
|
||||
let attrs = {
|
||||
let manifest = include_str!("hermes-setup.manifest");
|
||||
let win = tauri_build::WindowsAttributes::new().app_manifest(manifest);
|
||||
tauri_build::Attributes::new().windows_attributes(win)
|
||||
};
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let attrs = tauri_build::Attributes::new();
|
||||
|
||||
tauri_build::try_build(attrs).expect("failed to run tauri-build");
|
||||
}
|
||||
|
||||
fn resolve_commit_pin() -> Option<String> {
|
||||
// Commit pinning is OPT-IN. Only bake a commit when the caller explicitly
|
||||
// asks for one via HERMES_BUILD_PIN_COMMIT. With no env var, we return
|
||||
// None and the installer follows the branch HEAD at install time.
|
||||
let requested = std::env::var("HERMES_BUILD_PIN_COMMIT").ok()?;
|
||||
let requested = requested.trim();
|
||||
if requested.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Resolve the request (which may be a SHA, tag, or branch name) to an
|
||||
// immutable commit SHA so the baked pin is reproducible. `^{commit}`
|
||||
// dereferences tags to the commit they point at.
|
||||
if let Ok(out) = Command::new("git")
|
||||
.args(["rev-parse", "--verify", &format!("{requested}^{{commit}}")])
|
||||
.output()
|
||||
{
|
||||
if out.status.success() {
|
||||
if let Ok(s) = String::from_utf8(out.stdout) {
|
||||
let s = s.trim().to_string();
|
||||
if !s.is_empty() {
|
||||
return Some(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Couldn't resolve via git (e.g. building outside a checkout). Accept the
|
||||
// literal value only if it already looks like a SHA; otherwise fail loud
|
||||
// rather than bake an unresolvable ref into the binary.
|
||||
if is_sha(requested) {
|
||||
return Some(requested.to_string());
|
||||
}
|
||||
panic!(
|
||||
"HERMES_BUILD_PIN_COMMIT={requested:?} could not be resolved to a commit \
|
||||
(git rev-parse failed and it is not a valid SHA)"
|
||||
);
|
||||
}
|
||||
|
||||
/// True if `s` looks like an abbreviated-or-full git SHA (7..=40 hex chars).
|
||||
fn is_sha(s: &str) -> bool {
|
||||
let len = s.len();
|
||||
(7..=40).contains(&len) && s.chars().all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
fn resolve_branch_pin() -> Option<String> {
|
||||
if let Ok(v) = std::env::var("HERMES_BUILD_PIN_BRANCH") {
|
||||
if !v.trim().is_empty() {
|
||||
return Some(v.trim().to_string());
|
||||
}
|
||||
}
|
||||
let out = Command::new("git")
|
||||
.args(["rev-parse", "--abbrev-ref", "HEAD"])
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
|
||||
// "HEAD" is what you get on a detached checkout — no meaningful branch
|
||||
// to pin to. The commit pin still applies; just don't emit a branch.
|
||||
if s.is_empty() || s == "HEAD" {
|
||||
None
|
||||
} else {
|
||||
Some(s)
|
||||
}
|
||||
}
|
||||
|
||||
fn locate_git_dir() -> Option<std::path::PathBuf> {
|
||||
let out = Command::new("git")
|
||||
.args(["rev-parse", "--git-dir"])
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
|
||||
if s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(std::path::PathBuf::from(s))
|
||||
}
|
||||
|
||||
fn short(commit: &str) -> &str {
|
||||
if commit.len() >= 12 {
|
||||
&commit[..12]
|
||||
} else {
|
||||
commit
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2/capability",
|
||||
"identifier": "default",
|
||||
"description": "Capabilities required by Hermes Setup. Narrowly scoped: we don't write user files outside HERMES_HOME, we don't read arbitrary paths, and the only external network call goes through reqwest (Rust side, not exposed to the webview).",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-theme",
|
||||
"core:event:default",
|
||||
"opener:default",
|
||||
"dialog:default",
|
||||
"process:default",
|
||||
"shell:default"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,75 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<!--
|
||||
Hermes Setup application manifest.
|
||||
|
||||
The TL;DR: tell Windows we are NOT an installer in the classic "needs
|
||||
UAC elevation" sense, despite the product name. We provision into
|
||||
%LOCALAPPDATA%\hermes which is user-scoped and never touch HKLM or
|
||||
Program Files. install.ps1 runs as a child process and elevates
|
||||
itself only if a future stage explicitly needs HKLM access.
|
||||
|
||||
Without this manifest, the "Hermes Setup" productName embedded in
|
||||
the binary's resource trips Windows's installer-detection heuristic
|
||||
(https://learn.microsoft.com/en-us/windows/security/identity-protection/
|
||||
user-account-control/how-user-account-control-works#installer-detection)
|
||||
and CreateProcess fails with ERROR_ELEVATION_REQUIRED (740) when the
|
||||
user double-clicks. asInvoker disables that.
|
||||
-->
|
||||
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||
<assemblyIdentity
|
||||
version="0.0.1.0"
|
||||
processorArchitecture="*"
|
||||
name="NousResearch.Hermes.Setup"
|
||||
type="win32"
|
||||
/>
|
||||
<description>Hermes Setup</description>
|
||||
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<security>
|
||||
<requestedPrivileges>
|
||||
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
|
||||
</requestedPrivileges>
|
||||
</security>
|
||||
</trustInfo>
|
||||
|
||||
<!-- Tell Windows we know about all supported OSes (10 + 11) so it
|
||||
doesn't shim us into Vista-compat mode. -->
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<!-- Windows 10 / 11 -->
|
||||
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
|
||||
<!-- Windows 8.1 -->
|
||||
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
|
||||
<!-- Windows 8 -->
|
||||
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
|
||||
<!-- Windows 7 -->
|
||||
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
|
||||
<!-- Windows Vista -->
|
||||
<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
|
||||
</application>
|
||||
</compatibility>
|
||||
|
||||
<!-- Per-monitor v2 DPI awareness so the installer doesn't go blurry
|
||||
on high-DPI displays when dragged between monitors. -->
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
|
||||
<activeCodePage xmlns="http://schemas.microsoft.com/SMI/2019/WindowsSettings">UTF-8</activeCodePage>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
|
||||
<!-- Use the modern common controls (v6 themes). Without this, our
|
||||
file picker / shell dialogs fall back to 1990s-era visuals. -->
|
||||
<dependency>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity
|
||||
type="win32"
|
||||
name="Microsoft.Windows.Common-Controls"
|
||||
version="6.0.0.0"
|
||||
processorArchitecture="*"
|
||||
publicKeyToken="6595b64144ccf1df"
|
||||
language="*"
|
||||
/>
|
||||
</dependentAssembly>
|
||||
</dependency>
|
||||
</assembly>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 674 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 674 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 674 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 78 KiB |
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,112 @@
|
||||
//! Event types streamed from Rust → React.
|
||||
//!
|
||||
//! These mirror `apps/desktop/electron/bootstrap-runner.ts`'s event shape
|
||||
//! 1:1 so the React installer code can be roughly identical to the Electron
|
||||
//! install-overlay we'll replace.
|
||||
//!
|
||||
//! The Tauri event channel name is `"bootstrap"` for all of these — the
|
||||
//! `type` discriminator on each payload is how the frontend routes.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Stage definition as reported by `install.ps1 -Manifest`.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StageInfo {
|
||||
pub name: String,
|
||||
pub title: String,
|
||||
pub category: String,
|
||||
/// `needs_user_input=true` stages run with -NonInteractive and emit
|
||||
/// skipped=true; the post-install wizard takes over for those.
|
||||
#[serde(rename = "needs_user_input", alias = "needsUserInput")]
|
||||
pub needs_user_input: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Manifest {
|
||||
pub stages: Vec<StageInfo>,
|
||||
#[serde(rename = "protocol_version", alias = "protocolVersion", default)]
|
||||
pub protocol_version: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StageResultPayload {
|
||||
pub stage: String,
|
||||
pub ok: bool,
|
||||
#[serde(default)]
|
||||
pub skipped: bool,
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
/// install.ps1 may attach stage-specific structured data here.
|
||||
#[serde(default)]
|
||||
pub data: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// Run-state for a single stage as we transition through it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum StageState {
|
||||
Running,
|
||||
Succeeded,
|
||||
Skipped,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Which pipe a raw log line came from. Reported as structured metadata so
|
||||
/// the UI can style stderr subtly rather than mislabeling it as an error:
|
||||
/// uv/pip/git/npm write normal progress to stderr by design.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum LogStream {
|
||||
Stdout,
|
||||
Stderr,
|
||||
}
|
||||
|
||||
/// The single event channel `bootstrap` emits these. `type` discriminates.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "lowercase")]
|
||||
pub enum BootstrapEvent {
|
||||
/// Sent once at the start with the full stage list.
|
||||
Manifest {
|
||||
stages: Vec<StageInfo>,
|
||||
#[serde(rename = "protocolVersion")]
|
||||
protocol_version: Option<u32>,
|
||||
},
|
||||
/// Stage state transition. `result` populated only on terminal states.
|
||||
Stage {
|
||||
name: String,
|
||||
state: StageState,
|
||||
#[serde(rename = "durationMs", skip_serializing_if = "Option::is_none")]
|
||||
duration_ms: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
result: Option<StageResultPayload>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
error: Option<String>,
|
||||
},
|
||||
/// Raw stdout/stderr line from install.ps1 (or our wrapper). `stream`
|
||||
/// tells the UI which pipe it came from so stderr can be styled subtly
|
||||
/// instead of being mislabeled as an error.
|
||||
Log {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
stage: Option<String>,
|
||||
line: String,
|
||||
stream: LogStream,
|
||||
},
|
||||
/// Sent once when all stages complete successfully.
|
||||
Complete {
|
||||
#[serde(rename = "installRoot")]
|
||||
install_root: String,
|
||||
marker: Option<serde_json::Value>,
|
||||
},
|
||||
/// Sent once if the run aborts.
|
||||
Failed {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
stage: Option<String>,
|
||||
error: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl BootstrapEvent {
|
||||
/// Tauri event name. Single channel for all bootstrap events; the
|
||||
/// `type` tag tells the renderer how to interpret the payload.
|
||||
pub const CHANNEL: &'static str = "bootstrap";
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
//! Resolves and downloads `scripts/install.ps1` (and `install.sh`).
|
||||
//!
|
||||
//! Resolution order:
|
||||
//! 1. Dev shortcut: a sibling repo checkout via $HERMES_SETUP_DEV_REPO_ROOT
|
||||
//! env var. Lets devs iterate without re-publishing the script.
|
||||
//! 2. Bundled fallback: if the installer was bundled with a script (e.g.
|
||||
//! tauri's `resource` mechanism), serve from there. Not used today.
|
||||
//! 3. Network: download from GitHub raw at a pinned commit or branch.
|
||||
//! Commit pins are immutable; branch pins are HEAD-tracking.
|
||||
//!
|
||||
//! Mirrors `apps/desktop/electron/bootstrap-runner.ts`'s `resolveInstallScript`,
|
||||
//! but the dev-checkout resolution is driven by an env var rather than the
|
||||
//! Electron app's APP_ROOT/../.. trick, because Hermes-Setup.exe is meant
|
||||
//! to live OUTSIDE any repo checkout.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use std::path::{Path, PathBuf};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
use crate::paths;
|
||||
|
||||
/// Identity of the install.ps1 we'll execute. Used by both the manifest
|
||||
/// fetch and the per-stage runs.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ResolvedScript {
|
||||
pub path: PathBuf,
|
||||
pub source: ScriptSource,
|
||||
/// Commit pin (40-char SHA) if known. install.ps1's `-Commit` arg is
|
||||
/// what makes the repo stage clone the exact tested SHA.
|
||||
pub commit: Option<String>,
|
||||
pub branch: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ScriptSource {
|
||||
DevCheckout,
|
||||
Bundled,
|
||||
Cached,
|
||||
Downloaded,
|
||||
}
|
||||
|
||||
/// What flavor of script (Windows .ps1 vs Unix .sh).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum ScriptKind {
|
||||
Ps1,
|
||||
Sh,
|
||||
}
|
||||
|
||||
impl ScriptKind {
|
||||
pub fn for_current_os() -> Self {
|
||||
if cfg!(target_os = "windows") {
|
||||
Self::Ps1
|
||||
} else {
|
||||
Self::Sh
|
||||
}
|
||||
}
|
||||
|
||||
fn filename(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Ps1 => "install.ps1",
|
||||
Self::Sh => "install.sh",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates a string looks like a git SHA (7+ hex chars). Mirrors
|
||||
/// `STAMP_COMMIT_RE` from bootstrap-runner.ts.
|
||||
fn is_valid_commit(s: &str) -> bool {
|
||||
let len = s.len();
|
||||
(7..=40).contains(&len) && s.chars().all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// Resolver cache plan for a pin that already has a local path computed.
|
||||
///
|
||||
/// Immutable commit pins reuse cache forever. Mutable branch/tag pins always
|
||||
/// refresh, and only fall back to a stale cache when the refresh fails.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum CachePlan {
|
||||
/// On-disk hit for an immutable pin — skip the network.
|
||||
Reuse,
|
||||
/// Download (or re-download). `stale_ok` means a failed refresh may return
|
||||
/// the existing cache file (mutable pins with a prior download).
|
||||
Fetch { stale_ok: bool },
|
||||
}
|
||||
|
||||
pub(crate) fn cache_plan(immutable: bool, cached_exists: bool) -> CachePlan {
|
||||
if immutable && cached_exists {
|
||||
CachePlan::Reuse
|
||||
} else {
|
||||
CachePlan::Fetch {
|
||||
stale_ok: !immutable && cached_exists,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the install script to use for this run.
|
||||
///
|
||||
/// `pin` is the commit-or-branch from either Hermes-Setup's build-time
|
||||
/// constant (compiled into the installer) or a runtime override.
|
||||
pub async fn resolve(
|
||||
kind: ScriptKind,
|
||||
pin: &Pin,
|
||||
emit_log: &impl Fn(&str),
|
||||
) -> Result<ResolvedScript> {
|
||||
// 1. Dev shortcut.
|
||||
if let Ok(repo_root) = std::env::var("HERMES_SETUP_DEV_REPO_ROOT") {
|
||||
let candidate = PathBuf::from(repo_root).join("scripts").join(kind.filename());
|
||||
if candidate.exists() {
|
||||
emit_log(&format!(
|
||||
"[bootstrap] dev mode — using local {} at {}",
|
||||
kind.filename(),
|
||||
candidate.display()
|
||||
));
|
||||
return Ok(ResolvedScript {
|
||||
path: candidate,
|
||||
source: ScriptSource::DevCheckout,
|
||||
commit: pin.commit.clone(),
|
||||
branch: pin.branch.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 2. (Not implemented) bundled fallback.
|
||||
|
||||
// 3. Network. Pin must be a real commit or a branch ref.
|
||||
//
|
||||
// Commit SHAs are immutable — permanent cache reuse is safe.
|
||||
// Branch/tag pins are moving refs: always try to refresh so "Retry install"
|
||||
// cannot keep reusing a poisoned install-main.ps1 forever (#67193).
|
||||
let (commit_or_ref, immutable) = match (&pin.commit, &pin.branch) {
|
||||
(Some(c), _) if is_valid_commit(c) => (c.clone(), true),
|
||||
(_, Some(b)) if !b.trim().is_empty() => (b.clone(), false),
|
||||
(Some(other), _) => {
|
||||
return Err(anyhow!(
|
||||
"install script pin commit `{other}` is not a valid git SHA"
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
return Err(anyhow!(
|
||||
"no install-script pin supplied — installer cannot resolve a script source"
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let cached = cached_path(kind, &commit_or_ref);
|
||||
match cache_plan(immutable, cached.exists()) {
|
||||
CachePlan::Reuse => {
|
||||
emit_log(&format!(
|
||||
"[bootstrap] using cached {} for {}",
|
||||
kind.filename(),
|
||||
truncate_ref(&commit_or_ref)
|
||||
));
|
||||
// Immutable pins are cached forever, so a .ps1 cached by a
|
||||
// pre-BOM-fix installer would keep the #67193 encoding bug on
|
||||
// every retry. Upgrade it in place before handing it out.
|
||||
upgrade_cached_script(kind, &cached, emit_log);
|
||||
return Ok(ResolvedScript {
|
||||
path: cached,
|
||||
source: ScriptSource::Cached,
|
||||
commit: pin.commit.clone(),
|
||||
branch: pin.branch.clone(),
|
||||
});
|
||||
}
|
||||
CachePlan::Fetch { stale_ok } => {
|
||||
emit_log(&format!(
|
||||
"[bootstrap] downloading {} for {} {} from GitHub",
|
||||
kind.filename(),
|
||||
if immutable {
|
||||
"commit"
|
||||
} else {
|
||||
"mutable ref"
|
||||
},
|
||||
truncate_ref(&commit_or_ref)
|
||||
));
|
||||
|
||||
match download(kind, &commit_or_ref, &cached).await {
|
||||
Ok(()) => {
|
||||
emit_log(&format!("[bootstrap] cached to {}", cached.display()));
|
||||
Ok(ResolvedScript {
|
||||
path: cached,
|
||||
source: ScriptSource::Downloaded,
|
||||
commit: pin.commit.clone(),
|
||||
branch: pin.branch.clone(),
|
||||
})
|
||||
}
|
||||
Err(err) if stale_ok => {
|
||||
emit_log(&format!(
|
||||
"[bootstrap] WARNING: refresh failed for mutable ref {}; using stale cached {} at {}: {err:#}",
|
||||
truncate_ref(&commit_or_ref),
|
||||
kind.filename(),
|
||||
cached.display()
|
||||
));
|
||||
// Stale cache can predate the BOM fix too — upgrade it.
|
||||
upgrade_cached_script(kind, &cached, emit_log);
|
||||
Ok(ResolvedScript {
|
||||
path: cached,
|
||||
source: ScriptSource::Cached,
|
||||
commit: pin.commit.clone(),
|
||||
branch: pin.branch.clone(),
|
||||
})
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Pin {
|
||||
pub commit: Option<String>,
|
||||
pub branch: Option<String>,
|
||||
}
|
||||
|
||||
fn cached_path(kind: ScriptKind, commit_or_ref: &str) -> PathBuf {
|
||||
let safe = sanitize_ref(commit_or_ref);
|
||||
let filename = match kind {
|
||||
ScriptKind::Ps1 => format!("install-{safe}.ps1"),
|
||||
ScriptKind::Sh => format!("install-{safe}.sh"),
|
||||
};
|
||||
paths::bootstrap_cache_dir().join(filename)
|
||||
}
|
||||
|
||||
/// Replace anything that's not [A-Za-z0-9._-] with `_`. Branch refs can
|
||||
/// contain `/`, dots, etc.; we want a flat filename.
|
||||
fn sanitize_ref(s: &str) -> String {
|
||||
s.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn truncate_ref(s: &str) -> &str {
|
||||
if is_valid_commit(s) && s.len() >= 12 {
|
||||
&s[..12]
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// UTF-8 BOM. Windows PowerShell 5.1 reads a BOM-less `.ps1` using the system
|
||||
/// ANSI code page; a leading BOM is what tells it the file is UTF-8. The
|
||||
/// `irm | iex` / `[scriptblock]::Create` path strips BOMs on purpose, but the
|
||||
/// GUI bootstrap runs the *cached file* via `-File`, so we write the opposite
|
||||
/// (#67193).
|
||||
const UTF8_BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
|
||||
|
||||
/// Prepare bytes for the on-disk bootstrap cache.
|
||||
///
|
||||
/// `.ps1` files get a UTF-8 BOM (unless one is already present). `.sh` files
|
||||
/// are left unchanged — a BOM would break `#!/bin/bash`.
|
||||
pub(crate) fn prepare_cached_script_bytes(kind: ScriptKind, bytes: &[u8]) -> Vec<u8> {
|
||||
match kind {
|
||||
ScriptKind::Ps1 => {
|
||||
if bytes.starts_with(UTF8_BOM) {
|
||||
bytes.to_vec()
|
||||
} else {
|
||||
let mut out = Vec::with_capacity(UTF8_BOM.len() + bytes.len());
|
||||
out.extend_from_slice(UTF8_BOM);
|
||||
out.extend_from_slice(bytes);
|
||||
out
|
||||
}
|
||||
}
|
||||
ScriptKind::Sh => bytes.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Upgrade a cached script written by a pre-BOM-fix installer in place.
|
||||
///
|
||||
/// `prepare_cached_script_bytes` only runs inside `download()`, but immutable
|
||||
/// commit pins (and the stale-fallback path) reuse the on-disk file without
|
||||
/// re-downloading — so a BOM-less `.ps1` cached before the #67193 fix would
|
||||
/// keep reproducing the ANSI-codepage parse failure on every retry. Rewrites
|
||||
/// through the same atomic tmp+rename shape as `download()`. Best-effort: a
|
||||
/// failed upgrade logs a warning and keeps the original file (which is no
|
||||
/// worse than the pre-existing behavior).
|
||||
fn upgrade_cached_script(kind: ScriptKind, cached: &Path, emit_log: &impl Fn(&str)) {
|
||||
if !matches!(kind, ScriptKind::Ps1) {
|
||||
return;
|
||||
}
|
||||
let bytes = match std::fs::read(cached) {
|
||||
Ok(b) => b,
|
||||
Err(err) => {
|
||||
emit_log(&format!(
|
||||
"[bootstrap] WARNING: could not read cached script {} for BOM check: {err}",
|
||||
cached.display()
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if bytes.starts_with(UTF8_BOM) {
|
||||
return;
|
||||
}
|
||||
let upgraded = prepare_cached_script_bytes(kind, &bytes);
|
||||
let tmp = cached.with_extension("ps1.tmp");
|
||||
let result = std::fs::write(&tmp, &upgraded).and_then(|()| std::fs::rename(&tmp, cached));
|
||||
match result {
|
||||
Ok(()) => emit_log(&format!(
|
||||
"[bootstrap] upgraded cached {} with UTF-8 BOM (#67193)",
|
||||
cached.display()
|
||||
)),
|
||||
Err(err) => {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
emit_log(&format!(
|
||||
"[bootstrap] WARNING: could not upgrade cached {} with UTF-8 BOM: {err}",
|
||||
cached.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads to `dest_path` via reqwest with rustls. Atomically renames
|
||||
/// `dest_path.tmp` → `dest_path` so partial writes don't poison the cache.
|
||||
///
|
||||
/// The client carries explicit timeouts: mutable branch pins call this on
|
||||
/// EVERY run (#67193 cache-refresh fix), and the stale-cache fallback in
|
||||
/// `resolve()` only fires when this returns `Err`. Without a timeout, a
|
||||
/// black-holed connection (captive portal, hung proxy, silently dropped
|
||||
/// packets) never errors — the whole bootstrap would hang here instead of
|
||||
/// falling back to the cached script.
|
||||
async fn download(kind: ScriptKind, commit_or_ref: &str, dest_path: &Path) -> Result<()> {
|
||||
let url = format!(
|
||||
"https://raw.githubusercontent.com/NousResearch/hermes-agent/{}/scripts/{}",
|
||||
commit_or_ref,
|
||||
kind.filename()
|
||||
);
|
||||
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
std::fs::create_dir_all(parent).with_context(|| {
|
||||
format!("creating bootstrap-cache parent dir {}", parent.display())
|
||||
})?;
|
||||
}
|
||||
|
||||
let tmp_path = dest_path.with_extension({
|
||||
let ext = dest_path
|
||||
.extension()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("tmp");
|
||||
format!("{ext}.tmp")
|
||||
});
|
||||
|
||||
let response = reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_secs(10))
|
||||
.timeout(std::time::Duration::from_secs(60))
|
||||
.build()
|
||||
.context("building download client")?
|
||||
.get(&url)
|
||||
.header("User-Agent", "hermes-setup/0.0.1")
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("GET {url}"))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(anyhow!(
|
||||
"Failed to download {}: HTTP {} from {}",
|
||||
kind.filename(),
|
||||
response.status(),
|
||||
url
|
||||
));
|
||||
}
|
||||
|
||||
let bytes = response
|
||||
.bytes()
|
||||
.await
|
||||
.with_context(|| format!("reading body of {url}"))?;
|
||||
let bytes = prepare_cached_script_bytes(kind, &bytes);
|
||||
|
||||
let mut file = tokio::fs::File::create(&tmp_path)
|
||||
.await
|
||||
.with_context(|| format!("creating temp file {}", tmp_path.display()))?;
|
||||
file.write_all(&bytes)
|
||||
.await
|
||||
.with_context(|| format!("writing temp file {}", tmp_path.display()))?;
|
||||
file.flush().await.context("flushing temp file")?;
|
||||
drop(file);
|
||||
|
||||
tokio::fs::rename(&tmp_path, dest_path)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"renaming {} → {}",
|
||||
tmp_path.display(),
|
||||
dest_path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn is_valid_commit_accepts_short_and_full_shas() {
|
||||
assert!(is_valid_commit("02d26981d3d4ad50e142399b8476f59ad5953ff0"));
|
||||
assert!(is_valid_commit("02d2698"));
|
||||
assert!(!is_valid_commit("02d269"));
|
||||
assert!(!is_valid_commit("not-a-sha"));
|
||||
assert!(!is_valid_commit(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_ref_replaces_slashes() {
|
||||
assert_eq!(sanitize_ref("bb/gui"), "bb_gui");
|
||||
assert_eq!(sanitize_ref("main"), "main");
|
||||
assert_eq!(sanitize_ref("release/1.2.3"), "release_1.2.3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_cached_ps1_prefixes_utf8_bom() {
|
||||
let out = prepare_cached_script_bytes(ScriptKind::Ps1, b"Write-Host hi\n");
|
||||
assert!(out.starts_with(UTF8_BOM), "cached .ps1 must start with UTF-8 BOM");
|
||||
assert_eq!(&out[UTF8_BOM.len()..], b"Write-Host hi\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_cached_ps1_does_not_double_bom() {
|
||||
let mut already = UTF8_BOM.to_vec();
|
||||
already.extend_from_slice(b"x");
|
||||
let out = prepare_cached_script_bytes(ScriptKind::Ps1, &already);
|
||||
assert_eq!(out, already);
|
||||
assert_eq!(out.windows(3).filter(|w| *w == UTF8_BOM).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_cached_sh_stays_bomless() {
|
||||
let out = prepare_cached_script_bytes(ScriptKind::Sh, b"#!/bin/bash\n");
|
||||
assert!(!out.starts_with(UTF8_BOM));
|
||||
assert_eq!(out, b"#!/bin/bash\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commit_pins_are_immutable_branch_pins_are_not() {
|
||||
// Mirrors the resolve() immutable decision: SHA pins may reuse cache
|
||||
// forever; branch pins must refresh so Retry cannot keep a bad script.
|
||||
assert!(is_valid_commit("02d26981d3d4ad50e142399b8476f59ad5953ff0"));
|
||||
assert!(!is_valid_commit("main"));
|
||||
assert!(!is_valid_commit("release/1.2.3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_branch_cache_plans_refresh_with_stale_fallback() {
|
||||
// Resolver-level: a prior install-main.ps1 must not short-circuit
|
||||
// Retry — mutable pins refresh, and only fall back if download fails.
|
||||
assert_eq!(
|
||||
cache_plan(/*immutable=*/ false, /*cached_exists=*/ true),
|
||||
CachePlan::Fetch { stale_ok: true }
|
||||
);
|
||||
assert_eq!(
|
||||
cache_plan(/*immutable=*/ true, /*cached_exists=*/ true),
|
||||
CachePlan::Reuse
|
||||
);
|
||||
assert_eq!(
|
||||
cache_plan(/*immutable=*/ false, /*cached_exists=*/ false),
|
||||
CachePlan::Fetch { stale_ok: false }
|
||||
);
|
||||
assert_eq!(
|
||||
cache_plan(/*immutable=*/ true, /*cached_exists=*/ false),
|
||||
CachePlan::Fetch { stale_ok: false }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upgrade_cached_script_adds_bom_to_legacy_ps1() {
|
||||
// A .ps1 cached by a pre-#67193 installer has no BOM; the Reuse path
|
||||
// must upgrade it in place instead of serving the broken bytes forever.
|
||||
let dir = std::env::temp_dir().join(format!("hermes-bom-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let cached = dir.join("install-abc1234.ps1");
|
||||
std::fs::write(&cached, b"Write-Host legacy\n").unwrap();
|
||||
|
||||
upgrade_cached_script(ScriptKind::Ps1, &cached, &|_| {});
|
||||
let bytes = std::fs::read(&cached).unwrap();
|
||||
assert!(bytes.starts_with(UTF8_BOM), "legacy cache must gain a BOM");
|
||||
assert_eq!(&bytes[UTF8_BOM.len()..], b"Write-Host legacy\n");
|
||||
|
||||
// Idempotent: a second pass must not double the BOM.
|
||||
upgrade_cached_script(ScriptKind::Ps1, &cached, &|_| {});
|
||||
let again = std::fs::read(&cached).unwrap();
|
||||
assert_eq!(again, bytes);
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upgrade_cached_script_leaves_sh_untouched() {
|
||||
let dir = std::env::temp_dir().join(format!("hermes-bom-sh-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let cached = dir.join("install-main.sh");
|
||||
std::fs::write(&cached, b"#!/bin/bash\n").unwrap();
|
||||
|
||||
upgrade_cached_script(ScriptKind::Sh, &cached, &|_| {});
|
||||
assert_eq!(std::fs::read(&cached).unwrap(), b"#!/bin/bash\n");
|
||||
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Hermes Setup — Tauri entrypoint.
|
||||
//!
|
||||
//! Spawns a single window pointed at the React frontend (apps/bootstrap-installer/src/).
|
||||
//! All install-time work lives in `bootstrap.rs` and is invoked through the Tauri
|
||||
//! commands registered at the bottom of `run()`.
|
||||
//!
|
||||
//! The Windows-subsystem strip lives on the binary crate (src/main.rs), not
|
||||
//! here — a crate-level attribute on a lib doesn't propagate to the linker
|
||||
//! flags of the executable that consumes it.
|
||||
|
||||
mod bootstrap;
|
||||
mod events;
|
||||
mod install_script;
|
||||
mod powershell;
|
||||
mod paths;
|
||||
mod update;
|
||||
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
/// How the installer was invoked. Resolved once from the process args in
|
||||
/// `run()` and exposed to the frontend via `get_mode` so it can route to the
|
||||
/// install flow (first-run onboarding) or the update flow (driven by the
|
||||
/// desktop app handing off via `Hermes-Setup.exe --update`).
|
||||
///
|
||||
/// Bare launch (double-click, first-run) => Install.
|
||||
/// `--update` (spawned by the desktop's "Update" button) => Update.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AppMode {
|
||||
Install,
|
||||
Update,
|
||||
}
|
||||
|
||||
impl AppMode {
|
||||
/// Resolve the mode from an argument iterator. Anything containing the
|
||||
/// `--update` flag selects Update; otherwise Install. Kept arg-iterator
|
||||
/// generic (not reading `std::env` directly) so it's unit-testable.
|
||||
pub fn from_args<I, S>(args: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
for a in args {
|
||||
if a.as_ref() == "--update" {
|
||||
return AppMode::Update;
|
||||
}
|
||||
}
|
||||
AppMode::Install
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true when the args request a forced installer UI (repair/reinstall)
|
||||
/// via `--reinstall` or `--repair`, which overrides the macOS launcher
|
||||
/// fast-path so a broken install can be repaired. Arg-iterator generic so it's
|
||||
/// unit-testable, mirroring `AppMode::from_args`. Independent of mode selection:
|
||||
/// these flags never flip Install<->Update.
|
||||
pub fn force_setup_from_args<I, S>(args: I) -> bool
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<str>,
|
||||
{
|
||||
args.into_iter()
|
||||
.any(|a| a.as_ref() == "--reinstall" || a.as_ref() == "--repair")
|
||||
}
|
||||
|
||||
/// Process-wide install state, shared across Tauri commands.
|
||||
///
|
||||
/// The bootstrap is a one-shot, single-tenant process — we only need one
|
||||
/// of these per window. `Arc<Mutex<...>>` lets command handlers grab it
|
||||
/// without lifetime gymnastics.
|
||||
pub struct AppState {
|
||||
pub bootstrap: Mutex<Option<bootstrap::BootstrapHandle>>,
|
||||
/// How this process was launched (install vs update). Immutable for the
|
||||
/// lifetime of the process; read by the `get_mode` command.
|
||||
pub mode: AppMode,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
fn new(mode: AppMode) -> Self {
|
||||
Self {
|
||||
bootstrap: Mutex::new(None),
|
||||
mode,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Frontend → Rust: which flow should the UI render?
|
||||
#[tauri::command]
|
||||
fn get_mode(state: tauri::State<'_, Arc<AppState>>) -> AppMode {
|
||||
state.mode
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
// Tracing → bootstrap-installer.log under HERMES_HOME/logs/ so install
|
||||
// failures leave a trail for support. Console output also goes here in
|
||||
// debug builds.
|
||||
let _guard = paths::init_logging();
|
||||
|
||||
let mode = AppMode::from_args(std::env::args().skip(1));
|
||||
// Escape hatch: `--reinstall`/`--repair` forces the installer UI even when
|
||||
// Hermes is already installed, so users can re-run setup to repair a broken
|
||||
// install instead of the launcher fast path silently relaunching the app.
|
||||
let force_setup = force_setup_from_args(std::env::args().skip(1));
|
||||
tracing::info!(?mode, force_setup, "Hermes installer starting");
|
||||
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.manage(Arc::new(AppState::new(mode)))
|
||||
.setup(move |app| {
|
||||
use tauri::Manager;
|
||||
// Launcher fast path (macOS only): a bare ("Install") launch when
|
||||
// Hermes is already installed should NOT show the installer or
|
||||
// rebuild — it should just open the app, so the /Applications
|
||||
// "Hermes" doubles as a normal launcher (first run installs, every
|
||||
// later run launches instantly). The window is kept hidden until
|
||||
// here via `"visible": false` so this path never flashes a window.
|
||||
//
|
||||
// Gated to macOS deliberately: on Windows/Linux the installer keeps
|
||||
// its existing behavior (Windows users relaunch via the Start
|
||||
// Menu/Desktop "Hermes" shortcuts that install.ps1 creates, and a
|
||||
// reliable detached relaunch there needs the DETACHED_PROCESS +
|
||||
// startup-grace handling used by launch_hermes_desktop — out of
|
||||
// scope here). So this is a pure no-op on non-macOS.
|
||||
//
|
||||
// `--reinstall`/`--repair` opts out so a broken install can be
|
||||
// repaired by re-running setup instead of launching the bad app.
|
||||
if cfg!(target_os = "macos") && mode == AppMode::Install && !force_setup {
|
||||
let install_root = paths::hermes_home().join("hermes-agent");
|
||||
if bootstrap::hermes_is_installed(&install_root) {
|
||||
match bootstrap::spawn_installed_desktop(&install_root) {
|
||||
Ok(()) => {
|
||||
// Brief grace so the spawned app is registered
|
||||
// before we exit (mirrors launch_hermes_desktop).
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
tracing::info!(
|
||||
"hermes already installed — relaunched desktop; exiting installer"
|
||||
);
|
||||
app.handle().exit(0);
|
||||
return Ok(());
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
?err,
|
||||
"relaunch of installed desktop failed; showing installer UI"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// First run / repair install, or Update mode: reveal the UI.
|
||||
match app.get_webview_window("main") {
|
||||
Some(win) => {
|
||||
if let Err(err) = win.show() {
|
||||
tracing::error!(?err, "failed to show main installer window");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
tracing::error!("main installer window not found; installer UI will not appear");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
// Mode (install vs update)
|
||||
get_mode,
|
||||
// Bootstrap lifecycle
|
||||
bootstrap::start_bootstrap,
|
||||
bootstrap::cancel_bootstrap,
|
||||
bootstrap::get_bootstrap_status,
|
||||
// Update lifecycle
|
||||
update::start_update,
|
||||
// Hand-off
|
||||
bootstrap::launch_hermes_desktop,
|
||||
// Diagnostics
|
||||
paths::get_log_path,
|
||||
paths::get_hermes_home,
|
||||
paths::open_log_dir,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running Hermes Setup");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{force_setup_from_args, AppMode};
|
||||
|
||||
#[test]
|
||||
fn bare_args_are_install() {
|
||||
assert_eq!(AppMode::from_args(Vec::<String>::new()), AppMode::Install);
|
||||
assert_eq!(AppMode::from_args(["--foo", "bar"]), AppMode::Install);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_flag_selects_update() {
|
||||
assert_eq!(AppMode::from_args(["--update"]), AppMode::Update);
|
||||
assert_eq!(
|
||||
AppMode::from_args(["--something", "--update", "--else"]),
|
||||
AppMode::Update
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reinstall_and_repair_flags_force_setup() {
|
||||
assert!(force_setup_from_args(["--reinstall"]));
|
||||
assert!(force_setup_from_args(["--repair"]));
|
||||
assert!(force_setup_from_args(["--foo", "--repair", "--bar"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_or_unrelated_args_do_not_force_setup() {
|
||||
assert!(!force_setup_from_args(Vec::<String>::new()));
|
||||
assert!(!force_setup_from_args(["--foo", "bar"]));
|
||||
// --update must not be mistaken for a force-setup flag.
|
||||
assert!(!force_setup_from_args(["--update"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn force_setup_flags_do_not_affect_mode_selection() {
|
||||
// The repair flags must never flip Install<->Update.
|
||||
assert_eq!(AppMode::from_args(["--reinstall"]), AppMode::Install);
|
||||
assert_eq!(AppMode::from_args(["--repair"]), AppMode::Install);
|
||||
assert_eq!(
|
||||
AppMode::from_args(["--update", "--reinstall"]),
|
||||
AppMode::Update
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Hermes Setup — process entrypoint. All logic lives in lib.rs so it can
|
||||
// be unit-tested as a library; this file just calls into it.
|
||||
//
|
||||
// The windows_subsystem attribute MUST live here on the binary crate
|
||||
// (not lib.rs) — placing it on the lib was the bug that left a stray
|
||||
// cmd window behind Hermes-Setup.exe on release builds.
|
||||
//
|
||||
// `windows_subsystem = "windows"` strips the console allocation that
|
||||
// the default `windows_subsystem = "console"` would do, so double-clicking
|
||||
// the .exe gives you ONLY the Tauri window.
|
||||
//
|
||||
// debug_assertions guard: dev builds keep the console so tracing output
|
||||
// is visible during `cargo tauri dev`.
|
||||
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
hermes_bootstrap_lib::run()
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Filesystem paths + logging setup.
|
||||
//!
|
||||
//! Mirrors `hermes_constants.get_hermes_home()` from the Python CLI:
|
||||
//! Windows: %LOCALAPPDATA%\hermes
|
||||
//! macOS: ~/.hermes
|
||||
//! Linux: ~/.hermes (override via $HERMES_HOME)
|
||||
//!
|
||||
//! NOTE (macOS): Python's get_hermes_home(), scripts/install.sh, and the
|
||||
//! Electron desktop's resolveHermesHome() ALL use ~/.hermes on macOS — there
|
||||
//! is no ~/Library/Application Support branch anywhere else. An earlier
|
||||
//! version of this file used Application Support, which drifted from every
|
||||
//! other component: the installer wrote the install to one dir and the
|
||||
//! desktop looked for it in another, so first launch never found the backend.
|
||||
//!
|
||||
//! IMPORTANT: this must match exactly. Drift here means install.ps1
|
||||
//! writes to one place and the installer reads from another, breaking
|
||||
//! the bootstrap-complete check.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::process::Command;
|
||||
use tracing_appender::non_blocking::WorkerGuard;
|
||||
|
||||
/// Returns the canonical Hermes home directory, respecting $HERMES_HOME if set.
|
||||
pub fn hermes_home() -> PathBuf {
|
||||
if let Ok(override_path) = std::env::var("HERMES_HOME") {
|
||||
if !override_path.trim().is_empty() {
|
||||
return PathBuf::from(override_path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// %LOCALAPPDATA%\hermes — matches scripts/install.ps1's $HermesHome.
|
||||
if let Some(local_app_data) = dirs::data_local_dir() {
|
||||
return local_app_data.join("hermes");
|
||||
}
|
||||
}
|
||||
|
||||
// macOS + Linux + fallback: ~/.hermes (matches Python get_hermes_home(),
|
||||
// install.sh, and the Electron desktop's resolveHermesHome()).
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
return home.join(".hermes");
|
||||
}
|
||||
|
||||
// Last resort — current dir, almost certainly wrong but at least
|
||||
// doesn't panic.
|
||||
PathBuf::from(".hermes")
|
||||
}
|
||||
|
||||
pub fn log_dir() -> PathBuf {
|
||||
hermes_home().join("logs")
|
||||
}
|
||||
|
||||
pub fn log_path() -> PathBuf {
|
||||
log_dir().join("bootstrap-installer.log")
|
||||
}
|
||||
|
||||
pub fn bootstrap_cache_dir() -> PathBuf {
|
||||
hermes_home().join("bootstrap-cache")
|
||||
}
|
||||
|
||||
/// Stable location the installer copies itself to after a successful install.
|
||||
/// The desktop app re-invokes this with `--update`, and the start-menu /
|
||||
/// desktop shortcuts can point users back to it. Lives directly under
|
||||
/// HERMES_HOME so it survives repo checkout deletion (unlike anything under
|
||||
/// hermes-agent/).
|
||||
///
|
||||
/// On Windows this is `%LOCALAPPDATA%\hermes\hermes-setup.exe`; on other
|
||||
/// platforms the extension differs but the directory is the same.
|
||||
pub fn installer_dest() -> PathBuf {
|
||||
let name = if cfg!(target_os = "windows") {
|
||||
"hermes-setup.exe"
|
||||
} else {
|
||||
"hermes-setup"
|
||||
};
|
||||
hermes_home().join(name)
|
||||
}
|
||||
|
||||
/// Marker the updater writes for the duration of an in-app update and removes
|
||||
/// when it finishes (see update.rs `UpdateMarkerGuard`). A freshly-launched
|
||||
/// desktop checks this before spawning its own local backend: spawning one
|
||||
/// mid-update re-locks the venv shim and triggers `force_kill_other_hermes`,
|
||||
/// which then kills that legitimate backend in a respawn loop (#50238).
|
||||
///
|
||||
/// Lives directly under HERMES_HOME (same rationale as `installer_dest`) so the
|
||||
/// Electron desktop — which resolves HERMES_HOME identically and pins it into
|
||||
/// the updater's env — agrees on the exact path.
|
||||
pub fn update_in_progress_marker() -> PathBuf {
|
||||
hermes_home().join(".hermes-update-in-progress")
|
||||
}
|
||||
|
||||
/// Copy the currently-running installer binary to `installer_dest()` so it's
|
||||
/// available for future `--update` runs and shortcut launches.
|
||||
///
|
||||
/// No-ops (returns Ok) when the running exe is ALREADY the destination — which
|
||||
/// is exactly the case during an `--update` run (the desktop launched us FROM
|
||||
/// that path), where copying onto ourselves would be a Windows sharing
|
||||
/// violation. Best-effort: a failure here must not fail the install, so the
|
||||
/// caller logs and continues.
|
||||
///
|
||||
/// NOTE: because of that no-op, a user's staged installer is only ever written
|
||||
/// by a full install/repair. Every later `--update` runs the ORIGINAL binary,
|
||||
/// so an installer-protocol change can strand the whole installed base on a
|
||||
/// binary that predates it (see `restage_from_checkout`, which repairs this
|
||||
/// from the freshly-updated checkout).
|
||||
pub fn copy_self_to_hermes_home() -> std::io::Result<()> {
|
||||
let src = std::env::current_exe()?;
|
||||
let dest = installer_dest();
|
||||
|
||||
// Skip if we're already running from the destination (update re-invocation
|
||||
// or a prior copy). canonicalize both so symlinks / 8.3 short paths / case
|
||||
// differences don't trick us into a self-copy.
|
||||
let same = match (src.canonicalize(), dest.canonicalize()) {
|
||||
(Ok(a), Ok(b)) => a == b,
|
||||
_ => src == dest,
|
||||
};
|
||||
if same {
|
||||
tracing::info!(?dest, "installer already at destination; skipping self-copy");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::copy(&src, &dest)?;
|
||||
repair_macos_installer_helper(&dest);
|
||||
tracing::info!(?src, ?dest, "copied installer to HERMES_HOME");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn repair_macos_installer_helper(path: &Path) {
|
||||
// The staged helper may inherit quarantine from the downloaded installer.
|
||||
// Desktop later launches this exact file for in-app updates, so make it
|
||||
// executable before the update handoff reaches LaunchServices/Gatekeeper.
|
||||
let _ = Command::new("/usr/bin/xattr")
|
||||
.args(["-cr"])
|
||||
.arg(path)
|
||||
.status();
|
||||
|
||||
let verify = Command::new("/usr/bin/codesign")
|
||||
.arg("--verify")
|
||||
.arg(path)
|
||||
.status();
|
||||
|
||||
if !matches!(verify, Ok(status) if status.success()) {
|
||||
let _ = Command::new("/usr/bin/codesign")
|
||||
.args(["--force", "--sign", "-"])
|
||||
.arg(path)
|
||||
.status();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn repair_macos_installer_helper(_path: &Path) {}
|
||||
|
||||
/// Where the bootstrap-complete marker lives (existence-only for the Rust
|
||||
/// installer fast path; JSON schema-checked by the Electron app). Per main.ts:
|
||||
/// const BOOTSTRAP_COMPLETE_MARKER = path.join(ACTIVE_HERMES_ROOT, '.hermes-bootstrap-complete')
|
||||
/// We don't always know ACTIVE_HERMES_ROOT until install.ps1 reports it, so
|
||||
/// this is a probe helper, not a definitive path.
|
||||
pub fn likely_bootstrap_marker(install_root: &Path) -> PathBuf {
|
||||
install_root.join(".hermes-bootstrap-complete")
|
||||
}
|
||||
|
||||
/// Initializes tracing to bootstrap-installer.log under HERMES_HOME/logs/.
|
||||
/// Returns a guard that flushes the appender on drop — keep it alive for
|
||||
/// the lifetime of the process.
|
||||
pub fn init_logging() -> Option<WorkerGuard> {
|
||||
let dir = log_dir();
|
||||
if let Err(err) = std::fs::create_dir_all(&dir) {
|
||||
// No log dir → log to stderr only. Don't panic; the installer
|
||||
// should still be usable on an exotic filesystem.
|
||||
eprintln!("[hermes-setup] could not create log dir {dir:?}: {err}");
|
||||
return None;
|
||||
}
|
||||
|
||||
let file_appender = tracing_appender::rolling::never(&dir, "bootstrap-installer.log");
|
||||
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
|
||||
|
||||
let env_filter = tracing_subscriber::EnvFilter::try_from_env("HERMES_BOOTSTRAP_LOG")
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
|
||||
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(env_filter)
|
||||
.with_writer(non_blocking)
|
||||
.with_ansi(false)
|
||||
.with_target(true)
|
||||
.init();
|
||||
|
||||
Some(guard)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tauri commands
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_log_path() -> String {
|
||||
log_path().to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_hermes_home() -> String {
|
||||
hermes_home().to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_log_dir(app: tauri::AppHandle) -> Result<(), String> {
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
let path = log_dir();
|
||||
app.opener()
|
||||
.open_path(path.to_string_lossy(), None::<&str>)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -0,0 +1,842 @@
|
||||
//! Drives PowerShell (Windows) or bash (Unix) for install.ps1 / install.sh.
|
||||
//!
|
||||
//! Port of `spawnPowerShell` from bootstrap-runner.ts, with the same
|
||||
//! line-buffered stdout/stderr streaming + cancellation semantics.
|
||||
//!
|
||||
//! On Windows we pass `-NoProfile -ExecutionPolicy Bypass -File <script>`.
|
||||
//! On Unix we shell out to `bash <script>` since install.sh expects bash.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::path::Path;
|
||||
use std::process::{ExitStatus, Stdio};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::process::{Child, Command};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::timeout;
|
||||
|
||||
/// CP1252 mapping for bytes `0x80..=0x9F` (the range that differs from Latin-1).
|
||||
/// Undefined slots keep the C1 control code points, matching Windows-1252
|
||||
/// best-fit behavior used by `encoding_rs::WINDOWS_1252`.
|
||||
const CP1252_80_9F: [char; 32] = [
|
||||
'\u{20AC}', // 0x80 €
|
||||
'\u{0081}', // 0x81
|
||||
'\u{201A}', // 0x82 ‚
|
||||
'\u{0192}', // 0x83 ƒ
|
||||
'\u{201E}', // 0x84 „
|
||||
'\u{2026}', // 0x85 …
|
||||
'\u{2020}', // 0x86 †
|
||||
'\u{2021}', // 0x87 ‡
|
||||
'\u{02C6}', // 0x88 ˆ
|
||||
'\u{2030}', // 0x89 ‰
|
||||
'\u{0160}', // 0x8A Š
|
||||
'\u{2039}', // 0x8B ‹
|
||||
'\u{0152}', // 0x8C Œ
|
||||
'\u{008D}', // 0x8D
|
||||
'\u{017D}', // 0x8E Ž
|
||||
'\u{008F}', // 0x8F
|
||||
'\u{0090}', // 0x90
|
||||
'\u{2018}', // 0x91 ‘
|
||||
'\u{2019}', // 0x92 ’
|
||||
'\u{201C}', // 0x93 “
|
||||
'\u{201D}', // 0x94 ”
|
||||
'\u{2022}', // 0x95 •
|
||||
'\u{2013}', // 0x96 –
|
||||
'\u{2014}', // 0x97 —
|
||||
'\u{02DC}', // 0x98 ˜
|
||||
'\u{2122}', // 0x99 ™
|
||||
'\u{0161}', // 0x9A š
|
||||
'\u{203A}', // 0x9B ›
|
||||
'\u{0153}', // 0x9C œ
|
||||
'\u{009D}', // 0x9D
|
||||
'\u{017E}', // 0x9E ž
|
||||
'\u{0178}', // 0x9F Ÿ
|
||||
];
|
||||
|
||||
fn decode_cp1252_byte(b: u8) -> char {
|
||||
match b {
|
||||
0x00..=0x7F => b as char,
|
||||
0x80..=0x9F => CP1252_80_9F[(b - 0x80) as usize],
|
||||
// 0xA0..=0xFF match Unicode Latin-1 / Windows-1252.
|
||||
_ => b as char,
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode one stdout/stderr line from a child process.
|
||||
///
|
||||
/// Tokio's `BufReader::lines()` requires valid UTF-8 and aborts the line (with
|
||||
/// `stream did not contain valid UTF-8`) at the first accented byte. Windows
|
||||
/// PowerShell 5.1 emits localized ParserError text in the console ANSI code
|
||||
/// page (often CP1252), so Portuguese/Spanish/etc. users only saw a truncated
|
||||
/// `No` instead of `Não foi fornecido o terminador...` (#67193).
|
||||
///
|
||||
/// Prefer UTF-8 when the bytes are valid; otherwise decode as Windows-1252 so
|
||||
/// both Western-European letters and CP1252-only punctuation (e.g. `0x91` →
|
||||
/// U+2018) survive rather than disappearing into a read-error warning.
|
||||
pub(crate) fn decode_console_bytes(bytes: &[u8]) -> String {
|
||||
match std::str::from_utf8(bytes) {
|
||||
Ok(s) => s.to_string(),
|
||||
Err(_) => bytes.iter().copied().map(decode_cp1252_byte).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one line (LF or CRLF) and decode it with [`decode_console_bytes`].
|
||||
/// Returns `Ok(None)` on EOF with no bytes pending.
|
||||
pub(crate) async fn read_decoded_line<R>(
|
||||
reader: &mut R,
|
||||
buf: &mut Vec<u8>,
|
||||
) -> std::io::Result<Option<String>>
|
||||
where
|
||||
R: AsyncBufReadExt + Unpin,
|
||||
{
|
||||
// Cancel-safety: `buf` is NOT cleared on entry. When this future is
|
||||
// dropped mid-read inside `tokio::select!` (the other stream produced a
|
||||
// line first), `read_until` has already appended any consumed bytes to
|
||||
// `buf`; the next call resumes and appends the rest of the line. Clearing
|
||||
// on entry would silently drop those bytes. We clear only after a full
|
||||
// line has been decoded.
|
||||
let n = reader.read_until(b'\n', buf).await?;
|
||||
if n == 0 && buf.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
// n == 0 with a non-empty buf means EOF cut off an unterminated line
|
||||
// (possibly accumulated across cancelled reads) -- emit it.
|
||||
if buf.last() == Some(&b'\n') {
|
||||
buf.pop();
|
||||
if buf.last() == Some(&b'\r') {
|
||||
buf.pop();
|
||||
}
|
||||
}
|
||||
let line = decode_console_bytes(buf);
|
||||
buf.clear();
|
||||
Ok(Some(line))
|
||||
}
|
||||
|
||||
/// Hooks the caller installs to receive output.
|
||||
pub struct StreamSink {
|
||||
pub on_stdout_line: Box<dyn Fn(&str) + Send + Sync>,
|
||||
pub on_stderr_line: Box<dyn Fn(&str) + Send + Sync>,
|
||||
}
|
||||
|
||||
/// Outcome of a script invocation. Mirrors bootstrap-runner.ts's
|
||||
/// `{stdout, stderr, code, signal, killed}` shape.
|
||||
#[derive(Debug)]
|
||||
pub struct ScriptResult {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub exit_code: Option<i32>,
|
||||
pub killed: bool,
|
||||
}
|
||||
|
||||
/// Cancellation signal — `cancel_tx.send(()).await` aborts the running script.
|
||||
pub type CancelRx = mpsc::Receiver<()>;
|
||||
|
||||
/// How long a child's pipes get to reach EOF AFTER the child itself has exited.
|
||||
///
|
||||
/// This is not a timeout on the child. The clock starts once the process is
|
||||
/// already gone and everything it wrote is sitting in the pipe buffer, so a
|
||||
/// 40-minute `uv pip install` is untouched — the grace only covers the final
|
||||
/// drain.
|
||||
///
|
||||
/// It exists because pipe EOF is not the child's to give. The write end of a
|
||||
/// redirected pipe is handed to the child as an inheritable handle, so every
|
||||
/// descendant spawned without its own redirection holds a duplicate, and the
|
||||
/// read side does not see EOF until the last of them closes it. `hermes update`
|
||||
/// deliberately runs its build steps with stdout inherited, so the tree under a
|
||||
/// child is arbitrarily deep and not something the caller can enumerate. When
|
||||
/// one of those descendants is a resident gateway, the pipe stays open for the
|
||||
/// life of the gateway — and every obligation downstream of the read is
|
||||
/// stranded with it.
|
||||
///
|
||||
/// Same bound `Invoke-HermesStep` grew in `scripts/desktop-update/windows.ps1`
|
||||
/// (#90455), and the same shape as Go's `exec.Cmd.WaitDelay`.
|
||||
pub(crate) const DRAIN_GRACE: Duration = Duration::from_secs(20);
|
||||
|
||||
/// What [`pump_child`] observed.
|
||||
pub(crate) struct PumpOutcome {
|
||||
pub exit_code: Option<i32>,
|
||||
/// The child was killed because the caller cancelled.
|
||||
pub killed: bool,
|
||||
/// The child exited but its pipes never reached EOF within [`DRAIN_GRACE`],
|
||||
/// so the tail of its output was dropped. Callers must say so out loud: a
|
||||
/// silently truncated log is indistinguishable from one that was empty.
|
||||
pub abandoned: bool,
|
||||
}
|
||||
|
||||
/// Stream a child's stdout/stderr line by line, then reap it.
|
||||
///
|
||||
/// The contract that matters: the exit status comes from waiting on the
|
||||
/// *process*, never from pipe EOF. See [`DRAIN_GRACE`] for why those are not
|
||||
/// the same event; callers pass it, tests pass something they can wait out.
|
||||
pub(crate) async fn pump_child<FO, FE>(
|
||||
child: &mut Child,
|
||||
mut on_stdout: FO,
|
||||
mut on_stderr: FE,
|
||||
cancel_rx: &mut Option<CancelRx>,
|
||||
grace: Duration,
|
||||
) -> Result<PumpOutcome>
|
||||
where
|
||||
FO: FnMut(&str),
|
||||
FE: FnMut(&str),
|
||||
{
|
||||
let stdout = child.stdout.take().context("stdout was piped")?;
|
||||
let stderr = child.stderr.take().context("stderr was piped")?;
|
||||
let mut out = BufReader::new(stdout);
|
||||
let mut err = BufReader::new(stderr);
|
||||
let mut out_buf = Vec::new();
|
||||
let mut err_buf = Vec::new();
|
||||
let mut out_done = false;
|
||||
let mut err_done = false;
|
||||
let mut status: Option<ExitStatus> = None;
|
||||
let mut cancelled = false;
|
||||
|
||||
// Phase 1 — the child is alive, so there is no deadline. A slow child is
|
||||
// not a stuck one, and the point of streaming is that a long build keeps
|
||||
// reporting. We leave on whichever lands first: both pipes at EOF (the
|
||||
// clean case), the process exiting (the case that used to hang here), or
|
||||
// cancellation.
|
||||
while !(out_done && err_done) {
|
||||
tokio::select! {
|
||||
line = read_decoded_line(&mut out, &mut out_buf), if !out_done => match line {
|
||||
Ok(Some(l)) => on_stdout(&l),
|
||||
Ok(None) => out_done = true,
|
||||
Err(e) => {
|
||||
tracing::warn!("stdout read error: {e}");
|
||||
out_done = true;
|
||||
}
|
||||
},
|
||||
line = read_decoded_line(&mut err, &mut err_buf), if !err_done => match line {
|
||||
Ok(Some(l)) => on_stderr(&l),
|
||||
Ok(None) => err_done = true,
|
||||
Err(e) => {
|
||||
tracing::warn!("stderr read error: {e}");
|
||||
err_done = true;
|
||||
}
|
||||
},
|
||||
reaped = child.wait() => {
|
||||
status = Some(reaped.context("waiting for child to exit")?);
|
||||
break;
|
||||
}
|
||||
_ = recv_cancel(cancel_rx) => {
|
||||
cancelled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Kill outside the loop: `child.wait()` above holds the mutable borrow for
|
||||
// as long as the select is in scope.
|
||||
if cancelled {
|
||||
tracing::warn!("cancellation received — killing child");
|
||||
let _ = child.start_kill();
|
||||
}
|
||||
|
||||
// Phase 2 — bounded. Whatever the child already wrote is still worth
|
||||
// keeping, so we keep reading; we just stop caring once a descendant is the
|
||||
// only thing still holding the pipe open. Cancelling does not rescue us
|
||||
// either: `start_kill` kills the child, not the grandchild with the handle.
|
||||
let mut abandoned = false;
|
||||
if !(out_done && err_done) {
|
||||
let drain = async {
|
||||
while !(out_done && err_done) {
|
||||
tokio::select! {
|
||||
line = read_decoded_line(&mut out, &mut out_buf), if !out_done => match line {
|
||||
Ok(Some(l)) => on_stdout(&l),
|
||||
_ => out_done = true,
|
||||
},
|
||||
line = read_decoded_line(&mut err, &mut err_buf), if !err_done => match line {
|
||||
Ok(Some(l)) => on_stderr(&l),
|
||||
_ => err_done = true,
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
abandoned = timeout(grace, drain).await.is_err();
|
||||
}
|
||||
|
||||
let status = match status {
|
||||
Some(s) => s,
|
||||
// Both pipes reached EOF while the child stayed alive. Reads are done,
|
||||
// but the process is still the authoritative terminal condition — and
|
||||
// it may never exit on its own, so this wait stays cancellable. A bare
|
||||
// `child.wait()` here would strand the caller's cancel channel exactly
|
||||
// when it is the only way out.
|
||||
None => tokio::select! {
|
||||
reaped = child.wait() => reaped.context("waiting for child to exit")?,
|
||||
_ = recv_cancel(cancel_rx) => {
|
||||
tracing::warn!("cancellation received after EOF — killing child");
|
||||
cancelled = true;
|
||||
let _ = child.start_kill();
|
||||
child.wait().await.context("waiting for killed child to exit")?
|
||||
}
|
||||
},
|
||||
};
|
||||
Ok(PumpOutcome {
|
||||
exit_code: status.code(),
|
||||
killed: cancelled,
|
||||
abandoned,
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawns install.ps1 / install.sh with the given args and streams output.
|
||||
///
|
||||
/// `hermes_home_override` propagates to the child as $HERMES_HOME so the
|
||||
/// install script writes to the same directory the installer is reading from.
|
||||
pub async fn run_script(
|
||||
script_path: &Path,
|
||||
args: &[String],
|
||||
sink: StreamSink,
|
||||
hermes_home_override: Option<&str>,
|
||||
cancel_rx: &mut Option<CancelRx>,
|
||||
) -> Result<ScriptResult> {
|
||||
let mut cmd = build_command(script_path, args);
|
||||
|
||||
// The installer can be launched from a .app bundle that is later replaced
|
||||
// during self-update. Pin child scripts to a stable directory so bash/zsh
|
||||
// never starts from a deleted cwd and emits getcwd/job-working-directory
|
||||
// errors at the end of an otherwise successful install.
|
||||
if let Some(cwd) = stable_script_cwd(script_path, hermes_home_override) {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
|
||||
if let Some(home) = hermes_home_override {
|
||||
cmd.env("HERMES_HOME", home);
|
||||
}
|
||||
|
||||
cmd.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
|
||||
// On Windows, avoid spawning a flashing cmd window when we're hosted
|
||||
// inside a GUI process. Tauri's main window is already created, so
|
||||
// the side-effect console for the child is unwanted.
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// CREATE_NO_WINDOW = 0x08000000
|
||||
cmd.creation_flags(0x0800_0000);
|
||||
}
|
||||
|
||||
let mut child: Child = cmd
|
||||
.spawn()
|
||||
.with_context(|| format!("spawning {} via {}", script_path.display(), interpreter_label()))?;
|
||||
|
||||
// Byte-oriented readers + [`decode_console_bytes`]: do NOT use
|
||||
// `BufReader::lines()`, which requires valid UTF-8 and hides localized
|
||||
// PowerShell errors on non-English Windows (#67193). [`pump_child`] owns
|
||||
// that, plus the rule that the exit status comes from the process and not
|
||||
// from pipe EOF.
|
||||
let mut combined_stdout = String::new();
|
||||
let mut combined_stderr = String::new();
|
||||
|
||||
let outcome = pump_child(
|
||||
&mut child,
|
||||
|l| {
|
||||
(sink.on_stdout_line)(l);
|
||||
combined_stdout.push_str(l);
|
||||
combined_stdout.push('\n');
|
||||
},
|
||||
|l| {
|
||||
(sink.on_stderr_line)(l);
|
||||
combined_stderr.push_str(l);
|
||||
combined_stderr.push('\n');
|
||||
},
|
||||
cancel_rx,
|
||||
DRAIN_GRACE,
|
||||
)
|
||||
.await
|
||||
.context("streaming install script output")?;
|
||||
|
||||
if outcome.abandoned {
|
||||
let note = format!(
|
||||
"install script exited but a surviving descendant still holds its \
|
||||
stdout/stderr; gave up on the last {}s of output (#90455)",
|
||||
DRAIN_GRACE.as_secs()
|
||||
);
|
||||
tracing::warn!("{note}");
|
||||
(sink.on_stderr_line)(¬e);
|
||||
combined_stderr.push_str(¬e);
|
||||
combined_stderr.push('\n');
|
||||
}
|
||||
|
||||
Ok(ScriptResult {
|
||||
stdout: combined_stdout,
|
||||
stderr: combined_stderr,
|
||||
exit_code: outcome.exit_code,
|
||||
killed: outcome.killed,
|
||||
})
|
||||
}
|
||||
|
||||
fn stable_script_cwd<'a>(script_path: &'a Path, hermes_home_override: Option<&'a str>) -> Option<&'a Path> {
|
||||
if let Some(home) = hermes_home_override {
|
||||
let path = Path::new(home);
|
||||
if path.is_dir() {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
script_path.parent().filter(|p| p.is_dir())
|
||||
}
|
||||
|
||||
async fn recv_cancel(rx: &mut Option<CancelRx>) {
|
||||
match rx {
|
||||
Some(r) => {
|
||||
let _ = r.recv().await;
|
||||
}
|
||||
None => std::future::pending::<()>().await,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn build_command(script_path: &Path, args: &[String]) -> Command {
|
||||
// We want PowerShell 5.1 / 7. install.ps1 uses 5.1-safe syntax everywhere.
|
||||
// Prefer `powershell.exe` (5.1 baseline, present on every Windows since 7)
|
||||
// over `pwsh.exe` (7+, may not be present). Resolve it by absolute path —
|
||||
// see `windows_powershell_exe`.
|
||||
let mut cmd = Command::new(windows_powershell_exe());
|
||||
cmd.arg("-NoProfile");
|
||||
cmd.arg("-ExecutionPolicy").arg("Bypass");
|
||||
cmd.arg("-File").arg(script_path);
|
||||
for a in args {
|
||||
cmd.arg(a);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn build_command(script_path: &Path, args: &[String]) -> Command {
|
||||
// install.sh expects bash. /bin/bash is fine on macOS (Apple still
|
||||
// ships an old 3.2 bash; install.sh is written to that baseline).
|
||||
let mut cmd = Command::new("bash");
|
||||
cmd.arg(script_path);
|
||||
for a in args {
|
||||
cmd.arg(a);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Canonical PowerShell 5.1 location under a Windows root (`%SystemRoot%`).
|
||||
/// Kept separate (and test-visible) so the path layout is unit-tested on any
|
||||
/// host, not just Windows.
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
fn powershell_under_root(root: &Path) -> std::path::PathBuf {
|
||||
root.join("System32")
|
||||
.join("WindowsPowerShell")
|
||||
.join("v1.0")
|
||||
.join("powershell.exe")
|
||||
}
|
||||
|
||||
/// Resolves the PowerShell interpreter to spawn.
|
||||
///
|
||||
/// `Command::new("powershell.exe")` trusts PATH to contain
|
||||
/// `%SystemRoot%\System32\WindowsPowerShell\v1.0`. On machines whose PATH was
|
||||
/// trimmed or truncated (Windows silently drops entries once the variable grows
|
||||
/// past its length limit), that lookup fails and the spawn dies with
|
||||
/// "program not found" before install.ps1 ever runs — the installer then stalls
|
||||
/// at "0 of 0 steps". Resolve by absolute path first, then fall back to PATH
|
||||
/// (powershell 5.1, then pwsh 7), then a bare name as a last resort.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_powershell_exe() -> std::path::PathBuf {
|
||||
for var in ["SystemRoot", "windir"] {
|
||||
if let Ok(root) = std::env::var(var) {
|
||||
let candidate = powershell_under_root(Path::new(&root));
|
||||
if candidate.is_file() {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for exe in ["powershell.exe", "pwsh.exe"] {
|
||||
if let Ok(found) = which::which(exe) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
std::path::PathBuf::from("powershell.exe")
|
||||
}
|
||||
|
||||
/// Human-readable interpreter name for spawn-failure context. On Windows this
|
||||
/// is the resolved PowerShell path so a missing/odd interpreter is obvious in
|
||||
/// the log (the old message only printed the script path, which read as if the
|
||||
/// .ps1 itself was missing).
|
||||
#[cfg(target_os = "windows")]
|
||||
fn interpreter_label() -> String {
|
||||
windows_powershell_exe().display().to_string()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn interpreter_label() -> String {
|
||||
"bash".to_string()
|
||||
}
|
||||
|
||||
/// Parses the LAST line of stdout that looks like a JSON object matching
|
||||
/// the install.ps1 stage-result contract: `{ok: bool, stage: string, ...}`.
|
||||
///
|
||||
/// Mirrors `parseStageResult` from bootstrap-runner.ts. install.ps1 may
|
||||
/// print info/banner lines before the result frame; we scan from the end.
|
||||
pub fn parse_stage_result(stdout: &str) -> Option<crate::events::StageResultPayload> {
|
||||
for line in stdout.lines().rev() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed) {
|
||||
if value.get("ok").and_then(|v| v.as_bool()).is_some()
|
||||
&& value.get("stage").and_then(|v| v.as_str()).is_some()
|
||||
{
|
||||
if let Ok(parsed) =
|
||||
serde_json::from_value::<crate::events::StageResultPayload>(value)
|
||||
{
|
||||
return Some(parsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Same logic but for the `-Manifest` payload (the LAST line with a `stages`
|
||||
/// array). Returns the parsed manifest.
|
||||
pub fn parse_manifest(stdout: &str) -> Option<crate::events::Manifest> {
|
||||
for line in stdout.lines().rev() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(value) = serde_json::from_str::<serde_json::Value>(trimmed) {
|
||||
if value.get("stages").and_then(|v| v.as_array()).is_some() {
|
||||
if let Ok(parsed) = serde_json::from_value::<crate::events::Manifest>(value) {
|
||||
return Some(parsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::process::CommandExt;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_stage_result_picks_last_json_line() {
|
||||
let stdout = r#"
|
||||
[bootstrap] some info
|
||||
{"ok": false, "stage": "venv", "reason": "bad python"}
|
||||
{"ok": true, "stage": "venv"}
|
||||
final non-json banner
|
||||
"#;
|
||||
let result = parse_stage_result(stdout).unwrap();
|
||||
assert_eq!(result.stage, "venv");
|
||||
assert!(result.ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_manifest_finds_stages_array() {
|
||||
let stdout = r#"
|
||||
info line
|
||||
{"stages": [{"name": "uv", "title": "uv", "category": "prereqs", "needs_user_input": false}], "protocol_version": 1}
|
||||
"#;
|
||||
let m = parse_manifest(stdout).unwrap();
|
||||
assert_eq!(m.stages.len(), 1);
|
||||
assert_eq!(m.stages[0].name, "uv");
|
||||
assert_eq!(m.protocol_version, Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_returns_none_when_no_match() {
|
||||
assert!(parse_stage_result("just banner\n").is_none());
|
||||
assert!(parse_manifest("just banner\n").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_script_cwd_prefers_existing_hermes_home() {
|
||||
let script = Path::new("/tmp/install.sh");
|
||||
let cwd = stable_script_cwd(script, Some("/"));
|
||||
assert_eq!(cwd, Some(Path::new("/")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_under_root_uses_system32_v1_layout() {
|
||||
let resolved = powershell_under_root(Path::new("C:\\Windows"));
|
||||
let normalized = resolved.to_string_lossy().replace('\\', "/");
|
||||
assert!(
|
||||
normalized.ends_with("System32/WindowsPowerShell/v1.0/powershell.exe"),
|
||||
"unexpected powershell path: {normalized}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_console_bytes_keeps_valid_utf8() {
|
||||
assert_eq!(decode_console_bytes("café — ok".as_bytes()), "café — ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_console_bytes_preserves_cp1252_portuguese_error() {
|
||||
// "Não foi fornecido o terminador..." as Windows PowerShell 5.1 emits
|
||||
// under CP1252 (0xE3 = ã). BufReader::lines() previously failed here
|
||||
// with "stream did not contain valid UTF-8" and the UI only showed "No".
|
||||
let bytes: &[u8] = b"N\xE3o foi fornecido o terminador";
|
||||
assert_eq!(decode_console_bytes(bytes), "Não foi fornecido o terminador");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_console_bytes_maps_cp1252_only_punctuation() {
|
||||
// 0x91/0x92 are curly quotes in Windows-1252, but C1 controls under
|
||||
// Latin-1 (`b as char`). This locks the real CP1252 fallback.
|
||||
let bytes: &[u8] = b"say \x91hi\x92";
|
||||
assert_eq!(decode_console_bytes(bytes), "say \u{2018}hi\u{2019}");
|
||||
assert_ne!(
|
||||
decode_console_bytes(bytes),
|
||||
bytes.iter().map(|&b| b as char).collect::<String>(),
|
||||
"Latin-1 byte mapping must not be used for the 0x80..=0x9F range"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_decoded_line_survives_non_utf8_and_crlf() {
|
||||
let data: &[u8] = b"N\xE3o erro\r\nnext\n";
|
||||
let mut reader = BufReader::new(data);
|
||||
let mut buf = Vec::new();
|
||||
assert_eq!(
|
||||
read_decoded_line(&mut reader, &mut buf)
|
||||
.await
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("Não erro")
|
||||
);
|
||||
assert_eq!(
|
||||
read_decoded_line(&mut reader, &mut buf)
|
||||
.await
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("next")
|
||||
);
|
||||
assert!(read_decoded_line(&mut reader, &mut buf)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_decoded_line_preserves_partial_line_across_cancellation() {
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
let (mut tx, rx) = tokio::io::duplex(64);
|
||||
let mut reader = BufReader::new(rx);
|
||||
let mut buf = Vec::new();
|
||||
|
||||
tx.write_all(b"partial").await.unwrap();
|
||||
// Poll once, then cancel (drop) the future -- exactly what
|
||||
// tokio::select! does in run_script when the other stream produces
|
||||
// a line first. The consumed bytes must survive in `buf`.
|
||||
let _ = tokio::time::timeout(
|
||||
Duration::from_millis(0),
|
||||
read_decoded_line(&mut reader, &mut buf),
|
||||
)
|
||||
.await;
|
||||
|
||||
tx.write_all(b" line\n").await.unwrap();
|
||||
let line = read_decoded_line(&mut reader, &mut buf).await.unwrap();
|
||||
assert_eq!(line.as_deref(), Some("partial line"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_decoded_line_emits_unterminated_final_line_at_eof() {
|
||||
let data: &[u8] = b"no trailing newline";
|
||||
let mut reader = BufReader::new(data);
|
||||
let mut buf = Vec::new();
|
||||
assert_eq!(
|
||||
read_decoded_line(&mut reader, &mut buf)
|
||||
.await
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some("no trailing newline")
|
||||
);
|
||||
assert!(read_decoded_line(&mut reader, &mut buf)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none());
|
||||
}
|
||||
|
||||
/// Spawn `sh -c <script>` with both pipes redirected, the way run_script and
|
||||
/// run_streamed do.
|
||||
#[cfg(unix)]
|
||||
fn sh(script: &str) -> Child {
|
||||
Command::new("/bin/sh")
|
||||
.arg("-c")
|
||||
.arg(script)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn /bin/sh")
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn pump_collect(child: &mut Child, grace: Duration) -> (PumpOutcome, Vec<String>) {
|
||||
let mut lines = Vec::new();
|
||||
let outcome = pump_child(
|
||||
child,
|
||||
|l| lines.push(l.to_string()),
|
||||
|_| {},
|
||||
&mut None,
|
||||
grace,
|
||||
)
|
||||
.await
|
||||
.expect("pump");
|
||||
(outcome, lines)
|
||||
}
|
||||
|
||||
/// The #90455 deadlock: a child exits, but a descendant it spawned still
|
||||
/// holds the inherited write end of the pipe, so EOF never comes. The pump
|
||||
/// must return on the *process* exiting and abandon the drain.
|
||||
///
|
||||
/// The Windows half of this contract lives in `-SelfTestPipeDrain`
|
||||
/// (scripts/desktop-update/windows.ps1) and runs on the Windows CI lane; the
|
||||
/// pump logic under test here is OS-agnostic, only the fixture is not.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_returns_when_a_grandchild_still_holds_the_pipe() {
|
||||
// `sleep` inherits stdout and outlives the shell by design. Nothing
|
||||
// redirects it -- redirecting is what would close the handle and stop
|
||||
// the bug from reproducing at all.
|
||||
let mut child = sh("sleep 30 & echo hello; exit 7");
|
||||
let started = std::time::Instant::now();
|
||||
let (outcome, lines) = pump_collect(&mut child, Duration::from_millis(300)).await;
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert!(outcome.abandoned, "drain should have been abandoned");
|
||||
assert_eq!(
|
||||
outcome.exit_code,
|
||||
Some(7),
|
||||
"exit code must survive an abandoned drain"
|
||||
);
|
||||
assert_eq!(
|
||||
lines,
|
||||
vec!["hello"],
|
||||
"output written before the pipe was stranded must survive"
|
||||
);
|
||||
assert!(!outcome.killed);
|
||||
// Far below the grandchild's 30s: a pass cannot be it exiting on its own.
|
||||
assert!(elapsed < Duration::from_secs(10), "took {elapsed:?}");
|
||||
}
|
||||
|
||||
/// The other cliff: a child that leaks nothing must not pay the grace. This
|
||||
/// is what fails if the pump ever waits on the deadline unconditionally
|
||||
/// instead of only when a pipe outlives its process.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_does_not_pay_the_grace_when_pipes_close_cleanly() {
|
||||
let mut child = sh("echo one; echo two >&2; echo three; exit 3");
|
||||
let started = std::time::Instant::now();
|
||||
let (outcome, lines) = pump_collect(&mut child, Duration::from_secs(30)).await;
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert!(!outcome.abandoned);
|
||||
assert_eq!(outcome.exit_code, Some(3));
|
||||
assert_eq!(lines, vec!["one", "three"]);
|
||||
assert!(elapsed < Duration::from_secs(10), "took {elapsed:?}");
|
||||
}
|
||||
|
||||
/// A chatty child must stream at pipe speed, not at one buffer per tick.
|
||||
/// The PowerShell port of this pump regressed exactly here: idling after
|
||||
/// every chunk it *did* read metered the drain and backpressured the running
|
||||
/// child. `hermes update` is this shape -- the Electron build alone is
|
||||
/// megabytes.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_streams_a_flood_without_metering_it() {
|
||||
let mut child = sh("i=0; while [ $i -lt 20000 ]; do echo line$i; i=$((i+1)); done; exit 0");
|
||||
let started = std::time::Instant::now();
|
||||
let (outcome, lines) = pump_collect(&mut child, Duration::from_secs(30)).await;
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert_eq!(outcome.exit_code, Some(0));
|
||||
assert!(!outcome.abandoned);
|
||||
assert_eq!(lines.len(), 20000, "every line must survive");
|
||||
assert_eq!(lines.last().unwrap(), "line19999");
|
||||
// Loose on purpose: this catches per-chunk sleeping (which would put
|
||||
// this in the tens of seconds), not small scheduler variance.
|
||||
assert!(elapsed < Duration::from_secs(20), "took {elapsed:?}");
|
||||
}
|
||||
|
||||
/// Cancelling kills the child, but not a grandchild holding the pipe --
|
||||
/// `start_kill` only reaches the child. The bounded drain is what actually
|
||||
/// lets a cancel return, so cancellation and the grace are one mechanism.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_cancellation_returns_even_with_the_pipe_stranded() {
|
||||
let mut child = sh("sleep 30 & echo working; sleep 30");
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
let mut cancel = Some(rx);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let _ = tx.send(()).await;
|
||||
});
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
let mut lines = Vec::new();
|
||||
let outcome = pump_child(
|
||||
&mut child,
|
||||
|l| lines.push(l.to_string()),
|
||||
|_| {},
|
||||
&mut cancel,
|
||||
Duration::from_millis(300),
|
||||
)
|
||||
.await
|
||||
.expect("pump");
|
||||
|
||||
assert!(outcome.killed, "cancellation should report killed");
|
||||
assert!(outcome.abandoned, "the grandchild still holds the pipe");
|
||||
assert_eq!(lines, vec!["working"]);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
"took {:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
/// The reverse topology of the test above: the pipes die and the *process*
|
||||
/// outlives them. Phase 1 leaves on EOF with no exit status, so the final
|
||||
/// wait is the only thing left holding the turn -- and it has to stay
|
||||
/// cancellable. A bare `child.wait()` there strands the cancel channel
|
||||
/// against a child that may never exit on its own.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn pump_child_cancellation_returns_after_both_pipes_reach_eof() {
|
||||
// Closes fd 1 and 2, then lingers: both reads hit EOF immediately while
|
||||
// the process stays alive far past any plausible test duration.
|
||||
let mut child = sh("echo bye; exec 1>&- 2>&-; sleep 30");
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
let mut cancel = Some(rx);
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let _ = tx.send(()).await;
|
||||
});
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
let mut lines = Vec::new();
|
||||
let outcome = pump_child(
|
||||
&mut child,
|
||||
|l| lines.push(l.to_string()),
|
||||
|_| {},
|
||||
&mut cancel,
|
||||
Duration::from_millis(300),
|
||||
)
|
||||
.await
|
||||
.expect("pump");
|
||||
let elapsed = started.elapsed();
|
||||
|
||||
assert!(outcome.killed, "cancellation should report killed");
|
||||
assert!(
|
||||
!outcome.abandoned,
|
||||
"both pipes reached EOF, so nothing was abandoned"
|
||||
);
|
||||
assert_eq!(lines, vec!["bye"], "output written before EOF must survive");
|
||||
// Far below the child's 30s: a pass cannot be it exiting on its own.
|
||||
assert!(elapsed < Duration::from_secs(10), "took {elapsed:?}");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Hermes",
|
||||
"version": "0.0.1",
|
||||
"identifier": "com.nousresearch.hermes.setup",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
"devUrl": "http://127.0.0.1:5175",
|
||||
"beforeBuildCommand": "npm run build",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "Hermes",
|
||||
"width": 880,
|
||||
"height": 620,
|
||||
"minWidth": 720,
|
||||
"minHeight": 520,
|
||||
"resizable": true,
|
||||
"fullscreen": false,
|
||||
"decorations": true,
|
||||
"transparent": false,
|
||||
"center": true,
|
||||
"visible": false
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost"
|
||||
},
|
||||
"withGlobalTauri": false
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"category": "DeveloperTool",
|
||||
"shortDescription": "Hermes",
|
||||
"longDescription": "Installs Hermes Agent on your machine. Drives scripts/install.ps1 (Windows) and scripts/install.sh (macOS/Linux).",
|
||||
"publisher": "Nous Research",
|
||||
"copyright": "Copyright © 2026 Nous Research",
|
||||
"targets": [
|
||||
"app",
|
||||
"dmg",
|
||||
"appimage"
|
||||
],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"windows": {
|
||||
"webviewInstallMode": {
|
||||
"type": "embedBootstrapper"
|
||||
}
|
||||
},
|
||||
"macOS": {
|
||||
"minimumSystemVersion": "11.0",
|
||||
"hardenedRuntime": true,
|
||||
"entitlements": "entitlements.plist"
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"shell": {
|
||||
"open": true
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user