Skip to content

Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.

fix: recover from macOS in-app upgrade failures (#98)

澄潭d1321b03be67
diff --git a/apps/desktop/src-tauri/src/bootstrap.rs b/apps/desktop/src-tauri/src/bootstrap.rs
index c26a327d..5ae7a825 100644
--- a/apps/desktop/src-tauri/src/bootstrap.rs
+++ b/apps/desktop/src-tauri/src/bootstrap.rs
@@ -173,6 +173,48 @@ impl Resident {
std::thread::sleep(Duration::from_millis(20));
}
}
+ /// Keep the host lock while reusing the ordinary startup/recovery entry. A pending
+ /// orderly stop is never converted into an ordinary Drop (which may force-kill).
+ #[cfg(all(target_os = "macos", feature = "desktop-runtime"))]
+ pub(crate) fn replacement_after_upgrade_stop(
+ &mut self,
+ root: &Path,
+ daemon: &Path,
+ diagnostics: &NativeDiagnostics,
+ ) -> Result<Self, String> {
+ self.replace_stopped(|lock| {
+ Self::open_resident(
+ root,
+ daemon,
+ &AtomicBool::new(false),
+ diagnostics,
+ Some(lock),
+ )
+ })
+ }
+ #[cfg(any(test, all(target_os = "macos", feature = "desktop-runtime")))]
+ fn replace_stopped(
+ &mut self,
+ initialize: impl FnOnce(File) -> Result<Self, String>,
+ ) -> Result<Self, String> {
+ let owned = self.owned.as_mut().ok_or("UPGRADE_RESIDENT_NOT_OWNED")?;
+ if owned.shutdown.is_some() {
+ return Err("UPGRADE_RESIDENT_NOT_STOPPED".into());
+ }
+ if owned
+ .child
+ .try_wait()
+ .map_err(|_| "UPGRADE_STOP_FAILED")?
+ .is_none()
+ {
+ return Err("UPGRADE_STOP_PENDING".into());
+ }
+ let lock = self
+ ._lock
+ .try_clone()
+ .map_err(|_| "RESIDENT_LOCK_UNAVAILABLE")?;
+ initialize(lock)
+ }
pub fn open(root: &Path, daemon: &Path) -> Result<Self, String> {
Self::open_managed(
root,
@@ -966,3 +1008,5 @@ pub(crate) fn acquire_host_lock(root: &Path) -> Result<File, String> {
#[cfg(test)]
mod tests;
+#[cfg(test)]
+pub(crate) use tests::session_resident;
diff --git a/apps/desktop/src-tauri/src/bootstrap/tests.rs b/apps/desktop/src-tauri/src/bootstrap/tests.rs
index 60cad8d0..f8e5d6fe 100644
--- a/apps/desktop/src-tauri/src/bootstrap/tests.rs
+++ b/apps/desktop/src-tauri/src/bootstrap/tests.rs
@@ -1,5 +1,129 @@
use super::*;
+/// Native channel fixture for Session/transport checks; never a production daemon substitute.
+pub(crate) fn session_resident(root: &Path, client: Client) -> Resident {
+ use std::io::BufRead;
+ let mut resident = recovery_resident(root, false);
+ resident.client = client;
+ let (capability_reader, capability_writer) = pipe().unwrap();
+ let (ack_reader, mut ack_writer) = pipe().unwrap();
+ let owned = resident.owned.as_mut().unwrap();
+ owned.capability = capability_writer;
+ owned.ack = ack_reader;
+ std::thread::spawn(move || {
+ for line in std::io::BufReader::new(capability_reader).lines() {
+ let registration: serde_json::Value = serde_json::from_str(&line.unwrap()).unwrap();
+ let mut reply = serde_json::to_vec(&serde_json::json!({
+ "schema": "hiroute.protected-apply-ack/v2",
+ "registration_id": registration["registration_id"], "registered": true
+ }))
+ .unwrap();
+ reply.push(b'\n');
+ ack_writer.write_all(&reply).unwrap();
+ }
+ });
+ resident
+}
+
+fn recovery_resident(root: &Path, slow: bool) -> Resident {
+ let (reader, writer) = pipe().unwrap();
+ let (_, capability) = pipe().unwrap();
+ let (ack, _) = pipe().unwrap();
+ let mut command = Command::new(if slow { "/bin/sleep" } else { "/bin/cat" });
+ if slow {
+ command.arg("30");
+ }
+ Resident {
+ client: Client::new(
+ "hiroute-desktop",
+ LocalEndpoint::from_runtime_root(root.join("run")),
+ ),
+ owned: Some(OwnedChild {
+ child: command
+ .stdin(Stdio::from(reader))
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap(),
+ shutdown: Some(writer),
+ capability,
+ ack,
+ authority_healthy: true,
+ manual_input_candidates: BTreeSet::new(),
+ diagnostics: None,
+ }),
+ _lock: acquire_host_lock(root).unwrap(),
+ }
+}
+
+#[test]
+fn recovery_waits_for_exact_child_exit_and_never_drops_a_pending_child() {
+ let directory = tempfile::tempdir().unwrap();
+ let mut resident = recovery_resident(directory.path(), true);
+ assert_eq!(
+ resident
+ .replace_stopped(|_| panic!("startup before shutdown"))
+ .err()
+ .unwrap(),
+ "UPGRADE_RESIDENT_NOT_STOPPED"
+ );
+ drop(resident.owned.as_mut().unwrap().shutdown.take());
+ assert_eq!(
+ resident
+ .replace_stopped(|_| panic!("startup while old child lives"))
+ .err()
+ .unwrap(),
+ "UPGRADE_STOP_PENDING"
+ );
+ assert!(
+ resident
+ .owned
+ .as_mut()
+ .unwrap()
+ .child
+ .try_wait()
+ .unwrap()
+ .is_none()
+ );
+ assert!(acquire_host_lock(directory.path()).is_err());
+ // Explicitly clean up this test's sleeping fixture, not the production stop path.
+ resident.owned.as_mut().unwrap().child.kill().unwrap();
+ resident.owned.as_mut().unwrap().child.wait().unwrap();
+}
+
+#[test]
+fn recovery_preserves_host_lock_across_failed_and_successful_restarts() {
+ let directory = tempfile::tempdir().unwrap();
+ let mut resident = recovery_resident(directory.path(), false);
+ drop(resident.owned.as_mut().unwrap().shutdown.take());
+ resident.owned.as_mut().unwrap().child.wait().unwrap();
+ assert_eq!(
+ resident
+ .replace_stopped(|_| Err("DAEMON_START_FAILED".into()))
+ .err()
+ .unwrap(),
+ "DAEMON_START_FAILED"
+ );
+ assert!(acquire_host_lock(directory.path()).is_err());
+ let replacement = resident
+ .replace_stopped(|lock| {
+ assert!(acquire_host_lock(directory.path()).is_err());
+ Ok(Resident {
+ client: Client::new(
+ "hiroute-desktop",
+ LocalEndpoint::from_runtime_root(directory.path().join("run")),
+ ),
+ owned: None,
+ _lock: lock,
+ })
+ })
+ .unwrap();
+ drop(resident);
+ assert!(acquire_host_lock(directory.path()).is_err());
+ drop(replacement);
+ assert!(acquire_host_lock(directory.path()).is_ok());
+}
+
#[test]
fn upgrade_prepare_status_cancel_exchange_complete_correlated_frames() {
use hiroute_host_runtime::{LauncherUpgradeRequest, LauncherUpgradeStatus, UpgradeAction};
diff --git a/apps/desktop/src-tauri/src/bridge.rs b/apps/desktop/src-tauri/src/bridge.rs
index ec0c74f0..3fdd4c0e 100644
--- a/apps/desktop/src-tauri/src/bridge.rs
+++ b/apps/desktop/src-tauri/src/bridge.rs
@@ -49,6 +49,7 @@ pub use diagnostics::DiagnosticsState;
pub use startup::StartupState;
use startup::*;
mod web_confirmation;
+pub(crate) use web_confirmation::expire_window_confirmations;
use web_confirmation::*;
mod window_behavior;
use window_behavior::*;
@@ -63,6 +64,15 @@ pub struct DesktopState(
pub DiagnosticHandle,
);
+async fn confirmation_session(
+ state: &DesktopState,
+ epoch: u64,
+) -> Result<tokio::sync::MutexGuard<'_, Option<Session>>, DesktopFailure> {
+ crate::confirmation::lock_current_session(&state.0, &state.2, epoch)
+ .await
+ .map_err(Into::into)
+}
+
fn desktop_data_root(handle: &tauri::AppHandle) -> Result<std::path::PathBuf, ()> {
let root = handle.path().app_local_data_dir().map_err(|_| ())?;
#[cfg(debug_assertions)]
@@ -256,10 +266,8 @@ pub async fn refresh_route_references(
let epoch = state.2.load(Ordering::SeqCst);
let action = ActionDiagnostics::begin(&state.3, ActionOperation::PlanEditor);
action.preview(PreviewPhase::Begin, None);
- let context = state
- .0
- .lock()
- .await
+ let context = confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.preview_reference_refresh(language)
@@ -285,10 +293,8 @@ pub async fn preview_plan_editor(
let epoch = state.2.load(Ordering::SeqCst);
let action = ActionDiagnostics::begin(&state.3, ActionOperation::PlanEditor);
action.preview(PreviewPhase::Begin, None);
- let context = state
- .0
- .lock()
- .await
+ let context = confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.preview_editor(input)
@@ -326,7 +332,7 @@ pub async fn preview_rename(
let action = ActionDiagnostics::begin(&state.3, ActionOperation::Rename);
action.preview(PreviewPhase::Begin, None);
let context = {
- let mut guard = state.0.lock().await;
+ let mut guard = confirmation_session(&state, epoch).await?;
guard
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
@@ -354,10 +360,8 @@ pub async fn preview_restore_name(
let epoch = state.2.load(Ordering::SeqCst);
let action = ActionDiagnostics::begin(&state.3, ActionOperation::RestoreName);
action.preview(PreviewPhase::Begin, None);
- let context = state
- .0
- .lock()
- .await
+ let context = confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.preview_restore(input)
@@ -451,10 +455,8 @@ pub async fn preview_price_change(
let epoch = state.2.load(Ordering::SeqCst);
let action = ActionDiagnostics::begin(&state.3, ActionOperation::PriceChange);
action.preview(PreviewPhase::Begin, None);
- let context = state
- .0
- .lock()
- .await
+ let context = confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.preview_price(input)
@@ -536,10 +538,8 @@ pub async fn preview_agent_settings(
let epoch = state.2.load(Ordering::SeqCst);
let action = ActionDiagnostics::begin(&state.3, ActionOperation::AgentSettings);
action.preview(PreviewPhase::Begin, None);
- let prepared = state
- .0
- .lock()
- .await
+ let prepared = confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.preview_agent_settings(input)
@@ -585,10 +585,8 @@ pub async fn check_agent_authentication(
let epoch = state.2.load(Ordering::SeqCst);
let action = ActionDiagnostics::begin(&state.3, ActionOperation::AgentCheck);
action.preview(PreviewPhase::Begin, None);
- let context = state
- .0
- .lock()
- .await
+ let context = confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.prepare_agent_check(input)
@@ -621,10 +619,8 @@ pub async fn check_agent_live(
let epoch = state.2.load(Ordering::SeqCst);
let action = ActionDiagnostics::begin(&state.3, ActionOperation::AgentCheck);
action.preview(PreviewPhase::Begin, None);
- let context = state
- .0
- .lock()
- .await
+ let context = confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.prepare_agent_check(input)
@@ -653,13 +649,14 @@ async fn confirm(
) -> Result<NativeOutcome, DesktopFailure> {
let action = ActionDiagnostics::begin(&state.3, operation);
if state.2.load(Ordering::SeqCst) != epoch || !window.is_visible().unwrap_or(false) {
- state
- .0
- .lock()
- .await
- .as_mut()
- .ok_or("RESIDENT_UNAVAILABLE")?
- .invalidate_confirmation();
+ let mut guard = state.0.lock().await;
+ // Recovery may have installed another Session while this callback waited.
+ if state.2.load(Ordering::SeqCst) == epoch {
+ guard
+ .as_mut()
+ .ok_or("RESIDENT_UNAVAILABLE")?
+ .invalidate_confirmation();
+ }
action.confirmation(ConfirmationPhase::Expired, None);
action.end(ActionResult::Stale, None);
return Err("CONFIRMATION_STALE".into());
@@ -723,21 +720,21 @@ async fn confirm(
true
};
if state.2.load(Ordering::SeqCst) != epoch || !window.is_visible().unwrap_or(false) {
- state
- .0
- .lock()
- .await
- .as_mut()
- .ok_or("RESIDENT_UNAVAILABLE")?
- .invalidate_confirmation();
- // The approval was invalidated; the caller's existing semantics still decide what
- // happens next, and diagnostics only record that the confirmation expired.
+ let mut guard = state.0.lock().await;
+ if state.2.load(Ordering::SeqCst) == epoch {
+ guard
+ .as_mut()
+ .ok_or("RESIDENT_UNAVAILABLE")?
+ .invalidate_confirmation();
+ }
action.confirmation(ConfirmationPhase::Expired, None);
+ action.end(ActionResult::Stale, None);
+ return Err("CONFIRMATION_STALE".into());
}
action.apply(ApplyPhase::Begin, Some(revision), None);
let outcome = if let NativeConfirmation::SubscriptionCheck(context) = context {
let pending = {
- let mut guard = state.0.lock().await;
+ let mut guard = confirmation_session(state, epoch).await?;
guard
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
@@ -747,19 +744,15 @@ async fn confirm(
// Operation A performs connector I/O. Keep native close/recovery commands responsive while
// it runs so close can submit cancellation rather than waiting behind this command.
let completion = pending.execute().await;
- state
- .0
- .lock()
- .await
- .as_mut()
- .ok_or("RESIDENT_UNAVAILABLE")?
- .finish_subscription_check_confirmation(completion)
+ // Completion belongs to the Session that submitted it, not the window's prompt epoch.
+ // Window close must still release an A resource created after the close-time sweep.
+ crate::session::complete_subscription_check(&state.0, completion)
.await
.map(Box::new)
.map(NativeOutcome::SubscriptionCheck)
} else if let NativeConfirmation::Check(context) = context {
let dispatch = {
- let mut guard = state.0.lock().await;
+ let mut guard = confirmation_session(state, epoch).await?;
guard
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
@@ -772,7 +765,7 @@ async fn confirm(
}
}
} else {
- let mut guard = state.0.lock().await;
+ let mut guard = confirmation_session(state, epoch).await?;
let session = guard.as_mut().ok_or("RESIDENT_UNAVAILABLE")?;
match context {
NativeConfirmation::Agent(context) => session
@@ -987,21 +980,18 @@ pub fn run() {
})
.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
- window
- .state::<DesktopState>()
- .2
- .fetch_add(1, Ordering::SeqCst);
- window
- .state::<WebConfirmationState>()
- .cancel_window(window.label());
- window
- .state::<WorkerDependencyConfirmationState>()
- .cancel_window(window.label());
+ expire_window_confirmations(window.app_handle(), window.label());
api.prevent_close();
let _ = window.hide();
let state = window.state::<DesktopState>().0.clone();
+ let epoch = window.state::<DesktopState>().2.load(Ordering::SeqCst);
+ let handle = window.app_handle().clone();
tauri::async_runtime::spawn(async move {
- if let Some(session) = state.lock().await.as_mut() {
+ let mut guard = state.lock().await;
+ if handle.state::<DesktopState>().2.load(Ordering::SeqCst) != epoch {
+ return;
+ }
+ if let Some(session) = guard.as_mut() {
session.invalidate_confirmation();
session.stop_observing();
let _ = session.close_subscription_check().await;
diff --git a/apps/desktop/src-tauri/src/bridge/model_connections.rs b/apps/desktop/src-tauri/src/bridge/model_connections.rs
index a95123ee..b55c9f39 100644
--- a/apps/desktop/src-tauri/src/bridge/model_connections.rs
+++ b/apps/desktop/src-tauri/src/bridge/model_connections.rs
@@ -72,7 +72,7 @@ pub async fn check_subscription(
main_window(&window)?;
let epoch = state.2.load(Ordering::SeqCst);
let (client, close_requested) = {
- let mut guard = state.0.lock().await;
+ let mut guard = super::confirmation_session(&state, epoch).await?;
let session = guard.as_mut().ok_or("RESIDENT_UNAVAILABLE")?;
let close_requested = session.resume_subscription_interaction();
(session.client.clone(), close_requested)
@@ -82,10 +82,8 @@ pub async fn check_subscription(
.preview_subscription_check(&crate::random_id()?, candidate)
.await?,
)?;
- let context = state
- .0
- .lock()
- .await
+ let context = super::confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.prepare_subscription_check_confirmation(
@@ -550,10 +548,8 @@ pub async fn apply_compute_save(
let request: ComputeConnectionApplyRequestV1 =
request.try_into().map_err(DesktopFailure::from)?;
let epoch = state.2.load(Ordering::SeqCst);
- let context = state
- .0
- .lock()
- .await
+ let context = super::confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.prepare_model_save_confirmation(request, language)?;
diff --git a/apps/desktop/src-tauri/src/bridge/observation.rs b/apps/desktop/src-tauri/src/bridge/observation.rs
index 29702a57..8a87a454 100644
--- a/apps/desktop/src-tauri/src/bridge/observation.rs
+++ b/apps/desktop/src-tauri/src/bridge/observation.rs
@@ -29,10 +29,8 @@ pub(super) async fn observation_delete(
data_class: input.data_class,
delete_rollups: false,
};
- let preview = state
- .0
- .lock()
- .await
+ let preview = super::confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.deletion_preview(spec)
@@ -66,10 +64,8 @@ pub(super) async fn observation_delete(
if state.2.load(Ordering::SeqCst) != epoch || !window.is_visible().unwrap_or(false) {
return Err("CONFIRMATION_STALE".into());
}
- let outcome = state
- .0
- .lock()
- .await
+ let outcome = super::confirmation_session(&state, epoch)
+ .await?
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.deletion_apply(preview)
diff --git a/apps/desktop/src-tauri/src/bridge/web_confirmation.rs b/apps/desktop/src-tauri/src/bridge/web_confirmation.rs
index 97047037..7769d81d 100644
--- a/apps/desktop/src-tauri/src/bridge/web_confirmation.rs
+++ b/apps/desktop/src-tauri/src/bridge/web_confirmation.rs
@@ -10,6 +10,16 @@ use tokio::sync::oneshot;
pub(super) const WEB_CONFIRMATION_EVENT: &str = "hiroute-web-confirmation";
const WEB_CONFIRMATION_SCHEMA: &str = "hiroute.web-confirmation/v1";
+pub(crate) fn expire_window_confirmations(app: &tauri::AppHandle, window_label: &str) {
+ app.state::<super::DesktopState>()
+ .2
+ .fetch_add(1, Ordering::SeqCst);
+ app.state::<WebConfirmationState>()
+ .cancel_window(window_label);
+ app.state::<super::WorkerDependencyConfirmationState>()
+ .cancel_window(window_label);
+}
+
pub(super) struct WebConfirmationPrompt {
pub title: String,
pub message: String,
diff --git a/apps/desktop/src-tauri/src/bridge/worker_tasks.rs b/apps/desktop/src-tauri/src/bridge/worker_tasks.rs
index 90a045c1..c70d59f2 100644
--- a/apps/desktop/src-tauri/src/bridge/worker_tasks.rs
+++ b/apps/desktop/src-tauri/src/bridge/worker_tasks.rs
@@ -365,9 +365,13 @@ pub async fn worker_dependencies_discover(
pub async fn worker_dependencies_select_prepare(
window: WebviewWindow,
state: State<'_, WorkerDependencyConfirmationState>,
+ desktop: State<'_, DesktopState>,
input: WorkerDependenciesSelectRequestV1,
) -> Result<WorkerDependencyConfirmationV1, DesktopFailure> {
main_window(&window)?;
+ let epoch = desktop.2.load(std::sync::atomic::Ordering::SeqCst);
+ let session = super::confirmation_session(&desktop, epoch).await?;
+ session.as_ref().ok_or("RESIDENT_UNAVAILABLE")?;
let selection = normalize_worker_dependency_selection(&input)?;
state.prepare(window.label(), selection, now_ms()?)
}
@@ -380,11 +384,10 @@ pub async fn worker_dependencies_select_confirm(
input: WorkerDependencyConfirmationInput,
) -> Result<MachineEnvelopeV2<WorkerDependenciesViewV1>, DesktopFailure> {
main_window(&window)?;
+ let epoch = state.2.load(std::sync::atomic::Ordering::SeqCst);
+ let mut session = super::confirmation_session(&state, epoch).await?;
let selection = confirmations.take(window.label(), &input.confirmation_id, now_ms()?)?;
- state
- .0
- .lock()
- .await
+ session
.as_mut()
.ok_or("RESIDENT_UNAVAILABLE")?
.select_worker_dependencies(selection)
diff --git a/apps/desktop/src-tauri/src/confirmation.rs b/apps/desktop/src-tauri/src/confirmation.rs
index 79ed8208..adaaf1c7 100644
--- a/apps/desktop/src-tauri/src/confirmation.rs
+++ b/apps/desktop/src-tauri/src/confirmation.rs
@@ -1,18 +1,52 @@
//! Backend-only, single-use confirmation lifetime. It carries no business authority.
-use std::time::{Duration, Instant};
+use std::{
+ sync::{
+ Arc,
+ atomic::{AtomicU64, Ordering},
+ },
+ time::{Duration, Instant},
+};
pub(crate) const CONFIRMATION_TTL: Duration = Duration::from_secs(60);
+/// Recovery advances the epoch while holding this same mutex. Check only after
+/// acquiring it, before creating a permit or applying an already accepted decision.
+pub(crate) async fn lock_current_session<'a, T>(
+ sessions: &'a tokio::sync::Mutex<T>,
+ epoch: &AtomicU64,
+ captured: u64,
+) -> Result<tokio::sync::MutexGuard<'a, T>, &'static str> {
+ let guard = sessions.lock().await;
+ if epoch.load(Ordering::SeqCst) != captured {
+ return Err("CONFIRMATION_STALE");
+ }
+ Ok(guard)
+}
+
#[derive(Default)]
pub(crate) struct ConfirmationGate {
+ identity: Arc<()>,
generation: u64,
open: bool,
}
pub(crate) struct ConfirmationPermit {
+ identity: Arc<()>,
generation: u64,
created: Instant,
}
+/// Stable for the owning Session, including after its window confirmations expire.
+pub(crate) struct ConfirmationOwner(Arc<()>);
impl ConfirmationGate {
+ pub(crate) fn owner(&self) -> ConfirmationOwner {
+ ConfirmationOwner(self.identity.clone())
+ }
+ pub(crate) fn check_owner(&self, owner: &ConfirmationOwner) -> Result<(), &'static str> {
+ if Arc::ptr_eq(&self.identity, &owner.0) {
+ Ok(())
+ } else {
+ Err("CONFIRMATION_STALE")
+ }
+ }
pub fn is_open(&self) -> bool {
self.open
}
@@ -23,6 +57,7 @@ impl ConfirmationGate {
self.generation = self.generation.wrapping_add(1);
self.open = true;
Ok(ConfirmationPermit {
+ identity: self.identity.clone(),
generation: self.generation,
created: Instant::now(),
})
@@ -36,7 +71,10 @@ impl ConfirmationGate {
permit: &ConfirmationPermit,
accepted: bool,
) -> Result<bool, &'static str> {
- if !self.open || permit.generation != self.generation {
+ if !Arc::ptr_eq(&self.identity, &permit.identity)
+ || !self.open
+ || permit.generation != self.generation
+ {
return Err("CONFIRMATION_STALE");
}
self.open = false;
@@ -49,6 +87,57 @@ impl ConfirmationGate {
#[cfg(test)]
mod tests {
use super::*;
+ #[tokio::test]
+ async fn queued_preview_cannot_open_a_gate_in_the_replacement_session() {
+ let epoch = AtomicU64::new(0);
+ let sessions = tokio::sync::Mutex::new(ConfirmationGate::default());
+ let mut recovery = sessions.lock().await;
+ let captured = epoch.load(Ordering::SeqCst);
+ let preview = async {
+ let mut session = lock_current_session(&sessions, &epoch, captured).await?;
+ session.begin()
+ };
+ tokio::pin!(preview);
+ tokio::select! {
+ biased;
+ _ = &mut preview => panic!("preview passed the held recovery lock"),
+ _ = tokio::task::yield_now() => {}
+ }
+ *recovery = ConfirmationGate::default();
+ epoch.fetch_add(1, Ordering::SeqCst);
+ drop(recovery);
+ assert!(matches!(preview.await, Err("CONFIRMATION_STALE")));
+ let mut session = lock_current_session(&sessions, &epoch, 1).await.unwrap();
+ let fresh = session.begin().unwrap();
+ assert!(session.finish(&fresh, true).unwrap());
+ }
+ #[tokio::test]
+ async fn accepted_decision_waiting_for_the_lock_cannot_apply_after_recovery() {
+ let epoch = AtomicU64::new(0);
+ let sessions = tokio::sync::Mutex::new(Vec::<&str>::new());
+ let recovery = sessions.lock().await;
+ let captured = epoch.load(Ordering::SeqCst);
+ let apply = async {
+ let mut session = lock_current_session(&sessions, &epoch, captured).await?;
+ session.push("old accepted decision");
+ Ok::<_, &'static str>(())
+ };
+ tokio::pin!(apply);
+ tokio::select! {
+ biased;
+ _ = &mut apply => panic!("apply passed the held recovery lock"),
+ _ = tokio::task::yield_now() => {}
+ }
+ epoch.fetch_add(1, Ordering::SeqCst);
+ drop(recovery);
+ assert!(matches!(apply.await, Err("CONFIRMATION_STALE")));
+ assert!(sessions.lock().await.is_empty());
+ lock_current_session(&sessions, &epoch, 1)
+ .await
+ .unwrap()
+ .push("new accepted decision");
+ assert_eq!(*sessions.lock().await, ["new accepted decision"]);
+ }
#[test]
fn rejection_and_duplicate_callback_never_reopen_a_consumed_confirmation() {
let mut gate = ConfirmationGate::default();
@@ -70,6 +159,39 @@ mod tests {
assert!(gate.finish(&new, true).unwrap());
}
#[test]
+ fn replacement_session_rejects_old_first_permit_and_keeps_its_own_confirmation() {
+ let mut old = ConfirmationGate::default();
+ let old_permit = old.begin().unwrap();
+ let mut replacement = ConfirmationGate::default();
+ let new_permit = replacement.begin().unwrap();
+ // Both generations begin at one; the owning gate must still differ.
+ assert_eq!(old_permit.generation, new_permit.generation);
+ assert_eq!(
+ replacement.finish(&old_permit, true),
+ Err("CONFIRMATION_STALE")
+ );
+ assert_eq!(
+ replacement.finish(&old_permit, false),
+ Err("CONFIRMATION_STALE")
+ );
+ assert!(replacement.finish(&new_permit, true).unwrap());
+ }
+ #[test]
+ fn window_close_preserves_submitted_completion_owner_but_recovery_rejects_it() {
+ let mut session = ConfirmationGate::default();
+ let permit = session.begin().unwrap();
+ assert!(session.finish(&permit, true).unwrap());
+ let completion_owner = session.owner();
+ // Close may find no operation yet. Its later completion must still run cleanup.
+ session.invalidate();
+ assert_eq!(session.check_owner(&completion_owner), Ok(()));
+ let replacement = ConfirmationGate::default();
+ assert_eq!(
+ replacement.check_owner(&completion_owner),
+ Err("CONFIRMATION_STALE")
+ );
+ }
+ #[test]
fn expired_confirmation_is_consumed_and_requires_a_fresh_preview() {
let mut gate = ConfirmationGate::default();
let mut expired = gate.begin().unwrap();
diff --git a/apps/desktop/src-tauri/src/session/subscription.rs b/apps/desktop/src-tauri/src/session/subscription.rs
index 557cb22d..29a9e90e 100644
--- a/apps/desktop/src-tauri/src/session/subscription.rs
+++ b/apps/desktop/src-tauri/src/session/subscription.rs
@@ -1,5 +1,5 @@
use super::{Session, query, terminal};
-use crate::confirmation::ConfirmationPermit;
+use crate::confirmation::{ConfirmationOwner, ConfirmationPermit};
use crate::failure::DesktopFailure;
use crate::operation_observation::{IntentEvidence, SubmittedOperation};
use hiroute_application_api::*;
@@ -27,6 +27,7 @@ impl SubscriptionCheckConfirmation {
/// The only shared state is a close signal; no WebView can construct this value.
#[cfg(any(feature = "desktop-runtime", test))]
pub(crate) struct PendingSubscriptionCheck {
+ owner: ConfirmationOwner,
client: hiroute_client_core::Client,
request_id: String,
request: ComputeConnectionApplyRequestV1,
@@ -36,6 +37,7 @@ pub(crate) struct PendingSubscriptionCheck {
#[cfg(any(feature = "desktop-runtime", test))]
pub(crate) struct SubscriptionCheckCompletion {
+ owner: ConfirmationOwner,
idempotency_key: String,
accepted_digest: CanonicalDigest,
outcome: SubscriptionCheckSubmission,
@@ -72,6 +74,7 @@ impl PendingSubscriptionCheck {
))
};
SubscriptionCheckCompletion {
+ owner: self.owner,
idempotency_key,
accepted_digest,
outcome,
@@ -80,6 +83,22 @@ impl PendingSubscriptionCheck {
}
}
+/// The submitted operation's completion entry. Window-close epochs expire new intent,
+/// while the originating Session still owns cleanup for work already submitted.
+#[cfg(any(feature = "desktop-runtime", test))]
+pub(crate) async fn complete_subscription_check(
+ sessions: &tokio::sync::Mutex<Option<Session>>,
+ completion: SubscriptionCheckCompletion,
+) -> Result<ComputeSubscriptionCheckResultV2, DesktopFailure> {
+ sessions
+ .lock()
+ .await
+ .as_mut()
+ .ok_or("RESIDENT_UNAVAILABLE")?
+ .finish_subscription_check_confirmation(completion)
+ .await
+}
+
impl SubscriptionCheckConfirmation {
pub fn requires_confirmation(&self) -> bool {
false
@@ -219,6 +238,7 @@ impl Session {
let capability: zeroize::Zeroizing<String> =
return Err("TRUSTED_AUTHORITY_UNAVAILABLE".into());
Ok(PendingSubscriptionCheck {
+ owner: self.confirmation.owner(),
client: self.client.clone(),
request_id: crate::random_id()?,
request: context.request,
@@ -234,6 +254,7 @@ impl Session {
&mut self,
completion: SubscriptionCheckCompletion,
) -> Result<ComputeSubscriptionCheckResultV2, DesktopFailure> {
+ self.confirmation.check_owner(&completion.owner)?;
let owns_hint = self.subscription_hint.as_ref().is_some_and(|hint| {
hint.operation_kind == APPLY_SUBSCRIPTION_CHECK_OPERATION_V2
&& hint.idempotency_key == completion.idempotency_key
@@ -613,6 +634,7 @@ mod tests {
let root = tempfile::tempdir().unwrap();
let close_requested = Arc::new(AtomicBool::new(false));
let pending = PendingSubscriptionCheck {
+ owner: ConfirmationGate::default().owner(),
client: Client::new(
"desktop-test",
LocalEndpoint::from_runtime_root(root.path()),
@@ -645,3 +667,7 @@ mod tests {
));
}
}
+
+#[cfg(all(test, unix))]
+#[path = "subscription/completion_tests.rs"]
+mod completion_tests;
diff --git a/apps/desktop/src-tauri/src/session/subscription/completion_tests.rs b/apps/desktop/src-tauri/src/session/subscription/completion_tests.rs
new file mode 100644
index 00000000..65c2855b
--- /dev/null
+++ b/apps/desktop/src-tauri/src/session/subscription/completion_tests.rs
@@ -0,0 +1,228 @@
+//! Component regressions over the production completion entry and real Client Core transport.
+//! The scoped socket server models an A record arriving after the close-time sweep.
+use super::*;
+use hiroute_client_core::{Client, LocalEndpoint};
+use serde_json::{Value, json};
+use std::os::unix::fs::PermissionsExt;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use tokio::net::UnixListener;
+
+struct Fixture {
+ root: tempfile::TempDir,
+ client: Client,
+ calls: Arc<AtomicUsize>,
+ releases: Arc<AtomicUsize>,
+ created: Arc<AtomicBool>,
+ server: tokio::task::JoinHandle<()>,
+}
+impl Fixture {
+ fn new() -> Self {
+ let root = tempfile::Builder::new()
+ .prefix("hrsc-")
+ .tempdir_in(std::fs::canonicalize("/tmp").unwrap())
+ .unwrap();
+ let runtime = root.path().join("run");
+ let directory = runtime.join("hiroute");
+ std::fs::create_dir_all(&directory).unwrap();
+ std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let endpoint = LocalEndpoint::for_child(&runtime, std::process::id());
+ let listener = UnixListener::bind(endpoint.path()).unwrap();
+ std::fs::set_permissions(endpoint.path(), std::fs::Permissions::from_mode(0o600)).unwrap();
+ let client = Client::new("desktop-test", endpoint);
+ let calls = Arc::new(AtomicUsize::new(0));
+ let releases = Arc::new(AtomicUsize::new(0));
+ let created = Arc::new(AtomicBool::new(false));
+ let (server_calls, server_releases, server_created) =
+ (calls.clone(), releases.clone(), created.clone());
+ let server = tokio::spawn(async move {
+ loop {
+ let (stream, _) = listener.accept().await.unwrap();
+ let mut stream = BufReader::new(stream);
+ let mut line = String::new();
+ stream.read_line(&mut line).await.unwrap();
+ let hello: ClientHelloV1 = serde_json::from_str(&line).unwrap();
+ write(
+ &mut stream,
+ serde_json::to_value(negotiate_hello(&hello).unwrap()).unwrap(),
+ )
+ .await;
+ line.clear();
+ stream.read_line(&mut line).await.unwrap();
+ let request: LocalControlWireRequestV2 = serde_json::from_str(&line).unwrap();
+ server_calls.fetch_add(1, Ordering::SeqCst);
+ let data = match request.operation_id.as_str() {
+ "FindOperationByIdempotency" => json!({
+ "digest_matches": true,
+ "operation": if server_created.load(Ordering::SeqCst) { Some(json!({
+ "operation_id": "operation-a", "state": "succeeded", "sequence": 1,
+ "cancellable": false, "accepted_digest": CanonicalDigest::of_bytes(b"accepted"),
+ "safe_error_code": null
+ })) } else { None }
+ }),
+ LIST_COMPUTE_SUBSCRIPTIONS_OPERATION_V2 => json!({
+ "candidates": [], "discovery_state": "complete"
+ }),
+ GET_SUBSCRIPTION_CHECK_RESULT_OPERATION_V2 => result(false),
+ "GetClientServiceStatus" => json!({
+ "schema": "hiroute.client-service-status/v1", "daemon_role": "all",
+ "recovery_ready": true, "mutation_available": true, "gateway": "ready",
+ "active_publication": null, "revisions": { "target": 1, "dependencies": {} }
+ }),
+ RELEASE_SUBSCRIPTION_CHECK_OPERATION_V2 => {
+ assert_eq!(request.payload["validation_ref"], "validation-a");
+ assert!(request.protected_grant.is_some());
+ server_releases.fetch_add(1, Ordering::SeqCst);
+ result(true)
+ }
+ operation => panic!("unexpected completion operation: {operation}"),
+ };
+ write(
+ &mut stream,
+ json!({
+ "schema_version": LOCAL_CONTROL_SCHEMA_V2, "request_id": request.request_id,
+ "status": "succeeded", "data": data, "operation": null,
+ "warnings": [], "next_actions": [], "error": null
+ }),
+ )
+ .await;
+ }
+ });
+ Self {
+ root,
+ client,
+ calls,
+ releases,
+ created,
+ server,
+ }
+ }
+ fn session(&self) -> Session {
+ Session::new(crate::bootstrap::session_resident(
+ self.root.path(),
+ self.client.clone(),
+ ))
+ }
+}
+impl Drop for Fixture {
+ fn drop(&mut self) {
+ self.server.abort();
+ }
+}
+async fn write(stream: &mut BufReader<tokio::net::UnixStream>, value: Value) {
+ let mut bytes = serde_json::to_vec(&value).unwrap();
+ bytes.push(b'\n');
+ stream.get_mut().write_all(&bytes).await.unwrap();
+}
+fn operation() -> OperationReferenceV1 {
+ OperationReferenceV1 {
+ operation_id: "operation-a".into(),
+ state: "succeeded".into(),
+ sequence: 1,
+ cancellable: false,
+ }
+}
+fn result(released: bool) -> Value {
+ json!({
+ "candidate": {"candidate_ref": "candidate/one", "candidate_revision": 1},
+ "approval_operation": operation(), "status": if released { "released" } else { "source_changed" },
+ "validation": if released { None } else { Some(json!({
+ "approval_operation": operation(), "validation_ref": "validation-a", "validation_revision": 1
+ })) }
+ })
+}
+fn submitted(session: &mut Session) -> SubscriptionCheckCompletion {
+ let digest = CanonicalDigest::of_bytes(b"accepted");
+ session.subscription_hint = Some(SubmittedOperation {
+ plan_id: "candidate/one".into(),
+ principal_kind: PrincipalKind::Desktop,
+ operation_kind: APPLY_SUBSCRIPTION_CHECK_OPERATION_V2.into(),
+ idempotency_key: "a".repeat(64),
+ accepted_digest: digest.clone(),
+ operation_id: None,
+ after_sequence: 0,
+ intent: None,
+ latest_edit_not_applied: false,
+ });
+ SubscriptionCheckCompletion {
+ owner: session.confirmation.owner(),
+ idempotency_key: "a".repeat(64),
+ accepted_digest: digest.clone(),
+ close_requested: session.subscription_close_requested.clone(),
+ outcome: SubscriptionCheckSubmission::Submitted(Box::new(Ok(MachineEnvelopeV2 {
+ schema_version: LOCAL_CONTROL_SCHEMA_V2,
+ request_id: Some("request-a".into()),
+ status: MachineStatus::Succeeded,
+ data: Some(ApplyResultV1 {
+ operation_id: "operation-a".into(),
+ accepted_digest: digest,
+ state: "succeeded".into(),
+ }),
+ operation: Some(operation()),
+ warnings: vec![],
+ next_actions: vec![],
+ error: None,
+ }))),
+ }
+}
+
+#[tokio::test]
+async fn close_before_operation_record_releases_late_completed_validation() {
+ let fixture = Fixture::new();
+ let mut session = fixture.session();
+ let completion = submitted(&mut session);
+ // The submitted request is in flight, but the close-time query cannot find A yet.
+ session.invalidate_confirmation();
+ session.close_subscription_check().await.unwrap();
+ assert_eq!(fixture.releases.load(Ordering::SeqCst), 0);
+ assert!(session.subscription_hint.is_some());
+ fixture.created.store(true, Ordering::SeqCst);
+ let sessions = tokio::sync::Mutex::new(Some(session));
+ complete_subscription_check(&sessions, completion)
+ .await
+ .unwrap();
+ assert_eq!(fixture.releases.load(Ordering::SeqCst), 1);
+ assert!(
+ sessions
+ .lock()
+ .await
+ .as_ref()
+ .unwrap()
+ .subscription_hint
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn replacement_session_rejects_completion_before_queries_or_hint_changes() {
+ let fixture = Fixture::new();
+ let mut old = fixture.session();
+ let completion = submitted(&mut old);
+ drop(old); // The host lock also belongs to exactly one scoped fixture Session.
+ let mut replacement = fixture.session();
+ let _ = submitted(&mut replacement);
+ replacement
+ .subscription_hint
+ .as_mut()
+ .unwrap()
+ .idempotency_key = "new-hint".into();
+ let sessions = tokio::sync::Mutex::new(Some(replacement));
+ let failure = complete_subscription_check(&sessions, completion)
+ .await
+ .unwrap_err();
+ assert!(matches!(failure, DesktopFailure::Native { code } if code == "CONFIRMATION_STALE"));
+ assert_eq!(fixture.calls.load(Ordering::SeqCst), 0);
+ assert_eq!(fixture.releases.load(Ordering::SeqCst), 0);
+ assert_eq!(
+ sessions
+ .lock()
+ .await
+ .as_ref()
+ .unwrap()
+ .subscription_hint
+ .as_ref()
+ .unwrap()
+ .idempotency_key,
+ "new-hint"
+ );
+}
diff --git a/apps/desktop/src-tauri/src/updates.rs b/apps/desktop/src-tauri/src/updates.rs
index cd0aca95..6188a1f2 100644
--- a/apps/desktop/src-tauri/src/updates.rs
+++ b/apps/desktop/src-tauri/src/updates.rs
@@ -39,6 +39,13 @@ impl PreparedUpdate {
Ok(())
}
}
+#[derive(Clone, Copy, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum UpdateRecovery {
+ ServiceAvailable,
+ StopPending,
+ RestartRequired,
+}
#[derive(Clone, Serialize)]
pub struct UpdateView {
current_version: String,
@@ -50,6 +57,7 @@ pub struct UpdateView {
error: Option<String>,
can_install: bool,
package_ready: bool,
+ recovery: Option<UpdateRecovery>,
}
struct UpdateInner {
view: UpdateView,
@@ -105,6 +113,7 @@ impl UpdateState {
error: None,
can_install: current_app.is_some(),
package_ready: false,
+ recovery: None,
},
prepared: None,
}),
@@ -144,6 +153,9 @@ impl Updates {
self.cancelled.store(false, Ordering::SeqCst);
inner.view.phase = phase.into();
inner.view.error = None;
+ if matches!(inner.view.recovery, Some(UpdateRecovery::ServiceAvailable)) {
+ inner.view.recovery = None;
+ }
Ok(inner.view.clone())
}
fn fail(&self, error: String) {
@@ -295,6 +307,7 @@ pub async fn update_install(
let prepared = inner.prepared.clone().ok_or("UPGRADE_INSTALL_NOT_READY")?;
inner.view.phase = "waiting".into();
inner.view.error = None;
+ inner.view.recovery = None;
state.0.cancelled.store(false, Ordering::SeqCst);
prepared
};
@@ -303,15 +316,8 @@ pub async fn update_install(
let handle = window.app_handle().clone();
tauri::async_runtime::spawn(async move {
if let Err(error) = install(&updates, &sessions, &handle, prepared).await {
- // Resume only while the owned daemon is still serving. An already requested
- // orderly shutdown must finish; it cannot be converted into a new live session.
- let _ = resident_call(&sessions, |r| {
- if !r.upgrade_stop_requested() {
- r.upgrade_status(UpgradeAction::Cancel)?;
- }
- Ok(())
- })
- .await;
+ let recovery = recover_precommit(&updates, &sessions, &handle).await;
+ let _ = updates.edit(|view| view.recovery = Some(recovery));
updates.fail(error);
}
});
@@ -382,10 +388,53 @@ async fn install(
}
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
}
+ let installer = tokio::task::spawn_blocking(move || installer::start(&handoff))
+ .await
+ .map_err(|_| "UPGRADE_INSTALLER_UNAVAILABLE")??;
+ // Preflight succeeded while the old service was alive. An uncommitted helper is
+ // reaped on every error; it cannot infer authorization from the Desktop disappearing.
resident_call(sessions, |r| r.stop_for_upgrade()).await?;
- tokio::task::spawn_blocking(move || installer::launch(&handoff))
+ tokio::task::spawn_blocking(move || installer.commit())
.await
- .map_err(|_| "UPGRADE_INSTALLER_FAILED")??;
+ .map_err(|_| "UPGRADE_INSTALLER_COMMIT_FAILED")??;
app.exit(0);
Ok(())
}
+
+async fn recover_precommit(
+ updates: &Updates,
+ sessions: &Sessions,
+ app: &tauri::AppHandle,
+) -> UpdateRecovery {
+ let Some(root) = updates.data_root.clone() else {
+ return UpdateRecovery::RestartRequired;
+ };
+ let Ok(executable) = std::env::current_exe() else {
+ return UpdateRecovery::RestartRequired;
+ };
+ let diagnostics = app.state::<crate::bridge::DiagnosticsState>().startup();
+ let handle = app.clone();
+ let mut session = sessions.clone().lock_owned().await;
+ let result = tokio::task::spawn_blocking(move || {
+ let current = session.as_mut().ok_or("RESIDENT_UNAVAILABLE")?;
+ if !current.resident.upgrade_stop_requested() {
+ current.resident.upgrade_status(UpgradeAction::Cancel)?;
+ } else {
+ crate::bridge::expire_window_confirmations(&handle, "main");
+ current.invalidate_confirmation();
+ let resident = current.resident.replacement_after_upgrade_stop(
+ &root,
+ &executable.with_file_name("hirouted"),
+ &diagnostics,
+ )?;
+ *session = Some(crate::session::Session::new(resident));
+ }
+ Ok::<_, String>(())
+ })
+ .await;
+ match result {
+ Ok(Ok(())) => UpdateRecovery::ServiceAvailable,
+ Ok(Err(code)) if code == "UPGRADE_STOP_PENDING" => UpdateRecovery::StopPending,
+ _ => UpdateRecovery::RestartRequired,
+ }
+}
diff --git a/apps/desktop/src-tauri/src/updates/installer.rs b/apps/desktop/src-tauri/src/updates/installer.rs
index e4d20c06..27b51d8e 100644
--- a/apps/desktop/src-tauri/src/updates/installer.rs
+++ b/apps/desktop/src-tauri/src/updates/installer.rs
@@ -26,15 +26,31 @@ struct Handoff {
}
fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
use std::os::unix::fs::OpenOptionsExt;
- let mut file = fs::OpenOptions::new()
- .write(true)
- .create_new(true)
- .mode(0o600)
- .open(path)
- .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
- file.write_all(bytes)
- .and_then(|_| file.sync_all())
- .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED".into())
+ let parent = path.parent().ok_or("UPGRADE_INSTALLER_WRITE_FAILED")?;
+ if fs::symlink_metadata(path).is_ok() {
+ return Err("UPGRADE_INSTALLER_WRITE_FAILED".into());
+ }
+ let temporary = parent.join(format!(".marker-{}.tmp", crate::random_id()?));
+ let result = (|| {
+ let mut file = fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(&temporary)
+ .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
+ file.write_all(bytes)
+ .and_then(|_| file.sync_all())
+ .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
+ // Readers must see the complete decision/ack, never a newly created empty file.
+ fs::rename(&temporary, path).map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
+ fs::File::open(parent)
+ .and_then(|file| file.sync_all())
+ .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED".into())
+ })();
+ if result.is_err() {
+ let _ = fs::remove_file(&temporary);
+ }
+ result
}
pub(super) fn prepare(root: &Path, update: &PreparedUpdate) -> Result<PathBuf, String> {
let id = crate::random_id()?;
@@ -69,77 +85,49 @@ pub(super) fn prepare(root: &Path, update: &PreparedUpdate) -> Result<PathBuf, S
.map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
Ok(path)
}
-pub(super) fn launch(path: &Path) -> Result<(), String> {
- let directory = path.parent().ok_or("UPGRADE_INSTALLER_INVALID")?;
- use std::os::unix::fs::OpenOptionsExt;
- let log = fs::OpenOptions::new()
- .write(true)
- .create_new(true)
- .mode(0o600)
- .open(directory.join("installer.log"))
- .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
- let mut child =
- Command::new(std::env::current_exe().map_err(|_| "UPGRADE_INSTALLER_UNAVAILABLE")?)
- .arg("--finish-upgrade")
- .arg(path)
- .stdin(Stdio::null())
- .stdout(Stdio::null())
- .stderr(log)
- .spawn()
- .map_err(|_| "UPGRADE_INSTALLER_UNAVAILABLE")?;
- let deadline = Instant::now() + Duration::from_secs(10);
- let private = PrivateDir::open_existing(directory).map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
- loop {
- if let Some(mut ack) = private
- .open_read("started")
- .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
- {
- if ack
- .read_prefix(64)
- .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
- == b"hiroute.upgrade-installer-started/v1\n"
- {
- return Ok(());
- }
- return Err("UPGRADE_INSTALLER_INVALID".into());
- }
- if child
- .try_wait()
- .map_err(|_| "UPGRADE_INSTALLER_FAILED")?
- .is_some()
- || Instant::now() >= deadline
- {
- return Err("UPGRADE_INSTALLER_FAILED".into());
- }
- std::thread::sleep(Duration::from_millis(20));
- }
-}
+mod control;
+pub(super) use control::start;
+
pub fn finish_update_if_requested() -> Option<Result<(), String>> {
let mut arguments = std::env::args_os().skip(1);
if arguments.next().as_deref() != Some(std::ffi::OsStr::new("--finish-upgrade")) {
return None;
}
- Some((|| {
+ let result = (|| {
let path = PathBuf::from(arguments.next().ok_or("UPGRADE_INSTALLER_INVALID")?);
if arguments.next().is_some() {
return Err("UPGRADE_INSTALLER_INVALID".into());
}
- // Invalid arguments never authorize creating files beside an arbitrary supplied path.
+ // Only a validated handoff authorizes writing a private result. Every failure,
+ // including load(), still reaches the parent-owned stderr below.
let record = load(&path)?;
let result = finish(&path, record);
if let Err(error) = &result {
- // Preserve a small, private result beside the handoff. No credentials or database
- // bytes are involved; the existing manual recovery procedure remains authoritative.
let _ = write_private(
&path.with_file_name("failed.json"),
&serde_json::to_vec(&serde_json::json!({"code":error})).unwrap(),
);
- eprintln!("{error}");
}
result
- })())
+ })();
+ if let Err(error) = &result {
+ eprintln!("{error}");
+ }
+ Some(result)
}
+
fn load(path: &Path) -> Result<Handoff, String> {
+ let executable =
+ fs::canonicalize(std::env::current_exe().map_err(|_| "UPGRADE_INSTALLER_INVALID")?)
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ let current = executable
+ .parent()
+ .and_then(Path::parent)
+ .and_then(Path::parent)
+ .ok_or("UPGRADE_INSTALLER_INVALID")?;
+ load_for_app(path, current)
+}
+fn load_for_app(path: &Path, current: &Path) -> Result<Handoff, String> {
if !path.is_absolute() || path.file_name() != Some("handoff.json".as_ref()) {
return Err("UPGRADE_INSTALLER_INVALID".into());
}
@@ -163,13 +151,7 @@ fn load(path: &Path) -> Result<Handoff, String> {
|| record.parent_pid == 0
|| !record.data_root.is_absolute()
|| !path.starts_with(record.data_root.join("updates"))
- || record.current
- != fs::canonicalize(std::env::current_exe().map_err(|_| "UPGRADE_INSTALLER_INVALID")?)
- .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
- .parent()
- .and_then(Path::parent)
- .and_then(Path::parent)
- .ok_or("UPGRADE_INSTALLER_INVALID")?
+ || record.current != current
|| record.old_identity.app_path != record.current
|| record.new_identity.app_path != record.staged
|| record.staged.file_name() != Some("HiRoute.app".as_ref())
@@ -189,8 +171,6 @@ fn load(path: &Path) -> Result<Handoff, String> {
return Err("UPGRADE_INSTALLER_INVALID".into());
}
PrivateDir::open_existing(&record.data_root).map_err(|_| "PRIVATE_PATH_INVALID")?;
- PrivateDir::open_existing(record.staged.parent().unwrap())
- .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
record.release.revision_prefix()?;
Ok(record)
}
@@ -198,10 +178,11 @@ fn finish(path: &Path, record: Handoff) -> Result<(), String> {
if nix::unistd::getppid().as_raw() as u32 != record.parent_pid {
return Err("UPGRADE_INSTALLER_PARENT_MISMATCH".into());
}
- write_private(
- &path.with_file_name("started"),
- b"hiroute.upgrade-installer-started/v1\n",
- )?;
+ verify_packages(&record)?;
+ let directory = PrivateDir::open_existing(path.parent().unwrap())
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ write_private(&path.with_file_name("started"), control::STARTED)?;
+ control::await_commit(&directory, record.parent_pid, Duration::from_secs(60))?;
let pid = nix::unistd::Pid::from_raw(record.parent_pid as i32);
let deadline = Instant::now() + Duration::from_secs(45);
loop {
@@ -216,17 +197,7 @@ fn finish(path: &Path, record: Handoff) -> Result<(), String> {
}
// A newly launched host wins the lock and prevents replacement. Never replace underneath it.
let _lock = crate::bootstrap::acquire_host_lock(&record.data_root)?;
- if hiroute_host_runtime::verify_desktop_app(&record.current, "ai.hiroute.desktop", None, None)?
- != record.old_identity
- || hiroute_host_runtime::verify_desktop_app(
- &record.staged,
- "ai.hiroute.desktop",
- Some(&record.release),
- None,
- )? != record.new_identity
- {
- return Err("UPGRADE_PACKAGE_CHANGED".into());
- }
+ verify_packages(&record)?;
fs::rename(&record.current, &record.previous).map_err(|_| "UPGRADE_REPLACE_FAILED")?;
if fs::rename(&record.staged, &record.current).is_err() {
// The data has not been touched. Restore the displaced App name if the second rename
@@ -264,3 +235,21 @@ fn finish(path: &Path, record: Handoff) -> Result<(), String> {
let _ = fs::remove_dir(record.staged.parent().unwrap());
Ok(())
}
+
+fn verify_packages(record: &Handoff) -> Result<(), String> {
+ if hiroute_host_runtime::verify_desktop_app(&record.current, "ai.hiroute.desktop", None, None)?
+ != record.old_identity
+ || hiroute_host_runtime::verify_desktop_app(
+ &record.staged,
+ "ai.hiroute.desktop",
+ Some(&record.release),
+ None,
+ )? != record.new_identity
+ {
+ return Err("UPGRADE_PACKAGE_CHANGED".into());
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/apps/desktop/src-tauri/src/updates/installer/control.rs b/apps/desktop/src-tauri/src/updates/installer/control.rs
new file mode 100644
index 00000000..14c91464
--- /dev/null
+++ b/apps/desktop/src-tauri/src/updates/installer/control.rs
@@ -0,0 +1,187 @@
+//! Parent-owned precommit helper. Only an explicit decision authorizes installation.
+use super::write_private;
+use hiroute_diagnostics::files::PrivateDir;
+use std::{
+ path::Path,
+ process::{Child, Command, ExitStatus, Stdio},
+ time::{Duration, Instant},
+};
+
+pub(super) const STARTED: &[u8] = b"hiroute.upgrade-installer-started/v1\n";
+const COMMIT: &[u8] = b"hiroute.upgrade-installer-decision/v1\ncommit\n";
+const CANCEL: &[u8] = b"hiroute.upgrade-installer-decision/v1\ncancel\n";
+
+pub(in crate::updates) struct Installer {
+ child: Child,
+ directory: PrivateDir,
+ committed: bool,
+}
+impl Installer {
+ pub(in crate::updates) fn commit(mut self) -> Result<(), String> {
+ if let Some(status) = self
+ .child
+ .try_wait()
+ .map_err(|_| "UPGRADE_INSTALLER_WAIT_FAILED")?
+ {
+ return Err(failure(&self.directory, status));
+ }
+ self.directory
+ .recheck_identity()
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ write_private(&self.directory.path().join("decision"), COMMIT)?;
+ self.committed = true;
+ Ok(())
+ }
+}
+impl Drop for Installer {
+ fn drop(&mut self) {
+ if !self.committed {
+ let _ = write_private(&self.directory.path().join("decision"), CANCEL);
+ // This is our precommit helper, never a daemon/Worker. It has no authorization
+ // to replace an App; reap it before returning control to the old service.
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+ }
+}
+pub(in crate::updates) fn start(path: &Path) -> Result<Installer, String> {
+ let mut command =
+ Command::new(std::env::current_exe().map_err(|_| "UPGRADE_INSTALLER_UNAVAILABLE")?);
+ command.arg("--finish-upgrade").arg(path);
+ start_command(path, command, Duration::from_secs(10))
+}
+fn start_command(
+ path: &Path,
+ mut command: Command,
+ timeout: Duration,
+) -> Result<Installer, String> {
+ let directory = PrivateDir::open_existing(path.parent().ok_or("UPGRADE_INSTALLER_INVALID")?)
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ use std::os::unix::fs::OpenOptionsExt;
+ let log = std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(directory.path().join("installer.log"))
+ .map_err(|_| "UPGRADE_INSTALLER_WRITE_FAILED")?;
+ let child = command
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(log)
+ .spawn()
+ .map_err(|_| "UPGRADE_INSTALLER_UNAVAILABLE")?;
+ let mut installer = Installer {
+ child,
+ directory,
+ committed: false,
+ };
+ let deadline = Instant::now() + timeout;
+ loop {
+ if let Some(status) = installer
+ .child
+ .try_wait()
+ .map_err(|_| "UPGRADE_INSTALLER_WAIT_FAILED")?
+ {
+ return Err(failure(&installer.directory, status));
+ }
+ if let Some(mut ack) = installer
+ .directory
+ .open_read("started")
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
+ {
+ if ack
+ .read_prefix(64)
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
+ == STARTED
+ {
+ return Ok(installer);
+ }
+ return Err("UPGRADE_INSTALLER_INVALID".into());
+ }
+ if Instant::now() >= deadline {
+ return Err("UPGRADE_INSTALLER_START_TIMEOUT".into());
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+}
+fn stable_code(code: &str) -> bool {
+ code.len() <= 96
+ && (code.starts_with("UPGRADE_")
+ || code.starts_with("PACKAGE_")
+ || code.starts_with("PRIVATE_"))
+ && code
+ .bytes()
+ .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')
+}
+fn failure(directory: &PrivateDir, status: ExitStatus) -> String {
+ #[derive(serde::Deserialize)]
+ #[serde(deny_unknown_fields)]
+ struct Failure {
+ code: String,
+ }
+ let read = |name: &str| -> Option<Vec<u8>> {
+ let mut file = directory.open_read(name).ok()??;
+ if file.len() > 512 {
+ return None;
+ }
+ let bytes = file.read_prefix(512).ok()?;
+ file.recheck().ok()?;
+ Some(bytes)
+ };
+ if let Some(value) =
+ read("failed.json").and_then(|bytes| serde_json::from_slice::<Failure>(&bytes).ok())
+ && stable_code(&value.code)
+ {
+ return value.code;
+ }
+ // load failures cannot authorize a result write beside an untrusted handoff. stderr
+ // was opened by this parent; accept only a closed code, never arbitrary output.
+ if let Some(code) = read("installer.log").and_then(|bytes| String::from_utf8(bytes).ok())
+ && stable_code(code.trim())
+ {
+ return code.trim().to_owned();
+ }
+ use std::os::unix::process::ExitStatusExt;
+ if status.signal().is_some() {
+ "UPGRADE_INSTALLER_TERMINATED".into()
+ } else {
+ "UPGRADE_INSTALLER_EXIT_FAILED".into()
+ }
+}
+pub(super) fn await_commit(
+ directory: &PrivateDir,
+ parent_pid: u32,
+ timeout: Duration,
+) -> Result<(), String> {
+ let deadline = Instant::now() + timeout;
+ loop {
+ if let Some(mut decision) = directory
+ .open_read("decision")
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?
+ {
+ let bytes = decision
+ .read_prefix(128)
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ decision
+ .recheck()
+ .map_err(|_| "UPGRADE_INSTALLER_INVALID")?;
+ return match bytes.as_slice() {
+ COMMIT => Ok(()),
+ CANCEL => Err("UPGRADE_INSTALLER_CANCELLED".into()),
+ _ => Err("UPGRADE_INSTALLER_DECISION_INVALID".into()),
+ };
+ }
+ match nix::sys::signal::kill(nix::unistd::Pid::from_raw(parent_pid as i32), None) {
+ Err(nix::errno::Errno::ESRCH) => return Err("UPGRADE_INSTALLER_COMMIT_REQUIRED".into()),
+ Err(_) => return Err("UPGRADE_INSTALLER_PARENT_UNKNOWN".into()),
+ Ok(()) => {}
+ }
+ if Instant::now() >= deadline {
+ return Err("UPGRADE_INSTALLER_COMMIT_TIMEOUT".into());
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/apps/desktop/src-tauri/src/updates/installer/control/tests.rs b/apps/desktop/src-tauri/src/updates/installer/control/tests.rs
new file mode 100644
index 00000000..3b524962
--- /dev/null
+++ b/apps/desktop/src-tauri/src/updates/installer/control/tests.rs
@@ -0,0 +1,217 @@
+use super::*;
+use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
+
+fn private_directory() -> tempfile::TempDir {
+ let directory = tempfile::tempdir().unwrap();
+ fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).unwrap();
+ directory
+}
+fn command(directory: &Path, mode: &str) -> Command {
+ let mut command = Command::new(std::env::current_exe().unwrap());
+ command
+ .args([
+ "--exact",
+ "updates::installer::control::tests::helper_process",
+ "--nocapture",
+ ])
+ .env("HIROUTE_UPDATER_TEST_DIRECTORY", directory)
+ .env("HIROUTE_UPDATER_TEST_MODE", mode);
+ command
+}
+fn start_test(directory: &Path, mode: &str) -> Result<Installer, String> {
+ start_command(
+ &directory.join("handoff.json"),
+ command(directory, mode),
+ Duration::from_secs(2),
+ )
+}
+fn gone(pid: u32) -> bool {
+ nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid as i32), None)
+ == Err(nix::errno::Errno::ESRCH)
+}
+fn wait_for(path: &Path) {
+ let deadline = Instant::now() + Duration::from_secs(3);
+ while !path.exists() {
+ assert!(
+ Instant::now() < deadline,
+ "missing helper result: {}",
+ path.display()
+ );
+ std::thread::sleep(Duration::from_millis(10));
+ }
+}
+
+// Real subprocesses exercise the parent's ownership and OS reaping, without an App
+// fixture pretending to prove a production package installation.
+#[test]
+fn helper_process() {
+ let Some(path) = std::env::var_os("HIROUTE_UPDATER_TEST_DIRECTORY") else {
+ return;
+ };
+ let path = PathBuf::from(path);
+ fs::write(path.join("pid"), std::process::id().to_string()).unwrap();
+ match std::env::var("HIROUTE_UPDATER_TEST_MODE").unwrap().as_str() {
+ "failure" => {
+ eprintln!("UPGRADE_PACKAGE_CHANGED");
+ std::process::exit(42);
+ }
+ "no_ack" => std::thread::sleep(Duration::from_secs(30)),
+ "bad_ack" => {
+ write_private(&path.join("started"), b"partial").unwrap();
+ std::thread::sleep(Duration::from_secs(30));
+ }
+ "exit_after_ack" => {
+ write_private(&path.join("started"), STARTED).unwrap();
+ std::process::exit(43);
+ }
+ "ready" => {
+ let directory = PrivateDir::open_existing(&path).unwrap();
+ write_private(&path.join("started"), STARTED).unwrap();
+ if await_commit(
+ &directory,
+ nix::unistd::getppid().as_raw() as u32,
+ Duration::from_secs(5),
+ )
+ .is_ok()
+ {
+ write_private(&path.join("authorized"), b"yes").unwrap();
+ }
+ }
+ mode => panic!("unexpected helper mode {mode}"),
+ }
+}
+
+#[test]
+fn preflight_failure_returns_concrete_code_and_reaps_child() {
+ let directory = private_directory();
+ assert_eq!(
+ start_test(directory.path(), "failure").err().unwrap(),
+ "UPGRADE_PACKAGE_CHANGED"
+ );
+ let pid = fs::read_to_string(directory.path().join("pid"))
+ .unwrap()
+ .parse()
+ .unwrap();
+ assert!(gone(pid));
+ assert!(!directory.path().join("authorized").exists());
+}
+
+#[test]
+fn readiness_does_not_authorize_installation_and_drop_reaps_helper() {
+ let directory = private_directory();
+ let installer = start_test(directory.path(), "ready").unwrap();
+ let pid = installer.child.id();
+ assert!(!directory.path().join("authorized").exists());
+ drop(installer);
+ assert_eq!(fs::read(directory.path().join("decision")).unwrap(), CANCEL);
+ assert!(gone(pid));
+ assert!(!directory.path().join("authorized").exists());
+}
+
+#[test]
+fn explicit_commit_detaches_the_authorized_helper() {
+ let directory = private_directory();
+ let installer = start_test(directory.path(), "ready").unwrap();
+ let pid = installer.child.id();
+ installer.commit().unwrap();
+ wait_for(&directory.path().join("authorized"));
+ // Installer intentionally detached the real child. waitpid prevents a zombie in
+ // this test process while retaining the same production detach semantics.
+ nix::sys::wait::waitpid(nix::unistd::Pid::from_raw(pid as i32), None).unwrap();
+ assert_eq!(fs::read(directory.path().join("decision")).unwrap(), COMMIT);
+}
+
+#[test]
+fn dead_helper_cannot_be_committed() {
+ let directory = private_directory();
+ // Publish an ACK then terminate; wait explicitly to make the race deterministic.
+ let directory_handle = PrivateDir::open_existing(directory.path()).unwrap();
+ let mut child = command(directory.path(), "exit_after_ack")
+ .stdout(Stdio::null())
+ .spawn()
+ .unwrap();
+ child.wait().unwrap();
+ let installer = Installer {
+ child,
+ directory: directory_handle,
+ committed: false,
+ };
+ assert_eq!(
+ installer.commit().unwrap_err(),
+ "UPGRADE_INSTALLER_EXIT_FAILED"
+ );
+ assert_eq!(fs::read(directory.path().join("decision")).unwrap(), CANCEL);
+}
+
+#[test]
+fn missing_or_malformed_ack_never_leaves_a_helper_alive() {
+ for mode in ["no_ack", "bad_ack"] {
+ let directory = private_directory();
+ let error = start_command(
+ &directory.path().join("handoff.json"),
+ command(directory.path(), mode),
+ Duration::from_millis(300),
+ )
+ .err()
+ .unwrap();
+ assert_eq!(
+ error,
+ if mode == "no_ack" {
+ "UPGRADE_INSTALLER_START_TIMEOUT"
+ } else {
+ "UPGRADE_INSTALLER_INVALID"
+ }
+ );
+ let pid = fs::read_to_string(directory.path().join("pid"))
+ .unwrap()
+ .parse()
+ .unwrap();
+ assert!(gone(pid));
+ assert!(!directory.path().join("authorized").exists());
+ }
+}
+
+#[test]
+fn parent_death_and_commit_timeout_are_not_authorization() {
+ let directory = private_directory();
+ let handle = PrivateDir::open_existing(directory.path()).unwrap();
+ let mut parent = Command::new("/usr/bin/true").spawn().unwrap();
+ let pid = parent.id();
+ parent.wait().unwrap();
+ assert_eq!(
+ await_commit(&handle, pid, Duration::from_secs(1)).unwrap_err(),
+ "UPGRADE_INSTALLER_COMMIT_REQUIRED"
+ );
+ assert_eq!(
+ await_commit(&handle, std::process::id(), Duration::from_millis(30)).unwrap_err(),
+ "UPGRADE_INSTALLER_COMMIT_TIMEOUT"
+ );
+ write_private(&directory.path().join("decision"), CANCEL).unwrap();
+ assert_eq!(
+ await_commit(&handle, std::process::id(), Duration::from_secs(1)).unwrap_err(),
+ "UPGRADE_INSTALLER_CANCELLED"
+ );
+}
+
+#[test]
+fn malformed_decisions_and_untrusted_error_output_are_closed() {
+ let directory = private_directory();
+ let handle = PrivateDir::open_existing(directory.path()).unwrap();
+ write_private(&directory.path().join("decision"), b"commit").unwrap();
+ assert_eq!(
+ await_commit(&handle, std::process::id(), Duration::from_secs(1)).unwrap_err(),
+ "UPGRADE_INSTALLER_DECISION_INVALID"
+ );
+ write_private(
+ &directory.path().join("failed.json"),
+ br#"{"code":"/private/data/secret"}"#,
+ )
+ .unwrap();
+ write_private(
+ &directory.path().join("installer.log"),
+ b"UPGRADE_UNKNOWN\nprivate text",
+ )
+ .unwrap();
+ let status = Command::new("/usr/bin/false").status().unwrap();
+ assert_eq!(failure(&handle, status), "UPGRADE_INSTALLER_EXIT_FAILED");
+}
diff --git a/apps/desktop/src-tauri/src/updates/installer/tests.rs b/apps/desktop/src-tauri/src/updates/installer/tests.rs
new file mode 100644
index 00000000..c8599290
--- /dev/null
+++ b/apps/desktop/src-tauri/src/updates/installer/tests.rs
@@ -0,0 +1,117 @@
+use super::*;
+use hiroute_host_runtime::ReleaseNotes;
+use std::{collections::BTreeMap, os::unix::fs::PermissionsExt};
+
+fn directory(path: &Path, mode: u32) {
+ fs::create_dir_all(path).unwrap();
+ fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();
+}
+fn fixture(root: &Path) -> (PathBuf, Handoff) {
+ let install = root.join("Applications");
+ directory(&install, 0o775);
+ let current = install.join("HiRoute.app");
+ let staged = install.join(".HiRoute-update-fixture/HiRoute.app");
+ directory(&current, 0o755);
+ directory(staged.parent().unwrap(), 0o700);
+ directory(&staged, 0o755);
+ let data_root = root.join("data");
+ directory(&data_root, 0o700);
+ let handoff = data_root.join("updates/install-fixture/handoff.json");
+ directory(handoff.parent().unwrap(), 0o700);
+ let identity = |app_path: PathBuf| DesktopPackageIdentity {
+ app_path,
+ version: "0.3.0".into(),
+ revision: "c".repeat(40),
+ architecture: "arm64".into(),
+ distribution: "self-signed".into(),
+ inventory_sha256: "a".repeat(64),
+ binaries: BTreeMap::new(),
+ };
+ let record = Handoff {
+ schema: "hiroute.desktop-upgrade-handoff/v1".into(),
+ parent_pid: std::process::id(),
+ old_identity: identity(current.clone()),
+ new_identity: identity(staged.clone()),
+ current,
+ staged,
+ previous: install.join(".HiRoute-previous-fixture.app"),
+ data_root,
+ release: DesktopRelease {
+ version: "0.3.0".into(),
+ notes: ReleaseNotes {
+ zh: String::new(),
+ en: String::new(),
+ },
+ architecture: "arm64".into(),
+ distribution: "self-signed".into(),
+ filename: "HiRoute-0.3.0-cccccccccccc-macos-arm64-trial.dmg".into(),
+ sha256: "b".repeat(64),
+ size: 1,
+ },
+ };
+ write_private(&handoff, &serde_json::to_vec(&record).unwrap()).unwrap();
+ (handoff, record)
+}
+
+#[test]
+fn admin_writable_install_parent_is_not_a_diagnostics_private_root() {
+ let temporary = tempfile::tempdir().unwrap();
+ let root = fs::canonicalize(temporary.path()).unwrap();
+ let (path, record) = fixture(&root);
+ // Frozen 0.2.0 rejected non-sticky ancestors with group/other write bits.
+ // Current diagnostics has a different policy; do not use it as an old reader.
+ let mode = fs::metadata(record.current.parent().unwrap())
+ .unwrap()
+ .permissions()
+ .mode();
+ assert_ne!(mode & 0o022, 0);
+ assert_eq!(mode & 0o1000, 0);
+ let loaded = load_for_app(&path, &record.current).unwrap();
+ assert_eq!(loaded.staged, record.staged);
+ assert_eq!(
+ fs::metadata(record.staged.parent().unwrap())
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o700
+ );
+}
+
+#[test]
+fn handoff_still_binds_the_current_app_and_refuses_symlinked_handoff() {
+ let temporary = tempfile::tempdir().unwrap();
+ let (path, record) = fixture(&fs::canonicalize(temporary.path()).unwrap());
+ assert_eq!(
+ load_for_app(&path, &record.staged).err().unwrap(),
+ "UPGRADE_INSTALLER_INVALID"
+ );
+ fs::write(&record.previous, b"existing backup").unwrap();
+ assert_eq!(
+ load_for_app(&path, &record.current).err().unwrap(),
+ "UPGRADE_INSTALLER_INVALID"
+ );
+ fs::remove_file(&record.previous).unwrap();
+ let saved = path.with_file_name("saved.json");
+ fs::rename(&path, &saved).unwrap();
+ std::os::unix::fs::symlink(&saved, &path).unwrap();
+ assert!(load_for_app(&path, &record.current).is_err());
+}
+
+#[test]
+fn markers_publish_complete_private_bytes_without_overwriting() {
+ let temporary = tempfile::tempdir().unwrap();
+ let marker = temporary.path().join("decision");
+ write_private(&marker, b"complete decision\n").unwrap();
+ assert_eq!(fs::read(&marker).unwrap(), b"complete decision\n");
+ assert_eq!(
+ fs::metadata(&marker).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ assert_eq!(
+ write_private(&marker, b"replacement").unwrap_err(),
+ "UPGRADE_INSTALLER_WRITE_FAILED"
+ );
+ assert_eq!(fs::read(&marker).unwrap(), b"complete decision\n");
+ assert_eq!(fs::read_dir(temporary.path()).unwrap().count(), 1);
+}
diff --git a/apps/desktop/src/features/UpdatesSettings.tsx b/apps/desktop/src/features/UpdatesSettings.tsx
index aa2a7761..edea1d7e 100644
--- a/apps/desktop/src/features/UpdatesSettings.tsx
+++ b/apps/desktop/src/features/UpdatesSettings.tsx
@@ -13,14 +13,19 @@ type UpdateView = {
error: string | null;
can_install: boolean;
package_ready: boolean;
+ recovery: 'service_available' | 'stop_pending' | 'restart_required' | null;
};
const busyPhases = ['checking', 'downloading', 'verifying', 'waiting', 'installing'];
-export function UpdatesSettings({ active, language }: { active: boolean; language: Language }) {
+export function UpdatesSettings({ active, language, onServiceChanged }: { active: boolean; language: Language; onServiceChanged: () => Promise<void> }) {
const text = (zh: string, en: string) => language === 'zh' ? zh : en;
const [view, setView] = useState<UpdateView | null>(null);
const [error, setError] = useState('');
const [actionPending, setActionPending] = useState(false);
const busy = view !== null && busyPhases.includes(view.phase);
+ const recovery = view?.recovery;
+ useEffect(() => {
+ if (recovery) void onServiceChanged();
+ }, [recovery, onServiceChanged]);
useEffect(() => {
if (!active && !busy) return;
let current = true;
@@ -50,17 +55,21 @@ export function UpdatesSettings({ active, language }: { active: boolean; languag
: text('从官网获取稳定版本', 'Stable releases from the official website');
const code = view?.error || error;
const canCancel = view && ['downloading', 'verifying', 'waiting'].includes(view.phase);
+ const restartRequired = recovery === 'stop_pending' || recovery === 'restart_required';
return <section className="settings-group"><h2>{text('版本升级', 'Updates')}</h2><div className="settings-list">
<div className="settings-row"><div className="settings-copy"><strong>HiRoute {view?.current_version ?? ''}</strong><span role="status">{status}</span></div>
<div className="worker-settings-control">
{!busy && <button className="btn" type="button" disabled={actionPending} onClick={() => void act('update_check')}>{text('检查更新', 'Check for updates')}</button>}
{view && !busy && view.available && !view.package_ready && <button className="btn" type="button" disabled={actionPending || !view.can_install} onClick={() => void act('update_download')}>{text('下载更新', 'Download update')}</button>}
- {view?.package_ready && !busy && <button className="btn" type="button" disabled={actionPending} onClick={() => void act('update_install')}>{text('安装并重启', 'Install and restart')}</button>}
+ {view?.package_ready && !busy && <button className="btn" type="button" disabled={actionPending || restartRequired} onClick={() => void act('update_install')}>{text('安装并重启', 'Install and restart')}</button>}
{canCancel && <button className="btn" type="button" onClick={() => void act('update_cancel')}>{text('取消升级', 'Cancel update')}</button>}
</div>
</div>
{view?.available && !busy && <div className="gateway-risk">{view.available.notes[language]}</div>}
{view?.phase === 'ready' && <div className="gateway-risk">{text('安装前会等待现有调用和任务结束。安装与首次启动期间,Agent 路由会暂时不可用;需要时可按备份目录中的说明恢复旧 App 和旧数据。', 'Installation waits for current calls and tasks. Agent routing is temporarily unavailable during installation and first startup. If needed, follow the backup instructions to restore the previous App and data.')}</div>}
+ {recovery === 'service_available' && <div className="gateway-risk">{text('升级未完成,旧版本服务已恢复,可继续使用或重试安装。', 'The upgrade did not complete. The previous service is available; continue using HiRoute or retry installation.')}</div>}
+ {recovery === 'stop_pending' && <div className="settings-inline-error" role="status">{text('服务仍在停止,尚未替换应用。请等待服务退出后,完全退出并重新打开 HiRoute。', 'The service is still stopping and the App has not been replaced. Wait for the service to exit, then fully quit and reopen HiRoute.')}</div>}
+ {recovery === 'restart_required' && <div className="settings-inline-error" role="status">{text('尚未替换应用,旧版本服务未能恢复。请完全退出并重新打开 HiRoute,并查看启动页的恢复说明。', 'The App has not been replaced, but the previous service could not be restored. Fully quit and reopen HiRoute and follow the startup recovery instructions.')}</div>}
{code && <div className="settings-inline-error" role="status">{text(`升级不可用(${code})。可重试检查,或从官网下载安装包并完全退出 HiRoute 后覆盖安装。`, `Update unavailable (${code}). Check again, or download from the official website and fully quit HiRoute before replacing the App.`)}</div>}
{view && !view.can_install && <div className="gateway-risk">{text('应用内安装需要使用完整的 HiRoute App。', 'In-app installation requires a complete HiRoute App.')}</div>}
</div></section>;
diff --git a/apps/desktop/src/features/home/state.ts b/apps/desktop/src/features/home/state.ts
index 43c5c5b9..e1da5bda 100644
--- a/apps/desktop/src/features/home/state.ts
+++ b/apps/desktop/src/features/home/state.ts
@@ -7,6 +7,7 @@ import type {
HomePlans,
HomeRead,
HomeReads,
+ HomeService,
HomeSubscriptionCheck,
} from './types';
@@ -62,6 +63,24 @@ export function visibleData<T>(read: HomeRead<T>): T | undefined {
return read.status === 'ready' ? read.data : read.previous;
}
+export function deriveHomeServiceStatus(read: HomeRead<HomeService>): {
+ state: 'ready' | 'read_only' | 'unavailable' | 'unknown';
+ operational: boolean;
+} {
+ if (read.status !== 'ready') {
+ return { state: read.status === 'error' ? 'unavailable' : 'unknown', operational: false };
+ }
+ const service = read.data;
+ const running = service.daemon === 'running'
+ && ['ready', 'empty', 'no_new_calls'].includes(service.gateway);
+ return {
+ state: service.daemon === 'read_only' ? 'read_only'
+ : service.daemon === 'unavailable' ? 'unavailable'
+ : running ? 'ready' : 'unknown',
+ operational: running && Boolean(service.recoveryReady),
+ };
+}
+
function configuredFacet(state: HomeFacetState): boolean {
return state !== 'unconfigured' && state !== 'unknown' && state !== 'unsupported';
}
diff --git a/apps/desktop/src/product/DesktopApp.tsx b/apps/desktop/src/product/DesktopApp.tsx
index 6521abd1..8a1a28b5 100644
--- a/apps/desktop/src/product/DesktopApp.tsx
+++ b/apps/desktop/src/product/DesktopApp.tsx
@@ -18,6 +18,7 @@ import {
import {
Home,
HomeNavigation,
+ deriveHomeServiceStatus,
visibleData,
type HomeAction,
type HomeNavigationItem,
@@ -156,7 +157,7 @@ export function DesktopApp() {
{ id: 'sessions', label: text.pages.sessions, icon: 'sessions' },
];
- const service = visibleData(home.reads.service);
+ const serviceStatus = deriveHomeServiceStatus(home.reads.service);
const startupFailure = home.startup?.state === 'failed' ? home.startup : null;
const upgradePhase = home.startup?.state === 'starting' ? home.startup.upgrade_phase : undefined;
const upgradePhaseText = upgradePhase ? ({
@@ -166,17 +167,13 @@ export function DesktopApp() {
validation: language === 'zh' ? '正在校验升级结果' : 'Verifying upgraded data',
service_recovery: language === 'zh' ? '正在恢复本机服务' : 'Restoring the local service',
})[upgradePhase] : undefined;
- const serviceLabel = service?.daemon === 'read_only'
- ? text.serviceReadOnly
- : service?.daemon === 'unavailable'
- ? text.serviceUnavailable
- : service?.daemon === 'running' && ['ready', 'empty', 'no_new_calls'].includes(service.gateway)
- ? text.serviceReady
- : text.serviceUnknown;
- const serviceReady = service?.daemon === 'running' && service.gateway === 'ready';
- const serviceOperational = service?.daemon === 'running'
- && Boolean(service.recoveryReady)
- && ['ready', 'empty', 'no_new_calls'].includes(service.gateway);
+ const serviceLabel = {
+ read_only: text.serviceReadOnly,
+ unavailable: text.serviceUnavailable,
+ ready: text.serviceReady,
+ unknown: text.serviceUnknown,
+ }[serviceStatus.state];
+ const serviceOperational = serviceStatus.operational;
const navigationLabel = serviceOperational
? language === 'zh' ? '仅在本机运行' : 'Running locally'
: serviceLabel;
@@ -748,6 +745,7 @@ export function DesktopApp() {
textScale={preferences.textScale}
serviceLabel={settingsServiceLabel}
serviceReady={serviceOperational}
+ onServiceChanged={home.refreshDesktop}
onLanguageChange={preferences.setLanguage}
onThemeChange={preferences.setTheme}
onTextScaleChange={preferences.setTextScale}
diff --git a/apps/desktop/src/product/SettingsPage.tsx b/apps/desktop/src/product/SettingsPage.tsx
index 936f8eb6..22978228 100644
--- a/apps/desktop/src/product/SettingsPage.tsx
+++ b/apps/desktop/src/product/SettingsPage.tsx
@@ -11,6 +11,7 @@ import { listenerApplyRequest, listenerScopeFromAddress, type GatewayListenerSco
type SettingsPageProps = {
active: boolean; language: Language; languagePreference: LanguagePreference; theme: ThemePreference; textScale: TextScale;
serviceLabel: string; serviceReady: boolean;
+ onServiceChanged: () => Promise<void>;
onLanguageChange: (language: LanguagePreference) => void;
onThemeChange: (theme: ThemePreference) => void;
onTextScaleChange: (scale: TextScale) => void;
@@ -194,7 +195,7 @@ export function SettingsPage(props: SettingsPageProps) {
</div></div></section>
<SubscriptionProxySettings active={props.active} language={props.language} />
<DiagnosticsSettings active={props.active} language={props.language} />
- <UpdatesSettings active={props.active} language={props.language} />
+ <UpdatesSettings active={props.active} language={props.language} onServiceChanged={props.onServiceChanged} />
<section className="settings-group"><h2>CLI</h2><div className="settings-list"><div className="settings-row">
<div className="settings-copy"><strong>{text('终端入口', 'Terminal entry')}</strong><span>{cliEntry === null
? text('正在检查 ~/.local/bin/hiroute', 'Checking ~/.local/bin/hiroute')
diff --git a/apps/desktop/tests/service-recovery.test.mjs b/apps/desktop/tests/service-recovery.test.mjs
new file mode 100644
index 00000000..8f124d45
--- /dev/null
+++ b/apps/desktop/tests/service-recovery.test.mjs
@@ -0,0 +1,33 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ beginDomainRead,
+ deriveHomeServiceStatus,
+ failDomainRead,
+ resolveDomainRead,
+ visibleData,
+} from '../src/features/home/state.ts';
+
+test('failed recovery refresh preserves previous data without claiming a healthy service', () => {
+ const running = { daemon: 'running', gateway: 'ready', recoveryReady: true };
+ let slot = { requestId: null, targetKey: 'desktop/local', read: { status: 'ready', data: running } };
+ assert.deepEqual(deriveHomeServiceStatus(slot.read), { state: 'ready', operational: true });
+ slot = beginDomainRead(slot, 'recovery/1', 'desktop/local');
+ assert.deepEqual(deriveHomeServiceStatus(slot.read), { state: 'unknown', operational: false });
+ slot = failDomainRead(slot, 'recovery/1', 'desktop/local', 'RESIDENT_UNAVAILABLE');
+ assert.deepEqual(visibleData(slot.read), running);
+ assert.deepEqual(deriveHomeServiceStatus(slot.read), { state: 'unavailable', operational: false });
+ slot = beginDomainRead(slot, 'recovery/2', 'desktop/local');
+ slot = resolveDomainRead(slot, 'recovery/2', 'desktop/local', running);
+ assert.deepEqual(deriveHomeServiceStatus(slot.read), { state: 'ready', operational: true });
+});
+
+test('current empty, read-only and unrecovered service facts retain their distinct availability', () => {
+ const read = data => ({ status: 'ready', data });
+ assert.deepEqual(deriveHomeServiceStatus(read({ daemon: 'running', gateway: 'empty', recoveryReady: true })),
+ { state: 'ready', operational: true });
+ assert.deepEqual(deriveHomeServiceStatus(read({ daemon: 'running', gateway: 'ready', recoveryReady: false })),
+ { state: 'ready', operational: false });
+ assert.deepEqual(deriveHomeServiceStatus(read({ daemon: 'read_only', gateway: 'ready', recoveryReady: true })),
+ { state: 'read_only', operational: false });
+});
diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.json
index ab2cae30..fc5ff43b 100644
--- a/contracts/compatibility-support.v1.json
+++ b/contracts/compatibility-support.v1.json
@@ -363,6 +363,7 @@
"hiroute.subscription-maintenance/v2",
"hiroute.subscription-proxy/v1",
"hiroute.system-status/v1",
+ "hiroute.upgrade-installer-decision/v1",
"hiroute.upgrade-installer-started/v1",
"hiroute.upgrade-source-backup/v1",
"hiroute.value-ledger-entry/v1",
@@ -908,13 +909,15 @@
"hiroute.upgrade-recovery-package",
"hiroute.upgrade-installer-started",
"hiroute.daemon-upgrade-progress",
- "hiroute.upgrade-recovery-catalog"
+ "hiroute.upgrade-recovery-catalog",
+ "hiroute.upgrade-installer-decision"
],
"current_contracts": [
"hiroute.website.releases/v2",
"hiroute.desktop-upgrade-handoff/v1",
"hiroute.upgrade-installer-started/v1",
- "hiroute.daemon-upgrade-progress/v1"
+ "hiroute.daemon-upgrade-progress/v1",
+ "hiroute.upgrade-installer-decision/v1"
],
"legacy_support": []
},
diff --git a/docs/code-map/README.md b/docs/code-map/README.md
index 79165e81..be128e29 100644
--- a/docs/code-map/README.md
+++ b/docs/code-map/README.md
@@ -28,6 +28,7 @@ results in the relevant run record.
| Delegate, read, cancel or continue a Worker task | [Worker lifecycle and native differences](worker-context.md#follow-a-task-through-its-owners) | [Delegation](../../tools/product-e2e/tests/worker_delegation.rs), [read/Continue](../../tools/product-e2e/tests/worker_read.rs) |
| Inspect sessions, content, cost and competence | [Observation owners](architecture.md#observation-and-conversation-boundaries), [decision attribution](decision-foundation.md#observation-and-public-consumers) | [Session queries](../../crates/observation/src/query_v2/sessions_tests.rs), [stage summaries](../../crates/observation/src/store/tests/plan_quality/summary.rs) |
| Manage the service through CLI or Desktop | [client-core](../../crates/client-core/src), [CLI](../../crates/cli/src), [Desktop host](../../apps/desktop/src-tauri/src), [daemon control](../../crates/daemon/src/control) | [Real control process](../../tools/product-e2e/tests/control_shell.rs), [Desktop test map](../../apps/desktop/tests/README.md) |
+| Upgrade Desktop and recover a failed installation | [Updater](../../apps/desktop/src-tauri/src/updates.rs), [installer handshake](../../apps/desktop/src-tauri/src/updates/installer.rs), [resident restart](../../apps/desktop/src-tauri/src/bootstrap.rs) | Preflight → orderly stop → explicit commit; [macOS installation and recovery](../macos-installation.md) |
| Build macOS / Linux release installers for either architecture | [Release candidate entry](../../scripts/build-release.py), [build and publication guide](../release-builds.md) | [Package-to-publication contract](../../scripts/test-build-release.py), [Linux ABI and installed-runtime gate](../../scripts/linux-release-baseline.json); final publishing remains in [release.yml](../../.github/workflows/release.yml) |
## Read across boundaries