Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(desktop): the host stops only its own Runtime, judged by presence (#2269)

Call White33ab001b8a11
diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock
index 7302a04a5..9db016573 100644
--- a/desktop/Cargo.lock
+++ b/desktop/Cargo.lock
@@ -263,6 +263,7 @@ dependencies = [
"tempfile",
"tokio",
"url",
+ "windows-sys 0.61.2",
]
[[package]]
diff --git a/desktop/runtime-host/src/bootstrap.rs b/desktop/runtime-host/src/bootstrap.rs
index cb360ea64..2fd097ee1 100644
--- a/desktop/runtime-host/src/bootstrap.rs
+++ b/desktop/runtime-host/src/bootstrap.rs
@@ -10,10 +10,8 @@ use std::time::Duration;
use tokio::time::{sleep, Instant};
-use crate::health::{HealthProbe, RuntimeReadiness};
-use crate::launcher::{
- LaunchError, LaunchedRuntime, ResolvedRuntimeLauncher, RuntimeLauncher, RuntimeRemovalState, StartupReceipt,
-};
+use crate::health::{HealthProbe, Presence};
+use crate::launcher::{CliOutcome, LaunchError, LaunchExit, LaunchedRuntime, ResolvedRuntimeLauncher, RuntimeLauncher};
use crate::origin::LoopbackOrigin;
use crate::status::{BootstrapNotice, BootstrapNoticeCode, BootstrapStatus};
@@ -34,8 +32,12 @@ pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(500);
/// shell does not give up before the Runtime itself would.
pub const DEFAULT_READY_TIMEOUT: Duration = Duration::from_secs(120);
-/// Per-request timeout for a single readiness probe.
-pub const DEFAULT_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
+/// Per-request timeout for a single presence probe.
+///
+/// It must outlast a refused loopback connect on Windows, which resends the SYN
+/// after the RST and refuses only after about 2 s. A shorter budget turns
+/// `Absent` into `Unknown`, and uninstall is then blocked.
+pub const DEFAULT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
const READY_TIMEOUT_CEILING_SECONDS: u64 = 600;
@@ -96,14 +98,54 @@ fn parse_timeout(raw: &str) -> Option<Duration> {
.then(|| Duration::from_secs(seconds))
}
+/// What started a bootstrap run.
+///
+/// Only the app's own launch, including the relaunch after an update, and the
+/// user's Try again may stop a predecessor Runtime to hand over. A shell
+/// recovering by itself never does: if two shells ever ran at once, each would
+/// otherwise keep stopping the other's Runtime.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BootstrapTrigger {
+ Launch,
+ Retry,
+ Recovery,
+}
+
+impl BootstrapTrigger {
+ fn allows_handover(self) -> bool {
+ matches!(self, Self::Launch | Self::Retry)
+ }
+}
+
+/// How removing the app-private Runtime for uninstall ended.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RemovalOutcome {
+ /// This app's Runtime was stopped and its private files are gone.
+ Removed,
+ /// The launcher owns no private files, so nothing was changed.
+ NotPrivate,
+ /// Something may still be running from or installing into the files: a
+ /// Runtime this app did not start, one still starting, or a backend
+ /// install. Every file was kept.
+ Kept,
+ /// The Runtime's CLI could not run, so nothing proved that its installs had
+ /// stopped, and nothing was seen running either. Every file was kept; only
+ /// the user can choose to delete them anyway.
+ Unverified,
+ /// Removal began and did not finish. Part of the files may remain.
+ Failed,
+}
+
/// Owns one Runtime origin for the lifetime of the shell process.
///
-/// A host may run `bootstrap` many times — once at startup and once per user
-/// retry. It never overlaps launch commands. Normal lifecycle never stops a
-/// Runtime; explicit replacement and uninstall use the Runtime's own graceful
-/// CLI. After a completed successful launch still fails the full readiness
-/// budget, a later retry may re-run the idempotent start command to repair
-/// missing components.
+/// A host may run `bootstrap` many times — once at startup and once per retry or
+/// recovery. It never overlaps launch commands. A Runtime is this shell's only
+/// while its Controller carries the shell's Runtime identity, and only such a
+/// Runtime is stopped by Stop, Quit, or uninstall. The one other Runtime the
+/// shell ever stops is a desktop predecessor with another identity, on handover.
+/// After a completed successful launch still fails the full readiness budget, a
+/// later retry may re-run the idempotent start command to repair missing
+/// components.
pub struct RuntimeHost {
probe: Arc<dyn HealthProbe>,
launcher: Arc<dyn RuntimeLauncher>,
@@ -111,40 +153,84 @@ pub struct RuntimeHost {
launched_runtime: Mutex<LaunchState>,
}
-struct LaunchAttempt {
- runtime: LaunchedRuntime,
- launcher: Arc<dyn ResolvedRuntimeLauncher>,
+/// What the last successful bootstrap run adopted: the monitor's baseline.
+#[derive(Clone)]
+struct Adoption {
+ presence: Presence,
+ launcher: Option<Arc<dyn ResolvedRuntimeLauncher>>,
}
#[derive(Default)]
struct LaunchState {
- attempt: Option<LaunchAttempt>,
- ownership: Option<(Arc<dyn ResolvedRuntimeLauncher>, StartupReceipt)>,
- /// The shell has evidence that a Runtime may still be alive, without
- /// necessarily having scoped stop authority for it.
+ attempt: Option<LaunchedRuntime>,
+ adoption: Option<Adoption>,
+ /// The launcher whose Runtime identity the served Controller last carried.
+ /// It is the only stop authority, and it is re-read from every probe.
+ owner: Option<Arc<dyn ResolvedRuntimeLauncher>>,
+ /// The shell has evidence that a Runtime may still be alive, whether or not
+ /// it is this shell's.
runtime_may_be_running: bool,
stopping: bool,
+ /// Advances when a bootstrap run begins and when a stop or removal ends. A
+ /// probe records what it saw only while the epoch it was sent in is still
+ /// current, so one that a new run or a stop overtook cannot rewrite who
+ /// owns the origin.
+ epoch: u64,
}
impl LaunchState {
- fn capture_ownership(&mut self) {
- if let Some(attempt) = &self.attempt {
- if let Some(receipt) = attempt.runtime.watch.owned_receipt() {
- self.ownership = Some((attempt.launcher.clone(), receipt.clone()));
+ /// Records who serves the origin now, for a probe sent in `epoch`. An
+ /// unprovable probe keeps the last owner: a slow `/ready` is not evidence
+ /// that the Runtime changed hands.
+ fn observe(&mut self, epoch: u64, presence: &Presence, launcher: Option<&Arc<dyn ResolvedRuntimeLauncher>>) {
+ if self.stopping || self.epoch != epoch {
+ return;
+ }
+ match presence {
+ Presence::Mine { .. } => {
+ self.owner = launcher.cloned();
self.runtime_may_be_running = true;
}
+ Presence::Unknown => {}
+ Presence::Foreign { .. } | Presence::Unmanaged | Presence::Absent => self.owner = None,
}
}
+ fn launch_pending(&self) -> bool {
+ self.attempt.as_ref().is_some_and(|attempt| attempt.watch.pending())
+ }
+
+ /// Starts a bootstrap run: the last adoption no longer stands, and no probe
+ /// sent before now may record what it saw. Returns the run's epoch.
+ fn begin_run(&mut self) -> u64 {
+ self.adoption = None;
+ self.epoch += 1;
+ self.epoch
+ }
+
+ /// Forgets the Runtime a stop or removal ended. The fence stays up until
+ /// the caller finishes, and the epoch is kept so no earlier probe can
+ /// match it again.
+ fn forget(&mut self) {
+ *self = LaunchState {
+ stopping: self.stopping,
+ epoch: self.epoch,
+ ..LaunchState::default()
+ };
+ }
+
+ /// Ends a stop or removal. A probe still in flight saw the Runtime from
+ /// before it, so it may no longer record what it saw.
+ fn finish_stopping(&mut self) {
+ self.stopping = false;
+ self.epoch += 1;
+ }
+
fn retain_completed_attempt_liveness(&mut self) {
- if self
- .attempt
- .as_ref()
- .is_some_and(|attempt| attempt.runtime.watch.succeeded())
- {
- // A successful helper may have started a Runtime even when the
- // receipt is reused or absent. Completion is not proof of process
- // absence, so releasing the retry slot must retain this fence.
+ if self.attempt.as_ref().is_some_and(|attempt| attempt.watch.succeeded()) {
+ // A successful helper may have started or adopted a Runtime.
+ // Completion is not proof of process absence, so releasing the
+ // retry slot must retain this fence.
self.runtime_may_be_running = true;
}
}
@@ -169,62 +255,79 @@ impl RuntimeHost {
self.launched_runtime().attempt.is_some()
}
+ /// Whether the served Controller last carried this shell's Runtime identity.
pub fn has_owned_runtime(&self) -> bool {
- self.launched_runtime().ownership.is_some()
+ self.launched_runtime().owner.is_some()
}
- pub async fn stop_owned_runtime(&self) -> Result<(), LaunchError> {
- let (launcher, receipt) = {
+ /// Stops this shell's Runtime, scoped to its identity, for Stop and Quit.
+ ///
+ /// `Refused` with `not_owned` means the shell has no Runtime to stop, and
+ /// `Failed` with `launch_pending` that a start or stop is still running.
+ /// Neither runs the CLI.
+ pub async fn stop_owned_runtime(&self) -> CliOutcome {
+ let (launcher, runtime_id) = {
let mut state = self.launched_runtime();
- let ownership = state.ownership.clone().ok_or(LaunchError::NotOwned)?;
- if state.stopping
- || state
- .attempt
- .as_ref()
- .is_some_and(|attempt| !attempt.runtime.watch.succeeded() && !attempt.runtime.watch.failed())
- {
- return Err(LaunchError::RuntimeStop);
+ let Some((owner, runtime_id)) = state
+ .owner
+ .clone()
+ .and_then(|owner| Some((owner.clone(), owner.expected_runtime_id()?.to_owned())))
+ else {
+ return CliOutcome::Refused {
+ reason: "not_owned".to_owned(),
+ };
+ };
+ if state.stopping || state.launch_pending() {
+ return CliOutcome::Failed {
+ part: "launch_pending".to_owned(),
+ };
}
state.stopping = true;
- ownership
+ (owner, runtime_id)
};
- let stopping = launcher.clone();
- let result = tokio::task::spawn_blocking(move || stopping.stop(&receipt))
+ let outcome = tokio::task::spawn_blocking(move || launcher.stop(&runtime_id))
.await
- .map_err(|_| LaunchError::RuntimeStop)
- .and_then(|result| result);
+ .unwrap_or_else(|_| CliOutcome::Failed {
+ part: "unknown".to_owned(),
+ });
let mut state = self.launched_runtime();
- if state
- .ownership
- .as_ref()
- .is_some_and(|(owner, _)| Arc::ptr_eq(owner, &launcher))
- {
- if result.is_ok() {
- *state = LaunchState::default();
- } else if matches!(result, Err(LaunchError::OwnershipLost)) {
- // Refusal revokes the receipt, but does not prove that the
- // replacement Runtime is gone. Retain the uninstall fence.
+ match &outcome {
+ CliOutcome::Completed => state.forget(),
+ CliOutcome::Refused { .. } => {
+ // The service now carries another identity. That revokes stop
+ // authority but does not prove this shell's Runtime is gone, so
+ // the uninstall fence stays.
+ state.retain_completed_attempt_liveness();
state.attempt = None;
- state.ownership = None;
- state.stopping = false;
- } else {
- state.stopping = false;
+ state.owner = None;
}
+ CliOutcome::Failed { .. } | CliOutcome::Unrunnable => {}
}
- result
+ state.finish_stopping();
+ outcome
}
- /// Probes the exact validated origin using the same readiness contract as bootstrap.
- pub async fn is_ready(&self, origin: &LoopbackOrigin) -> bool {
- self.probe.is_healthy(origin).await
+ /// Whether the origin is still served by the Runtime the last bootstrap
+ /// adopted, judged by the same presence contract. Every probe also records
+ /// who owns the origin now, unless a bootstrap run began or a stop or
+ /// removal ended while it was in flight.
+ pub async fn is_serving(&self, origin: &LoopbackOrigin) -> bool {
+ let (adoption, epoch) = {
+ let state = self.launched_runtime();
+ let Some(adoption) = state.adoption.clone() else {
+ return false;
+ };
+ (adoption, state.epoch)
+ };
+ let presence = self.observe_presence(epoch, origin, adoption.launcher.as_ref()).await;
+ presence == adoption.presence
}
/// Releases only completed helper retry state after readiness loss.
///
/// Readiness loss is not process-loss evidence. A pending helper remains
- /// retained so recovery cannot overlap it, and a valid started receipt
- /// remains scoped stop authority. This transition never changes stopping
- /// state or clears the liveness fence.
+ /// retained so recovery cannot overlap it. This transition never changes
+ /// stopping state or clears the liveness fence.
pub fn release_after_readiness_loss(&self) {
let mut state = self.launched_runtime();
if state.stopping {
@@ -233,47 +336,60 @@ impl RuntimeHost {
if state
.attempt
.as_ref()
- .is_some_and(|attempt| attempt.runtime.watch.succeeded() || attempt.runtime.watch.failed())
+ .is_some_and(|attempt| attempt.watch.succeeded() || attempt.watch.failed())
{
state.retain_completed_attempt_liveness();
state.attempt = None;
}
}
- /// Gracefully stops and removes an app-private Runtime owned by this host.
+ /// Stops this app's Runtime and removes its private files, for uninstall.
///
- /// Installed/user-managed launchers return `false` and are never modified.
- pub async fn remove_private_runtime(&self, active_origin: Option<&LoopbackOrigin>) -> Result<bool, LaunchError> {
- let liveness_uncertain = {
- let state = self.launched_runtime();
- state.runtime_may_be_running || state.attempt.is_some()
- };
- // A receipt authorizes only receipt-scoped stop, never the launcher's
- // unscoped managed removal. Unavailable readiness remains unknown until
- // a successful scoped stop clears local liveness evidence.
- let state = match active_origin {
- Some(origin) => match self.probe.readiness(origin).await {
- Some(readiness) if readiness.desktop_ui_runtime_id.is_some() => RuntimeRemovalState::Unknown,
- Some(readiness) if readiness.desktop_runtime_id.is_some() => RuntimeRemovalState::Managed,
- Some(_) if liveness_uncertain => RuntimeRemovalState::Unknown,
- Some(_) => RuntimeRemovalState::External,
- None => RuntimeRemovalState::Unknown,
- },
- None if liveness_uncertain => RuntimeRemovalState::Unknown,
- None => RuntimeRemovalState::Inactive,
- };
- let launcher = self.launcher.clone();
- let removed = tokio::task::spawn_blocking(move || launcher.remove_private_runtime(state))
- .await
- .map_err(|_| LaunchError::RuntimeRemoval)??;
- if removed {
- *self.launched_runtime() = LaunchState::default();
+ /// Proceeds only while the origin is served by this app's Runtime or by
+ /// nothing, and only after the Runtime's own CLI stopped it and deleted the
+ /// backend root under every install claim. Installed and user-managed
+ /// launchers are never modified.
+ pub async fn remove_private_runtime(&self, active_origin: Option<&LoopbackOrigin>) -> RemovalOutcome {
+ if !self.launcher.owns_private_files() {
+ return RemovalOutcome::NotPrivate;
+ }
+ if !self.begin_removal() {
+ return RemovalOutcome::Kept;
}
- Ok(removed)
+ let outcome = self.remove_verified(active_origin).await;
+ self.finish_removal(outcome);
+ outcome
+ }
+
+ /// Deletes the private files without the Runtime's confirmation, after the
+ /// user chose "Delete anyway" for [`RemovalOutcome::Unverified`].
+ ///
+ /// The origin is checked again first: anything answering there now keeps
+ /// every file.
+ pub async fn remove_unverified_private_runtime(&self, active_origin: Option<&LoopbackOrigin>) -> RemovalOutcome {
+ if !self.launcher.owns_private_files() {
+ return RemovalOutcome::NotPrivate;
+ }
+ if !self.begin_removal() {
+ return RemovalOutcome::Kept;
+ }
+ let (_, presence) = self.removal_presence(active_origin).await;
+ let outcome = if presence == Presence::Absent {
+ let launcher = self.launcher.clone();
+ match tokio::task::spawn_blocking(move || launcher.remove_unverified_private_files()).await {
+ Ok(Ok(())) => RemovalOutcome::Removed,
+ _ => RemovalOutcome::Failed,
+ }
+ } else {
+ RemovalOutcome::Kept
+ };
+ self.finish_removal(outcome);
+ outcome
}
/// Runs the state machine once and returns its terminal status.
- pub async fn bootstrap(&self, sink: &dyn StatusSink) -> BootstrapStatus {
+ pub async fn bootstrap(&self, sink: &dyn StatusSink, trigger: BootstrapTrigger) -> BootstrapStatus {
+ let run = self.launched_runtime().begin_run();
let (origin, resolved_launcher) = match self.resolve_origin().await {
Ok(resolved) => resolved,
Err(error) => {
@@ -283,85 +399,64 @@ impl RuntimeHost {
)
}
};
+ let identified = resolved_launcher
+ .as_ref()
+ .is_some_and(|launcher| launcher.expected_runtime_id().is_some());
let mut attempt = 1;
- let mut handover_performed = false;
publish(sink, BootstrapStatus::probing(&origin, attempt));
- // External Runtimes and the same desktop Runtime are adopted. A
- // desktop-managed predecessor is stopped through its own graceful CLI
- // before the successor starts.
- if let Some(readiness) = self.probe.readiness(&origin).await {
- let needs_handover = resolved_launcher
- .as_ref()
- .is_some_and(|launcher| launcher.requires_handover(&readiness));
- if needs_handover {
- if let Err(error) = handover(resolved_launcher.as_ref().expect("checked launcher").clone()).await {
- return publish(
+ // This app's Runtime and any Runtime that is not a desktop predecessor
+ // are adopted. A predecessor with another desktop identity is replaced
+ // only by this app's `vibe start`, and only when this run may hand over.
+ let presence = self.observe_presence(run, &origin, resolved_launcher.as_ref()).await;
+ match presence {
+ Presence::Mine { ready: true } | Presence::Unmanaged => {
+ return self
+ .adopt(
sink,
- BootstrapStatus::failed(
- &origin,
- attempt,
- BootstrapNotice::new(error.notice_code()),
- error.is_retryable(),
- ),
- );
- }
- handover_performed = true;
- } else {
- cleanup_if_current(resolved_launcher.as_ref(), &readiness).await;
- return publish(
- sink,
- BootstrapStatus::ready(&origin, attempt, BootstrapNoticeCode::Adopted),
- );
+ &origin,
+ attempt,
+ presence,
+ resolved_launcher.as_ref(),
+ BootstrapNoticeCode::Adopted,
+ )
+ .await;
}
- }
- // `/ready` rejects a UI/Controller pair with different private Runtime
- // identities. That is intentionally not readiness, but the exact
- // mismatch response still authorizes the bundled successor to stop the
- // superseded desktop-managed service before launching.
- if !handover_performed
- && self
- .probe
- .mismatched_runtime_identity(&origin)
- .await
- .is_some_and(|identity| identity.desktop_runtime_id.is_some())
- && resolved_launcher
- .as_ref()
- .is_some_and(|launcher| launcher.expected_runtime_id().is_some())
- {
- if let Err(error) = handover(resolved_launcher.as_ref().expect("checked launcher").clone()).await {
- return publish(
- sink,
- BootstrapStatus::failed(
+ Presence::Foreign { ready: true, .. } if !identified => {
+ return self
+ .adopt(
+ sink,
&origin,
attempt,
- BootstrapNotice::new(error.notice_code()),
- error.is_retryable(),
- ),
- );
+ presence,
+ resolved_launcher.as_ref(),
+ BootstrapNoticeCode::Adopted,
+ )
+ .await;
+ }
+ Presence::Foreign { .. } if identified && !trigger.allows_handover() => {
+ return publish(sink, ownership_lost(&origin, attempt));
}
- handover_performed = true;
+ // A predecessor to hand over, starting, not provable, or nothing
+ // there. `vibe start` is idempotent and decides for itself whether
+ // a service already runs, and whether it may replace a predecessor.
+ _ => {}
}
// A launcher may report its non-zero exit after an earlier bootstrap
// timed out. Re-check the retained watch before deciding this run is
// already waiting on a viable launch.
- if self.clear_failed_launch() {
+ if let Some(code) = self.clear_failed_launch() {
return publish(
sink,
- BootstrapStatus::failed(
- &origin,
- attempt,
- BootstrapNotice::new(BootstrapNoticeCode::LauncherExited),
- true,
- ),
+ BootstrapStatus::failed(&origin, attempt, BootstrapNotice::new(code), true),
);
}
// A development override points at another local Runtime and is treated
// as externally managed. The shell must not start a differently
// configured default Runtime and then wait on the override forever.
- if resolved_launcher.is_none() {
+ let Some(launcher) = resolved_launcher.clone() else {
return publish(
sink,
BootstrapStatus::failed(
@@ -371,11 +466,11 @@ impl RuntimeHost {
true,
),
);
- }
+ };
// The lock makes the decision and launch atomic, so concurrent runs
// cannot both start the Runtime.
- if let Err(error) = self.launch_if_needed(resolved_launcher.clone()) {
+ if let Err(error) = self.launch_if_needed(launcher.clone(), trigger.allows_handover()) {
return publish(
sink,
BootstrapStatus::failed(
@@ -389,88 +484,67 @@ impl RuntimeHost {
publish(sink, BootstrapStatus::starting(&origin, attempt));
- let mut deadline = Instant::now() + self.settings.ready_timeout;
+ let deadline = Instant::now() + self.settings.ready_timeout;
while Instant::now() < deadline {
sleep(self.settings.poll_interval).await;
attempt += 1;
- let readiness = self.probe.readiness(&origin).await;
- let mut needs_polling_handover = false;
- if let Some(readiness) = readiness {
- if readiness_matches_launched_runtime(resolved_launcher.as_ref(), &readiness) {
- cleanup_if_current(resolved_launcher.as_ref(), &readiness).await;
- return publish(
- sink,
- BootstrapStatus::ready(
+ // Read before the probe, so a predecessor judged below was seen
+ // after this app's helper had exited.
+ let settled = !self.launched_runtime().launch_pending();
+ let presence = self.observe_presence(run, &origin, Some(&launcher)).await;
+ match presence {
+ Presence::Mine { ready: true } => {
+ return self
+ .adopt(
+ sink,
&origin,
attempt,
- if self.has_owned_runtime() {
- BootstrapNoticeCode::Ready
- } else {
- BootstrapNoticeCode::Adopted
- },
- ),
- );
+ presence,
+ Some(&launcher),
+ BootstrapNoticeCode::Ready,
+ )
+ .await;
}
- needs_polling_handover = !handover_performed
- && resolved_launcher
- .as_ref()
- .is_some_and(|launcher| launcher.requires_handover(&readiness));
- } else if !handover_performed {
- needs_polling_handover = self
- .probe
- .mismatched_runtime_identity(&origin)
- .await
- .is_some_and(|identity| identity.desktop_runtime_id.is_some())
- && resolved_launcher
- .as_ref()
- .is_some_and(|launcher| launcher.expected_runtime_id().is_some());
- }
- if needs_polling_handover {
- let launcher = resolved_launcher
- .as_ref()
- .expect("handover requires a launcher")
- .clone();
- if let Err(error) = handover(launcher).await {
- return publish(
- sink,
- BootstrapStatus::failed(
+ Presence::Unmanaged => {
+ return self
+ .adopt(
+ sink,
&origin,
attempt,
- BootstrapNotice::new(error.notice_code()),
- error.is_retryable(),
- ),
- );
+ presence,
+ Some(&launcher),
+ BootstrapNoticeCode::Adopted,
+ )
+ .await;
}
- handover_performed = true;
- *self.launched_runtime() = LaunchState::default();
- if let Err(error) = self.launch_if_needed(resolved_launcher.clone()) {
- return publish(
- sink,
- BootstrapStatus::failed(
+ Presence::Foreign { ready: true, .. } if !identified => {
+ return self
+ .adopt(
+ sink,
&origin,
attempt,
- BootstrapNotice::new(error.notice_code()),
- error.is_retryable(),
- ),
- );
+ presence,
+ Some(&launcher),
+ BootstrapNoticeCode::Adopted,
+ )
+ .await;
}
- // Handover may legitimately spend most of the original startup
- // budget. The newly launched successor gets its own full window.
- deadline = Instant::now() + self.settings.ready_timeout;
+ _ => {}
}
// A launcher that exited non-zero started nothing, so the remaining
// wait would be spent polling an address that will never answer.
- if self.clear_failed_launch() {
+ // Its exit also says whether it declined or failed a handover.
+ if let Some(code) = self.clear_failed_launch() {
return publish(
sink,
- BootstrapStatus::failed(
- &origin,
- attempt,
- BootstrapNotice::new(BootstrapNoticeCode::LauncherExited),
- true,
- ),
+ BootstrapStatus::failed(&origin, attempt, BootstrapNotice::new(code), true),
);
}
+ // While the helper runs, a predecessor may be the one it is
+ // replacing. Once it has exited, one still serving was not replaced.
+ if identified && settled && matches!(presence, Presence::Foreign { .. }) {
+ return publish(sink, ownership_lost(&origin, attempt));
+ }
publish(sink, BootstrapStatus::starting(&origin, attempt));
}
@@ -505,68 +579,175 @@ impl RuntimeHost {
.map_err(|_| LaunchError::EndpointOutput)?
}
+ /// Probes the origin, and records the answer only if `epoch`, read when
+ /// the probe was sent, is still current.
+ async fn observe_presence(
+ &self,
+ epoch: u64,
+ origin: &LoopbackOrigin,
+ launcher: Option<&Arc<dyn ResolvedRuntimeLauncher>>,
+ ) -> Presence {
+ let expected = launcher.and_then(|launcher| launcher.expected_runtime_id());
+ let presence = self.probe.presence(origin, expected).await;
+ self.launched_runtime().observe(epoch, &presence, launcher);
+ presence
+ }
+
+ async fn adopt(
+ &self,
+ sink: &dyn StatusSink,
+ origin: &LoopbackOrigin,
+ attempt: u32,
+ presence: Presence,
+ launcher: Option<&Arc<dyn ResolvedRuntimeLauncher>>,
+ notice: BootstrapNoticeCode,
+ ) -> BootstrapStatus {
+ let mine = matches!(presence, Presence::Mine { .. });
+ self.launched_runtime().adoption = Some(Adoption {
+ presence,
+ launcher: launcher.cloned(),
+ });
+ // Only this app's own Runtime proves which bundle is current.
+ if let Some(launcher) = launcher.filter(|_| mine).cloned() {
+ let _ = tokio::task::spawn_blocking(move || launcher.prune_superseded()).await;
+ }
+ publish(sink, BootstrapStatus::ready(origin, attempt, notice))
+ }
+
+ /// Fences removal against a start or stop that is still running.
+ fn begin_removal(&self) -> bool {
+ let mut state = self.launched_runtime();
+ if state.stopping || state.launch_pending() {
+ return false;
+ }
+ state.stopping = true;
+ true
+ }
+
+ fn finish_removal(&self, outcome: RemovalOutcome) {
+ let mut state = self.launched_runtime();
+ if outcome == RemovalOutcome::Removed {
+ state.forget();
+ }
+ state.finish_stopping();
+ }
+
+ async fn remove_verified(&self, active_origin: Option<&LoopbackOrigin>) -> RemovalOutcome {
+ let (resolved, presence) = self.removal_presence(active_origin).await;
+ if !matches!(presence, Presence::Mine { .. } | Presence::Absent) {
+ return RemovalOutcome::Kept;
+ }
+ let Some(resolved) = resolved else {
+ return RemovalOutcome::Unverified;
+ };
+ let Some(runtime_id) = resolved.expected_runtime_id().map(str::to_owned) else {
+ return RemovalOutcome::Kept;
+ };
+ let stopping = resolved.clone();
+ match run_blocking(move || stopping.stop(&runtime_id)).await {
+ CliOutcome::Completed => {}
+ CliOutcome::Unrunnable if presence == Presence::Absent => return RemovalOutcome::Unverified,
+ _ => return RemovalOutcome::Kept,
+ }
+ self.launched_runtime().forget();
+ match run_blocking(move || resolved.remove_backends()).await {
+ CliOutcome::Completed => {}
+ CliOutcome::Refused { .. } => return RemovalOutcome::Kept,
+ CliOutcome::Failed { .. } => return RemovalOutcome::Failed,
+ CliOutcome::Unrunnable => return RemovalOutcome::Unverified,
+ }
+ let launcher = self.launcher.clone();
+ match tokio::task::spawn_blocking(move || launcher.remove_private_files()).await {
+ Ok(Ok(())) => RemovalOutcome::Removed,
+ _ => RemovalOutcome::Failed,
+ }
+ }
+
+ /// Who serves the origin, judged against the bundle's identity. Without an
+ /// origin to ask, any sign of a Runtime this shell started is enough to be
+ /// unsure.
+ async fn removal_presence(
+ &self,
+ active_origin: Option<&LoopbackOrigin>,
+ ) -> (Option<Arc<dyn ResolvedRuntimeLauncher>>, Presence) {
+ let launcher = self.launcher.clone();
+ let resolved = tokio::task::spawn_blocking(move || launcher.resolve())
+ .await
+ .ok()
+ .and_then(Result::ok);
+ let origin = match (active_origin, &resolved) {
+ (Some(origin), _) => Some(origin.clone()),
+ (None, Some(resolved)) => {
+ let resolved = resolved.clone();
+ tokio::task::spawn_blocking(move || resolved.endpoint())
+ .await
+ .ok()
+ .and_then(Result::ok)
+ }
+ (None, None) => None,
+ };
+ let presence = match origin {
+ Some(origin) => {
+ let expected = resolved.as_ref().and_then(|resolved| resolved.expected_runtime_id());
+ self.probe.presence(&origin, expected).await
+ }
+ None => {
+ let state = self.launched_runtime();
+ if state.runtime_may_be_running || state.attempt.is_some() {
+ Presence::Unknown
+ } else {
+ Presence::Absent
+ }
+ }
+ };
+ (resolved, presence)
+ }
+
fn launched_runtime(&self) -> MutexGuard<'_, LaunchState> {
- let mut state = self
- .launched_runtime
+ self.launched_runtime
.lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- // A successful receipt can arrive between bootstrap attempts. Capture it
- // before releasing a completed helper's retry slot.
- state.capture_ownership();
- state
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
}
- fn launch_if_needed(&self, resolved_launcher: Option<Arc<dyn ResolvedRuntimeLauncher>>) -> Result<(), LaunchError> {
+ fn launch_if_needed(&self, launcher: Arc<dyn ResolvedRuntimeLauncher>, hand_over: bool) -> Result<(), LaunchError> {
let mut state = self.launched_runtime();
if state.stopping {
return Err(LaunchError::RuntimeStop);
}
- if state
- .attempt
- .as_ref()
- .is_some_and(|attempt| attempt.runtime.watch.succeeded())
- {
+ if state.attempt.as_ref().is_some_and(|attempt| attempt.watch.succeeded()) {
state.retain_completed_attempt_liveness();
state.attempt = None;
}
if state.attempt.is_none() {
- let launcher = match resolved_launcher {
- Some(resolved) => resolved,
- None => self.launcher.resolve()?,
- };
- let runtime = launcher.launch()?;
// Spawning the helper is evidence that a Runtime may exist even
- // when the helper later reports failure or no receipt. Keep that
- // fact separate from retry deduplication and stop authority.
- state.attempt = Some(LaunchAttempt { runtime, launcher });
+ // when the helper later reports failure. Keep that fact separate
+ // from retry deduplication and stop authority.
+ state.attempt = Some(launcher.launch(hand_over)?);
state.runtime_may_be_running = true;
}
Ok(())
}
- /// A failed helper releases its retry slot without erasing an earlier receipt.
- fn clear_failed_launch(&self) -> bool {
+ /// A failed helper releases its retry slot and nothing else. Returns the
+ /// notice its exit calls for.
+ fn clear_failed_launch(&self) -> Option<BootstrapNoticeCode> {
let mut state = self.launched_runtime();
- if state
- .attempt
- .as_ref()
- .is_some_and(|attempt| attempt.runtime.watch.failed())
- {
- state.attempt = None;
- return true;
- }
- false
+ let code = match state.attempt.as_ref()?.watch.exit()? {
+ LaunchExit::Started => return None,
+ LaunchExit::HandoverRefused => BootstrapNoticeCode::RuntimeOwnershipLost,
+ LaunchExit::HandoverFailed => BootstrapNoticeCode::RuntimeStopFailed,
+ LaunchExit::Failed => BootstrapNoticeCode::LauncherExited,
+ };
+ state.attempt = None;
+ Some(code)
}
- /// Readiness timeout releases only a completed helper, never stop authority.
- /// Pending helpers remain retained so Retry cannot overlap a live launch.
+ /// Readiness timeout releases only a completed helper, never the liveness
+ /// fence. Pending helpers remain retained so Retry cannot overlap a live
+ /// launch.
fn clear_successful_launch(&self) -> bool {
let mut state = self.launched_runtime();
- if state
- .attempt
- .as_ref()
- .is_some_and(|attempt| attempt.runtime.watch.succeeded())
- {
+ if state.attempt.as_ref().is_some_and(|attempt| attempt.watch.succeeded()) {
state.retain_completed_attempt_liveness();
state.attempt = None;
return true;
@@ -575,39 +756,21 @@ impl RuntimeHost {
}
}
-async fn handover(launcher: Arc<dyn ResolvedRuntimeLauncher>) -> Result<(), LaunchError> {
- tokio::task::spawn_blocking(move || launcher.handover())
+async fn run_blocking(verb: impl FnOnce() -> CliOutcome + Send + 'static) -> CliOutcome {
+ tokio::task::spawn_blocking(verb)
.await
- .map_err(|_| LaunchError::Handover)?
-}
-
-fn readiness_matches_launched_runtime(
- launcher: Option<&Arc<dyn ResolvedRuntimeLauncher>>,
- readiness: &RuntimeReadiness,
-) -> bool {
- match launcher.and_then(|launcher| launcher.expected_runtime_id()) {
- // A validated ready response without a desktop identity is an
- // externally managed Controller. It may still be served by a UI that
- // inherited the bundled launcher's identity, so polling must adopt it
- // just as the initial probe does. A tagged response remains bound to
- // the exact bundled identity.
- Some(expected) => readiness
- .desktop_runtime_id
- .as_deref()
- .is_none_or(|actual| actual == expected),
- None => true,
- }
+ .unwrap_or_else(|_| CliOutcome::Failed {
+ part: "unknown".to_owned(),
+ })
}
-async fn cleanup_if_current(launcher: Option<&Arc<dyn ResolvedRuntimeLauncher>>, readiness: &RuntimeReadiness) {
- let Some(launcher) = launcher else {
- return;
- };
- if launcher.expected_runtime_id() != readiness.desktop_runtime_id.as_deref() {
- return;
- }
- let launcher = launcher.clone();
- let _ = tokio::task::spawn_blocking(move || launcher.prune_superseded()).await;
+fn ownership_lost(origin: &LoopbackOrigin, attempt: u32) -> BootstrapStatus {
+ BootstrapStatus::failed(
+ origin,
+ attempt,
+ BootstrapNotice::new(BootstrapNoticeCode::RuntimeOwnershipLost),
+ true,
+ )
}
fn publish(sink: &dyn StatusSink, status: BootstrapStatus) -> BootstrapStatus {
@@ -618,447 +781,92 @@ fn publish(sink: &dyn StatusSink, status: BootstrapStatus) -> BootstrapStatus {
#[cfg(test)]
mod tests {
use super::*;
- use crate::launcher::{LaunchWatch, StartupReceipt};
- use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+ use crate::launcher::LaunchWatch;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ const ORIGIN: &str = "http://127.0.0.1:5123";
- struct ReadyProbe;
+ /// This app's Runtime, ready.
+ struct MineProbe;
#[async_trait::async_trait]
- impl HealthProbe for ReadyProbe {
- async fn readiness(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
- Some(RuntimeReadiness {
- desktop_runtime_id: None,
- desktop_ui_runtime_id: None,
- })
+ impl HealthProbe for MineProbe {
+ async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
+ Presence::Mine { ready: true }
}
}
- fn receipt_watch(outcome: &str) -> LaunchWatch {
- let receipt = StartupReceipt::from_json(
- format!(
- r#"{{"schema_version":1,"outcome":"{outcome}","service_pid":1234,"ui_pid":5678,"service_create_unix_ms":1789010100123.5,"ui_create_unix_ms":1789010100456.5}}"#
- ).as_bytes(),
- ).expect("valid receipt");
- LaunchWatch::exited_with_receipt(true, receipt)
- }
-
- #[derive(Clone)]
- struct RecordingLauncher {
- resolutions: Arc<AtomicUsize>,
- launches: Arc<AtomicUsize>,
- stops: Arc<AtomicUsize>,
- fail_stop: Arc<AtomicBool>,
- ownership_lost: Arc<AtomicBool>,
- removals: Arc<Mutex<Vec<RuntimeRemovalState>>>,
- watch: LaunchWatch,
- private_cleanup: Option<Arc<crate::BundledVibeLauncher>>,
- }
-
- impl Default for RecordingLauncher {
- fn default() -> Self {
- Self {
- resolutions: Arc::default(),
- launches: Arc::default(),
- stops: Arc::default(),
- fail_stop: Arc::default(),
- ownership_lost: Arc::default(),
- removals: Arc::default(),
- watch: receipt_watch("started"),
- private_cleanup: None,
- }
- }
+ #[derive(Default)]
+ struct CountingLauncher {
+ launches: AtomicUsize,
+ stops: AtomicUsize,
}
- impl RuntimeLauncher for RecordingLauncher {
+ impl RuntimeLauncher for CountingLauncher {
fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
- self.resolutions.fetch_add(1, Ordering::SeqCst);
- Ok(Arc::new(self.clone()))
- }
-
- fn remove_private_runtime(&self, state: RuntimeRemovalState) -> Result<bool, LaunchError> {
- self.removals.lock().expect("record removals").push(state);
- match &self.private_cleanup {
- Some(launcher) => launcher.remove_private_runtime(state),
- None => Err(LaunchError::RuntimeRemoval),
- }
+ unreachable!("the tests hand the resolved launcher over directly")
}
}
- impl ResolvedRuntimeLauncher for RecordingLauncher {
+ impl ResolvedRuntimeLauncher for Arc<CountingLauncher> {
fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
- Ok(LoopbackOrigin::parse("http://127.0.0.1:5123").expect("test origin"))
+ Ok(LoopbackOrigin::parse(ORIGIN).expect("test origin"))
}
- fn launch(&self) -> Result<LaunchedRuntime, LaunchError> {
+ fn launch(&self, _hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
self.launches.fetch_add(1, Ordering::SeqCst);
Ok(LaunchedRuntime {
- pid: 9012,
- watch: self.watch.clone(),
+ pid: 1,
+ watch: LaunchWatch::exited(LaunchExit::Started),
})
}
- fn stop(&self, receipt: &StartupReceipt) -> Result<(), LaunchError> {
- assert_eq!(Some(receipt), self.watch.owned_receipt());
- self.stops.fetch_add(1, Ordering::SeqCst);
- if self.ownership_lost.load(Ordering::SeqCst) {
- Err(LaunchError::OwnershipLost)
- } else if self.fail_stop.load(Ordering::SeqCst) {
- Err(LaunchError::RuntimeStop)
- } else {
- Ok(())
- }
+ fn expected_runtime_id(&self) -> Option<&str> {
+ Some("b")
}
- }
- #[tokio::test]
- async fn an_adopted_runtime_can_never_be_stopped_by_the_host() {
- let launcher = Arc::new(RecordingLauncher::default());
- let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
- assert_eq!(
- host.bootstrap(&DiscardStatus).await.notice.code,
- BootstrapNoticeCode::Adopted
- );
- assert!(!host.has_launched());
- assert!(!host.has_owned_runtime());
- assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
- assert_eq!(launcher.resolutions.load(Ordering::SeqCst), 1);
- assert_eq!(launcher.stops.load(Ordering::SeqCst), 0);
- }
-
- struct TransientProbe(AtomicBool);
-
- #[async_trait::async_trait]
- impl HealthProbe for TransientProbe {
- async fn readiness(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
- self.0.swap(true, Ordering::SeqCst).then_some(RuntimeReadiness {
- desktop_runtime_id: None,
- desktop_ui_runtime_id: None,
- })
+ fn stop(&self, _runtime_id: &str) -> CliOutcome {
+ self.stops.fetch_add(1, Ordering::SeqCst);
+ CliOutcome::Completed
}
}
- #[tokio::test(start_paused = true)]
- async fn successful_reuse_after_a_transient_probe_miss_never_grants_stop_authority() {
- let launcher = Arc::new(RecordingLauncher {
- watch: receipt_watch("reused"),
- ..RecordingLauncher::default()
- });
- let host = RuntimeHost::new(
- Arc::new(TransientProbe(AtomicBool::new(false))),
- launcher.clone(),
- RuntimeHostSettings::default(),
- );
- let status = host.bootstrap(&DiscardStatus).await;
- assert_eq!(status.phase, crate::BootstrapPhase::Ready);
- assert_eq!(status.notice.code, BootstrapNoticeCode::Adopted);
- assert_eq!(launcher.launches.load(Ordering::SeqCst), 1);
- assert!(host.has_launched());
- assert!(!host.has_owned_runtime());
- assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
- assert_eq!(launcher.stops.load(Ordering::SeqCst), 0);
- }
-
- #[tokio::test(start_paused = true)]
- async fn timeout_then_retry_then_uninstall_retains_unknown_liveness_fence() {
- let launcher = Arc::new(RecordingLauncher {
- watch: receipt_watch("reused"),
- ..RecordingLauncher::default()
- });
- let host = RuntimeHost::new(
- Arc::new(TransientProbe(AtomicBool::new(false))),
- launcher.clone(),
- RuntimeHostSettings {
- ready_timeout: Duration::ZERO,
- ..RuntimeHostSettings::default()
- },
- );
-
- assert_eq!(
- host.bootstrap(&DiscardStatus).await.notice.code,
- BootstrapNoticeCode::ReadyTimeout
- );
- assert!(
- !host.has_launched(),
- "a completed helper must release retry deduplication"
- );
- assert!(
- !host.has_owned_runtime(),
- "a reused receipt never grants stop authority"
- );
-
- assert_eq!(host.bootstrap(&DiscardStatus).await.phase, crate::BootstrapPhase::Ready);
- assert!(matches!(
- host.remove_private_runtime(None).await,
- Err(LaunchError::RuntimeRemoval)
- ));
- assert_eq!(
- *launcher.removals.lock().expect("recorded removal"),
- [RuntimeRemovalState::Unknown]
- );
- }
-
- #[tokio::test(start_paused = true)]
- async fn timeout_then_late_ready_retry_preserves_scoped_stop_authority() {
- let launcher = Arc::new(RecordingLauncher::default());
- let host = RuntimeHost::new(
- Arc::new(TransientProbe(AtomicBool::new(false))),
- launcher.clone(),
- RuntimeHostSettings {
- ready_timeout: Duration::ZERO,
- ..RuntimeHostSettings::default()
- },
- );
- assert_eq!(
- host.bootstrap(&DiscardStatus).await.notice.code,
- BootstrapNoticeCode::ReadyTimeout
- );
- assert!(!host.has_launched(), "completed helper releases the retry slot");
- assert!(host.has_owned_runtime(), "timeout is not evidence of ownership loss");
- assert_eq!(host.bootstrap(&DiscardStatus).await.phase, crate::BootstrapPhase::Ready);
- assert_eq!(launcher.launches.load(Ordering::SeqCst), 1);
- host.stop_owned_runtime()
- .await
- .expect("retained receipt authorizes scoped stop");
- assert_eq!(launcher.stops.load(Ordering::SeqCst), 1);
- assert!(!host.has_owned_runtime());
- }
-
+ /// While a Stop, Quit, or uninstall is running, nothing starts a Runtime,
+ /// no second stop overlaps it, and no probe hands stop authority to or away
+ /// from anyone.
#[tokio::test]
- async fn only_completed_successful_started_receipts_grant_stop_authority() {
- for watch in [
- LaunchWatch::default(),
- LaunchWatch::exited(true),
- LaunchWatch::exited(false),
- receipt_watch("reused"),
- ] {
- let completed = watch.succeeded() || watch.failed();
- let launcher = Arc::new(RecordingLauncher {
- watch,
- ..RecordingLauncher::default()
- });
- let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
- host.launch_if_needed(Some(launcher.clone())).expect("fake launch");
- assert!(host.has_launched());
- assert!(!host.has_owned_runtime());
- host.release_after_readiness_loss();
- assert_eq!(
- host.has_launched(),
- !completed,
- "only completed helpers release retry deduplication"
- );
- assert!(!host.has_owned_runtime(), "readiness loss never grants authority");
- assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
- assert_eq!(launcher.stops.load(Ordering::SeqCst), 0);
- assert!(matches!(
- host.remove_private_runtime(None).await,
- Err(LaunchError::RuntimeRemoval)
- ));
- assert_eq!(
- *launcher.removals.lock().expect("recorded removal"),
- [RuntimeRemovalState::Unknown]
- );
+ async fn a_running_stop_fences_launch_stop_and_ownership() {
+ let counting = Arc::new(CountingLauncher::default());
+ let resolved: Arc<dyn ResolvedRuntimeLauncher> = Arc::new(counting.clone());
+ let host = RuntimeHost::new(Arc::new(MineProbe), counting.clone(), RuntimeHostSettings::default());
+ {
+ let mut state = host.launched_runtime();
+ state.owner = Some(resolved.clone());
+ state.stopping = true;
}
- }
- #[tokio::test]
- async fn receipt_refusal_revokes_authority_without_retrying_or_stopping_a_replacement() {
- let launcher = Arc::new(RecordingLauncher::default());
- let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
- host.launch_if_needed(Some(launcher.clone())).expect("fake launch");
- assert!(host.has_owned_runtime());
- launcher.ownership_lost.store(true, Ordering::SeqCst);
assert!(matches!(
- host.stop_owned_runtime().await,
- Err(LaunchError::OwnershipLost)
+ host.launch_if_needed(resolved.clone(), false),
+ Err(LaunchError::RuntimeStop)
));
- assert!(!host.has_owned_runtime());
- assert!(!host.has_launched());
- assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
- assert_eq!(launcher.stops.load(Ordering::SeqCst), 1);
+ assert_eq!(counting.launches.load(Ordering::SeqCst), 0);
assert_eq!(
- host.bootstrap(&DiscardStatus).await.notice.code,
- BootstrapNoticeCode::Adopted
- );
- assert!(!host.has_owned_runtime());
- assert_eq!(launcher.launches.load(Ordering::SeqCst), 1);
- }
-
- #[tokio::test]
- async fn receipt_refusal_retains_unknown_liveness_for_uninstall() {
- let launcher = Arc::new(RecordingLauncher::default());
- let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
- host.launch_if_needed(Some(launcher.clone())).expect("fake launch");
- launcher.ownership_lost.store(true, Ordering::SeqCst);
-
- assert!(matches!(
host.stop_owned_runtime().await,
- Err(LaunchError::OwnershipLost)
- ));
- assert!(matches!(
- host.remove_private_runtime(None).await,
- Err(LaunchError::RuntimeRemoval)
- ));
- assert_eq!(
- *launcher.removals.lock().expect("recorded removal"),
- [RuntimeRemovalState::Unknown]
+ CliOutcome::Failed {
+ part: "launch_pending".to_owned()
+ }
);
- }
-
- #[tokio::test]
- async fn stop_uses_the_retained_launcher_and_releases_only_successful_ownership() {
- let resolver = Arc::new(RecordingLauncher::default());
- let launched = Arc::new(RecordingLauncher::default());
- let host = RuntimeHost::new(Arc::new(ReadyProbe), resolver.clone(), RuntimeHostSettings::default());
- host.launch_if_needed(Some(launched.clone())).expect("fake launch");
- launched.fail_stop.store(true, Ordering::SeqCst);
- assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::RuntimeStop)));
- assert!(host.has_launched());
- assert!(host.has_owned_runtime());
- launched.fail_stop.store(false, Ordering::SeqCst);
- host.stop_owned_runtime().await.expect("explicit retry succeeds");
- assert!(!host.has_launched());
- assert!(!host.has_owned_runtime());
- assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
- assert_eq!(launched.stops.load(Ordering::SeqCst), 2);
- assert_eq!(resolver.resolutions.load(Ordering::SeqCst), 0);
- assert_eq!(resolver.stops.load(Ordering::SeqCst), 0);
- }
+ assert_eq!(counting.stops.load(Ordering::SeqCst), 0);
- #[tokio::test]
- async fn readiness_loss_releases_retry_slot_but_retains_scoped_stop_authority() {
- let launcher = Arc::new(RecordingLauncher::default());
- let host = RuntimeHost::new(Arc::new(ReadyProbe), launcher.clone(), RuntimeHostSettings::default());
- host.launch_if_needed(Some(launcher.clone())).expect("fake launch");
- host.release_after_readiness_loss();
- assert!(!host.has_launched(), "completed helper retry slot is released");
- assert!(
- host.has_owned_runtime(),
- "readiness loss does not revoke a valid receipt"
- );
- assert!(matches!(
- host.remove_private_runtime(None).await,
- Err(LaunchError::RuntimeRemoval)
- ));
- assert_eq!(
- *launcher.removals.lock().expect("recorded removal"),
- [RuntimeRemovalState::Unknown]
- );
- host.stop_owned_runtime()
- .await
- .expect("the retained receipt reaches explicit scoped stop");
- assert_eq!(launcher.stops.load(Ordering::SeqCst), 1);
+ let origin = LoopbackOrigin::parse(ORIGIN).expect("test origin");
+ host.launched_runtime().owner = None;
+ let epoch = host.launched_runtime().epoch;
+ host.observe_presence(epoch, &origin, Some(&resolved)).await;
assert!(
!host.has_owned_runtime(),
- "successful stop clears the receipt and liveness fence"
- );
- }
-
- #[tokio::test]
- async fn a_replacement_receipt_cannot_stop_the_previous_launcher() {
- let previous = Arc::new(RecordingLauncher::default());
- let mut replacement_receipt = serde_json::to_value(receipt_watch("started").owned_receipt().unwrap()).unwrap();
- replacement_receipt["service_pid"] = serde_json::json!(4321);
- let replacement = Arc::new(RecordingLauncher {
- watch: LaunchWatch::exited_with_receipt(true, serde_json::from_value(replacement_receipt).unwrap()),
- ..RecordingLauncher::default()
- });
- let host = RuntimeHost::new(Arc::new(ReadyProbe), previous.clone(), RuntimeHostSettings::default());
-
- host.launch_if_needed(Some(previous.clone())).expect("previous launch");
- host.release_after_readiness_loss();
- let previous_receipt = previous
- .watch
- .owned_receipt()
- .expect("previous started receipt")
- .clone();
- previous.ownership_lost.store(true, Ordering::SeqCst);
-
- host.launch_if_needed(Some(replacement.clone()))
- .expect("replacement launch");
- assert!(
- host.has_owned_runtime(),
- "the newer receipt replaces old scoped authority"
+ "a probe during a stop must not restore stop authority"
);
- assert!(matches!(
- previous.stop(&previous_receipt),
- Err(LaunchError::OwnershipLost)
- ));
- let previous_stop_attempts = previous.stops.load(Ordering::SeqCst);
- host.stop_owned_runtime()
- .await
- .expect("the replacement receipt is stoppable");
- assert_eq!(previous.stops.load(Ordering::SeqCst), previous_stop_attempts);
- assert_eq!(replacement.stops.load(Ordering::SeqCst), 1);
- }
-
- #[tokio::test]
- async fn recovery_receipt_requires_scoped_stop_before_unknown_private_files_can_be_removed() {
- // The real bundled remover must refuse before preparing a bundle or
- // invoking unscoped handover. All paths below belong to this test.
- for refused in [false, true] {
- let root = std::env::temp_dir().join(format!("avibe-h4-removal-{}-{refused}", std::process::id()));
- let installs = root.join("runtime");
- let backends = root.join("backends");
- std::fs::create_dir_all(&installs).unwrap();
- std::fs::create_dir_all(&backends).unwrap();
- std::fs::write(installs.join("active"), b"live runtime bytes").unwrap();
- std::fs::write(backends.join("active"), b"live backend bytes").unwrap();
- std::fs::write(root.join("unrelated"), b"unrelated state").unwrap();
- let launcher = Arc::new(RecordingLauncher {
- private_cleanup: Some(Arc::new(crate::BundledVibeLauncher::new(
- root.join("missing-bundle"),
- installs.clone(),
- backends.clone(),
- crate::BootstrapLog::disabled(),
- ))),
- ..RecordingLauncher::default()
- });
- let host = RuntimeHost::new(
- Arc::new(TransientProbe(AtomicBool::new(false))),
- launcher.clone(),
- RuntimeHostSettings {
- ready_timeout: Duration::ZERO,
- ..RuntimeHostSettings::default()
- },
- );
- host.launch_if_needed(Some(launcher.clone())).unwrap();
- host.release_after_readiness_loss();
- assert!(host.has_owned_runtime());
- let origin = LoopbackOrigin::parse("http://127.0.0.1:5123").unwrap();
- for active in [None, Some(&origin)] {
- assert!(matches!(
- host.remove_private_runtime(active).await,
- Err(LaunchError::RuntimeRemoval)
- ));
- }
- assert_eq!(*launcher.removals.lock().unwrap(), [RuntimeRemovalState::Unknown; 2]);
- assert_eq!(launcher.stops.load(Ordering::SeqCst), 0);
- assert_eq!(std::fs::read(installs.join("active")).unwrap(), b"live runtime bytes");
- assert_eq!(std::fs::read(backends.join("active")).unwrap(), b"live backend bytes");
- launcher.ownership_lost.store(refused, Ordering::SeqCst);
- let stopped = host.stop_owned_runtime().await;
- if refused {
- assert!(matches!(stopped, Err(LaunchError::OwnershipLost)));
- assert!(!host.has_owned_runtime());
- assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
- assert!(matches!(
- host.remove_private_runtime(None).await,
- Err(LaunchError::RuntimeRemoval)
- ));
- assert!(installs.join("active").exists() && backends.join("active").exists());
- } else {
- stopped.unwrap();
- assert!(host.remove_private_runtime(None).await.unwrap());
- assert!(!installs.exists() && !backends.exists());
- assert_eq!(
- launcher.removals.lock().unwrap().last(),
- Some(&RuntimeRemovalState::Inactive)
- );
- }
- assert_eq!(launcher.stops.load(Ordering::SeqCst), 1);
- assert_eq!(std::fs::read(root.join("unrelated")).unwrap(), b"unrelated state");
- std::fs::remove_dir_all(root).unwrap();
- }
+ assert!(!host.launched_runtime().runtime_may_be_running);
}
#[test]
diff --git a/desktop/runtime-host/src/health.rs b/desktop/runtime-host/src/health.rs
index 9c7fe0ff5..96cc3893e 100644
--- a/desktop/runtime-host/src/health.rs
+++ b/desktop/runtime-host/src/health.rs
@@ -1,4 +1,4 @@
-//! Readiness probing against the Avibe Web UI server.
+//! Presence probing against the Avibe Web UI server.
use std::time::Duration;
@@ -8,35 +8,35 @@ use crate::origin::LoopbackOrigin;
const MAX_READINESS_BYTES: usize = 1024;
+/// What one `/ready` response proves about the Runtime serving an origin,
+/// judged against the desktop Runtime identity this shell runs.
+///
+/// The identity that decides is the Controller's: it owns the service lock, the
+/// agents, and every process a scoped stop can find. The UI identity never makes
+/// a Runtime this shell's.
#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct RuntimeReadiness {
- /// Identity of the Controller Runtime, when it is desktop-managed.
- pub desktop_runtime_id: Option<String>,
- /// Identity of the UI Runtime serving an external Controller, when the UI
- /// is known to come from a bundled private tree.
- pub desktop_ui_runtime_id: Option<String>,
+pub enum Presence {
+ /// The Controller carries the expected identity. `ready` is false for the
+ /// exact identity mismatch: the Controller is this shell's but the UI is not.
+ Mine { ready: bool },
+ /// The Controller carries another valid desktop identity.
+ Foreign { runtime_id: String, ready: bool },
+ /// A ready Avibe Runtime whose Controller carries no desktop identity.
+ Unmanaged,
+ /// Nothing accepted the connection.
+ Absent,
+ /// Anything else: not ready, not Avibe, or not provable.
+ Unknown,
}
-/// Answers whether the Avibe UI and Controller serve this origin and, for an
-/// app-private Runtime, which immutable archive is running.
+/// Classifies one `/ready` response for a shell expecting `expected`, the
+/// identity of the Runtime it runs, if any.
///
/// Transport errors and raw response bodies stay inside the probe so nothing
/// from the network reaches the bootstrap UI.
#[async_trait]
pub trait HealthProbe: Send + Sync {
- async fn readiness(&self, origin: &LoopbackOrigin) -> Option<RuntimeReadiness>;
-
- /// Returns the Controller identity from an explicit UI/Controller mismatch.
- ///
- /// This is not readiness: callers may use it only to hand a superseded
- /// desktop-managed Runtime over to its bundled successor.
- async fn mismatched_runtime_identity(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
- None
- }
-
- async fn is_healthy(&self, origin: &LoopbackOrigin) -> bool {
- self.readiness(origin).await.is_some()
- }
+ async fn presence(&self, origin: &LoopbackOrigin, expected: Option<&str>) -> Presence;
}
/// `GET <origin>/ready`, requiring UI, service ownership, and Controller IPC.
@@ -62,26 +62,44 @@ impl HttpHealthProbe {
#[async_trait]
impl HealthProbe for HttpHealthProbe {
- async fn readiness(&self, origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
- let Ok(response) = self.client.get(origin.readiness_url()).send().await else {
- return None;
+ async fn presence(&self, origin: &LoopbackOrigin, expected: Option<&str>) -> Presence {
+ let response = match self.client.get(origin.readiness_url()).send().await {
+ Ok(response) => response,
+ Err(error) if is_connection_refused(&error) => return Presence::Absent,
+ Err(_) => return Presence::Unknown,
};
- if !response.status().is_success() {
- return None;
+ let status = response.status();
+ let Some(body) = bounded_response_body(response).await else {
+ return Presence::Unknown;
+ };
+ let controller = match status {
+ reqwest::StatusCode::OK => parse_readiness_body(&body).map(|runtime_id| (runtime_id, true)),
+ reqwest::StatusCode::SERVICE_UNAVAILABLE => {
+ parse_runtime_identity_mismatch_body(&body).map(|runtime_id| (Some(runtime_id), false))
+ }
+ _ => None,
+ };
+ match controller {
+ Some((runtime_id, ready)) => classify(runtime_id, ready, expected),
+ None => Presence::Unknown,
}
- let body = bounded_response_body(response).await?;
- parse_avibe_readiness_body(&body)
}
+}
- async fn mismatched_runtime_identity(&self, origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
- let Ok(response) = self.client.get(origin.readiness_url()).send().await else {
- return None;
- };
- if response.status() != reqwest::StatusCode::SERVICE_UNAVAILABLE {
- return None;
- }
- let body = bounded_response_body(response).await?;
- parse_runtime_identity_mismatch_body(&body)
+/// Whether a request failed because the connection was refused, the only
+/// connect failure that proves nothing listens. A timeout, a denied socket or
+/// an unavailable local address may hide a listener.
+fn is_connection_refused(error: &(dyn std::error::Error + 'static)) -> bool {
+ std::iter::successors(Some(error), |error| error.source())
+ .filter_map(|error| error.downcast_ref::<std::io::Error>())
+ .any(|error| error.kind() == std::io::ErrorKind::ConnectionRefused)
+}
+
+fn classify(controller_runtime_id: Option<String>, ready: bool, expected: Option<&str>) -> Presence {
+ match controller_runtime_id {
+ Some(runtime_id) if Some(runtime_id.as_str()) == expected => Presence::Mine { ready },
+ Some(runtime_id) => Presence::Foreign { runtime_id, ready },
+ None => Presence::Unmanaged,
}
}
@@ -108,15 +126,13 @@ async fn bounded_response_body(mut response: reqwest::Response) -> Option<String
String::from_utf8(body).ok()
}
-/// Whether a `/ready` body proves both the UI and Controller are ready.
+/// Parses the exact affirmative `/ready` payload into its Controller identity.
///
/// The Python endpoint performs the authoritative service-lock and internal IPC
-/// checks. Rust accepts only its exact affirmative payload.
-pub fn is_avibe_readiness_body(body: &str) -> bool {
- parse_avibe_readiness_body(body).is_some()
-}
-
-pub fn parse_avibe_readiness_body(body: &str) -> Option<RuntimeReadiness> {
+/// checks. Rust accepts only its exact payload: `Some(None)` is a ready
+/// Controller without a desktop identity. A UI identity alone names only where
+/// the UI runs from, so it is validated and then set aside.
+fn parse_readiness_body(body: &str) -> Option<Option<String>> {
let Ok(payload) = serde_json::from_str::<serde_json::Value>(body) else {
return None;
};
@@ -142,22 +158,16 @@ pub fn parse_avibe_readiness_body(body: &str) -> Option<RuntimeReadiness> {
|| object.get("schema_version").and_then(serde_json::Value::as_u64) != Some(1)
|| object.get("product").and_then(serde_json::Value::as_str) != Some("avibe")
|| object.get("ready").and_then(serde_json::Value::as_bool) != Some(true)
- || controller_runtime_id.or(ui_runtime_id).is_some_and(|value| {
- value.len() != 64
- || !value
- .bytes()
- .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
- })
+ || controller_runtime_id
+ .or(ui_runtime_id)
+ .is_some_and(|value| !is_runtime_id(value))
{
return None;
}
- Some(RuntimeReadiness {
- desktop_runtime_id: controller_runtime_id.map(str::to_owned),
- desktop_ui_runtime_id: ui_runtime_id.map(str::to_owned),
- })
+ Some(controller_runtime_id.map(str::to_owned))
}
-fn parse_runtime_identity_mismatch_body(body: &str) -> Option<RuntimeReadiness> {
+fn parse_runtime_identity_mismatch_body(body: &str) -> Option<String> {
let Ok(payload) = serde_json::from_str::<serde_json::Value>(body) else {
return None;
};
@@ -168,17 +178,18 @@ fn parse_runtime_identity_mismatch_body(body: &str) -> Option<RuntimeReadiness>
|| object.get("product").and_then(serde_json::Value::as_str) != Some("avibe")
|| object.get("ready").and_then(serde_json::Value::as_bool) != Some(false)
|| object.get("code").and_then(serde_json::Value::as_str) != Some("runtime_identity_mismatch")
- || runtime_id.len() != 64
- || !runtime_id
- .bytes()
- .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
+ || !is_runtime_id(runtime_id)
{
return None;
}
- Some(RuntimeReadiness {
- desktop_runtime_id: Some(runtime_id.to_owned()),
- desktop_ui_runtime_id: None,
- })
+ Some(runtime_id.to_owned())
+}
+
+fn is_runtime_id(value: &str) -> bool {
+ value.len() == 64
+ && value
+ .bytes()
+ .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
}
#[cfg(test)]
@@ -337,37 +348,40 @@ mod tests {
);
}
+ fn tagged_ready_body(runtime_id: &str) -> String {
+ format!(r#"{{"schema_version":1,"product":"avibe","ready":true,"desktop_runtime_id":"{runtime_id}"}}"#)
+ }
+
+ fn mismatch_body(runtime_id: &str) -> String {
+ format!(
+ r#"{{"schema_version":1,"product":"avibe","ready":false,"code":"runtime_identity_mismatch","desktop_runtime_id":"{runtime_id}"}}"#
+ )
+ }
+
+ async fn served_presence(status: &str, body: &[u8], expected: Option<&str>) -> Presence {
+ let server = TestServer::start(response(status, &[("Content-Length", body.len().to_string())], body));
+ let probe = HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
+ let presence = probe.presence(&server.origin, expected).await;
+ assert!(server.finish());
+ presence
+ }
+
#[test]
- fn accepts_the_exact_runtime_readiness_payload() {
- assert!(is_avibe_readiness_body(
- r#"{"schema_version":1,"product":"avibe","ready":true}"#
- ));
+ fn readiness_payloads_parse_to_the_controller_identity_only() {
+ let ours = "a".repeat(64);
+ assert_eq!(parse_readiness_body(READY_BODY), Some(None));
+ assert_eq!(parse_readiness_body(&tagged_ready_body(&ours)), Some(Some(ours)));
+ // A UI started from a bundled tree, serving an external Controller.
assert_eq!(
- parse_avibe_readiness_body(EXTERNAL_CONTROLLER_BUNDLED_UI_READY_BODY),
- Some(RuntimeReadiness {
- desktop_runtime_id: None,
- desktop_ui_runtime_id: Some("a".repeat(64)),
- })
+ parse_readiness_body(EXTERNAL_CONTROLLER_BUNDLED_UI_READY_BODY),
+ Some(None)
);
assert_eq!(
- parse_avibe_readiness_body(&format!(
- r#"{{"schema_version":1,"product":"avibe","ready":true,"desktop_runtime_id":"{}"}}"#,
- "a".repeat(64)
- )),
- Some(RuntimeReadiness {
- desktop_runtime_id: Some("a".repeat(64)),
- desktop_ui_runtime_id: None,
- })
- );
- assert_eq!(
- parse_avibe_readiness_body(&format!(
+ parse_readiness_body(&format!(
r#"{{"schema_version":1,"product":"avibe","ready":true,"desktop_ui_runtime_id":"{}"}}"#,
"b".repeat(64)
)),
- Some(RuntimeReadiness {
- desktop_runtime_id: None,
- desktop_ui_runtime_id: Some("b".repeat(64)),
- })
+ Some(None)
);
}
@@ -375,13 +389,8 @@ mod tests {
fn accepts_only_the_exact_runtime_identity_mismatch_payload() {
let runtime_id = "a".repeat(64);
assert_eq!(
- parse_runtime_identity_mismatch_body(&format!(
- r#"{{"schema_version":1,"product":"avibe","ready":false,"code":"runtime_identity_mismatch","desktop_runtime_id":"{runtime_id}"}}"#
- )),
- Some(RuntimeReadiness {
- desktop_runtime_id: Some(runtime_id),
- desktop_ui_runtime_id: None,
- })
+ parse_runtime_identity_mismatch_body(&mismatch_body(&runtime_id)),
+ Some(runtime_id)
);
assert_eq!(
parse_runtime_identity_mismatch_body(
@@ -390,9 +399,7 @@ mod tests {
None
);
for invalid in ["", "bad", &"A".repeat(64)] {
- assert!(parse_runtime_identity_mismatch_body(&format!(
- r#"{{"schema_version":1,"product":"avibe","ready":false,"code":"runtime_identity_mismatch","desktop_runtime_id":"{invalid}"}}"#
- )).is_none());
+ assert!(parse_runtime_identity_mismatch_body(&mismatch_body(invalid)).is_none());
}
assert!(parse_runtime_identity_mismatch_body(
r#"{"schema_version":1,"product":"avibe","ready":false,"code":"controller_unavailable"}"#
@@ -423,7 +430,10 @@ mod tests {
"[]",
];
for body in bodies {
- assert!(!is_avibe_readiness_body(body), "body {body:?} must not be adopted");
+ assert!(
+ parse_readiness_body(body).is_none(),
+ "body {body:?} must not be adopted"
+ );
}
}
@@ -433,39 +443,123 @@ mod tests {
}
#[tokio::test]
- async fn the_probe_accepts_the_exact_body_from_its_loopback_listener() {
- let server = TestServer::start(response(
- "200 OK",
- &[("Content-Length", READY_BODY.len().to_string())],
- READY_BODY.as_bytes(),
- ));
- let probe = HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
-
- assert!(probe.is_healthy(&server.origin).await);
- assert!(server.finish());
+ async fn presence_is_decided_by_the_controller_identity_against_the_expected_one() {
+ let ours = "a".repeat(64);
+ let other = "b".repeat(64);
+ let cases = [
+ (
+ "200 OK",
+ tagged_ready_body(&ours),
+ Some(ours.as_str()),
+ Presence::Mine { ready: true },
+ ),
+ (
+ "503 Service Unavailable",
+ mismatch_body(&ours),
+ Some(ours.as_str()),
+ Presence::Mine { ready: false },
+ ),
+ (
+ "200 OK",
+ tagged_ready_body(&other),
+ Some(ours.as_str()),
+ Presence::Foreign {
+ runtime_id: other.clone(),
+ ready: true,
+ },
+ ),
+ (
+ "503 Service Unavailable",
+ mismatch_body(&other),
+ Some(ours.as_str()),
+ Presence::Foreign {
+ runtime_id: other.clone(),
+ ready: false,
+ },
+ ),
+ // A shell without a bundled Runtime has no identity of its own.
+ (
+ "200 OK",
+ tagged_ready_body(&ours),
+ None,
+ Presence::Foreign {
+ runtime_id: ours.clone(),
+ ready: true,
+ },
+ ),
+ (
+ "200 OK",
+ READY_BODY.to_owned(),
+ Some(ours.as_str()),
+ Presence::Unmanaged,
+ ),
+ // A UI identity never makes an external Controller this shell's.
+ (
+ "200 OK",
+ EXTERNAL_CONTROLLER_BUNDLED_UI_READY_BODY.to_owned(),
+ Some(ours.as_str()),
+ Presence::Unmanaged,
+ ),
+ // The body proves readiness only with its own status.
+ (
+ "500 Internal Server Error",
+ tagged_ready_body(&ours),
+ Some(ours.as_str()),
+ Presence::Unknown,
+ ),
+ ("200 OK", mismatch_body(&ours), Some(ours.as_str()), Presence::Unknown),
+ (
+ "503 Service Unavailable",
+ r#"{"schema_version":1,"product":"avibe","ready":false,"code":"controller_unavailable"}"#.to_owned(),
+ Some(ours.as_str()),
+ Presence::Unknown,
+ ),
+ ("200 OK", "ok".to_owned(), Some(ours.as_str()), Presence::Unknown),
+ ];
+ for (status, body, expected, presence) in cases {
+ assert_eq!(
+ served_presence(status, body.as_bytes(), expected).await,
+ presence,
+ "{status} {body}"
+ );
+ }
}
#[tokio::test]
- async fn the_probe_recovers_identity_from_an_explicit_mismatch() {
- let runtime_id = "a".repeat(64);
- let body = format!(
- r#"{{"schema_version":1,"product":"avibe","ready":false,"code":"runtime_identity_mismatch","desktop_runtime_id":"{runtime_id}"}}"#
- );
- let server = TestServer::start(response(
- "503 Service Unavailable",
- &[("Content-Length", body.len().to_string())],
- body.as_bytes(),
- ));
- let probe = HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
+ async fn a_refused_connection_is_absent() {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("test listener binds");
+ let origin = LoopbackOrigin::parse(&format!("http://{}", listener.local_addr().expect("address")))
+ .expect("test origin is loopback");
+ drop(listener);
+ let probe = HttpHealthProbe::new(crate::bootstrap::DEFAULT_PROBE_TIMEOUT).expect("probe builds");
+
+ assert_eq!(probe.presence(&origin, Some(&"a".repeat(64))).await, Presence::Absent);
+ }
- assert_eq!(
- probe.mismatched_runtime_identity(&server.origin).await,
- Some(RuntimeReadiness {
- desktop_runtime_id: Some(runtime_id),
- desktop_ui_runtime_id: None,
- })
- );
- assert!(server.finish());
+ #[test]
+ fn no_other_connect_failure_proves_absence() {
+ // The shape reqwest reports: a connect error caused by the socket's error.
+ #[derive(Debug)]
+ struct Connect(std::io::Error);
+ impl std::fmt::Display for Connect {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str("tcp connect error")
+ }
+ }
+ impl std::error::Error for Connect {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ Some(&self.0)
+ }
+ }
+
+ for (kind, refused) in [
+ (std::io::ErrorKind::ConnectionRefused, true),
+ (std::io::ErrorKind::PermissionDenied, false),
+ (std::io::ErrorKind::AddrNotAvailable, false),
+ (std::io::ErrorKind::TimedOut, false),
+ ] {
+ assert_eq!(is_connection_refused(&Connect(kind.into())), refused, "{kind:?}");
+ }
}
#[tokio::test]
@@ -482,7 +576,7 @@ mod tests {
));
let probe = HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
- assert!(!probe.is_healthy(&redirect.origin).await);
+ assert_eq!(probe.presence(&redirect.origin, None).await, Presence::Unknown);
assert!(redirect.finish());
assert!(!target.finish(), "the redirected listener must never be contacted");
}
@@ -493,7 +587,7 @@ mod tests {
let server = TestServer::start(response("200 OK", &[], &body));
let probe = HttpHealthProbe::new(Duration::from_secs(2)).expect("probe builds");
- assert!(!probe.is_healthy(&server.origin).await);
+ assert_eq!(probe.presence(&server.origin, None).await, Presence::Unknown);
assert!(server.finish());
}
}
diff --git a/desktop/runtime-host/src/launcher.rs b/desktop/runtime-host/src/launcher.rs
index 4f2580c64..4ad0196ac 100644
--- a/desktop/runtime-host/src/launcher.rs
+++ b/desktop/runtime-host/src/launcher.rs
@@ -3,8 +3,9 @@
//! Two rules shape this module:
//!
//! 1. The Runtime outlives normal shell lifecycle. Launched processes are
-//! detached and reaped; only explicit replacement or uninstall asks the
-//! Runtime's own CLI to stop it gracefully.
+//! detached and reaped; only a handover, an explicit Stop or Quit, or
+//! uninstall asks the Runtime's own CLI to stop it, and always scoped to one
+//! Runtime identity.
//! 2. No shell interpreter is involved. The executable is resolved to a real
//! path and spawned directly, so no user-controlled string is ever parsed as
//! a command line.
@@ -17,10 +18,9 @@ use std::process::{Command, Stdio};
use std::sync::{mpsc, Arc, OnceLock};
use std::time::{Duration, Instant};
-use serde::{Deserialize, Serialize};
+use serde::Deserialize;
use crate::bootstrap_log::BootstrapLog;
-use crate::health::RuntimeReadiness;
use crate::origin::LoopbackOrigin;
use crate::private_runtime::{InstalledPrivateRuntime, PrivateRuntimeBundle, PrivateRuntimeError};
use crate::status::BootstrapNoticeCode;
@@ -58,8 +58,11 @@ pub const DESKTOP_BACKENDS_ROOT_ENV: &str = "AVIBE_DESKTOP_BACKENDS_ROOT";
/// same Runtime. The shell owns a WebView for exactly this purpose, so it always
/// opts out.
const START_ARGS: [&str; 2] = ["start", "--no-open-browser"];
-const STOP_ARGS: [&str; 1] = ["stop"];
+/// Lets this start stop another desktop Runtime that serves this home. `vibe
+/// start` refuses that handover without it.
+const HAND_OVER_ARG: &str = "--hand-over";
const ENDPOINT_ARGS: [&str; 3] = ["desktop", "endpoint", "--json"];
+const REMOVE_BACKENDS_ARGS: [&str; 2] = ["desktop", "remove-backends"];
/// How long the shell waits for the Runtime to name its own address.
///
/// Sized for a *cold* first launch, not a warm one. The bundle has just been
@@ -78,18 +81,16 @@ const ENDPOINT_ARGS: [&str; 3] = ["desktop", "endpoint", "--json"];
/// endpoint is genuinely broken, and that failure is already retryable.
const ENDPOINT_TIMEOUT: Duration = Duration::from_secs(60);
-/// How much of the endpoint helper's stderr the bootstrap log keeps.
-const MAX_ENDPOINT_STDERR_BYTES: usize = 4 * 1024;
+/// How much of a helper's stderr the shell keeps: the bootstrap log's
+/// diagnostic, and a lifecycle verb's closing JSON verdict.
+const MAX_STDERR_TAIL_BYTES: usize = 4 * 1024;
-/// How long the stderr reader is given to reach EOF once the query is over.
+/// How long the stderr reader is given to reach EOF once the helper is over.
///
/// A grandchild that inherited the pipe can hold it open after the child is
/// gone, and a diagnostic is worth waiting a moment for and nothing more.
-const ENDPOINT_STDERR_DRAIN: Duration = Duration::from_secs(2);
+const STDERR_DRAIN: Duration = Duration::from_secs(2);
const MAX_ENDPOINT_BYTES: u64 = 4096;
-const START_RECEIPT_PREFIX: &[u8] = b"@avibe-start-receipt:";
-const MAX_START_OUTPUT_BYTES: usize = 65_536;
-const START_OUTPUT_DRAIN_TIMEOUT: Duration = Duration::from_secs(1);
#[cfg(windows)]
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
@@ -113,26 +114,27 @@ pub enum LaunchError {
InvalidOrigin,
#[error("failed to start the installed Avibe Runtime")]
Spawn(#[source] std::io::Error),
- #[error("failed to stop the superseded desktop-managed Runtime")]
- Handover,
- #[error("the Runtime was not launched by this host")]
- NotOwned,
- #[error("failed to stop the shell-started Runtime")]
+ #[error("the Runtime is being stopped")]
RuntimeStop,
- #[error("the Runtime ownership receipt no longer matches the service")]
- OwnershipLost,
}
-/// What the shell proved about a Runtime before removing app-private files.
+/// How one run of a Runtime lifecycle verb ended: `vibe stop
+/// --expect-runtime-id` or `vibe desktop remove-backends`.
///
-/// Removal fails closed when an adopted origin stops answering: deleting its
-/// executable tree would strand a still-running Controller or UI process.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum RuntimeRemovalState {
- Inactive,
- Managed,
- External,
- Unknown,
+/// Read from the exit code and the last JSON line the verb wrote to stderr.
+/// The reason and part are stable codes for the log; none of them reaches the
+/// WebView.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum CliOutcome {
+ /// Exit 0.
+ Completed,
+ /// Exit 3: the verb refused and changed nothing.
+ Refused { reason: String },
+ /// Exit 2, any other exit, or a signal: part of the work may not have
+ /// happened, and something may still be running.
+ Failed { part: String },
+ /// The verb could not be run at all, so it proved nothing either way.
+ Unrunnable,
}
impl LaunchError {
@@ -151,10 +153,7 @@ impl LaunchError {
BootstrapNoticeCode::RuntimeDiscoveryFailed
}
Self::InvalidOrigin => BootstrapNoticeCode::InvalidOrigin,
- Self::OwnershipLost => BootstrapNoticeCode::RuntimeOwnershipLost,
- Self::Spawn(_) | Self::Handover | Self::NotOwned | Self::RuntimeStop => {
- BootstrapNoticeCode::RuntimeSpawnFailed
- }
+ Self::Spawn(_) | Self::RuntimeStop => BootstrapNoticeCode::RuntimeSpawnFailed,
}
}
}
@@ -166,125 +165,126 @@ impl LaunchError {
pub trait RuntimeLauncher: Send + Sync {
fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError>;
- /// Gracefully stops and removes an app-private Runtime, if this launcher owns
- /// one. Installed/user-managed launchers deliberately do nothing.
- fn remove_private_runtime(&self, _state: RuntimeRemovalState) -> Result<bool, LaunchError> {
- Ok(false)
+ /// Whether uninstall has app-private files to remove. Installed and
+ /// user-managed launchers own nothing and are never modified.
+ fn owns_private_files(&self) -> bool {
+ false
+ }
+
+ /// Deletes the private Runtime tree.
+ ///
+ /// Runs only after the Runtime was stopped and `remove-backends` deleted
+ /// the backend root under every install claim. The backend root is left
+ /// alone on purpose: an install that starts afterwards owns it.
+ fn remove_private_files(&self) -> Result<(), LaunchError> {
+ Ok(())
+ }
+
+ /// Deletes the private Runtime tree and the backend root without the
+ /// Runtime's confirmation that its installs have stopped. Only a user who
+ /// chose "Delete anyway" reaches this.
+ fn remove_unverified_private_files(&self) -> Result<(), LaunchError> {
+ Ok(())
}
}
/// One executable frozen for a single bootstrap attempt.
///
-/// Both methods use this exact executable. `launch` returns as soon as it is
-/// spawned; readiness is decided by the readiness probe.
+/// Every method uses this exact executable. `launch` returns as soon as it is
+/// spawned; readiness is decided by the presence probe.
pub trait ResolvedRuntimeLauncher: Send + Sync {
fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError>;
- fn launch(&self) -> Result<LaunchedRuntime, LaunchError>;
-
- fn stop(&self, _receipt: &StartupReceipt) -> Result<(), LaunchError> {
- Err(LaunchError::RuntimeStop)
- }
+ /// `hand_over` lets the start replace another desktop Runtime serving this
+ /// home. The start owns that act and reports it in its exit.
+ fn launch(&self, hand_over: bool) -> Result<LaunchedRuntime, LaunchError>;
+ /// The provenance id of the Runtime this launcher starts, if it has one.
+ /// Only a Runtime serving this id is this launcher's own.
fn expected_runtime_id(&self) -> Option<&str> {
None
}
- fn requires_handover(&self, readiness: &RuntimeReadiness) -> bool {
- matches!(
- (self.expected_runtime_id(), readiness.desktop_runtime_id.as_deref()),
- (Some(expected), Some(actual)) if expected != actual
- )
+ /// Stops the Runtime whose identity is `runtime_id`, and nothing else.
+ fn stop(&self, _runtime_id: &str) -> CliOutcome {
+ CliOutcome::Unrunnable
}
- fn handover(&self) -> Result<(), LaunchError> {
- Ok(())
+ /// Deletes the app-private backend root under every install claim.
+ fn remove_backends(&self) -> CliOutcome {
+ CliOutcome::Unrunnable
}
fn prune_superseded(&self) {}
}
-#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
-#[serde(deny_unknown_fields)]
-pub struct StartupReceipt {
- schema_version: u32,
- outcome: StartupOutcome,
- service_pid: u32,
- ui_pid: u32,
- service_create_unix_ms: f64,
- ui_create_unix_ms: f64,
-}
-
-#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
-#[serde(rename_all = "lowercase")]
-enum StartupOutcome {
+/// What the launcher's exit says about one start.
+///
+/// `vibe start` is short-lived by design: it brings the Runtime up and exits, so
+/// the shell cannot treat "it is gone" as failure. Its exit code distinguishes
+/// startup failure from completion, and for a start of this shell's own Runtime
+/// the handover's verdict: stop authority comes from the Runtime's identity,
+/// never from this helper.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LaunchExit {
+ /// 0: the start completed.
Started,
- Reused,
+ /// 3 from a start of this shell's Runtime: another desktop Runtime serves
+ /// this home, and the start did not replace it.
+ HandoverRefused,
+ /// 2 from a start asked to hand over: the Runtime it replaced may be left
+ /// partly running.
+ HandoverFailed,
+ /// Any other exit, or a signal.
+ Failed,
}
-impl StartupReceipt {
- pub(crate) fn from_json(bytes: &[u8]) -> Option<Self> {
- let receipt: Self = serde_json::from_slice(bytes).ok()?;
- (receipt.schema_version == 1
- && receipt.service_pid > 0
- && receipt.ui_pid > 0
- && receipt.service_create_unix_ms.is_finite()
- && receipt.service_create_unix_ms > 0.0
- && receipt.ui_create_unix_ms.is_finite()
- && receipt.ui_create_unix_ms > 0.0)
- .then_some(receipt)
+impl LaunchExit {
+ fn of(code: Option<i32>, identified: bool, hand_over: bool) -> Self {
+ match code {
+ Some(0) => Self::Started,
+ Some(3) if identified => Self::HandoverRefused,
+ Some(2) if hand_over => Self::HandoverFailed,
+ _ => Self::Failed,
+ }
}
}
-#[derive(Debug)]
-struct LaunchOutcome {
- succeeded: bool,
- receipt: Option<StartupReceipt>,
-}
-
/// Whether the launcher process itself survived long enough to do its job.
-///
-/// `vibe start` is short-lived by design: it brings the Runtime up and exits, so
-/// the shell cannot treat "it is gone" as failure. Its exit code distinguishes
-/// startup failure from completion; only the receipt proves stop authority.
-/// Empty means "still running, or not observable" and grants no authority.
+/// Empty means "still running, or not observable".
#[derive(Debug, Clone, Default)]
-pub struct LaunchWatch(Arc<OnceLock<LaunchOutcome>>);
+pub struct LaunchWatch(Arc<OnceLock<LaunchExit>>);
impl LaunchWatch {
/// A watch that has already seen the launcher exit. For launchers that learn
/// the outcome synchronously, and for tests.
- pub fn exited(succeeded: bool) -> Self {
+ pub fn exited(exit: LaunchExit) -> Self {
let watch = Self::default();
- watch.record(succeeded, None);
+ watch.record(exit);
watch
}
- pub fn exited_with_receipt(succeeded: bool, receipt: StartupReceipt) -> Self {
- let watch = Self::default();
- watch.record(succeeded, Some(receipt));
- watch
+ /// The exit seen, if the launcher has exited.
+ pub fn exit(&self) -> Option<LaunchExit> {
+ self.0.get().copied()
}
/// True only once the launcher has been *seen* to exit non-zero.
pub fn failed(&self) -> bool {
- self.0.get().is_some_and(|outcome| !outcome.succeeded)
+ self.exit().is_some_and(|exit| exit != LaunchExit::Started)
}
/// True only once the launcher has been *seen* to exit successfully.
pub fn succeeded(&self) -> bool {
- self.0.get().is_some_and(|outcome| outcome.succeeded)
+ self.exit() == Some(LaunchExit::Started)
}
- pub(crate) fn owned_receipt(&self) -> Option<&StartupReceipt> {
- let outcome = self.0.get().filter(|outcome| outcome.succeeded)?;
- outcome
- .receipt
- .as_ref()
- .filter(|receipt| receipt.outcome == StartupOutcome::Started)
+ /// Neither outcome has been seen: the launcher may still be starting pieces.
+ pub fn pending(&self) -> bool {
+ self.0.get().is_none()
}
- fn record(&self, succeeded: bool, receipt: Option<StartupReceipt>) {
- let _ = self.0.set(LaunchOutcome { succeeded, receipt });
+ fn record(&self, exit: LaunchExit) {
+ let _ = self.0.set(exit);
}
}
@@ -385,27 +385,20 @@ impl RuntimeLauncher for BundledVibeLauncher {
}))
}
- fn remove_private_runtime(&self, state: RuntimeRemovalState) -> Result<bool, LaunchError> {
- if state == RuntimeRemovalState::Unknown {
- return Err(LaunchError::RuntimeRemoval);
- }
+ fn owns_private_files(&self) -> bool {
+ true
+ }
+
+ fn remove_private_files(&self) -> Result<(), LaunchError> {
+ self.bundle.remove_all().map_err(|_| LaunchError::RuntimeRemoval)
+ }
+
+ fn remove_unverified_private_files(&self) -> Result<(), LaunchError> {
+ // Checked before anything is deleted, so an unsafe backend root keeps
+ // the Runtime tree too.
validate_private_directory_root(&self.backend_root)?;
- if state == RuntimeRemovalState::Managed {
- let runtime = self.bundle.prepare().map_err(|_| LaunchError::RuntimeInstall)?;
- let command = RuntimeCommand::private(
- runtime.root,
- runtime.python,
- runtime.node,
- runtime.npm_cli,
- self.backend_root.clone(),
- &runtime.runtime_id,
- env::var_os("PATH").as_deref(),
- );
- run_handover(&command)?;
- }
self.bundle.remove_all().map_err(|_| LaunchError::RuntimeRemoval)?;
- remove_private_directory_root(&self.backend_root)?;
- Ok(true)
+ remove_private_directory_root(&self.backend_root)
}
}
@@ -442,16 +435,15 @@ impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
query_endpoint(&self.command, &self.log)
}
- fn launch(&self) -> Result<LaunchedRuntime, LaunchError> {
- let mut child = spawn_detached(&self.command).map_err(LaunchError::Spawn)?;
+ fn launch(&self, hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
+ // Only this shell's own Runtime is started by a CLI of its version,
+ // which knows the flag and exits by the handover contract.
+ let identified = self.expected_runtime_id.is_some();
+ let hand_over = hand_over && identified;
+ let started = Instant::now();
+ let child = spawn_detached(&self.command, hand_over).map_err(LaunchError::Spawn)?;
let pid = child.id();
let watch = LaunchWatch::default();
- let stdout = child.stdout.take().expect("startup stdout is piped");
- let (sender, receiver) = mpsc::sync_channel(1);
- std::thread::spawn(move || {
- let receipt = read_startup_receipt(stdout);
- let _ = sender.send(receipt);
- });
// Reap the launcher process so it cannot linger as a zombie. `vibe start`
// returns once the Runtime daemons are up; those daemons are grandchildren
@@ -461,11 +453,21 @@ impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
// The wait was already happening; recording its verdict costs nothing and
// is the only place the shell can learn that the launcher died.
let reaped = watch.clone();
+ let log = self.log.clone();
std::thread::spawn(move || {
let mut child = child;
if let Ok(status) = child.wait() {
- let receipt = receiver.recv_timeout(START_OUTPUT_DRAIN_TIMEOUT).ok().flatten();
- reaped.record(status.success(), receipt);
+ let exit = LaunchExit::of(status.code(), identified, hand_over);
+ log.record(
+ "runtime.start",
+ &[
+ ("outcome", format!("{exit:?}")),
+ ("exit", status.to_string()),
+ ("hand_over", hand_over.to_string()),
+ ("ms", started.elapsed().as_millis().to_string()),
+ ],
+ );
+ reaped.record(exit);
}
});
@@ -476,20 +478,17 @@ impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
self.expected_runtime_id.as_deref()
}
- fn handover(&self) -> Result<(), LaunchError> {
- run_handover(&self.command)
+ fn stop(&self, runtime_id: &str) -> CliOutcome {
+ run_lifecycle_verb(&self.command, &stop_arguments(runtime_id), &self.log, "runtime.stop")
}
- fn stop(&self, receipt: &StartupReceipt) -> Result<(), LaunchError> {
- let status = scoped_stop_command(&self.command, receipt)?
- .spawn()
- .and_then(|mut child| child.wait())
- .map_err(|_| LaunchError::RuntimeStop)?;
- match status.code() {
- Some(0) => Ok(()),
- Some(3) => Err(LaunchError::OwnershipLost),
- _ => Err(LaunchError::RuntimeStop),
- }
+ fn remove_backends(&self) -> CliOutcome {
+ run_lifecycle_verb(
+ &self.command,
+ &REMOVE_BACKENDS_ARGS,
+ &self.log,
+ "runtime.remove_backends",
+ )
}
fn prune_superseded(&self) {
@@ -654,7 +653,7 @@ fn query_endpoint_within(
let result = endpoint_descriptor(runtime, timeout, &mut status, &mut stderr_reader);
// Collected after the query returns, so a timeout that had to kill the child
// still reports what that child said before it was killed.
- let stderr = stderr_reader.and_then(|reader| reader.recv_timeout(ENDPOINT_STDERR_DRAIN).ok());
+ let stderr = stderr_reader.and_then(|reader| reader.recv_timeout(STDERR_DRAIN).ok());
let attempt = EndpointAttempt {
result,
status,
@@ -747,8 +746,8 @@ fn spawn_stderr_tail(mut stderr: std::process::ChildStderr) -> mpsc::Receiver<Ve
Ok(0) | Err(_) => break,
Ok(read) => {
tail.extend_from_slice(&chunk[..read]);
- if tail.len() > MAX_ENDPOINT_STDERR_BYTES {
- tail.drain(..tail.len() - MAX_ENDPOINT_STDERR_BYTES);
+ if tail.len() > MAX_STDERR_TAIL_BYTES {
+ tail.drain(..tail.len() - MAX_STDERR_TAIL_BYTES);
}
}
}
@@ -931,42 +930,88 @@ fn is_executable(_metadata: &std::fs::Metadata) -> bool {
true
}
-fn spawn_detached(runtime: &RuntimeCommand) -> std::io::Result<std::process::Child> {
- lifecycle_command(runtime, &START_ARGS).stdout(Stdio::piped()).spawn()
+fn spawn_detached(runtime: &RuntimeCommand, hand_over: bool) -> std::io::Result<std::process::Child> {
+ let mut command = lifecycle_command(runtime, &START_ARGS);
+ if hand_over {
+ command.arg(HAND_OVER_ARG);
+ }
+ command.spawn()
}
-fn read_startup_receipt(mut stdout: impl Read) -> Option<StartupReceipt> {
- let mut bytes = Vec::new();
- let mut chunk = [0; 4096];
- let mut oversized = false;
- loop {
- let count = stdout.read(&mut chunk).ok()?;
- if count == 0 {
- break;
- }
- if !oversized && bytes.len() + count <= MAX_START_OUTPUT_BYTES {
- bytes.extend_from_slice(&chunk[..count]);
- } else {
- oversized = true;
- bytes.clear();
+/// `vibe stop`, scoped to one Runtime identity. There is no unscoped form: a
+/// refusal is final, never a cue to stop whatever holds the service.
+fn stop_arguments(runtime_id: &str) -> [&str; 3] {
+ ["stop", "--expect-runtime-id", runtime_id]
+}
+
+/// Runs one lifecycle verb to completion and reads its verdict.
+///
+/// The verb owns its graceful and forced-stop budgets. An outer deadline would
+/// kill this coordinator while the Runtime is still shutting down, and the
+/// caller would then act against services that are still alive.
+fn run_lifecycle_verb(runtime: &RuntimeCommand, args: &[&str], log: &BootstrapLog, event: &str) -> CliOutcome {
+ let started = Instant::now();
+ let mut command = lifecycle_command(runtime, args);
+ // The verdict is on stderr. It stays in this process and the log.
+ command.stderr(Stdio::piped());
+ let mut child = match command.spawn() {
+ Ok(child) => child,
+ Err(error) => {
+ log.record(
+ event,
+ &[("outcome", "unrunnable".to_owned()), ("error", error.to_string())],
+ );
+ return CliOutcome::Unrunnable;
}
+ };
+ let stderr = child.stderr.take().map(spawn_stderr_tail);
+ let status = child.wait();
+ let stderr = stderr
+ .and_then(|reader| reader.recv_timeout(STDERR_DRAIN).ok())
+ .unwrap_or_default();
+ let code = status.as_ref().ok().and_then(|status| status.code());
+ let outcome = cli_outcome(code, &stderr);
+ let mut fields = vec![
+ ("outcome", format!("{outcome:?}")),
+ ("ms", started.elapsed().as_millis().to_string()),
+ ];
+ match &status {
+ Ok(status) => fields.push(("exit", status.to_string())),
+ Err(error) => fields.push(("error", error.to_string())),
}
- if oversized {
- return None;
+ if !stderr.is_empty() {
+ fields.push(("stderr", String::from_utf8_lossy(&stderr).into_owned()));
}
- let mut receipts = bytes
- .split(|byte| *byte == b'\n')
- .filter_map(|line| line.strip_prefix(START_RECEIPT_PREFIX));
- let receipt = StartupReceipt::from_json(receipts.next()?)?;
- receipts.next().is_none().then_some(receipt)
+ log.record(event, &fields);
+ outcome
}
-fn scoped_stop_command(runtime: &RuntimeCommand, receipt: &StartupReceipt) -> Result<Command, LaunchError> {
- if receipt.outcome != StartupOutcome::Started {
- return Err(LaunchError::NotOwned);
+/// The frozen exit contract: 0 completed, 3 refused, 2 failed. Anything else,
+/// including a signal, is a failure whose part is unknown.
+fn cli_outcome(code: Option<i32>, stderr: &[u8]) -> CliOutcome {
+ match code {
+ Some(0) => CliOutcome::Completed,
+ Some(3) => CliOutcome::Refused {
+ reason: last_json_string(stderr, "reason"),
+ },
+ Some(2) => CliOutcome::Failed {
+ part: last_json_string(stderr, "failed"),
+ },
+ _ => CliOutcome::Failed {
+ part: "unknown".to_owned(),
+ },
}
- let json = serde_json::to_string(receipt).map_err(|_| LaunchError::RuntimeStop)?;
- Ok(lifecycle_command(runtime, &["stop", "--receipt", &json]))
+}
+
+/// A string field of the last JSON line on stderr. The verb writes a localized
+/// line for people first, then this one for the shell.
+fn last_json_string(stderr: &[u8], field: &str) -> String {
+ String::from_utf8_lossy(stderr)
+ .lines()
+ .rev()
+ .find_map(|line| serde_json::from_str::<serde_json::Value>(line.trim()).ok())
+ .and_then(|verdict| verdict.get(field)?.as_str().map(str::to_owned))
+ .unwrap_or_else(|| "unknown".to_owned())
}
fn lifecycle_command(runtime: &RuntimeCommand, args: &[&str]) -> Command {
@@ -998,168 +1043,81 @@ fn lifecycle_command(runtime: &RuntimeCommand, args: &[&str]) -> Command {
command
}
-fn run_handover(runtime: &RuntimeCommand) -> Result<(), LaunchError> {
- // `vibe stop` owns the component-specific graceful and forced-stop budgets.
- // A shorter outer deadline would kill this coordinator while its children
- // are still shutting down and then start a successor against live services.
- let status = lifecycle_command(runtime, &STOP_ARGS)
- .spawn()
- .and_then(|mut child| child.wait())
- .map_err(|_| LaunchError::Handover)?;
- if status.success() {
- Ok(())
- } else {
- Err(LaunchError::Handover)
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsStr;
- fn receipt(outcome: &str) -> StartupReceipt {
- StartupReceipt::from_json(
- format!(
- r#"{{"schema_version":1,"outcome":"{outcome}","service_pid":1234,"ui_pid":5678,"service_create_unix_ms":1789010100123.5,"ui_create_unix_ms":1789010100456.5}}"#
- ).as_bytes(),
- ).expect("valid fixture")
- }
-
- #[test]
- fn startup_receipts_are_extracted_from_one_exact_prefixed_line_only() {
- for outcome in ["started", "reused"] {
- let expected = receipt(outcome);
- let json = serde_json::to_string(&expected).expect("fixture JSON");
- let output = format!("Starting 服务…\r\n@avibe-start-receipt:{json}\r\nReady\n");
- assert_eq!(read_startup_receipt(output.as_bytes()), Some(expected));
- for output in [
- format!("{json}\n"),
- format!("prefix @avibe-start-receipt:{json}\n"),
- format!("@avibe-start-receipt:{json}\n@avibe-start-receipt:{json}\n"),
- format!("@avibe-start-receipt:{json}\n@avibe-start-receipt:broken\n"),
- ] {
- assert!(read_startup_receipt(output.as_bytes()).is_none());
- }
- }
- assert!(read_startup_receipt(b"legacy successful startup\n".as_slice()).is_none());
- }
-
- #[test]
- fn startup_receipt_validation_fails_closed_for_every_required_field() {
- let valid = serde_json::to_value(receipt("started")).expect("fixture JSON");
- for field in valid.as_object().expect("receipt object").keys() {
- let mut missing = valid.clone();
- missing.as_object_mut().expect("receipt object").remove(field);
- assert!(
- StartupReceipt::from_json(&serde_json::to_vec(&missing).unwrap()).is_none(),
- "{field}"
- );
- }
- for (field, value) in [
- ("schema_version", serde_json::json!(2)),
- ("outcome", serde_json::json!("unknown")),
- ("service_pid", serde_json::json!(0)),
- ("ui_pid", serde_json::json!(-1)),
- ("service_create_unix_ms", serde_json::json!(0)),
- ("ui_create_unix_ms", serde_json::json!(-0.5)),
- ("ui_create_unix_ms", serde_json::json!(null)),
- ("unexpected", serde_json::json!(true)),
- ] {
- let mut invalid = valid.clone();
- invalid[field] = value;
- assert!(
- StartupReceipt::from_json(&serde_json::to_vec(&invalid).unwrap()).is_none(),
- "{field}"
- );
- }
- }
-
- #[test]
- fn oversized_startup_output_is_drained_but_never_grants_authority() {
- let json = serde_json::to_string(&receipt("started")).expect("fixture JSON");
- let line = format!("\n@avibe-start-receipt:{json}\n");
- let mut output = vec![b'x'; MAX_START_OUTPUT_BYTES - line.len()];
- output.extend_from_slice(line.as_bytes());
- assert!(read_startup_receipt(output.as_slice()).is_some());
- output.extend(vec![b'x'; MAX_START_OUTPUT_BYTES * 2]);
- let mut cursor = std::io::Cursor::new(output);
- assert!(read_startup_receipt(&mut cursor).is_none());
- assert_eq!(cursor.position(), cursor.get_ref().len() as u64);
- }
-
- #[test]
- fn receipts_cannot_authorize_failed_pending_or_reused_launches() {
- assert!(LaunchWatch::default().owned_receipt().is_none());
- assert!(LaunchWatch::exited(true).owned_receipt().is_none());
- assert!(LaunchWatch::exited_with_receipt(false, receipt("started"))
- .owned_receipt()
- .is_none());
- assert!(LaunchWatch::exited_with_receipt(true, receipt("reused"))
- .owned_receipt()
- .is_none());
- assert!(LaunchWatch::exited_with_receipt(true, receipt("started"))
- .owned_receipt()
- .is_some());
- let runtime = RuntimeCommand::installed(PathBuf::from("/never-executed"));
- assert!(matches!(
- scoped_stop_command(&runtime, &receipt("reused")),
- Err(LaunchError::NotOwned)
- ));
- }
-
+ /// The lifecycle verbs read the frozen CLI contract from a real process:
+ /// the exit code decides, and the last JSON line on stderr names the reason
+ /// or the failed part. Every verb runs the resolved executable as a desktop
+ /// shell child, and a stop always names one Runtime identity.
#[cfg(unix)]
#[test]
- fn a_real_launcher_publishes_only_its_completed_receipt() {
- for outcome in ["started", "reused"] {
- let dir = scratch_dir("startup-receipt");
- let json = serde_json::to_string(&receipt(outcome)).expect("fixture JSON");
+ fn lifecycle_verbs_read_the_frozen_exit_contract_from_the_runtime_cli() {
+ let runtime_id = "a".repeat(64);
+ let failed = |part: &str| CliOutcome::Failed { part: part.to_owned() };
+ for (body, expected) in [
+ ("exit 0", CliOutcome::Completed),
+ (
+ r#"printf '%s\n' '{"reason":"service_runtime_id_mismatch"}' >&2; exit 3"#,
+ CliOutcome::Refused {
+ reason: "service_runtime_id_mismatch".to_owned(),
+ },
+ ),
+ (
+ r#"printf '%s\n' '无法停止远程访问' '{"failed":"remote_access","remaining":[]}' >&2; exit 2"#,
+ failed("remote_access"),
+ ),
+ ("echo 'no verdict' >&2; exit 2", failed("unknown")),
+ ("exit 1", failed("unknown")),
+ ("kill -9 $$", failed("unknown")),
+ ] {
+ let dir = scratch_dir("lifecycle-verb");
+ let recording = dir.join("argv");
let executable = write_fake_runtime(
&dir,
- &format!("#!/bin/sh\nprintf '%s\\n' 'Starting 服务…' '@avibe-start-receipt:{json}' 'Ready'\n"),
+ &format!(
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" \"shell=$AVIBE_DESKTOP_SHELL\" >> \"{}\"\n{body}\n",
+ recording.display()
+ ),
);
let resolved = InstalledVibeLauncher {
candidates: vec![executable],
}
.resolve()
.expect("fake resolve");
- let launched = resolved.launch().expect("fake launch");
- let deadline = Instant::now() + Duration::from_secs(5);
- while !launched.watch.succeeded() && Instant::now() < deadline {
- std::thread::sleep(Duration::from_millis(10));
- }
- assert!(launched.watch.succeeded());
- assert_eq!(launched.watch.owned_receipt().is_some(), outcome == "started");
+ assert_eq!(resolved.stop(&runtime_id), expected, "{body}");
+ assert_eq!(resolved.remove_backends(), expected, "{body}");
+ assert_eq!(
+ std::fs::read_to_string(&recording)
+ .expect("recorded argv")
+ .lines()
+ .collect::<Vec<_>>(),
+ [
+ "stop",
+ "--expect-runtime-id",
+ &runtime_id,
+ "shell=1",
+ "desktop",
+ "remove-backends",
+ "shell=1",
+ ],
+ "{body}"
+ );
std::fs::remove_dir_all(dir).expect("remove test-owned state");
}
- }
- #[cfg(unix)]
- #[test]
- fn scoped_stop_exit_three_never_falls_back_to_unscoped_stop() {
- let dir = scratch_dir("receipt-refused");
- let recording = dir.join("argv");
- let executable = write_fake_runtime(&dir, &format!(
- "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"{}\"\nprintf '%s\\n' '{{\"reason\":\"service_pid_mismatch\"}}' >&2\nexit 3\n", recording.display()
- ));
+ let dir = scratch_dir("lifecycle-unrunnable");
+ let executable = write_fake_runtime(&dir, "#!/bin/sh\nexit 0\n");
let resolved = InstalledVibeLauncher {
- candidates: vec![executable],
+ candidates: vec![executable.clone()],
}
.resolve()
.expect("fake resolve");
- let receipt = receipt("started");
- assert!(matches!(resolved.stop(&receipt), Err(LaunchError::OwnershipLost)));
- assert_eq!(
- std::fs::read_to_string(recording)
- .expect("recorded argv")
- .lines()
- .collect::<Vec<_>>(),
- [
- "stop",
- "--receipt",
- &serde_json::to_string(&receipt).expect("fixture JSON")
- ]
- );
+ std::fs::remove_file(executable).expect("the Runtime disappears after resolution");
+ assert_eq!(resolved.stop(&runtime_id), CliOutcome::Unrunnable);
+ assert_eq!(resolved.remove_backends(), CliOutcome::Unrunnable);
std::fs::remove_dir_all(dir).expect("remove test-owned state");
}
@@ -1171,46 +1129,18 @@ mod tests {
environment: vec![(OsString::from("AVIBE_DESKTOP_MANAGED_RUNTIME"), OsString::from("1"))],
withholds_inherited_python: true,
};
- let receipt = receipt("started");
- let json = serde_json::to_string(&receipt).expect("fixture JSON");
- let command = scoped_stop_command(&runtime, &receipt).expect("scoped stop");
+ let runtime_id = "b".repeat(64);
+ let command = lifecycle_command(&runtime, &stop_arguments(&runtime_id));
assert_eq!(command.get_program(), runtime.executable.as_os_str());
assert_eq!(
command.get_args().collect::<Vec<_>>(),
- ["-m", "vibe", "stop", "--receipt", &json]
+ ["-m", "vibe", "stop", "--expect-runtime-id", runtime_id.as_str()]
);
let environment: Vec<_> = command.get_envs().collect();
assert!(environment.contains(&(OsStr::new(DESKTOP_SHELL_ENV), Some(OsStr::new("1")))));
assert!(environment.contains(&(OsStr::new("AVIBE_DESKTOP_MANAGED_RUNTIME"), Some(OsStr::new("1")))));
}
- #[cfg(unix)]
- #[test]
- fn owned_stop_invokes_the_resolved_executable_without_rediscovery() {
- let dir = scratch_dir("owned-stop");
- let recording = dir.join("stop-argv");
- let executable = write_fake_runtime(
- &dir,
- &format!(
- "#!/bin/sh\nprintf '%s\\n' \"$@\" \"shell=$AVIBE_DESKTOP_SHELL\" > \"{}\"\n",
- recording.display()
- ),
- );
- let resolved = InstalledVibeLauncher {
- candidates: vec![executable],
- }
- .resolve()
- .expect("fake resolve");
- let receipt = receipt("started");
- let json = serde_json::to_string(&receipt).expect("fixture JSON");
- resolved.stop(&receipt).expect("fake stop");
- assert_eq!(
- wait_for_file(&recording).lines().collect::<Vec<_>>(),
- ["stop", "--receipt", &json, "shell=1"]
- );
- std::fs::remove_dir_all(dir).expect("remove test-owned state");
- }
-
fn executable_name() -> String {
format!("vibe{}", env::consts::EXE_SUFFIX)
}
@@ -1442,9 +1372,13 @@ mod tests {
dir
}
+ /// A verified removal leaves the backend root alone: `remove-backends`
+ /// already deleted it under every install claim, and an install that began
+ /// afterwards owns what is there now. Only "Delete anyway" deletes it here,
+ /// and neither path touches user state.
#[test]
- fn inactive_broken_private_runtime_is_removed_without_preparing_the_bundle() {
- let root = scratch_dir("remove-broken-inactive");
+ fn only_an_unverified_removal_deletes_the_backend_root_itself() {
+ let root = scratch_dir("remove-private-files");
let install_root = root.join("application-data").join("runtime");
let backend_root = root.join("application-data").join("backends");
let user_state = root.join("user-state");
@@ -1460,10 +1394,18 @@ mod tests {
backend_root.clone(),
BootstrapLog::disabled(),
);
+ assert!(launcher.owns_private_files());
- assert!(launcher
- .remove_private_runtime(RuntimeRemovalState::Inactive)
- .expect("inactive broken Runtime is removable"));
+ launcher
+ .remove_private_files()
+ .expect("the private Runtime tree is removed");
+ assert!(!install_root.exists());
+ assert!(backend_root.join("codex").is_file());
+
+ std::fs::create_dir_all(&install_root).expect("broken private Runtime root");
+ launcher
+ .remove_unverified_private_files()
+ .expect("an inactive broken Runtime is removable without preparing the bundle");
assert!(!install_root.exists());
assert!(!backend_root.exists());
assert_eq!(
@@ -1474,38 +1416,6 @@ mod tests {
std::fs::remove_dir_all(root).ok();
}
- #[test]
- fn unknown_runtime_ownership_blocks_private_file_removal() {
- let root = scratch_dir("remove-unknown");
- let install_root = root.join("application-data").join("runtime");
- let backend_root = root.join("application-data").join("backends");
- std::fs::create_dir_all(&install_root).expect("private Runtime root");
- std::fs::create_dir_all(&backend_root).expect("private backend root");
- std::fs::write(install_root.join("active"), b"potentially active").expect("private Runtime file");
- std::fs::write(backend_root.join("active"), b"potentially active").expect("private backend file");
- let launcher = BundledVibeLauncher::new(
- root.join("missing-bundle"),
- install_root.clone(),
- backend_root.clone(),
- BootstrapLog::disabled(),
- );
-
- assert!(matches!(
- launcher.remove_private_runtime(RuntimeRemovalState::Unknown),
- Err(LaunchError::RuntimeRemoval)
- ));
- assert!(
- install_root.is_dir(),
- "uncertain ownership must preserve the executable tree"
- );
- assert!(
- backend_root.is_dir(),
- "uncertain ownership must preserve private backends"
- );
-
- std::fs::remove_dir_all(root).ok();
- }
-
#[test]
fn a_non_directory_backend_root_blocks_all_private_removal() {
let root = scratch_dir("remove-backend-file");
@@ -1522,7 +1432,7 @@ mod tests {
);
assert!(matches!(
- launcher.remove_private_runtime(RuntimeRemovalState::Inactive),
+ launcher.remove_unverified_private_files(),
Err(LaunchError::RuntimeRemoval)
));
assert!(install_root.is_dir());
@@ -1553,7 +1463,7 @@ mod tests {
);
assert!(matches!(
- launcher.remove_private_runtime(RuntimeRemovalState::Inactive),
+ launcher.remove_unverified_private_files(),
Err(LaunchError::RuntimeRemoval)
));
assert!(install_root.is_dir());
@@ -1566,14 +1476,23 @@ mod tests {
}
/// Writes a runnable stand-in for `vibe` and returns its path.
+ ///
+ /// A child process writes it, so this test process never holds a writable
+ /// descriptor on a file it is about to exec. Tests run on parallel threads,
+ /// and a child that another thread forks between our open and close
+ /// inherits that descriptor until its own exec; exec'ing the file then
+ /// fails with ETXTBSY. Writing to a temporary name and renaming does not
+ /// help, because the renamed file is the same inode.
#[cfg(unix)]
fn write_fake_runtime(dir: &Path, body: &str) -> PathBuf {
- use std::os::unix::fs::PermissionsExt;
-
let executable = dir.join("vibe");
- std::fs::write(&executable, body).expect("fake runtime is written");
- std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755))
- .expect("fake runtime is runnable");
+ let status = Command::new("/bin/sh")
+ .args(["-c", "printf '%s' \"$2\" > \"$1\" && chmod 755 \"$1\"", "sh"])
+ .arg(&executable)
+ .arg(body)
+ .status()
+ .expect("the fake runtime writer runs");
+ assert!(status.success(), "the fake runtime is written");
executable
}
@@ -1607,7 +1526,7 @@ mod tests {
let resolved = launcher.resolve().expect("the first executable resolves");
std::fs::remove_file(first).expect("the first executable is removed");
assert!(
- matches!(resolved.launch(), Err(LaunchError::Spawn(_))),
+ matches!(resolved.launch(false), Err(LaunchError::Spawn(_))),
"an in-flight attempt must not silently switch to the second candidate"
);
assert!(
@@ -1633,40 +1552,62 @@ mod tests {
panic!("{} was never written", path.display());
}
+ /// A launcher of this shell's own Runtime, whose CLI is of the shell's version.
+ #[cfg(unix)]
+ fn identified(executable: PathBuf) -> ResolvedVibeExecutable {
+ ResolvedVibeExecutable {
+ command: RuntimeCommand::installed(executable),
+ expected_runtime_id: Some("a".repeat(64)),
+ cleanup: None,
+ log: BootstrapLog::disabled(),
+ }
+ }
+
/// Asserts the launch contract against what the operating system actually
/// receives, rather than against the constant the code was built from.
#[cfg(unix)]
#[test]
fn the_runtime_is_started_headless_and_marked_as_shell_started() {
- let dir = scratch_dir("launch");
- let recording = dir.join("argv");
- let executable = write_fake_runtime(
- &dir,
- &format!(
- "#!/bin/sh\nprintf '%s\\n' \"$@\" \"shell=$AVIBE_DESKTOP_SHELL\" > \"{}\"\n",
- recording.display()
+ // Only this shell's own Runtime is asked to hand over: an installed
+ // CLI may predate the flag, and would refuse the start.
+ for (identified_launcher, hand_over, expected) in [
+ (false, true, &["start", "--no-open-browser", "shell=1"][..]),
+ (true, false, &["start", "--no-open-browser", "shell=1"][..]),
+ (
+ true,
+ true,
+ &["start", "--no-open-browser", "--hand-over", "shell=1"][..],
),
- );
+ ] {
+ let dir = scratch_dir("launch");
+ let recording = dir.join("argv");
+ let executable = write_fake_runtime(
+ &dir,
+ &format!(
+ "#!/bin/sh\nprintf '%s\\n' \"$@\" \"shell=$AVIBE_DESKTOP_SHELL\" > \"{}\"\n",
+ recording.display()
+ ),
+ );
- let launcher = InstalledVibeLauncher {
- candidates: vec![executable],
- };
- let launched = launcher
- .resolve()
- .expect("the fake runtime resolves")
- .launch()
- .expect("the fake runtime starts");
- assert!(launched.pid > 0);
+ let resolved: Arc<dyn ResolvedRuntimeLauncher> = if identified_launcher {
+ Arc::new(identified(executable))
+ } else {
+ InstalledVibeLauncher {
+ candidates: vec![executable],
+ }
+ .resolve()
+ .expect("the fake runtime resolves")
+ };
+ let launched = resolved.launch(hand_over).expect("the fake runtime starts");
+ assert!(launched.pid > 0);
- let recorded = wait_for_file(&recording);
- assert_eq!(
- recorded.lines().collect::<Vec<_>>(),
+ let recorded = wait_for_file(&recording);
// Without --no-open-browser the Runtime would open a second window
// onto the Workbench, in the system browser.
- ["start", "--no-open-browser", "shell=1"],
- );
+ assert_eq!(recorded.lines().collect::<Vec<_>>(), expected);
- std::fs::remove_dir_all(&dir).ok();
+ std::fs::remove_dir_all(&dir).ok();
+ }
}
#[cfg(unix)]
@@ -2060,77 +2001,53 @@ mod tests {
std::fs::remove_dir_all(&dir).ok();
}
- #[cfg(unix)]
- #[test]
- fn a_superseded_runtime_is_stopped_through_the_cli_contract() {
- let dir = scratch_dir("handover");
- let recording = dir.join("stop-argv");
- let executable = write_fake_runtime(
- &dir,
- &format!(
- "#!/bin/sh\nprintf '%s\\n' \"$@\" \"shell=$AVIBE_DESKTOP_SHELL\" > \"{}\"\n",
- recording.display()
- ),
- );
- let launcher = InstalledVibeLauncher {
- candidates: vec![executable],
- };
-
- launcher
- .resolve()
- .expect("the fake runtime resolves")
- .handover()
- .expect("the fake runtime stops");
-
- assert_eq!(
- wait_for_file(&recording).lines().collect::<Vec<_>>(),
- ["stop", "shell=1"],
- );
- std::fs::remove_dir_all(&dir).ok();
- }
-
/// The bootstrap loop aborts a doomed wait on this verdict, so it has to be
- /// right in both directions: a launcher that refused its arguments must be
- /// visible, and the ordinary `vibe start` — which exits 0 once the Runtime is
- /// up — must never be mistaken for one.
+ /// right in every direction: a launcher that refused or failed must be
+ /// visible, the ordinary `vibe start` — which exits 0 once the Runtime is
+ /// up — must never be mistaken for one, and a handover verdict is read only
+ /// from a CLI that speaks the handover contract.
#[cfg(unix)]
#[test]
- fn only_a_non_zero_launcher_exit_is_reported_as_a_failure() {
- let refused = scratch_dir("exit-nonzero");
- let launcher = InstalledVibeLauncher {
- candidates: vec![write_fake_runtime(&refused, "#!/bin/sh\nexit 3\n")],
- };
- let launched = launcher
- .resolve()
- .expect("the fake runtime resolves")
- .launch()
- .expect("the fake runtime starts");
- // The wait runs on a detached thread, so the verdict arrives late.
- for _ in 0..200 {
- if launched.watch.failed() {
- break;
+ fn a_launcher_exit_is_read_by_the_start_contract_it_was_launched_under() {
+ for (identified_launcher, hand_over, code, expected) in [
+ (true, true, 0, LaunchExit::Started),
+ (true, true, 3, LaunchExit::HandoverRefused),
+ (true, false, 3, LaunchExit::HandoverRefused),
+ (true, true, 2, LaunchExit::HandoverFailed),
+ // Without a handover, a 2 is an ordinary failure, such as a usage error.
+ (true, false, 2, LaunchExit::Failed),
+ (true, true, 1, LaunchExit::Failed),
+ // An installed CLI never hands over, so its 3 and 2 are failures.
+ (false, true, 3, LaunchExit::Failed),
+ (false, true, 2, LaunchExit::Failed),
+ (false, false, 0, LaunchExit::Started),
+ ] {
+ let dir = scratch_dir("launch-exit");
+ let executable = write_fake_runtime(&dir, &format!("#!/bin/sh\nexit {code}\n"));
+ let resolved: Arc<dyn ResolvedRuntimeLauncher> = if identified_launcher {
+ Arc::new(identified(executable))
+ } else {
+ InstalledVibeLauncher {
+ candidates: vec![executable],
+ }
+ .resolve()
+ .expect("the fake runtime resolves")
+ };
+ let launched = resolved.launch(hand_over).expect("the fake runtime starts");
+ // The wait runs on a detached thread, so the verdict arrives late.
+ for _ in 0..200 {
+ if !launched.watch.pending() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(25));
}
- std::thread::sleep(std::time::Duration::from_millis(25));
+ assert_eq!(
+ launched.watch.exit(),
+ Some(expected),
+ "identified={identified_launcher} hand_over={hand_over} exit={code}"
+ );
+ std::fs::remove_dir_all(&dir).ok();
}
- assert!(launched.watch.failed(), "a launcher that exited non-zero is invisible");
-
- let succeeded = scratch_dir("exit-zero");
- let launcher = InstalledVibeLauncher {
- candidates: vec![write_fake_runtime(&succeeded, "#!/bin/sh\nexit 0\n")],
- };
- let launched = launcher
- .resolve()
- .expect("the fake runtime resolves")
- .launch()
- .expect("the fake runtime starts");
- std::thread::sleep(std::time::Duration::from_millis(250));
- assert!(
- !launched.watch.failed(),
- "a normal start would be aborted as if it had failed"
- );
-
- std::fs::remove_dir_all(&refused).ok();
- std::fs::remove_dir_all(&succeeded).ok();
}
#[test]
diff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rs
index 3c0e78f9e..af4a9233f 100644
--- a/desktop/runtime-host/src/lib.rs
+++ b/desktop/runtime-host/src/lib.rs
@@ -7,10 +7,10 @@
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
-//! use avibe_runtime_host::{default_runtime_host, BootstrapPhase, DiscardStatus};
+//! use avibe_runtime_host::{default_runtime_host, BootstrapPhase, BootstrapTrigger, DiscardStatus};
//!
//! let host = default_runtime_host()?;
-//! let status = host.bootstrap(&DiscardStatus).await;
+//! let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
//! if status.phase == BootstrapPhase::Ready {
//! // Only now may the WebView leave the bootstrap page.
//! }
@@ -34,15 +34,15 @@ pub mod window_frame;
use std::sync::Arc;
pub use bootstrap::{
- DiscardStatus, RuntimeHost, RuntimeHostSettings, StatusSink, DEFAULT_POLL_INTERVAL, DEFAULT_PROBE_TIMEOUT,
- DEFAULT_READY_TIMEOUT, ORIGIN_ENV, READY_TIMEOUT_ENV,
+ BootstrapTrigger, DiscardStatus, RemovalOutcome, RuntimeHost, RuntimeHostSettings, StatusSink,
+ DEFAULT_POLL_INTERVAL, DEFAULT_PROBE_TIMEOUT, DEFAULT_READY_TIMEOUT, ORIGIN_ENV, READY_TIMEOUT_ENV,
};
pub use bootstrap_log::{BootstrapLog, BOOTSTRAP_LOG_NAME};
-pub use health::{is_avibe_readiness_body, parse_avibe_readiness_body, HealthProbe, HttpHealthProbe, RuntimeReadiness};
+pub use health::{HealthProbe, HttpHealthProbe, Presence};
pub use launcher::{
- vibe_executable_candidates, BundledVibeLauncher, InstalledVibeLauncher, LaunchError, LaunchWatch, LaunchedRuntime,
- ResolvedRuntimeLauncher, RuntimeLauncher, RuntimeRemovalState, DESKTOP_BACKENDS_ROOT_ENV, DESKTOP_NPM_CLI_ENV,
- DESKTOP_RUNTIME_ROOT_ENV, UV_TOOL_BIN_DIR_ENV, VIBE_PATH_ENV,
+ vibe_executable_candidates, BundledVibeLauncher, CliOutcome, InstalledVibeLauncher, LaunchError, LaunchExit,
+ LaunchWatch, LaunchedRuntime, ResolvedRuntimeLauncher, RuntimeLauncher, DESKTOP_BACKENDS_ROOT_ENV,
+ DESKTOP_NPM_CLI_ENV, DESKTOP_RUNTIME_ROOT_ENV, UV_TOOL_BIN_DIR_ENV, VIBE_PATH_ENV,
};
pub use origin::{is_shell_ui_url, LoopbackOrigin, OriginError, DEV_SERVER_PORT};
pub use private_runtime::{PrivateRuntimeBundle, PrivateRuntimeError, RuntimeBundleManifest};
diff --git a/desktop/runtime-host/src/status.rs b/desktop/runtime-host/src/status.rs
index 70416abfe..22d5437b3 100644
--- a/desktop/runtime-host/src/status.rs
+++ b/desktop/runtime-host/src/status.rs
@@ -43,6 +43,7 @@ pub enum BootstrapNoticeCode {
RuntimeSpawnFailed,
RuntimeStopped,
RuntimeOwnershipLost,
+ RuntimeStopFailed,
LauncherExited,
ReadyTimeout,
WorkbenchNavigationFailed,
@@ -212,6 +213,7 @@ mod tests {
(BootstrapNoticeCode::RuntimeSpawnFailed, "runtime_spawn_failed"),
(BootstrapNoticeCode::RuntimeStopped, "runtime_stopped"),
(BootstrapNoticeCode::RuntimeOwnershipLost, "runtime_ownership_lost"),
+ (BootstrapNoticeCode::RuntimeStopFailed, "runtime_stop_failed"),
(BootstrapNoticeCode::LauncherExited, "launcher_exited"),
(BootstrapNoticeCode::ReadyTimeout, "ready_timeout"),
(
diff --git a/desktop/runtime-host/tests/bootstrap.rs b/desktop/runtime-host/tests/bootstrap.rs
index 8e330295f..28add65e7 100644
--- a/desktop/runtime-host/tests/bootstrap.rs
+++ b/desktop/runtime-host/tests/bootstrap.rs
@@ -3,90 +3,81 @@
//! Every test drives a real `RuntimeHost` through fake collaborators, so the
//! guarantees under test are the ones the shell actually relies on: adopt what
//! is already running, start what is not, never start twice, never navigate
-//! before the Runtime answers.
+//! before the Runtime answers, and never stop or delete a Runtime this app did
+//! not start.
//!
//! Time is virtual (`start_paused`), so the 120-second production wait is
//! exercised in microseconds.
-use std::sync::atomic::{AtomicUsize, Ordering};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use async_trait::async_trait;
use avibe_runtime_host::deep_link::DeepLinks;
use avibe_runtime_host::{
- parse_avibe_readiness_body, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus, HealthProbe, LaunchError,
- LaunchWatch, LaunchedRuntime, LoopbackOrigin, ResolvedRuntimeLauncher, RuntimeHost, RuntimeHostSettings,
- RuntimeLauncher, RuntimeReadiness, RuntimeRemovalState, StatusSink,
+ bundled_runtime_host, BootstrapLog, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus, BootstrapTrigger,
+ CliOutcome, HealthProbe, LaunchError, LaunchExit, LaunchWatch, LaunchedRuntime, LoopbackOrigin, Presence,
+ RemovalOutcome, ResolvedRuntimeLauncher, RuntimeHost, RuntimeHostSettings, RuntimeLauncher, StatusSink,
};
+use tokio::sync::Notify;
+
+use BootstrapTrigger::{Launch, Recovery, Retry};
const TEST_ORIGIN: &str = "http://127.0.0.1:5123";
-const EXTERNAL_CONTROLLER_BUNDLED_UI_READY_BODY: &str =
- include_str!("../../../tests/fixtures/desktop_ready_external_controller_bundled_ui.json");
-type RemovalRecord = RuntimeRemovalState;
-/// Answers "not yet" until the given probe call, then "ready" forever.
-struct FakeProbe {
- healthy_from: usize,
- runtime_id: Option<String>,
- ui_runtime_id: Option<String>,
- identity_mismatch_at: Option<usize>,
- calls: AtomicUsize,
+fn predecessor() -> String {
+ "a".repeat(64)
}
-impl FakeProbe {
- fn healthy_from(call: usize) -> Arc<Self> {
- Arc::new(Self {
- healthy_from: call,
- runtime_id: None,
- ui_runtime_id: None,
- identity_mismatch_at: None,
- calls: AtomicUsize::new(0),
- })
- }
+fn bundle_id() -> String {
+ "b".repeat(64)
+}
- fn healthy_from_readiness(call: usize, readiness: &RuntimeReadiness) -> Arc<Self> {
- Arc::new(Self {
- healthy_from: call,
- runtime_id: readiness.desktop_runtime_id.clone(),
- ui_runtime_id: readiness.desktop_ui_runtime_id.clone(),
- identity_mismatch_at: None,
- calls: AtomicUsize::new(0),
- })
- }
+fn origin() -> LoopbackOrigin {
+ LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin")
+}
- fn healthy_managed(runtime_id: &str) -> Arc<Self> {
- Arc::new(Self {
- healthy_from: 1,
- runtime_id: Some(runtime_id.to_owned()),
- ui_runtime_id: None,
- identity_mismatch_at: None,
- calls: AtomicUsize::new(0),
- })
- }
+/// What the origin serves on one probe call.
+#[derive(Clone)]
+enum Served {
+ /// Nothing accepts the connection.
+ Nothing,
+ /// Something answers, but readiness cannot be proven.
+ Starting,
+ /// A ready Controller carrying this desktop identity, or none.
+ Ready(Option<String>),
+ /// The Controller carries this identity, but its UI runs another one.
+ UiMismatch(String),
+}
- fn mismatched_managed(runtime_id: &str) -> Arc<Self> {
+/// Serves `script[n]` on probe call `n`, repeating the last entry, and
+/// classifies it against the caller's expected identity as `/ready` does.
+struct FakeProbe {
+ script: Vec<Served>,
+ calls: AtomicUsize,
+}
+
+impl FakeProbe {
+ fn serving(script: impl IntoIterator<Item = Served>) -> Arc<Self> {
+ let script: Vec<Served> = script.into_iter().collect();
+ assert!(!script.is_empty(), "a probe script serves something");
Arc::new(Self {
- healthy_from: usize::MAX,
- runtime_id: Some(runtime_id.to_owned()),
- ui_runtime_id: None,
- identity_mismatch_at: Some(1),
+ script,
calls: AtomicUsize::new(0),
})
}
- fn mismatch_after_launch_then_healthy(runtime_id: &str) -> Arc<Self> {
- Arc::new(Self {
- healthy_from: 3,
- runtime_id: Some(runtime_id.to_owned()),
- ui_runtime_id: None,
- identity_mismatch_at: Some(2),
- calls: AtomicUsize::new(0),
- })
+ /// Nothing proves readiness until call `call`, then an untagged Runtime.
+ fn healthy_from(call: usize) -> Arc<Self> {
+ let mut script = vec![Served::Starting; call.saturating_sub(1)];
+ script.push(Served::Ready(None));
+ Self::serving(script)
}
fn never_healthy() -> Arc<Self> {
- Self::healthy_from(usize::MAX)
+ Self::serving([Served::Starting])
}
fn calls(&self) -> usize {
@@ -96,167 +87,244 @@ impl FakeProbe {
#[async_trait]
impl HealthProbe for FakeProbe {
- async fn readiness(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
- let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
- (call >= self.healthy_from).then(|| RuntimeReadiness {
- desktop_runtime_id: self.runtime_id.clone(),
- desktop_ui_runtime_id: self.ui_runtime_id.clone(),
- })
+ async fn presence(&self, _origin: &LoopbackOrigin, expected: Option<&str>) -> Presence {
+ let call = self.calls.fetch_add(1, Ordering::SeqCst);
+ let served = self.script[call.min(self.script.len() - 1)].clone();
+ let classify = |runtime_id: String, ready: bool| {
+ if Some(runtime_id.as_str()) == expected {
+ Presence::Mine { ready }
+ } else {
+ Presence::Foreign { runtime_id, ready }
+ }
+ };
+ match served {
+ Served::Nothing => Presence::Absent,
+ Served::Starting => Presence::Unknown,
+ Served::Ready(None) => Presence::Unmanaged,
+ Served::Ready(Some(runtime_id)) => classify(runtime_id, true),
+ Served::UiMismatch(runtime_id) => classify(runtime_id, false),
+ }
}
+}
+
+/// Answers like `inner`, except that probe call `held` answers only once the
+/// test releases it: a probe still in flight while the host moves on.
+struct HeldProbe {
+ inner: Arc<FakeProbe>,
+ held: usize,
+ in_flight: Notify,
+ release: Notify,
+}
- async fn mismatched_runtime_identity(&self, _origin: &LoopbackOrigin) -> Option<RuntimeReadiness> {
- (self.identity_mismatch_at == Some(self.calls())).then(|| RuntimeReadiness {
- desktop_runtime_id: self.runtime_id.clone(),
- desktop_ui_runtime_id: None,
+impl HeldProbe {
+ fn holding(held: usize, script: impl IntoIterator<Item = Served>) -> Arc<Self> {
+ Arc::new(Self {
+ inner: FakeProbe::serving(script),
+ held,
+ in_flight: Notify::new(),
+ release: Notify::new(),
})
}
}
-/// Records launch attempts; the first `failures` of them report no executable.
-struct FakeLauncher {
- calls: Arc<AtomicUsize>,
- failures: usize,
- dies_immediately: bool,
- succeeds_immediately: bool,
+#[async_trait]
+impl HealthProbe for HeldProbe {
+ async fn presence(&self, origin: &LoopbackOrigin, expected: Option<&str>) -> Presence {
+ let call = self.inner.calls();
+ let presence = self.inner.presence(origin, expected).await;
+ if call == self.held {
+ self.in_flight.notify_one();
+ self.release.notified().await;
+ }
+ presence
+ }
+}
+
+/// A lifecycle verb the host ran through the launcher.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Verb {
+ Stop { runtime_id: String },
+ RemoveBackends,
+ RemoveFiles,
+ RemoveUnverifiedFiles,
+}
+
+struct LauncherState {
runtime_id: Option<String>,
- handovers: Arc<AtomicUsize>,
- cleanups: Arc<AtomicUsize>,
- removals: Arc<Mutex<Vec<RemovalRecord>>>,
+ private: bool,
+ /// The first `failures` launches report no executable.
+ failures: usize,
+ /// `None` keeps the launch helper running; `Some` has already seen it exit.
+ exit: Option<LaunchExit>,
+ resolvable: AtomicBool,
+ launches: AtomicUsize,
+ /// Whether each launch asked `vibe start` to hand over a predecessor.
+ handover_requests: Mutex<Vec<bool>>,
+ prunes: AtomicUsize,
+ verbs: Mutex<Vec<Verb>>,
+ stop_outcome: Mutex<CliOutcome>,
+ remove_backends_outcome: Mutex<CliOutcome>,
}
+#[derive(Clone)]
+struct FakeLauncher(Arc<LauncherState>);
+
impl FakeLauncher {
+ fn new(runtime_id: Option<String>, private: bool, failures: usize, exit: Option<LaunchExit>) -> Arc<Self> {
+ Arc::new(Self(Arc::new(LauncherState {
+ runtime_id,
+ private,
+ failures,
+ exit,
+ resolvable: AtomicBool::new(true),
+ launches: AtomicUsize::new(0),
+ handover_requests: Mutex::new(Vec::new()),
+ prunes: AtomicUsize::new(0),
+ verbs: Mutex::new(Vec::new()),
+ stop_outcome: Mutex::new(CliOutcome::Completed),
+ remove_backends_outcome: Mutex::new(CliOutcome::Completed),
+ })))
+ }
+
+ /// An installed `vibe`: no Runtime identity and no private files.
fn working() -> Arc<Self> {
- Arc::new(Self {
- calls: Arc::new(AtomicUsize::new(0)),
- failures: 0,
- dies_immediately: false,
- succeeds_immediately: false,
- runtime_id: None,
- handovers: Arc::new(AtomicUsize::new(0)),
- cleanups: Arc::new(AtomicUsize::new(0)),
- removals: Arc::new(Mutex::new(Vec::new())),
- })
+ Self::new(None, false, 0, None)
}
- fn managed(runtime_id: &str) -> Arc<Self> {
- Arc::new(Self {
- calls: Arc::new(AtomicUsize::new(0)),
- failures: 0,
- dies_immediately: false,
- succeeds_immediately: false,
- runtime_id: Some(runtime_id.to_owned()),
- handovers: Arc::new(AtomicUsize::new(0)),
- cleanups: Arc::new(AtomicUsize::new(0)),
- removals: Arc::new(Mutex::new(Vec::new())),
- })
+ /// This app's bundled Runtime.
+ fn bundled() -> Arc<Self> {
+ Self::new(Some(bundle_id()), true, 0, None)
+ }
+
+ /// This app's bundled Runtime, whose start helper has already exited.
+ fn bundled_exiting(exit: LaunchExit) -> Arc<Self> {
+ Self::new(Some(bundle_id()), true, 0, Some(exit))
}
fn failing_first(failures: usize) -> Arc<Self> {
- Arc::new(Self {
- calls: Arc::new(AtomicUsize::new(0)),
- failures,
- dies_immediately: false,
- succeeds_immediately: false,
- runtime_id: None,
- handovers: Arc::new(AtomicUsize::new(0)),
- cleanups: Arc::new(AtomicUsize::new(0)),
- removals: Arc::new(Mutex::new(Vec::new())),
- })
+ Self::new(None, false, failures, None)
}
/// Spawns successfully, then exits non-zero without starting a Runtime —
/// what an installed `vibe` too old for the shell's arguments does.
fn dying() -> Arc<Self> {
- Arc::new(Self {
- calls: Arc::new(AtomicUsize::new(0)),
- failures: 0,
- dies_immediately: true,
- succeeds_immediately: false,
- runtime_id: None,
- handovers: Arc::new(AtomicUsize::new(0)),
- cleanups: Arc::new(AtomicUsize::new(0)),
- removals: Arc::new(Mutex::new(Vec::new())),
- })
+ Self::new(None, false, 0, Some(LaunchExit::Failed))
}
/// The start helper exits zero, but no Runtime ever answers `/ready`.
fn zero_exit_without_runtime() -> Arc<Self> {
- Arc::new(Self {
- calls: Arc::new(AtomicUsize::new(0)),
- failures: 0,
- dies_immediately: false,
- succeeds_immediately: true,
- runtime_id: None,
- handovers: Arc::new(AtomicUsize::new(0)),
- cleanups: Arc::new(AtomicUsize::new(0)),
- removals: Arc::new(Mutex::new(Vec::new())),
- })
+ Self::new(None, false, 0, Some(LaunchExit::Started))
}
fn calls(&self) -> usize {
- self.calls.load(Ordering::SeqCst)
+ self.0.launches.load(Ordering::SeqCst)
+ }
+
+ fn handover_requests(&self) -> Vec<bool> {
+ self.0.handover_requests.lock().expect("launch recorder").clone()
+ }
+
+ fn prunes(&self) -> usize {
+ self.0.prunes.load(Ordering::SeqCst)
+ }
+
+ fn verbs(&self) -> Vec<Verb> {
+ self.0.verbs.lock().expect("verb recorder").clone()
+ }
+
+ fn stops(&self) -> Vec<String> {
+ self.verbs()
+ .into_iter()
+ .filter_map(|verb| match verb {
+ Verb::Stop { runtime_id } => Some(runtime_id),
+ _ => None,
+ })
+ .collect()
+ }
+
+ fn answer_stop(&self, outcome: CliOutcome) {
+ *self.0.stop_outcome.lock().expect("stop outcome") = outcome;
+ }
+
+ fn answer_remove_backends(&self, outcome: CliOutcome) {
+ *self.0.remove_backends_outcome.lock().expect("removal outcome") = outcome;
+ }
+
+ /// The bundle can no longer be prepared, so no CLI verb can run.
+ fn stop_resolving(&self) {
+ self.0.resolvable.store(false, Ordering::SeqCst);
+ }
+
+ fn record(&self, verb: Verb) {
+ self.0.verbs.lock().expect("verb recorder").push(verb);
}
}
impl RuntimeLauncher for FakeLauncher {
fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
- Ok(Arc::new(Self {
- calls: self.calls.clone(),
- failures: self.failures,
- dies_immediately: self.dies_immediately,
- succeeds_immediately: self.succeeds_immediately,
- runtime_id: self.runtime_id.clone(),
- handovers: self.handovers.clone(),
- cleanups: self.cleanups.clone(),
- removals: self.removals.clone(),
- }))
- }
-
- fn remove_private_runtime(&self, state: RuntimeRemovalState) -> Result<bool, LaunchError> {
- self.removals
- .lock()
- .expect("removal recorder is not poisoned")
- .push(state);
- if state == RuntimeRemovalState::Unknown {
- return Err(LaunchError::RuntimeRemoval);
+ if !self.0.resolvable.load(Ordering::SeqCst) {
+ return Err(LaunchError::RuntimeInstall);
}
- Ok(true)
+ Ok(Arc::new(self.clone()))
+ }
+
+ fn owns_private_files(&self) -> bool {
+ self.0.private
+ }
+
+ fn remove_private_files(&self) -> Result<(), LaunchError> {
+ self.record(Verb::RemoveFiles);
+ Ok(())
+ }
+
+ fn remove_unverified_private_files(&self) -> Result<(), LaunchError> {
+ self.record(Verb::RemoveUnverifiedFiles);
+ Ok(())
}
}
impl ResolvedRuntimeLauncher for FakeLauncher {
fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
- Ok(LoopbackOrigin::parse(TEST_ORIGIN).expect("the test endpoint is valid"))
+ Ok(origin())
}
- fn launch(&self) -> Result<LaunchedRuntime, LaunchError> {
- let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
- if call <= self.failures {
+ fn launch(&self, hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
+ let call = self.0.launches.fetch_add(1, Ordering::SeqCst) + 1;
+ self.0
+ .handover_requests
+ .lock()
+ .expect("launch recorder")
+ .push(hand_over);
+ if call <= self.0.failures {
return Err(LaunchError::ExecutableNotFound);
}
Ok(LaunchedRuntime {
pid: 4242,
- watch: if self.dies_immediately {
- LaunchWatch::exited(false)
- } else if self.succeeds_immediately {
- LaunchWatch::exited(true)
- } else {
- LaunchWatch::default()
+ watch: match self.0.exit {
+ Some(exit) => LaunchWatch::exited(exit),
+ None => LaunchWatch::default(),
},
})
}
fn expected_runtime_id(&self) -> Option<&str> {
- self.runtime_id.as_deref()
+ self.0.runtime_id.as_deref()
}
- fn handover(&self) -> Result<(), LaunchError> {
- self.handovers.fetch_add(1, Ordering::SeqCst);
- Ok(())
+ fn stop(&self, runtime_id: &str) -> CliOutcome {
+ self.record(Verb::Stop {
+ runtime_id: runtime_id.to_owned(),
+ });
+ self.0.stop_outcome.lock().expect("stop outcome").clone()
+ }
+
+ fn remove_backends(&self) -> CliOutcome {
+ self.record(Verb::RemoveBackends);
+ self.0.remove_backends_outcome.lock().expect("removal outcome").clone()
}
fn prune_superseded(&self) {
- self.cleanups.fetch_add(1, Ordering::SeqCst);
+ self.0.prunes.fetch_add(1, Ordering::SeqCst);
}
}
@@ -297,22 +365,24 @@ fn immediate_timeout_settings() -> RuntimeHostSettings {
}
}
-fn host(probe: Arc<FakeProbe>, launcher: Arc<FakeLauncher>, settings: RuntimeHostSettings) -> RuntimeHost {
+fn runtime_host(probe: Arc<FakeProbe>, launcher: Arc<FakeLauncher>, settings: RuntimeHostSettings) -> RuntimeHost {
RuntimeHost::new(probe, launcher, settings)
}
+async fn boot(host: &RuntimeHost, trigger: BootstrapTrigger) -> BootstrapStatus {
+ host.bootstrap(&Recorder::default(), trigger).await
+}
+
#[tokio::test(start_paused = true)]
async fn a_cold_link_is_consumed_only_after_ready_navigation_commits_and_never_replayed() {
let launcher = FakeLauncher::working();
- let host = host(FakeProbe::healthy_from(3), launcher.clone(), fast_settings());
+ let host = runtime_host(FakeProbe::healthy_from(3), launcher.clone(), fast_settings());
let recorder = Recorder::default();
let mut links = DeepLinks::default();
links.receive(["avibe", "avibe://show/cold.session"]);
- let ready = host.bootstrap(&recorder).await;
+ let ready = host.bootstrap(&recorder, Launch).await;
for status in recorder
- .statuses
- .lock()
- .unwrap()
+ .statuses()
.iter()
.filter(|status| status.phase != BootstrapPhase::Ready)
{
@@ -332,25 +402,25 @@ async fn a_cold_link_is_consumed_only_after_ready_navigation_commits_and_never_r
#[tokio::test(start_paused = true)]
async fn bootstrap_failure_discards_the_link_without_navigating_or_replaying_on_retry() {
- let host = host(FakeProbe::never_healthy(), FakeLauncher::working(), fast_settings());
+ let host = runtime_host(FakeProbe::never_healthy(), FakeLauncher::working(), fast_settings());
let recorder = Recorder::default();
let mut links = DeepLinks::default();
links.receive(["avibe://session/failed"]);
- let failed = host.bootstrap(&recorder).await;
+ let failed = host.bootstrap(&recorder, Launch).await;
assert_eq!(failed.phase, BootstrapPhase::Failed);
assert!(links.bootstrap_navigation(&failed).is_none());
links.receive(["avibe://session/arrived-after-failure"]);
let healthy = RuntimeHost::new(FakeProbe::healthy_from(1), FakeLauncher::working(), fast_settings());
- let ready = healthy.bootstrap(&recorder).await;
+ let ready = healthy.bootstrap(&recorder, Retry).await;
assert_eq!(links.bootstrap_navigation(&ready).unwrap().url().path(), "/");
}
#[tokio::test(start_paused = true)]
async fn a_ready_link_survives_failed_handoffs_until_the_current_window_accepts_it() {
- let host = host(FakeProbe::healthy_from(1), FakeLauncher::working(), fast_settings());
+ let host = runtime_host(FakeProbe::healthy_from(1), FakeLauncher::working(), fast_settings());
let mut links = DeepLinks::default();
links.receive(["avibe://session/retry"]);
- let ready = host.bootstrap(&Recorder::default()).await;
+ let ready = boot(&host, Launch).await;
let origin = LoopbackOrigin::parse(&ready.origin).unwrap();
let first = links.bootstrap_navigation(&ready).unwrap();
assert!(!links.commit_navigation(&first, false, 1, 1));
@@ -361,7 +431,7 @@ async fn a_ready_link_survives_failed_handoffs_until_the_current_window_accepts_
true,
);
assert!(links.bootstrap_navigation(&handoff_failed).is_none());
- let retried = host.bootstrap(&Recorder::default()).await;
+ let retried = boot(&host, Retry).await;
let replacement = links.bootstrap_navigation(&retried).unwrap();
assert_eq!(replacement.url(), first.url());
assert!(!links.commit_navigation(&replacement, true, 1, 2));
@@ -374,161 +444,263 @@ async fn a_ready_link_survives_failed_handoffs_until_the_current_window_accepts_
#[tokio::test(start_paused = true)]
async fn an_already_running_runtime_is_adopted_without_starting_anything() {
let probe = FakeProbe::healthy_from(1);
- let launcher = FakeLauncher::working();
- let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(probe.clone(), launcher.clone(), fast_settings());
let recorder = Recorder::default();
- let status = host.bootstrap(&recorder).await;
+ let status = host.bootstrap(&recorder, Launch).await;
assert_eq!(status.phase, BootstrapPhase::Ready);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::Adopted);
assert_eq!(status.origin, TEST_ORIGIN);
assert_eq!(status.attempt, 1);
assert_eq!(launcher.calls(), 0, "an adopted Runtime must never be re-started");
assert_eq!(probe.calls(), 1);
assert_eq!(recorder.phases(), vec![BootstrapPhase::Probing, BootstrapPhase::Ready]);
assert!(!host.has_launched());
+ assert!(!host.has_owned_runtime(), "an untagged Runtime is never this app's");
+ assert!(launcher.verbs().is_empty(), "an untagged Runtime is never stopped");
+ assert_eq!(launcher.prunes(), 0);
}
#[tokio::test(start_paused = true)]
-async fn a_matching_desktop_runtime_is_adopted_and_superseded_installs_are_pruned() {
- let runtime_id = "a".repeat(64);
- let probe = FakeProbe::healthy_managed(&runtime_id);
- let launcher = FakeLauncher::managed(&runtime_id);
- let host = host(probe, launcher.clone(), fast_settings());
+async fn this_apps_running_runtime_is_adopted_as_its_own_and_superseded_installs_are_pruned() {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([Served::Ready(Some(bundle_id()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
- let status = host.bootstrap(&Recorder::default()).await;
+ let status = boot(&host, Launch).await;
assert_eq!(status.phase, BootstrapPhase::Ready);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::Adopted);
assert_eq!(launcher.calls(), 0);
- assert_eq!(launcher.handovers.load(Ordering::SeqCst), 0);
- assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 1);
+ assert!(launcher.verbs().is_empty());
+ assert_eq!(launcher.prunes(), 1);
+ assert!(
+ host.has_owned_runtime(),
+ "a Runtime carrying this app's identity is stoppable even when an earlier shell started it"
+ );
}
-#[tokio::test]
-async fn uninstall_marks_an_adopted_private_runtime_as_managed() {
- let runtime_id = "a".repeat(64);
- let probe = FakeProbe::healthy_managed(&runtime_id);
- let launcher = FakeLauncher::managed(&runtime_id);
- let host = host(probe, launcher.clone(), fast_settings());
- let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
-
- assert!(host
- .remove_private_runtime(Some(&origin))
- .await
- .expect("private Runtime removal"));
- assert_eq!(
- launcher
- .removals
- .lock()
- .expect("removal recorder is not poisoned")
- .as_slice(),
- [RuntimeRemovalState::Managed]
+#[tokio::test(start_paused = true)]
+async fn this_apps_runtime_with_a_stale_ui_is_restarted_rather_than_handed_over() {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([Served::UiMismatch(bundle_id()), Served::Ready(Some(bundle_id()))]),
+ launcher.clone(),
+ fast_settings(),
);
-}
-#[tokio::test]
-async fn uninstall_refuses_to_remove_files_when_an_adopted_runtime_stops_answering() {
- let probe = FakeProbe::never_healthy();
- let launcher = FakeLauncher::managed(&"a".repeat(64));
- let host = host(probe, launcher.clone(), fast_settings());
- let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
-
- assert!(matches!(
- host.remove_private_runtime(Some(&origin)).await,
- Err(LaunchError::RuntimeRemoval)
- ));
- assert_eq!(
- launcher
- .removals
- .lock()
- .expect("removal recorder is not poisoned")
- .as_slice(),
- [RuntimeRemovalState::Unknown]
+ let status = boot(&host, Launch).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Ready);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::Ready);
+ assert_eq!(launcher.calls(), 1, "`vibe start` replaces the stale UI");
+ assert!(
+ launcher.verbs().is_empty(),
+ "this app's own Controller is never handed over"
);
}
-#[tokio::test]
-async fn uninstall_can_remove_an_inactive_private_runtime_without_probing_or_launching() {
- let probe = FakeProbe::never_healthy();
- let launcher = FakeLauncher::managed(&"a".repeat(64));
- let host = host(probe.clone(), launcher.clone(), fast_settings());
-
- assert!(host
- .remove_private_runtime(None)
- .await
- .expect("inactive private Runtime removal"));
- assert_eq!(probe.calls(), 0);
- assert_eq!(
- launcher
- .removals
- .lock()
- .expect("removal recorder is not poisoned")
- .as_slice(),
- [RuntimeRemovalState::Inactive]
+#[tokio::test(start_paused = true)]
+async fn launch_and_retry_ask_this_apps_start_to_hand_over_a_desktop_predecessor() {
+ for trigger in [Launch, Retry] {
+ for predecessor_state in [Served::Ready(Some(predecessor())), Served::UiMismatch(predecessor())] {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([predecessor_state, Served::Starting, Served::Ready(Some(bundle_id()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
+
+ let status = boot(&host, trigger).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Ready, "{trigger:?}");
+ assert_eq!(status.notice.code, BootstrapNoticeCode::Ready);
+ assert_eq!(
+ launcher.handover_requests(),
+ [true],
+ "`vibe start` replaces the predecessor"
+ );
+ assert!(launcher.verbs().is_empty(), "the host itself never stops a predecessor");
+ assert_eq!(launcher.prunes(), 1);
+ assert!(host.has_owned_runtime());
+ }
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_predecessor_still_serving_after_this_apps_start_exited_is_never_stopped() {
+ // Found on the first probe, and while polling after `vibe start` settled.
+ for script in [
+ vec![Served::Ready(Some(predecessor()))],
+ vec![Served::Nothing, Served::Ready(Some(predecessor()))],
+ ] {
+ let launcher = FakeLauncher::bundled_exiting(LaunchExit::Started);
+ let host = runtime_host(FakeProbe::serving(script), launcher.clone(), fast_settings());
+
+ let status = boot(&host, Launch).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeOwnershipLost);
+ assert!(status.retryable);
+ assert!(launcher.verbs().is_empty());
+ assert_eq!(
+ launcher.calls(),
+ 1,
+ "a predecessor that stayed is not a reason to start again"
+ );
+ assert!(!host.has_owned_runtime());
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_predecessor_is_never_judged_while_this_apps_start_helper_still_runs() {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([Served::Nothing, Served::Ready(Some(predecessor()))]),
+ launcher.clone(),
+ fast_settings(),
);
+
+ // Found while polling, and again on the Retry's first probe.
+ for trigger in [Launch, Retry] {
+ let status = boot(&host, trigger).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed, "{trigger:?}");
+ assert_eq!(status.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ assert!(status.retryable);
+ assert!(
+ launcher.verbs().is_empty(),
+ "the running helper may still be replacing the predecessor"
+ );
+ assert_eq!(launcher.calls(), 1, "a second helper must never overlap the first");
+ }
}
#[tokio::test(start_paused = true)]
-async fn a_superseded_desktop_runtime_is_stopped_before_the_successor_starts() {
- let expected = "b".repeat(64);
- let probe = FakeProbe::mismatched_managed(&"a".repeat(64));
- let launcher = FakeLauncher::managed(&expected);
- let host = host(probe, launcher.clone(), immediate_timeout_settings());
+async fn recovery_never_asks_to_hand_over_a_foreign_runtime() {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([Served::Ready(Some(predecessor()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
- let status = host.bootstrap(&Recorder::default()).await;
+ let status = boot(&host, Recovery).await;
assert_eq!(status.phase, BootstrapPhase::Failed);
- assert_eq!(status.notice.code, BootstrapNoticeCode::ReadyTimeout);
- assert_eq!(launcher.handovers.load(Ordering::SeqCst), 1);
- assert_eq!(launcher.calls(), 1);
- assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 0);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeOwnershipLost);
+ assert!(status.retryable, "the user's Try again may hand over");
+ assert_eq!(launcher.calls(), 0);
+ assert!(launcher.verbs().is_empty());
+
+ // Nothing answered, so recovery starts this app's Runtime, but its `vibe
+ // start` may not replace a predecessor it then finds, and declines.
+ let launcher = FakeLauncher::bundled_exiting(LaunchExit::HandoverRefused);
+ let host = runtime_host(
+ FakeProbe::serving([Served::Nothing, Served::Ready(Some(predecessor()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
+
+ let status = boot(&host, Recovery).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeOwnershipLost);
+ assert!(status.retryable);
+ assert_eq!(
+ launcher.handover_requests(),
+ [false],
+ "recovery must not let `vibe start` stop another shell's Runtime"
+ );
+ assert!(launcher.verbs().is_empty());
+ assert!(!host.has_owned_runtime());
}
#[tokio::test(start_paused = true)]
-async fn an_unknown_predecessor_never_authorizes_initial_or_polling_handover() {
- for mismatch_at in [1, 2] {
- let probe = Arc::new(FakeProbe {
- healthy_from: usize::MAX,
- runtime_id: None,
- ui_runtime_id: None,
- identity_mismatch_at: Some(mismatch_at),
- calls: AtomicUsize::new(0),
- });
- let launcher = FakeLauncher::managed(&"b".repeat(64));
- let host = host(probe, launcher.clone(), fast_settings());
- assert_eq!(host.bootstrap(&Recorder::default()).await.phase, BootstrapPhase::Failed);
- assert_eq!(launcher.handovers.load(Ordering::SeqCst), 0);
- assert_eq!(launcher.calls(), 1);
+async fn a_start_that_did_not_replace_its_predecessor_fails_closed_by_its_exit() {
+ for (exit, notice) in [
+ (LaunchExit::HandoverRefused, BootstrapNoticeCode::RuntimeOwnershipLost),
+ (LaunchExit::HandoverFailed, BootstrapNoticeCode::RuntimeStopFailed),
+ (LaunchExit::Failed, BootstrapNoticeCode::LauncherExited),
+ ] {
+ let launcher = FakeLauncher::bundled_exiting(exit);
+ let host = runtime_host(
+ FakeProbe::serving([Served::Ready(Some(predecessor()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
+
+ let status = boot(&host, Launch).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed, "{exit:?}");
+ assert_eq!(status.notice.code, notice, "{exit:?}");
+ assert!(status.retryable);
+ assert_eq!(launcher.handover_requests(), [true]);
+ assert!(launcher.verbs().is_empty(), "{exit:?}");
+ assert!(!host.has_launched(), "{exit:?} releases the retry slot");
}
}
#[tokio::test(start_paused = true)]
-async fn an_identity_mismatch_discovered_while_polling_hands_over_and_relaunches_immediately() {
- let expected = "b".repeat(64);
- let probe = FakeProbe::mismatch_after_launch_then_healthy(&expected);
- let launcher = FakeLauncher::managed(&expected);
- let host = host(probe, launcher.clone(), fast_settings());
+async fn a_retry_that_finds_a_failed_start_reports_it_and_leaves_the_predecessor_alone() {
+ // The helper's non-zero exit landed after the first run timed out.
+ let launcher = FakeLauncher::bundled_exiting(LaunchExit::Failed);
+ let host = runtime_host(
+ FakeProbe::serving([Served::Nothing, Served::Ready(Some(predecessor()))]),
+ launcher.clone(),
+ immediate_timeout_settings(),
+ );
+ assert_eq!(boot(&host, Launch).await.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ assert!(host.has_launched());
+
+ let status = boot(&host, Retry).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::LauncherExited);
+ assert!(
+ launcher.verbs().is_empty(),
+ "a predecessor is never stopped on the way to a failure"
+ );
+ assert_eq!(launcher.calls(), 1);
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_shell_without_a_runtime_identity_adopts_a_desktop_runtime_it_can_never_stop() {
+ let launcher = FakeLauncher::working();
+ let host = runtime_host(
+ FakeProbe::serving([Served::Ready(Some(predecessor()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
- let status = host.bootstrap(&Recorder::default()).await;
+ let status = boot(&host, Launch).await;
assert_eq!(status.phase, BootstrapPhase::Ready);
- assert_eq!(launcher.handovers.load(Ordering::SeqCst), 1);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::Adopted);
+ assert!(!host.has_owned_runtime());
assert_eq!(
- launcher.calls(),
- 2,
- "the post-handover successor must launch in the same run"
+ host.stop_owned_runtime().await,
+ CliOutcome::Refused {
+ reason: "not_owned".to_owned()
+ }
);
- assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 1);
+ assert!(launcher.verbs().is_empty());
+ assert_eq!(launcher.calls(), 0);
}
#[tokio::test(start_paused = true)]
async fn an_absent_runtime_is_started_and_adopted_once_it_answers() {
let probe = FakeProbe::healthy_from(3);
let launcher = FakeLauncher::working();
- let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let host = runtime_host(probe.clone(), launcher.clone(), fast_settings());
let recorder = Recorder::default();
- let status = host.bootstrap(&recorder).await;
+ let status = host.bootstrap(&recorder, Launch).await;
assert_eq!(status.phase, BootstrapPhase::Ready);
assert_eq!(launcher.calls(), 1, "exactly one Runtime is started");
@@ -545,122 +717,526 @@ async fn an_absent_runtime_is_started_and_adopted_once_it_answers() {
}
#[tokio::test(start_paused = true)]
-async fn a_helper_adopts_untagged_readiness_after_launch_without_handover_or_pruning() {
- // The first probe misses, so the bundled helper is started. The next
- // probe is the real external-adoption shape produced by `/ready`: the
- // Controller is healthy but has no desktop identity.
- let readiness = parse_avibe_readiness_body(r#"{"schema_version":1,"product":"avibe","ready":true}"#)
- .expect("the Python /ready payload is accepted by the Rust parser");
- assert_eq!(readiness.desktop_runtime_id, None);
- let probe = FakeProbe::healthy_from_readiness(2, &readiness);
- let launcher = FakeLauncher::managed(&"b".repeat(64));
- let host = host(probe, launcher.clone(), fast_settings());
+async fn a_helper_adopts_untagged_readiness_after_launch_without_handover_pruning_or_removal() {
+ // The first probe misses, so the bundled helper is started and exits. The
+ // next probe is an external Controller without a desktop identity.
+ let launcher = FakeLauncher::bundled_exiting(LaunchExit::Started);
+ let host = runtime_host(
+ FakeProbe::serving([Served::Nothing, Served::Ready(None)]),
+ launcher.clone(),
+ fast_settings(),
+ );
- let status = host.bootstrap(&Recorder::default()).await;
+ let status = boot(&host, Launch).await;
assert_eq!(status.phase, BootstrapPhase::Ready);
assert_eq!(status.notice.code, BootstrapNoticeCode::Adopted);
assert_eq!(launcher.calls(), 1);
- assert_eq!(launcher.handovers.load(Ordering::SeqCst), 0);
- assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 0);
+ assert_eq!(launcher.prunes(), 0);
assert!(!host.has_owned_runtime());
// The helper may have created the UI from the private tree even though the
- // adopted Controller is external. Do not delete that tree on a no-ID
- // readiness response while launch liveness is still uncertain.
- let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
- assert!(matches!(
- host.remove_private_runtime(Some(&origin)).await,
- Err(LaunchError::RuntimeRemoval)
- ));
+ // adopted Controller is external, so its files are kept.
+ assert_eq!(host.remove_private_runtime(Some(&origin())).await, RemovalOutcome::Kept);
+ assert!(launcher.verbs().is_empty());
+}
+
+#[tokio::test(start_paused = true)]
+async fn the_monitor_serves_only_the_adopted_presence_and_rereads_the_owner_on_every_probe() {
+ // Another shell's Runtime replaced this app's: serving ends, and so does
+ // the authority to stop anything.
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([
+ Served::Ready(Some(bundle_id())),
+ Served::Ready(Some(bundle_id())),
+ Served::Ready(Some(predecessor())),
+ ]),
+ launcher.clone(),
+ fast_settings(),
+ );
+ boot(&host, Launch).await;
+ assert!(host.is_serving(&origin()).await);
+ assert!(host.has_owned_runtime());
+ assert!(!host.is_serving(&origin()).await);
+ assert!(!host.has_owned_runtime());
assert_eq!(
- launcher
- .removals
- .lock()
- .expect("removal recorder is not poisoned")
- .as_slice(),
- [RuntimeRemovalState::Unknown]
+ host.stop_owned_runtime().await,
+ CliOutcome::Refused {
+ reason: "not_owned".to_owned()
+ }
);
+ assert!(launcher.verbs().is_empty());
+
+ // A probe that proves nothing is not a change of hands.
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([
+ Served::Ready(Some(bundle_id())),
+ Served::Starting,
+ Served::Ready(Some(bundle_id())),
+ ]),
+ launcher.clone(),
+ fast_settings(),
+ );
+ boot(&host, Launch).await;
+ assert!(!host.is_serving(&origin()).await);
+ assert!(host.has_owned_runtime());
+ assert_eq!(host.stop_owned_runtime().await, CliOutcome::Completed);
+ assert_eq!(launcher.stops(), [bundle_id()]);
}
-#[tokio::test]
-async fn uninstall_keeps_a_preexisting_untagged_external_runtime_external() {
- let readiness = parse_avibe_readiness_body(r#"{"schema_version":1,"product":"avibe","ready":true}"#)
- .expect("the Python /ready payload is accepted by the Rust parser");
- let probe = FakeProbe::healthy_from_readiness(1, &readiness);
- let launcher = FakeLauncher::working();
- let host = host(probe, launcher.clone(), fast_settings());
- let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
+#[tokio::test(start_paused = true)]
+async fn a_monitor_probe_overtaken_by_a_new_run_or_a_stop_never_rewrites_ownership() {
+ // Window recreation: the monitor's probe found nothing, and a new run
+ // adopted this app's Runtime before that answer landed.
+ let launcher = FakeLauncher::bundled();
+ let probe = HeldProbe::holding(
+ 1,
+ [
+ Served::Ready(Some(bundle_id())),
+ Served::Nothing,
+ Served::Ready(Some(bundle_id())),
+ ],
+ );
+ let host = Arc::new(RuntimeHost::new(probe.clone(), launcher.clone(), fast_settings()));
+ boot(&host, Launch).await;
+ let monitor = tokio::spawn({
+ let host = host.clone();
+ async move { host.is_serving(&origin()).await }
+ });
+ probe.in_flight.notified().await;
+ assert_eq!(boot(&host, Recovery).await.notice.code, BootstrapNoticeCode::Adopted);
+ probe.release.notify_one();
+ monitor.await.expect("monitor probe");
+ assert!(
+ host.has_owned_runtime(),
+ "a stale Absent must not revoke the new run's stop authority"
+ );
+
+ // Stop: the monitor's probe found this app's Runtime serving, and the stop
+ // completed before that answer landed.
+ let launcher = FakeLauncher::bundled();
+ let probe = HeldProbe::holding(1, [Served::Ready(Some(bundle_id()))]);
+ let host = Arc::new(RuntimeHost::new(probe.clone(), launcher.clone(), fast_settings()));
+ boot(&host, Launch).await;
+ let monitor = tokio::spawn({
+ let host = host.clone();
+ async move { host.is_serving(&origin()).await }
+ });
+ probe.in_flight.notified().await;
+ assert_eq!(host.stop_owned_runtime().await, CliOutcome::Completed);
+ probe.release.notify_one();
+ monitor.await.expect("monitor probe");
+ assert!(
+ !host.has_owned_runtime(),
+ "a stale Mine must not restore stop authority over a stopped Runtime"
+ );
+ // Nor the evidence that a Runtime may still live: with no origin to ask,
+ // uninstall leaves the choice to the user instead of keeping every file.
+ launcher.stop_resolving();
+ assert_eq!(host.remove_private_runtime(None).await, RemovalOutcome::Unverified);
+ assert_eq!(launcher.stops(), [bundle_id()]);
+}
- assert!(host
- .remove_private_runtime(Some(&origin))
- .await
- .expect("external private-runtime cleanup"));
+#[tokio::test(start_paused = true)]
+async fn a_host_without_an_adoption_is_never_serving() {
+ let host = runtime_host(FakeProbe::healthy_from(1), FakeLauncher::working(), fast_settings());
+ assert!(!host.is_serving(&origin()).await);
+}
+
+#[tokio::test(start_paused = true)]
+async fn stop_reaches_only_this_apps_runtime_and_takes_its_tunnel_down() {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([Served::Ready(Some(bundle_id()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
+ boot(&host, Launch).await;
+
+ assert_eq!(host.stop_owned_runtime().await, CliOutcome::Completed);
+ assert_eq!(launcher.stops(), [bundle_id()]);
+ assert!(!host.has_owned_runtime());
assert_eq!(
- launcher
- .removals
- .lock()
- .expect("removal recorder is not poisoned")
- .as_slice(),
- [RuntimeRemovalState::External]
+ host.stop_owned_runtime().await,
+ CliOutcome::Refused {
+ reason: "not_owned".to_owned()
+ },
+ "a stopped Runtime is not stopped again"
+ );
+ assert_eq!(launcher.stops().len(), 1);
+
+ for served in [Served::Ready(None), Served::Nothing, Served::Starting] {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([served]),
+ launcher.clone(),
+ immediate_timeout_settings(),
+ );
+ boot(&host, Launch).await;
+ assert!(!host.has_owned_runtime());
+ assert_eq!(
+ host.stop_owned_runtime().await,
+ CliOutcome::Refused {
+ reason: "not_owned".to_owned()
+ }
+ );
+ assert!(launcher.stops().is_empty());
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_refused_stop_revokes_authority_and_an_unfinished_one_keeps_it() {
+ let refused = CliOutcome::Refused {
+ reason: "runtime_id_mismatch".to_owned(),
+ };
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([Served::Ready(Some(bundle_id()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
+ boot(&host, Launch).await;
+ launcher.answer_stop(refused.clone());
+ assert_eq!(host.stop_owned_runtime().await, refused);
+ assert!(!host.has_owned_runtime());
+ assert_eq!(
+ host.stop_owned_runtime().await,
+ CliOutcome::Refused {
+ reason: "not_owned".to_owned()
+ }
);
+ assert_eq!(launcher.stops().len(), 1);
+ // A refusal does not prove this app's Runtime gone, so uninstall without
+ // an origin to ask keeps the files.
+ launcher.stop_resolving();
+ assert_eq!(host.remove_private_runtime(None).await, RemovalOutcome::Kept);
+ assert_eq!(launcher.stops().len(), 1);
+
+ for unfinished in [
+ CliOutcome::Failed {
+ part: "service".to_owned(),
+ },
+ CliOutcome::Unrunnable,
+ ] {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([Served::Ready(Some(bundle_id()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
+ boot(&host, Launch).await;
+ launcher.answer_stop(unfinished.clone());
+ assert_eq!(host.stop_owned_runtime().await, unfinished);
+ assert!(host.has_owned_runtime(), "{unfinished:?} keeps the Runtime stoppable");
+ launcher.answer_stop(CliOutcome::Completed);
+ assert_eq!(host.stop_owned_runtime().await, CliOutcome::Completed);
+ assert_eq!(launcher.stops(), [bundle_id(), bundle_id()]);
+ }
}
#[tokio::test(start_paused = true)]
-async fn an_external_controller_with_a_bundled_ui_stays_unknown_after_shell_reopen() {
- let readiness = parse_avibe_readiness_body(EXTERNAL_CONTROLLER_BUNDLED_UI_READY_BODY)
- .expect("the tagged UI readiness payload is accepted by the Rust parser");
- let probe = FakeProbe::healthy_from_readiness(2, &readiness);
- let launcher = FakeLauncher::managed(&"b".repeat(64));
- let first = host(probe.clone(), launcher.clone(), fast_settings());
- let origin = LoopbackOrigin::parse(TEST_ORIGIN).expect("test origin");
+async fn neither_stop_nor_uninstall_overlaps_a_launch_that_is_still_running() {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(
+ FakeProbe::serving([Served::Nothing, Served::Ready(Some(bundle_id()))]),
+ launcher.clone(),
+ fast_settings(),
+ );
+ assert_eq!(boot(&host, Launch).await.notice.code, BootstrapNoticeCode::Ready);
+ assert!(host.has_launched() && host.has_owned_runtime());
assert_eq!(
- first.bootstrap(&Recorder::default()).await.notice.code,
- BootstrapNoticeCode::Adopted
- );
- assert!(matches!(
- first.remove_private_runtime(Some(&origin)).await,
- Err(LaunchError::RuntimeRemoval)
- ));
-
- // Closing the shell drops in-memory state, but the same UI identity in
- // /ready still proves that private UI files may be serving the Controller.
- drop(first);
- let reopened = host(probe, launcher.clone(), fast_settings());
+ host.stop_owned_runtime().await,
+ CliOutcome::Failed {
+ part: "launch_pending".to_owned()
+ }
+ );
+ assert_eq!(host.remove_private_runtime(Some(&origin())).await, RemovalOutcome::Kept);
+ assert!(launcher.verbs().is_empty());
+}
+
+#[tokio::test(start_paused = true)]
+async fn uninstall_stops_this_apps_runtime_then_removes_backends_then_its_files() {
+ for served in [
+ Served::Ready(Some(bundle_id())),
+ Served::UiMismatch(bundle_id()),
+ Served::Nothing,
+ ] {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(FakeProbe::serving([served]), launcher.clone(), fast_settings());
+
+ assert_eq!(
+ host.remove_private_runtime(Some(&origin())).await,
+ RemovalOutcome::Removed
+ );
+ assert_eq!(
+ launcher.verbs(),
+ [
+ Verb::Stop {
+ runtime_id: bundle_id()
+ },
+ Verb::RemoveBackends,
+ Verb::RemoveFiles,
+ ]
+ );
+ assert_eq!(launcher.calls(), 0, "uninstall never starts a Runtime");
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn uninstall_keeps_every_file_while_another_runtime_may_use_them() {
+ for served in [
+ Served::Ready(Some(predecessor())),
+ Served::UiMismatch(predecessor()),
+ Served::Ready(None),
+ Served::Starting,
+ ] {
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(FakeProbe::serving([served]), launcher.clone(), fast_settings());
+
+ assert_eq!(host.remove_private_runtime(Some(&origin())).await, RemovalOutcome::Kept);
+ assert_eq!(
+ host.remove_unverified_private_runtime(Some(&origin())).await,
+ RemovalOutcome::Kept,
+ "Delete anyway is never offered past a Runtime that answers"
+ );
+ assert!(launcher.verbs().is_empty(), "nothing is stopped or deleted");
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn uninstall_keeps_every_file_when_this_apps_runtime_does_not_confirm_its_stop() {
+ for (served, stop, removal) in [
+ (
+ Served::Ready(Some(bundle_id())),
+ CliOutcome::Refused {
+ reason: "runtime_id_mismatch".to_owned(),
+ },
+ RemovalOutcome::Kept,
+ ),
+ (
+ Served::Ready(Some(bundle_id())),
+ CliOutcome::Failed {
+ part: "service".to_owned(),
+ },
+ RemovalOutcome::Kept,
+ ),
+ (
+ Served::Ready(Some(bundle_id())),
+ CliOutcome::Unrunnable,
+ RemovalOutcome::Kept,
+ ),
+ (Served::Nothing, CliOutcome::Unrunnable, RemovalOutcome::Unverified),
+ (
+ Served::Nothing,
+ CliOutcome::Failed {
+ part: "remote_access".to_owned(),
+ },
+ RemovalOutcome::Kept,
+ ),
+ ] {
+ let launcher = FakeLauncher::bundled();
+ launcher.answer_stop(stop.clone());
+ let host = runtime_host(FakeProbe::serving([served]), launcher.clone(), fast_settings());
+
+ assert_eq!(host.remove_private_runtime(Some(&origin())).await, removal, "{stop:?}");
+ assert_eq!(
+ launcher.verbs(),
+ [Verb::Stop {
+ runtime_id: bundle_id()
+ }],
+ "{stop:?} deletes nothing"
+ );
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn uninstall_deletes_the_bundle_only_after_every_backend_install_was_claimed() {
+ for (backends, removal) in [
+ (
+ CliOutcome::Refused {
+ reason: "install_locked".to_owned(),
+ },
+ RemovalOutcome::Kept,
+ ),
+ (
+ CliOutcome::Failed {
+ part: "backend_removal_failed".to_owned(),
+ },
+ RemovalOutcome::Failed,
+ ),
+ (CliOutcome::Unrunnable, RemovalOutcome::Unverified),
+ ] {
+ let launcher = FakeLauncher::bundled();
+ launcher.answer_remove_backends(backends.clone());
+ let host = runtime_host(
+ FakeProbe::serving([Served::Ready(Some(bundle_id())), Served::Nothing]),
+ launcher.clone(),
+ fast_settings(),
+ );
+
+ assert_eq!(
+ host.remove_private_runtime(Some(&origin())).await,
+ removal,
+ "{backends:?}"
+ );
+ assert_eq!(
+ launcher.verbs(),
+ [
+ Verb::Stop {
+ runtime_id: bundle_id()
+ },
+ Verb::RemoveBackends,
+ ],
+ "{backends:?} keeps the bundle"
+ );
+ assert!(!host.has_owned_runtime(), "the stopped Runtime is no longer stoppable");
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn delete_anyway_rechecks_the_origin_and_deletes_only_while_nothing_answers() {
+ let launcher = FakeLauncher::bundled();
+ launcher.answer_stop(CliOutcome::Unrunnable);
+ let host = runtime_host(
+ FakeProbe::serving([Served::Nothing, Served::Nothing, Served::Ready(None)]),
+ launcher.clone(),
+ fast_settings(),
+ );
assert_eq!(
- reopened.bootstrap(&Recorder::default()).await.notice.code,
- BootstrapNoticeCode::Adopted
+ host.remove_private_runtime(Some(&origin())).await,
+ RemovalOutcome::Unverified
);
- assert!(matches!(
- reopened.remove_private_runtime(Some(&origin)).await,
- Err(LaunchError::RuntimeRemoval)
- ));
assert_eq!(
- launcher.calls(),
- 1,
- "reopening adopts the surviving UI without relaunching it"
+ host.remove_unverified_private_runtime(Some(&origin())).await,
+ RemovalOutcome::Removed
);
- assert_eq!(launcher.handovers.load(Ordering::SeqCst), 0);
- assert_eq!(launcher.cleanups.load(Ordering::SeqCst), 0);
assert_eq!(
- launcher
- .removals
- .lock()
- .expect("removal recorder is not poisoned")
- .as_slice(),
- [RuntimeRemovalState::Unknown, RuntimeRemovalState::Unknown]
+ host.remove_unverified_private_runtime(Some(&origin())).await,
+ RemovalOutcome::Kept,
+ "a Runtime that answers again keeps the files"
+ );
+ assert_eq!(
+ launcher.verbs(),
+ [
+ Verb::Stop {
+ runtime_id: bundle_id()
+ },
+ Verb::RemoveUnverifiedFiles,
+ ]
);
}
+#[tokio::test(start_paused = true)]
+async fn uninstall_without_an_origin_keeps_the_files_while_a_launched_runtime_may_live() {
+ // A never-launched shell whose bundle cannot run has nothing that could
+ // still be installing, so only the user's choice is left.
+ let launcher = FakeLauncher::bundled();
+ launcher.stop_resolving();
+ let host = runtime_host(
+ FakeProbe::never_healthy(),
+ launcher.clone(),
+ immediate_timeout_settings(),
+ );
+ assert_eq!(host.remove_private_runtime(None).await, RemovalOutcome::Unverified);
+ assert!(launcher.verbs().is_empty());
+
+ // Once this shell has spawned a helper, a Runtime may be alive whatever the
+ // helper reported, so without an origin to ask every file is kept.
+ for exit in [LaunchExit::Started, LaunchExit::Failed] {
+ let launcher = FakeLauncher::bundled_exiting(exit);
+ let host = runtime_host(
+ FakeProbe::never_healthy(),
+ launcher.clone(),
+ immediate_timeout_settings(),
+ );
+ boot(&host, Launch).await;
+ boot(&host, Retry).await;
+ assert!(!host.has_launched(), "{exit:?} released the retry slot");
+ launcher.stop_resolving();
+ assert_eq!(
+ host.remove_private_runtime(None).await,
+ RemovalOutcome::Kept,
+ "{exit:?}"
+ );
+ assert_eq!(
+ host.remove_unverified_private_runtime(None).await,
+ RemovalOutcome::Kept,
+ "{exit:?}"
+ );
+ assert!(launcher.verbs().is_empty(), "{exit:?}");
+ }
+}
+
+#[tokio::test]
+async fn uninstall_of_an_installed_runtime_changes_nothing() {
+ let launcher = FakeLauncher::working();
+ let host = runtime_host(FakeProbe::serving([Served::Nothing]), launcher.clone(), fast_settings());
+ assert_eq!(
+ host.remove_private_runtime(Some(&origin())).await,
+ RemovalOutcome::NotPrivate
+ );
+ assert_eq!(
+ host.remove_unverified_private_runtime(Some(&origin())).await,
+ RemovalOutcome::NotPrivate
+ );
+ assert!(launcher.verbs().is_empty());
+}
+
+/// A bundle that cannot be prepared cannot run its CLI to prove its installs
+/// stopped. The real bundled host keeps every file until the user chooses to
+/// delete them anyway, and never touches anything outside its own roots.
+#[tokio::test]
+async fn a_broken_bundle_keeps_its_files_until_the_user_deletes_them_anyway() {
+ let root = temp_root("broken-bundle");
+ let installs = root.join("runtime");
+ let backends = root.join("backends");
+ std::fs::create_dir_all(installs.join("1.0.0")).unwrap();
+ std::fs::create_dir_all(backends.join("opencode")).unwrap();
+ std::fs::write(installs.join("1.0.0").join("python"), b"runtime bytes").unwrap();
+ std::fs::write(backends.join("opencode").join("bin"), b"backend bytes").unwrap();
+ std::fs::write(root.join("unrelated"), b"unrelated state").unwrap();
+ let host = bundled_runtime_host(
+ root.join("missing-bundle"),
+ installs.clone(),
+ backends.clone(),
+ BootstrapLog::disabled(),
+ )
+ .expect("the bundled host builds");
+
+ assert_eq!(host.remove_private_runtime(None).await, RemovalOutcome::Unverified);
+ assert!(installs.join("1.0.0").join("python").exists());
+ assert!(backends.join("opencode").join("bin").exists());
+
+ assert_eq!(
+ host.remove_unverified_private_runtime(None).await,
+ RemovalOutcome::Removed
+ );
+ assert!(!installs.exists() && !backends.exists());
+ assert_eq!(std::fs::read(root.join("unrelated")).unwrap(), b"unrelated state");
+ std::fs::remove_dir_all(root).unwrap();
+}
+
+fn temp_root(label: &str) -> PathBuf {
+ let unique = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("clock after epoch")
+ .as_nanos();
+ let root = std::env::temp_dir().join(format!("avibe-host-{label}-{}-{unique}", std::process::id()));
+ std::fs::create_dir_all(&root).unwrap();
+ root
+}
+
#[tokio::test(start_paused = true)]
async fn the_shell_learns_of_readiness_only_after_the_runtime_answers() {
let probe = FakeProbe::healthy_from(4);
let launcher = FakeLauncher::working();
- let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let host = runtime_host(probe.clone(), launcher.clone(), fast_settings());
let recorder = Recorder::default();
- let status = host.bootstrap(&recorder).await;
+ let status = host.bootstrap(&recorder, Launch).await;
let statuses = recorder.statuses();
// Ready is emitted once, last, and only on the probe call that succeeded.
@@ -678,11 +1254,11 @@ async fn the_shell_learns_of_readiness_only_after_the_runtime_answers() {
#[tokio::test(start_paused = true)]
async fn a_runtime_that_never_answers_fails_with_a_retryable_timeout() {
let probe = FakeProbe::never_healthy();
- let launcher = FakeLauncher::working();
- let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let launcher = FakeLauncher::bundled();
+ let host = runtime_host(probe.clone(), launcher.clone(), fast_settings());
let recorder = Recorder::default();
- let status = host.bootstrap(&recorder).await;
+ let status = host.bootstrap(&recorder, Launch).await;
assert_eq!(status.phase, BootstrapPhase::Failed);
assert!(status.retryable, "a slow machine deserves another try");
@@ -690,6 +1266,7 @@ async fn a_runtime_that_never_answers_fails_with_a_retryable_timeout() {
assert_eq!(status.notice.seconds, Some(2));
assert!(status.attempt > 1, "the wait is polled, not a single shot");
assert_eq!(launcher.calls(), 1);
+ assert!(launcher.verbs().is_empty(), "an unprovable Runtime is never stopped");
assert!(
!recorder.phases().contains(&BootstrapPhase::Ready),
"a timed-out run must never report readiness"
@@ -702,14 +1279,14 @@ async fn retrying_after_a_timeout_never_starts_a_second_runtime() {
// first run has already given up.
let probe = FakeProbe::healthy_from(7);
let launcher = FakeLauncher::working();
- let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let host = runtime_host(probe.clone(), launcher.clone(), fast_settings());
- let first = host.bootstrap(&Recorder::default()).await;
+ let first = boot(&host, Launch).await;
assert_eq!(first.phase, BootstrapPhase::Failed);
assert_eq!(launcher.calls(), 1);
let recorder = Recorder::default();
- let second = host.bootstrap(&recorder).await;
+ let second = host.bootstrap(&recorder, Retry).await;
assert_eq!(second.phase, BootstrapPhase::Ready);
assert_eq!(
@@ -727,19 +1304,19 @@ async fn retrying_after_a_timeout_never_starts_a_second_runtime() {
async fn a_launcher_failure_observed_after_timeout_is_rechecked_on_retry() {
let probe = FakeProbe::never_healthy();
let launcher = FakeLauncher::dying();
- let host = host(probe, launcher.clone(), immediate_timeout_settings());
+ let host = runtime_host(probe, launcher.clone(), immediate_timeout_settings());
// The zero-length budget expires before the polling loop can inspect the
// watch, matching a real launcher whose non-zero exit lands just after a
// normal timeout.
- let first = host.bootstrap(&Recorder::default()).await;
+ let first = boot(&host, Launch).await;
assert_eq!(first.phase, BootstrapPhase::Failed);
assert_eq!(first.notice.code, BootstrapNoticeCode::ReadyTimeout);
assert_eq!(first.notice.seconds, Some(0));
assert!(host.has_launched(), "the timed-out launch watch must be retained");
assert_eq!(launcher.calls(), 1);
- let second = host.bootstrap(&Recorder::default()).await;
+ let second = boot(&host, Retry).await;
assert_eq!(second.phase, BootstrapPhase::Failed);
assert_eq!(second.notice.code, BootstrapNoticeCode::LauncherExited);
assert!(
@@ -751,21 +1328,8 @@ async fn a_launcher_failure_observed_after_timeout_is_rechecked_on_retry() {
1,
"observing the failed launch must not start a replacement in the same retry"
);
- assert!(matches!(
- host.remove_private_runtime(None).await,
- Err(LaunchError::RuntimeRemoval)
- ));
- assert_eq!(
- launcher
- .removals
- .lock()
- .expect("removal recorder is not poisoned")
- .as_slice(),
- [RuntimeRemovalState::Unknown],
- "a failed helper does not prove that a previously launched Runtime is absent"
- );
- let third = host.bootstrap(&Recorder::default()).await;
+ let third = boot(&host, Retry).await;
assert_eq!(third.phase, BootstrapPhase::Failed);
assert_eq!(launcher.calls(), 2, "the next retry may start the Runtime again");
}
@@ -774,10 +1338,10 @@ async fn a_launcher_failure_observed_after_timeout_is_rechecked_on_retry() {
async fn a_long_running_launcher_is_retained_across_repeated_timeouts() {
let probe = FakeProbe::never_healthy();
let launcher = FakeLauncher::working();
- let host = host(probe, launcher.clone(), immediate_timeout_settings());
+ let host = runtime_host(probe, launcher.clone(), immediate_timeout_settings());
- let first = host.bootstrap(&Recorder::default()).await;
- let second = host.bootstrap(&Recorder::default()).await;
+ let first = boot(&host, Launch).await;
+ let second = boot(&host, Retry).await;
assert_eq!(first.phase, BootstrapPhase::Failed);
assert_eq!(second.phase, BootstrapPhase::Failed);
@@ -794,9 +1358,9 @@ async fn a_long_running_launcher_is_retained_across_repeated_timeouts() {
async fn a_zero_exit_launch_without_readiness_can_be_retried() {
let probe = FakeProbe::never_healthy();
let launcher = FakeLauncher::zero_exit_without_runtime();
- let host = host(probe, launcher.clone(), immediate_timeout_settings());
+ let host = runtime_host(probe, launcher.clone(), immediate_timeout_settings());
- let first = host.bootstrap(&Recorder::default()).await;
+ let first = boot(&host, Launch).await;
assert_eq!(first.phase, BootstrapPhase::Failed);
assert_eq!(first.notice.code, BootstrapNoticeCode::ReadyTimeout);
assert!(
@@ -805,7 +1369,7 @@ async fn a_zero_exit_launch_without_readiness_can_be_retried() {
);
assert_eq!(launcher.calls(), 1);
- let second = host.bootstrap(&Recorder::default()).await;
+ let second = boot(&host, Retry).await;
assert_eq!(second.phase, BootstrapPhase::Failed);
assert_eq!(
launcher.calls(),
@@ -817,16 +1381,13 @@ async fn a_zero_exit_launch_without_readiness_can_be_retried() {
#[tokio::test]
async fn readiness_loss_keeps_a_pending_helper_deduplicated() {
let launcher = FakeLauncher::working();
- let host = host(
+ let host = runtime_host(
FakeProbe::never_healthy(),
launcher.clone(),
immediate_timeout_settings(),
);
- assert_eq!(
- host.bootstrap(&Recorder::default()).await.notice.code,
- BootstrapNoticeCode::ReadyTimeout
- );
+ assert_eq!(boot(&host, Launch).await.notice.code, BootstrapNoticeCode::ReadyTimeout);
assert!(host.has_launched(), "the timeout retains the pending helper");
host.release_after_readiness_loss();
@@ -841,10 +1402,10 @@ async fn readiness_loss_keeps_a_pending_helper_deduplicated() {
async fn concurrent_bootstraps_start_at_most_one_runtime() {
let probe = FakeProbe::healthy_from(3);
let launcher = FakeLauncher::working();
- let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let host = runtime_host(probe.clone(), launcher.clone(), fast_settings());
let (left, right) = (Recorder::default(), Recorder::default());
- let (first, second) = tokio::join!(host.bootstrap(&left), host.bootstrap(&right));
+ let (first, second) = tokio::join!(host.bootstrap(&left, Launch), host.bootstrap(&right, Launch));
assert_eq!(first.phase, BootstrapPhase::Ready);
assert_eq!(second.phase, BootstrapPhase::Ready);
@@ -855,9 +1416,9 @@ async fn concurrent_bootstraps_start_at_most_one_runtime() {
async fn a_missing_executable_fails_retryably_and_the_next_attempt_may_start_one() {
let probe = FakeProbe::healthy_from(3);
let launcher = FakeLauncher::failing_first(1);
- let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let host = runtime_host(probe.clone(), launcher.clone(), fast_settings());
- let first = host.bootstrap(&Recorder::default()).await;
+ let first = boot(&host, Launch).await;
assert_eq!(first.phase, BootstrapPhase::Failed);
assert!(first.retryable);
assert_eq!(launcher.calls(), 1);
@@ -866,7 +1427,7 @@ async fn a_missing_executable_fails_retryably_and_the_next_attempt_may_start_one
"a launch that failed did not start anything, so it must not block the retry"
);
- let second = host.bootstrap(&Recorder::default()).await;
+ let second = boot(&host, Retry).await;
assert_eq!(second.phase, BootstrapPhase::Ready);
assert_eq!(launcher.calls(), 2, "the retry is allowed to start the Runtime");
assert!(host.has_launched());
@@ -879,11 +1440,11 @@ async fn a_missing_executable_fails_retryably_and_the_next_attempt_may_start_one
async fn a_launcher_that_exits_without_starting_anything_gives_up_early() {
let probe = FakeProbe::never_healthy();
let launcher = FakeLauncher::dying();
- let host = host(probe.clone(), launcher.clone(), fast_settings());
+ let host = runtime_host(probe.clone(), launcher.clone(), fast_settings());
let recorder = Recorder::default();
let started = tokio::time::Instant::now();
- let status = host.bootstrap(&recorder).await;
+ let status = host.bootstrap(&recorder, Launch).await;
let waited = started.elapsed();
assert_eq!(status.phase, BootstrapPhase::Failed);
@@ -897,7 +1458,7 @@ async fn a_launcher_that_exits_without_starting_anything_gives_up_early() {
// Nothing is running, so the retry has to be allowed to start one.
assert!(!host.has_launched());
- assert_eq!(host.bootstrap(&Recorder::default()).await.phase, BootstrapPhase::Failed);
+ assert_eq!(boot(&host, Retry).await.phase, BootstrapPhase::Failed);
assert_eq!(launcher.calls(), 2, "the retry starts a Runtime again");
}
@@ -909,10 +1470,10 @@ async fn a_non_loopback_origin_fails_immediately_and_is_not_retryable() {
origin_override: Some("http://avibe.example.com:5123".to_owned()),
..fast_settings()
};
- let host = host(probe.clone(), launcher.clone(), settings);
+ let host = runtime_host(probe.clone(), launcher.clone(), settings);
let recorder = Recorder::default();
- let status = host.bootstrap(&recorder).await;
+ let status = host.bootstrap(&recorder, Launch).await;
assert_eq!(status.phase, BootstrapPhase::Failed);
assert!(!status.retryable, "retrying cannot make a remote origin acceptable");
@@ -934,10 +1495,10 @@ async fn an_override_origin_is_adopted_only_and_never_starts_the_default_runtime
origin_override: Some(TEST_ORIGIN.to_owned()),
..fast_settings()
};
- let host = host(probe.clone(), launcher.clone(), settings);
+ let host = runtime_host(probe.clone(), launcher.clone(), settings);
let recorder = Recorder::default();
- let status = host.bootstrap(&recorder).await;
+ let status = host.bootstrap(&recorder, Launch).await;
assert_eq!(status.phase, BootstrapPhase::Failed);
assert!(status.retryable);
@@ -952,10 +1513,10 @@ async fn an_override_origin_is_adopted_only_and_never_starts_the_default_runtime
async fn the_production_wait_is_bounded() {
let probe = FakeProbe::never_healthy();
let launcher = FakeLauncher::working();
- let host = host(probe.clone(), launcher.clone(), RuntimeHostSettings::default());
+ let host = runtime_host(probe.clone(), launcher.clone(), RuntimeHostSettings::default());
let started = tokio::time::Instant::now();
- let status = host.bootstrap(&Recorder::default()).await;
+ let status = boot(&host, Launch).await;
let waited = started.elapsed();
assert_eq!(status.phase, BootstrapPhase::Failed);
diff --git a/desktop/scripts/verify-i18n.mjs b/desktop/scripts/verify-i18n.mjs
index d631fbeb5..bfe9e2ec8 100644
--- a/desktop/scripts/verify-i18n.mjs
+++ b/desktop/scripts/verify-i18n.mjs
@@ -13,6 +13,7 @@ const expectedNoticeCodes = [
'runtime_not_found',
'runtime_ownership_lost',
'runtime_spawn_failed',
+ 'runtime_stop_failed',
'runtime_stopped',
'starting',
'workbench_navigation_failed',
diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml
index 3ef84cba9..5cc3306eb 100644
--- a/desktop/src-tauri/Cargo.toml
+++ b/desktop/src-tauri/Cargo.toml
@@ -42,6 +42,11 @@ url.workspace = true
[dev-dependencies]
async-trait.workspace = true
+tauri = { version = "2", features = ["tray-icon", "test"] }
+
+[target.'cfg(windows)'.dev-dependencies]
+# Reads a native menu item's text, where muda keeps its accelerator.
+windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging"] }
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6.2"
diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rs
index 55a5fe653..3863ed223 100644
--- a/desktop/src-tauri/build.rs
+++ b/desktop/src-tauri/build.rs
@@ -7,5 +7,20 @@ fn main() {
// the shell's own local page.
let manifest =
tauri_build::AppManifest::new().commands(&["bootstrap_status", "bootstrap_retry", "open_install_docs"]);
- tauri_build::try_build(tauri_build::Attributes::new().app_manifest(manifest)).expect("failed to run tauri-build");
+ let mut attributes = tauri_build::Attributes::new().app_manifest(manifest);
+ // tauri-build embeds its Windows application manifest, which binds Common
+ // Controls v6, into the app binary only. A test binary that builds a Tauri
+ // app then fails to load with STATUS_ENTRYPOINT_NOT_FOUND. The linker embeds
+ // a verbatim copy into every binary this package links instead.
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
+ && std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
+ {
+ let windows_manifest = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").expect("manifest dir"))
+ .join("windows-app-manifest.xml");
+ println!("cargo:rerun-if-changed={}", windows_manifest.display());
+ println!("cargo:rustc-link-arg=/MANIFEST:EMBED");
+ println!("cargo:rustc-link-arg=/MANIFESTINPUT:{}", windows_manifest.display());
+ attributes = attributes.windows_attributes(tauri_build::WindowsAttributes::new_without_app_manifest());
+ }
+ tauri_build::try_build(attributes).expect("failed to run tauri-build");
}
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index a822c7959..772631158 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -35,16 +35,16 @@ use avibe_runtime_host::deep_link::{DeepLinkNavigation, DeepLinks};
#[cfg(not(feature = "bundled-runtime"))]
use avibe_runtime_host::default_runtime_host;
#[cfg(feature = "bundled-runtime")]
-use avibe_runtime_host::{bundled_runtime_host, BootstrapLog, BOOTSTRAP_LOG_NAME};
+use avibe_runtime_host::{bundled_runtime_host, BootstrapLog, RemovalOutcome, BOOTSTRAP_LOG_NAME};
use avibe_runtime_host::{
- is_shell_ui_url, BootstrapNotice, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus, LaunchError,
- LoopbackOrigin, RuntimeHost, StatusSink,
+ is_shell_ui_url, BootstrapNotice, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus, BootstrapTrigger,
+ CliOutcome, LoopbackOrigin, RuntimeHost, StatusSink,
};
use serde::Deserialize;
use tauri::menu::{CheckMenuItem, Menu, MenuItem, MenuItemKind, PredefinedMenuItem, Submenu};
use tauri::plugin::Builder as PluginBuilder;
use tauri::tray::TrayIconBuilder;
-use tauri::{AppHandle, Emitter, Manager, WebviewWindow, WebviewWindowBuilder};
+use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow, WebviewWindowBuilder};
use tauri::{RunEvent, WindowEvent};
use tauri_plugin_autostart::ManagerExt;
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind, MessageDialogResult};
@@ -134,7 +134,6 @@ struct NativeTrayCatalog {
busy_title: String,
busy_message: String,
failure_title: String,
- stop_failure: String,
login_failure: String,
}
@@ -153,6 +152,12 @@ struct NativeUninstallCatalog {
success_message: String,
failure_title: String,
failure_message: String,
+ blocked_title: String,
+ blocked_message: String,
+ unverified_title: String,
+ unverified_message: String,
+ unverified_delete: String,
+ unverified_keep: String,
}
fn native_catalog_for_locales(locales: impl IntoIterator<Item = String>) -> DesktopBootstrapCatalog {
@@ -313,7 +318,7 @@ fn install_native_tray(app: &AppHandle) -> tauri::Result<()> {
login_state.unwrap_or(false),
None::<&str>,
)?;
- let quit = MenuItem::with_id(app, QUIT_MENU_ID, &catalog.quit, true, None::<&str>)?;
+ let quit = quit_menu_item(app, &catalog.quit)?;
let notifications = CheckMenuItem::with_id(
app,
notifications::MENU_ID,
@@ -340,7 +345,7 @@ fn install_native_tray(app: &AppHandle) -> tauri::Result<()> {
&quit,
],
)?;
- let application_menu = application_menu(app)?;
+ let application_menu = application_menu(app, &quit)?;
let application = application_menu.items()?.into_iter().find_map(|item| match item {
MenuItemKind::Submenu(submenu) => Some(submenu),
_ => None,
@@ -636,12 +641,11 @@ fn request_runtime_lifecycle(app: AppHandle, quit: bool) {
}
fn stop_runtime(app: AppHandle, quit: bool) {
- let (host, activity, origin, previous_status) = {
+ let (host, activity, previous_status) = {
let shell = app.state::<Shell>();
(
shell.host.clone(),
shell.activity.clone(),
- shell.active_origin.lock().ok().and_then(|origin| origin.clone()),
shell.latest.lock().ok().and_then(|latest| latest.clone()),
)
};
@@ -652,50 +656,32 @@ fn stop_runtime(app: AppHandle, quit: bool) {
refresh_runtime_tray(&app, TrayRuntimeState::Stopping);
notifications::stop(&app);
tauri::async_runtime::spawn(async move {
- match host.stop_owned_runtime().await {
- Ok(()) if quit => exit_shell(&app),
- Ok(()) => {
- let _ = return_to_bootstrap(&app);
- let mut stopped = BootstrapStatus::rejected(BootstrapNoticeCode::RuntimeStopped, true);
- if let Some(previous) = previous_status {
- stopped.origin = previous.origin;
- }
- activity.store(ACTIVITY_IDLE, Ordering::SeqCst);
- WindowSink {
- app: app.clone(),
- latest: app.state::<Shell>().latest.clone(),
- }
- .publish(stopped);
- }
- Err(LaunchError::OwnershipLost | LaunchError::NotOwned) => {
- let _ = return_to_bootstrap(&app);
- let mut lost = BootstrapStatus::rejected(BootstrapNoticeCode::RuntimeOwnershipLost, true);
- if let Some(previous) = previous_status {
- lost.origin = previous.origin;
- }
- activity.store(ACTIVITY_IDLE, Ordering::SeqCst);
- WindowSink {
- app: app.clone(),
- latest: app.state::<Shell>().latest.clone(),
- }
- .publish(lost);
- focus_or_restore_main_window(&app);
- }
- Err(_) => {
- if let Some(origin) = origin {
- activity.store(ACTIVITY_MONITOR, Ordering::SeqCst);
- start_runtime_monitor(app.clone(), origin, activity);
- } else {
- activity.store(ACTIVITY_IDLE, Ordering::SeqCst);
- }
- refresh_latest_tray(&app);
- let catalog = native_tray_catalog();
- app.dialog()
- .message(catalog.stop_failure)
- .title(catalog.failure_title)
- .kind(MessageDialogKind::Error)
- .show(|_| {});
- }
+ let outcome = host.stop_owned_runtime().await;
+ if quit && outcome == CliOutcome::Completed {
+ exit_shell(&app);
+ return;
+ }
+ // Whatever the stop did, the Workbench no longer reflects a Runtime the
+ // shell vouches for. The bootstrap page says what happened, and Try
+ // again re-checks the origin.
+ let (code, focus) = match outcome {
+ CliOutcome::Completed => (BootstrapNoticeCode::RuntimeStopped, false),
+ CliOutcome::Refused { .. } => (BootstrapNoticeCode::RuntimeOwnershipLost, true),
+ CliOutcome::Failed { .. } | CliOutcome::Unrunnable => (BootstrapNoticeCode::RuntimeStopFailed, true),
+ };
+ let _ = return_to_bootstrap(&app);
+ let mut status = BootstrapStatus::rejected(code, true);
+ if let Some(previous) = previous_status {
+ status.origin = previous.origin;
+ }
+ activity.store(ACTIVITY_IDLE, Ordering::SeqCst);
+ WindowSink {
+ app: app.clone(),
+ latest: app.state::<Shell>().latest.clone(),
+ }
+ .publish(status);
+ if focus {
+ focus_or_restore_main_window(&app);
}
});
}
@@ -799,7 +785,8 @@ impl ReadinessLoss {
if generation.load(Ordering::SeqCst) != observed_generation {
return false;
}
- // Three readiness misses do not prove process exit or revoke a receipt.
+ // Three serving misses do not prove the process exited, so a pending
+ // helper keeps its launch fence.
host.release_after_readiness_loss();
true
}
@@ -885,7 +872,7 @@ fn bootstrap_status(window: WebviewWindow, app: AppHandle) -> Result<Option<Boot
#[tauri::command]
fn bootstrap_retry(window: WebviewWindow, app: AppHandle) -> Result<bool, String> {
ensure_shell_ui(&window)?;
- Ok(spawn_bootstrap(app))
+ Ok(spawn_bootstrap(app, BootstrapTrigger::Retry))
}
/// Opens installation guidance in the system browser.
@@ -903,7 +890,7 @@ fn open_install_docs(window: WebviewWindow) -> Result<(), String> {
///
/// The return value is part of the retry contract: the bootstrap page must not
/// hide its Retry action when another run still owns the activity.
-fn spawn_bootstrap(app: AppHandle) -> bool {
+fn spawn_bootstrap(app: AppHandle, trigger: BootstrapTrigger) -> bool {
let activity = app.state::<Shell>().activity.clone();
if activity
.compare_exchange(ACTIVITY_IDLE, ACTIVITY_BOOTSTRAP, Ordering::SeqCst, Ordering::SeqCst)
@@ -911,12 +898,15 @@ fn spawn_bootstrap(app: AppHandle) -> bool {
{
return false;
}
- spawn_owned_bootstrap(app);
+ spawn_owned_bootstrap(app, trigger);
true
}
/// Runs bootstrap after the caller has atomically acquired bootstrap activity.
-fn spawn_owned_bootstrap(app: AppHandle) {
+///
+/// Only the app-launch run and the user's Try again may hand over from a
+/// predecessor Runtime; every run the shell starts by itself is a recovery.
+fn spawn_owned_bootstrap(app: AppHandle, trigger: BootstrapTrigger) {
let (host, latest, activity) = {
let shell = app.state::<Shell>();
(shell.host.clone(), shell.latest.clone(), shell.activity.clone())
@@ -927,7 +917,7 @@ fn spawn_owned_bootstrap(app: AppHandle) {
app: app.clone(),
latest,
};
- let status = host.bootstrap(&sink).await;
+ let status = host.bootstrap(&sink, trigger).await;
if status.phase == BootstrapPhase::Ready {
open_workbench(&app, &status, activity);
@@ -987,7 +977,7 @@ fn open_workbench(app: &AppHandle, ready: &BootstrapStatus, activity: Arc<Atomic
let Some(window) = app.get_webview_window(MAIN_WINDOW) else {
let _ = activity.compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_IDLE, Ordering::SeqCst, Ordering::SeqCst);
if app.get_webview_window(MAIN_WINDOW).is_some() {
- let _ = spawn_bootstrap(app.clone());
+ let _ = spawn_bootstrap(app.clone(), BootstrapTrigger::Recovery);
}
return;
};
@@ -1070,10 +1060,11 @@ fn start_runtime_monitor(app: AppHandle, origin: LoopbackOrigin, activity: Arc<A
{
break;
}
- let ready = host.is_ready(&origin).await;
- // Window recreation can transfer ownership while the network probe
- // is pending. The superseded monitor must not mutate the new
- // bootstrap run's launch ownership after the await point.
+ let ready = host.is_serving(&origin).await;
+ // Window recreation or a stop can take over while the probe is
+ // pending. The host has already dropped the probe's observation;
+ // the superseded monitor must not touch the tray or start a
+ // recovery either.
if activity.load(Ordering::SeqCst) != ACTIVITY_MONITOR
|| generation.load(Ordering::SeqCst) != observed_generation
{
@@ -1091,7 +1082,7 @@ fn start_runtime_monitor(app: AppHandle, origin: LoopbackOrigin, activity: Arc<A
&& recover_after_readiness_loss(
|| restore_bootstrap_view(&app),
|| notifications::stop(&app),
- || spawn_owned_bootstrap(app.clone()),
+ || spawn_owned_bootstrap(app.clone(), BootstrapTrigger::Recovery),
|| {
activity
.compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_MONITOR, Ordering::SeqCst, Ordering::SeqCst)
@@ -1172,7 +1163,7 @@ fn rediscover_after_runtime_rebind(app: AppHandle, origin: LoopbackOrigin) {
tauri::async_runtime::spawn(async move {
if return_to_bootstrap(&app) {
- spawn_owned_bootstrap(app);
+ spawn_owned_bootstrap(app, BootstrapTrigger::Recovery);
return;
}
if activity
@@ -1298,7 +1289,9 @@ fn focus_or_restore_main_window(app: &AppHandle) {
.filter(|status| {
matches!(
status.notice.code,
- BootstrapNoticeCode::RuntimeStopped | BootstrapNoticeCode::RuntimeOwnershipLost
+ BootstrapNoticeCode::RuntimeStopped
+ | BootstrapNoticeCode::RuntimeOwnershipLost
+ | BootstrapNoticeCode::RuntimeStopFailed
)
});
if let Some(status) = stopped {
@@ -1330,7 +1323,7 @@ fn focus_or_restore_main_window(app: &AppHandle) {
if let Ok(mut latest) = latest.lock() {
*latest = None;
}
- spawn_owned_bootstrap(app.clone());
+ spawn_owned_bootstrap(app.clone(), BootstrapTrigger::Recovery);
}
}
}
@@ -1394,23 +1387,48 @@ fn commit_deep_link_navigation(
}
}
-fn application_menu(app: &AppHandle) -> tauri::Result<Menu<tauri::Wry>> {
- let menu = Menu::default(app)?;
- #[cfg(feature = "bundled-runtime")]
- {
- use tauri::menu::{MenuItem, PredefinedMenuItem};
+/// Quit, shared by the tray and the application menu. It carries the
+/// platform's Quit chord, so every Quit the menus offer asks about the Runtime.
+fn quit_menu_item<R: Runtime>(app: &AppHandle<R>, label: &str) -> tauri::Result<MenuItem<R>> {
+ MenuItem::with_id(app, QUIT_MENU_ID, label, true, Some("CmdOrCtrl+Q"))
+}
- let first_submenu = menu.items()?.into_iter().find_map(|item| match item {
- MenuItemKind::Submenu(submenu) => Some(submenu),
- _ => None,
- });
- if let Some(submenu) = first_submenu {
+/// Stop and Quit, from any menu or chord, run the Runtime lifecycle flow.
+/// `Some(true)` quits.
+fn runtime_lifecycle_request(id: &str) -> Option<bool> {
+ match id {
+ STOP_MENU_ID => Some(false),
+ QUIT_MENU_ID => Some(true),
+ _ => None,
+ }
+}
+
+fn application_menu<R: Runtime>(app: &AppHandle<R>, quit: &MenuItem<R>) -> tauri::Result<Menu<R>> {
+ let menu = Menu::default(app)?;
+ let first_submenu = menu.items()?.into_iter().find_map(|item| match item {
+ MenuItemKind::Submenu(submenu) => Some(submenu),
+ _ => None,
+ });
+ if let Some(submenu) = first_submenu {
+ // `Menu::default` ends this submenu (the macOS app menu, or File) with
+ // a predefined Quit that ends the process without `ExitRequested`, so
+ // it would leave this app's Runtime running. `quit` takes its place.
+ let predefined_quit = PredefinedMenuItem::quit(app, None)?.text()?;
+ for item in submenu.items()? {
+ if let MenuItemKind::Predefined(predefined) = &item {
+ if predefined.text()? == predefined_quit {
+ submenu.remove(predefined)?;
+ }
+ }
+ }
+ #[cfg(feature = "bundled-runtime")]
+ {
let catalog = native_uninstall_catalog();
let separator = PredefinedMenuItem::separator(app)?;
let uninstall = MenuItem::with_id(app, UNINSTALL_MENU_ID, catalog.menu_label, true, None::<&str>)?;
- let position = submenu.items()?.len().saturating_sub(1);
- submenu.insert_items(&[&separator, &uninstall], position)?;
+ submenu.append_items(&[&separator, &uninstall])?;
}
+ submenu.append(quit)?;
}
Ok(menu)
}
@@ -1438,20 +1456,100 @@ fn claim_runtime_removal(activity: &AtomicU8) -> bool {
fn recover_after_runtime_removal_failure(app: &AppHandle, activity: Arc<AtomicU8>) {
let _ = activity.compare_exchange(ACTIVITY_UNINSTALL, ACTIVITY_IDLE, Ordering::SeqCst, Ordering::SeqCst);
if return_to_bootstrap(app) {
- let _ = spawn_bootstrap(app.clone());
+ let _ = spawn_bootstrap(app.clone(), BootstrapTrigger::Recovery);
}
}
#[cfg(feature = "bundled-runtime")]
-fn report_runtime_removal_failure(app: &AppHandle, activity: Arc<AtomicU8>, catalog: &NativeUninstallCatalog) {
+fn report_runtime_removal_failure(
+ app: &AppHandle,
+ activity: Arc<AtomicU8>,
+ catalog: &NativeUninstallCatalog,
+ failure: UninstallFailure,
+) {
recover_after_runtime_removal_failure(app, activity);
+ let (title, message, kind) = match failure {
+ // The user chose to keep the files; there is nothing to report.
+ UninstallFailure::Declined => return,
+ UninstallFailure::Blocked => (
+ &catalog.blocked_title,
+ &catalog.blocked_message,
+ MessageDialogKind::Warning,
+ ),
+ UninstallFailure::Failed => (
+ &catalog.failure_title,
+ &catalog.failure_message,
+ MessageDialogKind::Error,
+ ),
+ };
app.dialog()
- .message(catalog.failure_message.clone())
- .title(catalog.failure_title.clone())
- .kind(MessageDialogKind::Error)
+ .message(message.clone())
+ .title(title.clone())
+ .kind(kind)
.show(|_| {});
}
+/// Why a confirmed uninstall kept the installation.
+#[cfg(feature = "bundled-runtime")]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum UninstallFailure {
+ /// Something still running may use the files, so every file was kept.
+ Blocked,
+ /// Removal failed or could not begin. Part of the files may remain.
+ Failed,
+ /// The user kept the files rather than delete them unverified.
+ Declined,
+}
+
+/// Removes this app's private Runtime for a confirmed uninstall.
+///
+/// When the Runtime's own CLI cannot run to prove its installs stopped, and
+/// nothing is seen running, only the user's explicit choice deletes the files
+/// anyway. Every other outcome that keeps the files has no override.
+#[cfg(feature = "bundled-runtime")]
+async fn remove_private_runtime_with_consent<Consent>(
+ host: &RuntimeHost,
+ origin: Option<&LoopbackOrigin>,
+ confirm_unverified: impl FnOnce() -> Consent,
+) -> Result<(), UninstallFailure>
+where
+ Consent: std::future::Future<Output = bool>,
+{
+ let outcome = match host.remove_private_runtime(origin).await {
+ RemovalOutcome::Unverified => {
+ if !confirm_unverified().await {
+ return Err(UninstallFailure::Declined);
+ }
+ host.remove_unverified_private_runtime(origin).await
+ }
+ outcome => outcome,
+ };
+ match outcome {
+ RemovalOutcome::Removed | RemovalOutcome::NotPrivate => Ok(()),
+ RemovalOutcome::Kept => Err(UninstallFailure::Blocked),
+ RemovalOutcome::Unverified | RemovalOutcome::Failed => Err(UninstallFailure::Failed),
+ }
+}
+
+/// Asks whether to delete the private files although nothing proved that the
+/// Runtime's installs have stopped. Dismissing the dialog keeps them.
+#[cfg(feature = "bundled-runtime")]
+async fn confirm_unverified_removal(app: AppHandle, catalog: NativeUninstallCatalog) -> bool {
+ tauri::async_runtime::spawn_blocking(move || {
+ app.dialog()
+ .message(catalog.unverified_message)
+ .title(catalog.unverified_title)
+ .kind(MessageDialogKind::Warning)
+ .buttons(MessageDialogButtons::OkCancelCustom(
+ catalog.unverified_delete,
+ catalog.unverified_keep,
+ ))
+ .blocking_show()
+ })
+ .await
+ .unwrap_or(false)
+}
+
/// The confirmed uninstall's one decision: an opt-in login registration is
/// cleared before the private Runtime is deleted, so the OS never keeps
/// launching an application the user just removed. Failing to inspect or to
@@ -1468,10 +1566,10 @@ async fn remove_runtime_after_login_cleanup<Removal>(
disable_login: impl FnOnce() -> Result<(), String>,
remove_runtime: impl FnOnce() -> Removal,
restore_login: impl FnOnce() -> bool,
- report_failure: impl FnOnce(),
+ report_failure: impl FnOnce(UninstallFailure),
) -> UninstallOutcome
where
- Removal: std::future::Future<Output = bool>,
+ Removal: std::future::Future<Output = Result<(), UninstallFailure>>,
{
let cleared = match login_enabled {
Ok(true) => disable_login().map(|()| true),
@@ -1479,24 +1577,24 @@ where
Err(error) => Err(error),
};
let Ok(cleared) = cleared else {
- report_failure();
+ report_failure(UninstallFailure::Failed);
return UninstallOutcome::Kept;
};
- if remove_runtime().await {
+ let Err(failure) = remove_runtime().await else {
return UninstallOutcome::Removed;
- }
+ };
let outcome = if cleared && !restore_login() {
UninstallOutcome::KeptWithoutLogin
} else {
UninstallOutcome::Kept
};
- report_failure();
+ report_failure(failure);
outcome
}
/// How a confirmed uninstall ended. Only `Removed` reached the success dialog
/// and the shell exit; the other two left the installation in place and
-/// reported the failure.
+/// reported why, unless the user chose to keep the files.
#[cfg(feature = "bundled-runtime")]
#[derive(Debug, PartialEq, Eq)]
enum UninstallOutcome {
@@ -1557,22 +1655,23 @@ fn request_private_runtime_removal(app: AppHandle) {
|| login_app.autolaunch().disable().map_err(|error| error.to_string()),
|| async move {
notifications::stop(&confirmation_app);
- match host.remove_private_runtime(active_origin.as_ref()).await {
- Ok(true) => {
- let exit_app = confirmation_app.clone();
- confirmation_app
- .dialog()
- .message(removal_catalog.success_message.clone())
- .title(removal_catalog.success_title.clone())
- .kind(MessageDialogKind::Info)
- .show(move |_| exit_shell(&exit_app));
- true
- }
- Ok(false) | Err(_) => false,
- }
+ let consent_app = confirmation_app.clone();
+ let consent_catalog = removal_catalog.clone();
+ remove_private_runtime_with_consent(&host, active_origin.as_ref(), || {
+ confirm_unverified_removal(consent_app, consent_catalog)
+ })
+ .await?;
+ let exit_app = confirmation_app.clone();
+ confirmation_app
+ .dialog()
+ .message(removal_catalog.success_message.clone())
+ .title(removal_catalog.success_title.clone())
+ .kind(MessageDialogKind::Info)
+ .show(move |_| exit_shell(&exit_app));
+ Ok(())
},
|| set_start_at_login(&restore_app, Ok(true)),
- || report_runtime_removal_failure(&failure_app, activity, &catalog),
+ |failure| report_runtime_removal_failure(&failure_app, activity, &catalog, failure),
)
.await;
});
@@ -1603,13 +1702,14 @@ pub fn run() {
.plugin(tauri_plugin_autostart::Builder::new().build())
.plugin(tauri_plugin_notification::init())
.on_menu_event(|app, event| {
+ if let Some(quit) = runtime_lifecycle_request(event.id().as_ref()) {
+ request_runtime_lifecycle(app.clone(), quit);
+ }
match event.id().as_ref() {
OPEN_MENU_ID => focus_or_restore_main_window(app),
SETTINGS_MENU_ID => open_workbench_settings(app),
updater::MENU_ID => updater::check(app.clone(), true),
updater::CHANNEL_ID => updater::toggle_channel(app),
- STOP_MENU_ID => request_runtime_lifecycle(app.clone(), false),
- QUIT_MENU_ID => request_runtime_lifecycle(app.clone(), true),
LOGIN_MENU_ID => toggle_start_at_login(app),
notifications::MENU_ID => {
let notifications = app.state::<notifications::Notifications>();
@@ -1739,7 +1839,7 @@ pub fn run() {
updater::init(app.handle())?;
install_native_tray(app.handle())?;
updater::check(app.handle().clone(), false);
- let _ = spawn_bootstrap(app.handle().clone());
+ let _ = spawn_bootstrap(app.handle().clone(), BootstrapTrigger::Launch);
Ok(())
})
.run(tauri::generate_context!())
@@ -1750,7 +1850,10 @@ pub fn run() {
mod tests {
use super::*;
use async_trait::async_trait;
- use avibe_runtime_host::{HealthProbe, LaunchWatch, LaunchedRuntime, ResolvedRuntimeLauncher, RuntimeLauncher};
+ use avibe_runtime_host::{
+ HealthProbe, LaunchError, LaunchExit, LaunchWatch, LaunchedRuntime, Presence, ResolvedRuntimeLauncher,
+ RuntimeLauncher,
+ };
use std::sync::atomic::AtomicUsize;
#[test]
@@ -1832,6 +1935,61 @@ mod tests {
}
}
+ #[test]
+ fn stop_and_quit_run_the_runtime_lifecycle_from_every_menu() {
+ assert_eq!(runtime_lifecycle_request(STOP_MENU_ID), Some(false));
+ assert_eq!(runtime_lifecycle_request(QUIT_MENU_ID), Some(true));
+ assert_eq!(runtime_lifecycle_request(OPEN_MENU_ID), None);
+ }
+
+ // muda builds macOS menus only on the main thread, which a test never runs
+ // on. The guest acceptance run covers the macOS app menu and its ⌘Q.
+ #[cfg(windows)]
+ #[test]
+ fn the_application_menu_quits_only_through_the_runtime_lifecycle() {
+ use tauri::menu::ContextMenu;
+ use windows_sys::Win32::UI::WindowsAndMessaging::{GetMenuItemCount, GetMenuStringW, HMENU, MF_BYPOSITION};
+
+ let app = tauri::test::mock_app();
+ let handle = app.handle();
+ let quit = quit_menu_item(handle, "Quit Avibe").expect("quit item");
+ let menu = application_menu(handle, &quit).expect("application menu");
+ let predefined_quit = PredefinedMenuItem::quit(handle, None)
+ .and_then(|item| item.text())
+ .expect("predefined quit text");
+ let submenus: Vec<_> = menu
+ .items()
+ .expect("menu items")
+ .into_iter()
+ .filter_map(|item| match item {
+ MenuItemKind::Submenu(submenu) => Some(submenu),
+ _ => None,
+ })
+ .collect();
+ for submenu in &submenus {
+ for item in submenu.items().expect("submenu items") {
+ if let MenuItemKind::Predefined(predefined) = item {
+ assert_ne!(predefined.text().expect("predefined text"), predefined_quit);
+ }
+ }
+ }
+ let first = submenus.first().expect("File submenu");
+ let Some(MenuItemKind::MenuItem(last)) = first.items().expect("File items").pop() else {
+ panic!("File must end with this app's Quit");
+ };
+ assert_eq!(runtime_lifecycle_request(last.id().as_ref()), Some(true));
+
+ // muda keeps an accelerator only in the native item text.
+ let hmenu = first.hpopupmenu().expect("File HMENU") as HMENU;
+ let mut text = [0u16; 64];
+ let len = unsafe {
+ let last = u32::try_from(GetMenuItemCount(hmenu) - 1).expect("File has items");
+ GetMenuStringW(hmenu, last, text.as_mut_ptr(), text.len() as i32, MF_BYPOSITION)
+ };
+ let len = usize::try_from(len).expect("menu string");
+ assert_eq!(String::from_utf16_lossy(&text[..len]), "Quit Avibe\tCtrl+Q");
+ }
+
#[test]
fn tray_status_is_a_projection_of_bootstrap_and_the_proved_listener() {
let origin = LoopbackOrigin::parse("http://127.0.0.1:6123").expect("test listener");
@@ -1868,35 +2026,29 @@ mod tests {
assert!(loss.observe(false));
}
- struct RecoveryProbe(Mutex<std::collections::VecDeque<bool>>);
+ struct RecoveryProbe(Mutex<std::collections::VecDeque<Presence>>);
#[async_trait]
impl HealthProbe for RecoveryProbe {
- async fn readiness(&self, _origin: &LoopbackOrigin) -> Option<avibe_runtime_host::RuntimeReadiness> {
- self.0
- .lock()
- .unwrap()
- .pop_front()
- .unwrap_or(false)
- .then_some(avibe_runtime_host::RuntimeReadiness {
- desktop_runtime_id: None,
- desktop_ui_runtime_id: None,
- })
+ async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
+ self.0.lock().unwrap().pop_front().unwrap_or(Presence::Absent)
}
}
struct RecoveryLauncher {
watches: Mutex<std::collections::VecDeque<LaunchWatch>>,
launches: Arc<AtomicUsize>,
- stops: Arc<Mutex<Vec<avibe_runtime_host::launcher::StartupReceipt>>>,
+ stops: Arc<Mutex<Vec<String>>>,
}
struct RecoveryExecutable {
watch: LaunchWatch,
launches: Arc<AtomicUsize>,
- stops: Arc<Mutex<Vec<avibe_runtime_host::launcher::StartupReceipt>>>,
+ stops: Arc<Mutex<Vec<String>>>,
}
+ const RECOVERY_RUNTIME_ID: &str = "4d";
+
impl RuntimeLauncher for RecoveryLauncher {
fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
Ok(Arc::new(RecoveryExecutable {
@@ -1912,7 +2064,11 @@ mod tests {
Ok(LoopbackOrigin::parse("http://127.0.0.1:5123").unwrap())
}
- fn launch(&self) -> Result<LaunchedRuntime, LaunchError> {
+ fn expected_runtime_id(&self) -> Option<&str> {
+ Some(RECOVERY_RUNTIME_ID)
+ }
+
+ fn launch(&self, _hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
self.launches.fetch_add(1, Ordering::SeqCst);
Ok(LaunchedRuntime {
pid: 1,
@@ -1920,34 +2076,35 @@ mod tests {
})
}
- fn stop(&self, receipt: &avibe_runtime_host::launcher::StartupReceipt) -> Result<(), LaunchError> {
- self.stops.lock().unwrap().push(receipt.clone());
- Ok(())
+ fn stop(&self, runtime_id: &str) -> CliOutcome {
+ self.stops.lock().unwrap().push(runtime_id.to_owned());
+ CliOutcome::Completed
}
}
#[test]
fn monitor_recovery_preserves_started_authority_and_pending_helper_exclusion() {
- use avibe_runtime_host::launcher::StartupReceipt;
use avibe_runtime_host::{DiscardStatus, RuntimeHostSettings};
- let receipt: StartupReceipt = serde_json::from_value(serde_json::json!({
- "schema_version": 1, "outcome": "started", "service_pid": 1234, "ui_pid": 5678,
- "service_create_unix_ms": 1789010100123.5, "ui_create_unix_ms": 1789010100456.5,
- }))
- .unwrap();
- let mut reused_json = serde_json::to_value(&receipt).unwrap();
- reused_json["outcome"] = serde_json::json!("reused");
- let reused: StartupReceipt = serde_json::from_value(reused_json).unwrap();
+ let mine = Presence::Mine { ready: true };
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
for pending in [false, true] {
- // Start -> ready -> three monitor misses -> recovery helper -> ready.
+ // Start -> ready -> three monitor misses -> recovery -> ready.
let probe = Arc::new(RecoveryProbe(Mutex::new(
- [false, true, false, false, false, false, true].into(),
+ [
+ Presence::Absent,
+ mine.clone(),
+ Presence::Absent,
+ Presence::Absent,
+ Presence::Absent,
+ Presence::Absent,
+ mine.clone(),
+ ]
+ .into(),
)));
let launcher = Arc::new(RecoveryLauncher {
watches: Mutex::new(
@@ -1955,9 +2112,9 @@ mod tests {
if pending {
LaunchWatch::default()
} else {
- LaunchWatch::exited_with_receipt(true, receipt.clone())
+ LaunchWatch::exited(LaunchExit::Started)
},
- LaunchWatch::exited_with_receipt(true, reused.clone()),
+ LaunchWatch::exited(LaunchExit::Started),
]
.into(),
),
@@ -1974,7 +2131,7 @@ mod tests {
},
);
runtime.block_on(async {
- let ready = host.bootstrap(&DiscardStatus).await;
+ let ready = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
assert_eq!(ready.phase, BootstrapPhase::Ready);
let origin = LoopbackOrigin::parse(&ready.origin).unwrap();
let activity = AtomicU8::new(ACTIVITY_MONITOR);
@@ -1997,38 +2154,44 @@ mod tests {
activity.store(ACTIVITY_MONITOR, Ordering::SeqCst);
let mut loss = ReadinessLoss::default();
for miss in 1..=3 {
- let ready = host.is_ready(&origin).await;
+ let ready = host.is_serving(&origin).await;
assert!(!ready);
assert_eq!(loss.begin_recovery(ready, &host, &activity, &generation, 7), miss == 3);
}
+ // Nothing answers, so stop authority is gone, but a pending
+ // helper keeps its launch fence.
assert_eq!(host.has_launched(), pending);
- assert_eq!(host.has_owned_runtime(), !pending);
+ assert!(!host.has_owned_runtime());
assert!(!stop_is_available(
host.has_owned_runtime(),
activity.load(Ordering::SeqCst)
));
- let recovered = host.bootstrap(&DiscardStatus).await;
+ let recovered = host.bootstrap(&DiscardStatus, BootstrapTrigger::Recovery).await;
assert_eq!(recovered.phase, BootstrapPhase::Ready);
let window_generation = AtomicU64::new(1);
assert_eq!(
complete_workbench_handoff(&activity, &window_generation, 1),
WorkbenchHandoff::Monitor
);
- assert_eq!(
- stop_is_available(host.has_owned_runtime(), activity.load(Ordering::SeqCst)),
- !pending
- );
+ // The recovered Controller carries this app's identity again.
+ assert!(stop_is_available(
+ host.has_owned_runtime(),
+ activity.load(Ordering::SeqCst)
+ ));
assert_eq!(launcher.launches.load(Ordering::SeqCst), if pending { 1 } else { 2 });
if pending {
- assert!(matches!(host.stop_owned_runtime().await, Err(LaunchError::NotOwned)));
+ assert_eq!(
+ host.stop_owned_runtime().await,
+ CliOutcome::Failed {
+ part: "launch_pending".to_owned()
+ }
+ );
assert!(launcher.stops.lock().unwrap().is_empty());
} else {
- host.stop_owned_runtime()
- .await
- .expect("original receipt survives reused recovery");
+ assert_eq!(host.stop_owned_runtime().await, CliOutcome::Completed);
assert_eq!(
launcher.stops.lock().unwrap().as_slice(),
- std::slice::from_ref(&receipt)
+ [RECOVERY_RUNTIME_ID.to_owned()]
);
assert!(!host.has_owned_runtime());
}
@@ -2098,7 +2261,7 @@ mod tests {
RestoreLogin,
RenderLogin(bool),
ReportLoginFailure,
- ReportFailure,
+ ReportFailure(UninstallFailure),
}
/// A confirmed uninstall whose restore, when it runs, writes `restore_write`
@@ -2107,7 +2270,7 @@ mod tests {
fn uninstall_run(
login_enabled: Result<bool, String>,
disable_login: Result<(), String>,
- removed: bool,
+ removed: Result<(), UninstallFailure>,
restore_write: Result<(), String>,
restore_observed: Result<bool, String>,
) -> (UninstallOutcome, Vec<UninstallEffect>) {
@@ -2136,7 +2299,7 @@ mod tests {
|| effects.borrow_mut().push(UninstallEffect::ReportLoginFailure),
)
},
- || effects.borrow_mut().push(UninstallEffect::ReportFailure),
+ |failure| effects.borrow_mut().push(UninstallEffect::ReportFailure(failure)),
),
);
(outcome, effects.into_inner())
@@ -2147,7 +2310,7 @@ mod tests {
fn uninstall_effects(
login_enabled: Result<bool, String>,
disable_login: Result<(), String>,
- removed: bool,
+ removed: Result<(), UninstallFailure>,
) -> Vec<UninstallEffect> {
uninstall_run(login_enabled, disable_login, removed, Ok(()), Ok(true)).1
}
@@ -2156,7 +2319,7 @@ mod tests {
#[test]
fn uninstall_clears_an_enabled_login_item_before_removing_the_private_runtime() {
assert_eq!(
- uninstall_run(Ok(true), Ok(()), true, Ok(()), Ok(true)),
+ uninstall_run(Ok(true), Ok(()), Ok(()), Ok(()), Ok(true)),
(
UninstallOutcome::Removed,
vec![UninstallEffect::DisableLogin, UninstallEffect::RemoveRuntime],
@@ -2168,14 +2331,17 @@ mod tests {
#[test]
fn uninstall_leaves_an_already_disabled_login_item_alone() {
assert_eq!(
- uninstall_effects(Ok(false), Ok(()), true),
+ uninstall_effects(Ok(false), Ok(()), Ok(())),
vec![UninstallEffect::RemoveRuntime]
);
// The removal failed, but this uninstall never disabled anything, so
// there is no registration of its own to put back.
assert_eq!(
- uninstall_effects(Ok(false), Ok(()), false),
- vec![UninstallEffect::RemoveRuntime, UninstallEffect::ReportFailure],
+ uninstall_effects(Ok(false), Ok(()), Err(UninstallFailure::Blocked)),
+ vec![
+ UninstallEffect::RemoveRuntime,
+ UninstallEffect::ReportFailure(UninstallFailure::Blocked)
+ ],
);
}
@@ -2183,20 +2349,27 @@ mod tests {
#[test]
fn uninstall_restores_the_login_item_it_cleared_when_the_removal_does_not_happen() {
// The application is still installed, so the login registration this
- // uninstall cleared has to come back before the failure is reported.
- assert_eq!(
- uninstall_run(Ok(true), Ok(()), false, Ok(()), Ok(true)),
- (
- UninstallOutcome::Kept,
- vec![
- UninstallEffect::DisableLogin,
- UninstallEffect::RemoveRuntime,
- UninstallEffect::RestoreLogin,
- UninstallEffect::RenderLogin(true),
- UninstallEffect::ReportFailure,
- ],
- ),
- );
+ // uninstall cleared has to come back before the failure is reported,
+ // including when the user chose to keep the files.
+ for failure in [
+ UninstallFailure::Blocked,
+ UninstallFailure::Failed,
+ UninstallFailure::Declined,
+ ] {
+ assert_eq!(
+ uninstall_run(Ok(true), Ok(()), Err(failure), Ok(()), Ok(true)),
+ (
+ UninstallOutcome::Kept,
+ vec![
+ UninstallEffect::DisableLogin,
+ UninstallEffect::RemoveRuntime,
+ UninstallEffect::RestoreLogin,
+ UninstallEffect::RenderLogin(true),
+ UninstallEffect::ReportFailure(failure),
+ ],
+ ),
+ );
+ }
}
#[cfg(feature = "bundled-runtime")]
@@ -2212,23 +2385,38 @@ mod tests {
UninstallEffect::RestoreLogin,
UninstallEffect::RenderLogin(false),
UninstallEffect::ReportLoginFailure,
- UninstallEffect::ReportFailure,
+ UninstallEffect::ReportFailure(UninstallFailure::Failed),
];
assert_eq!(
- uninstall_run(Ok(true), Ok(()), false, Err("enable failed".to_owned()), Ok(false)),
+ uninstall_run(
+ Ok(true),
+ Ok(()),
+ Err(UninstallFailure::Failed),
+ Err("enable failed".to_owned()),
+ Ok(false)
+ ),
(UninstallOutcome::KeptWithoutLogin, lost),
);
// A write that claims success but reads back disabled is the same loss.
assert_eq!(
- uninstall_run(Ok(true), Ok(()), false, Ok(()), Ok(false)).0,
+ uninstall_run(Ok(true), Ok(()), Err(UninstallFailure::Failed), Ok(()), Ok(false)).0,
UninstallOutcome::KeptWithoutLogin,
);
// So is a write whose result cannot be read back; the checkbox then
// falls back to unchecked.
- let (outcome, effects) = uninstall_run(Ok(true), Ok(()), false, Ok(()), Err("state unavailable".to_owned()));
+ let (outcome, effects) = uninstall_run(
+ Ok(true),
+ Ok(()),
+ Err(UninstallFailure::Failed),
+ Ok(()),
+ Err("state unavailable".to_owned()),
+ );
assert_eq!(outcome, UninstallOutcome::KeptWithoutLogin);
assert!(effects.contains(&UninstallEffect::RenderLogin(false)));
- assert!(effects.ends_with(&[UninstallEffect::ReportLoginFailure, UninstallEffect::ReportFailure]));
+ assert!(effects.ends_with(&[
+ UninstallEffect::ReportLoginFailure,
+ UninstallEffect::ReportFailure(UninstallFailure::Failed)
+ ]));
}
#[cfg(feature = "bundled-runtime")]
@@ -2238,17 +2426,20 @@ mod tests {
// no exit, and the user is told the uninstall failed. Nothing was
// disabled, so nothing is restored either.
assert_eq!(
- uninstall_effects(Ok(true), Err("disable failed".to_owned()), true),
- vec![UninstallEffect::DisableLogin, UninstallEffect::ReportFailure],
+ uninstall_effects(Ok(true), Err("disable failed".to_owned()), Ok(())),
+ vec![
+ UninstallEffect::DisableLogin,
+ UninstallEffect::ReportFailure(UninstallFailure::Failed)
+ ],
);
// The registration could not even be inspected — same answer, and
// nothing is disabled on a state the shell could not read.
assert_eq!(
- uninstall_effects(Err("state unavailable".to_owned()), Ok(()), true),
- vec![UninstallEffect::ReportFailure],
+ uninstall_effects(Err("state unavailable".to_owned()), Ok(()), Ok(())),
+ vec![UninstallEffect::ReportFailure(UninstallFailure::Failed)],
);
assert_eq!(
- uninstall_run(Ok(true), Err("disable failed".to_owned()), true, Ok(()), Ok(true)).0,
+ uninstall_run(Ok(true), Err("disable failed".to_owned()), Ok(()), Ok(()), Ok(true)).0,
UninstallOutcome::Kept,
);
}
@@ -2390,6 +2581,70 @@ mod tests {
assert_eq!(effects, vec![RecoveryEffect::HandOff, RecoveryEffect::RetainOwnership]);
}
+ #[cfg(feature = "bundled-runtime")]
+ #[test]
+ fn an_unverified_removal_deletes_the_private_files_only_with_consent() {
+ let unique = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let root = std::env::temp_dir().join(format!("avibe-shell-consent-{}-{unique}", std::process::id()));
+ let installs = root.join("installs");
+ let backends = root.join("backends");
+ std::fs::create_dir_all(installs.join("1.0.0")).unwrap();
+ std::fs::create_dir_all(backends.join("opencode")).unwrap();
+ std::fs::write(installs.join("1.0.0").join("python"), b"runtime bytes").unwrap();
+ std::fs::write(backends.join("opencode").join("bin"), b"backend bytes").unwrap();
+ std::fs::write(root.join("unrelated"), b"unrelated state").unwrap();
+ // The bundle is missing, so the Runtime's own CLI can never run to
+ // confirm that its installs stopped.
+ let host = bundled_runtime_host(
+ root.join("missing-bundle"),
+ installs.clone(),
+ backends.clone(),
+ BootstrapLog::disabled(),
+ )
+ .unwrap();
+ let files_remain = || installs.join("1.0.0").join("python").exists() && backends.join("opencode").exists();
+ let asked = std::cell::Cell::new(0);
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+
+ runtime.block_on(async {
+ // Keeping the files is the answer unless the user says otherwise.
+ let declined = remove_private_runtime_with_consent(&host, None, || {
+ asked.set(asked.get() + 1);
+ async { false }
+ })
+ .await;
+ assert_eq!(declined, Err(UninstallFailure::Declined));
+ assert_eq!(asked.get(), 1);
+ assert!(files_remain());
+
+ // Something answering at the origin keeps every file, and the user
+ // is never offered the override.
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let answering = LoopbackOrigin::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
+ std::thread::spawn(move || listener.incoming().for_each(drop));
+ let blocked = remove_private_runtime_with_consent(&host, Some(&answering), || {
+ asked.set(asked.get() + 1);
+ async { true }
+ })
+ .await;
+ assert_eq!(blocked, Err(UninstallFailure::Blocked));
+ assert_eq!(asked.get(), 1);
+ assert!(files_remain());
+
+ let removed = remove_private_runtime_with_consent(&host, None, || async { true }).await;
+ assert_eq!(removed, Ok(()));
+ });
+ assert!(!installs.exists() && !backends.exists());
+ assert_eq!(std::fs::read(root.join("unrelated")).unwrap(), b"unrelated state");
+ std::fs::remove_dir_all(root).unwrap();
+ }
+
#[cfg(feature = "bundled-runtime")]
#[test]
fn native_uninstall_copy_uses_the_first_supported_system_locale() {
@@ -2400,8 +2655,21 @@ mod tests {
assert_ne!(chinese.menu_label, english.menu_label);
assert_ne!(chinese.confirm_message, english.confirm_message);
- assert!(!chinese.failure_message.is_empty());
- assert!(!english.failure_message.is_empty());
+ for catalog in [&chinese, &english] {
+ for copy in [
+ &catalog.failure_message,
+ &catalog.blocked_title,
+ &catalog.blocked_message,
+ &catalog.unverified_title,
+ &catalog.unverified_message,
+ &catalog.unverified_delete,
+ &catalog.unverified_keep,
+ ] {
+ assert!(!copy.is_empty());
+ }
+ }
+ assert_ne!(chinese.blocked_message, english.blocked_message);
+ assert_ne!(chinese.unverified_message, english.unverified_message);
}
#[test]
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
index aa59d90f5..5ab314c7b 100644
--- a/desktop/src-tauri/tests/shell_boundaries.rs
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -462,7 +462,7 @@ fn product_packages_expose_an_explicit_private_runtime_uninstall_path() {
for required in [
"UNINSTALL_MENU_ID",
"fn request_private_runtime_removal",
- "host.remove_private_runtime(active_origin.as_ref()).await",
+ "remove_private_runtime_with_consent(&host, active_origin.as_ref(),",
"native_uninstall_catalog()",
"sys_locale::get_locales()",
"../../../ui/src/i18n/en.json",
@@ -496,16 +496,22 @@ fn product_packages_expose_an_explicit_private_runtime_uninstall_path() {
fn post_navigation_recovery_stays_in_the_unprivileged_rust_shell() {
let source = shipping_source("src/lib.rs");
for required in [
- "host.is_ready(&origin).await",
+ "host.is_serving(&origin).await",
"release_after_readiness_loss",
"return_to_bootstrap(&app)",
- "spawn_owned_bootstrap(app)",
+ "spawn_owned_bootstrap(app, BootstrapTrigger::Recovery)",
] {
assert!(
source.contains(required),
"the post-navigation recovery path must retain {required:?}"
);
}
+ // Handing a predecessor's Runtime over stops it, so only the app launch and
+ // the user's Try again may ask for it; every recovery path must not.
+ assert_eq!(source.matches("BootstrapTrigger::Launch").count(), 1);
+ assert!(source.contains("spawn_bootstrap(app.handle().clone(), BootstrapTrigger::Launch)"));
+ assert_eq!(source.matches("BootstrapTrigger::Retry").count(), 1);
+ assert!(source.contains("Ok(spawn_bootstrap(app, BootstrapTrigger::Retry))"));
assert!(
source.contains("compare_exchange(ACTIVITY_BOOTSTRAP, ACTIVITY_MONITOR")
&& source.contains("compare_exchange(ACTIVITY_MONITOR, ACTIVITY_BOOTSTRAP"),
@@ -521,7 +527,7 @@ fn macos_reopen_recreates_or_refocuses_the_main_window() {
"fn focus_or_restore_main_window",
"RunEvent::Reopen",
"claim_recreated_window_bootstrap(&activity)",
- "spawn_owned_bootstrap(app.clone())",
+ "spawn_owned_bootstrap(app.clone(), BootstrapTrigger::Recovery)",
"WebviewWindowBuilder::from_config",
] {
assert!(
@@ -545,7 +551,7 @@ fn recreated_windows_transfer_monitor_ownership_before_bootstrapping() {
);
}
let awaited_probe = source
- .find("let ready = host.is_ready(&origin).await;")
+ .find("let ready = host.is_serving(&origin).await;")
.expect("the monitor awaits readiness");
let ownership_recheck = source[awaited_probe..]
.find("activity.load(Ordering::SeqCst) != ACTIVITY_MONITOR")
@@ -696,8 +702,8 @@ fn a_dropped_retry_is_reported_to_the_bootstrap_page() {
let source = shipping_source("src/lib.rs");
for required in [
"fn bootstrap_retry(window: WebviewWindow, app: AppHandle) -> Result<bool, String>",
- "Ok(spawn_bootstrap(app))",
- "fn spawn_bootstrap(app: AppHandle) -> bool",
+ "Ok(spawn_bootstrap(app, BootstrapTrigger::Retry))",
+ "fn spawn_bootstrap(app: AppHandle, trigger: BootstrapTrigger) -> bool",
"return false",
] {
assert!(
@@ -751,7 +757,7 @@ fn native_lifecycle_controls_never_add_a_webview_permission() {
}
#[test]
-fn native_lifecycle_authority_requires_a_receipt_not_a_launch_attempt() {
+fn native_lifecycle_authority_requires_the_runtime_identity_not_a_launch_attempt() {
let source = shipping_source("src/lib.rs");
assert!(source.contains("shell.host.has_owned_runtime()"));
assert!(!source.contains("host.has_launched()"));
@@ -762,17 +768,22 @@ fn native_lifecycle_authority_requires_a_receipt_not_a_launch_attempt() {
.split("fn toggle_start_at_login")
.next()
.expect("stop body");
- let refusal = stop
- .split("Err(LaunchError::OwnershipLost | LaunchError::NotOwned)")
- .nth(1)
- .expect("receipt refusal")
- .split("Err(_)")
- .next()
- .expect("refusal handling");
- assert!(refusal.contains("BootstrapNoticeCode::RuntimeOwnershipLost"));
- assert!(refusal.contains("ACTIVITY_IDLE"));
- assert!(refusal.contains("focus_or_restore_main_window(&app)"));
- assert!(!refusal.contains("start_runtime_monitor("));
+ // Quit exits only after the Runtime's own CLI confirmed the stop.
+ assert!(stop.contains("if quit && outcome == CliOutcome::Completed"));
+ let arm = |pattern: &str| {
+ stop.split(pattern)
+ .nth(1)
+ .and_then(|rest| rest.lines().next())
+ .unwrap_or_else(|| panic!("the stop maps {pattern}"))
+ .to_owned()
+ };
+ assert!(arm("CliOutcome::Refused { .. } =>").contains("BootstrapNoticeCode::RuntimeOwnershipLost"));
+ assert!(
+ arm("CliOutcome::Failed { .. } | CliOutcome::Unrunnable =>").contains("BootstrapNoticeCode::RuntimeStopFailed")
+ );
+ assert!(stop.contains("ACTIVITY_IDLE"));
+ assert!(stop.contains("focus_or_restore_main_window(&app)"));
+ assert!(!stop.contains("start_runtime_monitor("));
assert!(!stop.contains("spawn_bootstrap("));
}
diff --git a/desktop/src-tauri/windows-app-manifest.xml b/desktop/src-tauri/windows-app-manifest.xml
new file mode 100644
index 000000000..2d510ed31
--- /dev/null
+++ b/desktop/src-tauri/windows-app-manifest.xml
@@ -0,0 +1,14 @@
+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
+ <dependency>
+ <dependentAssembly>
+ <assemblyIdentity
+ type="win32"
+ name="Microsoft.Windows.Common-Controls"
+ version="6.0.0.0"
+ processorArchitecture="*"
+ publicKeyToken="6595b64144ccf1df"
+ language="*"
+ />
+ </dependentAssembly>
+ </dependency>
+</assembly>
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 164a5fa40..f0e5209ef 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -23,6 +23,7 @@ type NoticeCode =
| 'runtime_spawn_failed'
| 'runtime_stopped'
| 'runtime_ownership_lost'
+ | 'runtime_stop_failed'
| 'launcher_exited'
| 'ready_timeout'
| 'workbench_navigation_failed'
@@ -64,6 +65,7 @@ const NOTICE_CODES: ReadonlySet<string> = new Set<NoticeCode>([
'runtime_spawn_failed',
'runtime_stopped',
'runtime_ownership_lost',
+ 'runtime_stop_failed',
'launcher_exited',
'ready_timeout',
'workbench_navigation_failed',
diff --git a/docs/plans/desktop-runtime-scoped-stop.md b/docs/plans/desktop-runtime-scoped-stop.md
index 8d5cd5160..767b1ad6d 100644
--- a/docs/plans/desktop-runtime-scoped-stop.md
+++ b/docs/plans/desktop-runtime-scoped-stop.md
@@ -1,6 +1,7 @@
# Desktop Runtime scoped stop and installer ownership
-Refs #2135 (Python half), #2131.
+Refs #2135, #2131. PR 2a is the Python half; PR 2b is the desktop host and
+removes the startup receipt from both sides.
## Outcome and boundaries
@@ -8,14 +9,17 @@ A desktop app must update smoothly and never stop a Runtime it did not start.
Authority to stop follows provenance: the desktop host knows which Runtime id its
bundle started, and asks Python to stop only processes that carry that id. The
scoped stop reads no file: no pidfile, lock record or installer record decides
-what is signalled. `/ready` and `/internal/health` are unchanged, and so are
-plain `vibe stop` and `vibe stop --receipt`.
+what is signalled. `/ready` and `/internal/health` are unchanged, and so is
+plain `vibe stop`. The startup receipt (`@avibe-start-receipt:` and
+`vibe stop --receipt`) is gone: provenance is the Runtime id, not a receipt the
+host has to keep.
## `vibe stop --expect-runtime-id <RUNTIME_ID>`
`RUNTIME_ID` is the 64-character lowercase hex `AVIBE_DESKTOP_RUNTIME_ID` the
desktop host exports to the Runtime it launches. Every process that Runtime
-starts inherits it. The flag is mutually exclusive with `--receipt`.
+starts inherits it. The stop also stops the home's tunnel connector, under the
+rule in the ledger below.
### Discovery is one scan
@@ -96,13 +100,22 @@ are never localized; the exit-2 diagnostics go through `vibe/i18n/`
## Handover
-When a desktop `vibe start` finds a controller whose health names another
-desktop Runtime id, it calls the same `runtime.stop_desktop_runtime` with that
-observed id and fails the start if the stop is refused or fails. It also fails
-the start if the UI pidfile still names a running UI afterwards: that UI is not
-the superseded Runtime's, and the start would otherwise reuse it or replace it
-with an unscoped stop. The tunnel connector is left for the successor to adopt.
-These errors go through `vibe/i18n/` (`desktopRuntime.handover*`).
+`vibe start` alone owns the act of replacing a superseded desktop Runtime, and
+does it only when asked with `--hand-over`, a hidden flag the desktop host
+passes on app launch or a user Retry. When a desktop `vibe start` finds a
+controller whose health names another desktop Runtime id:
+
+- without `--hand-over` it exits 3 and leaves that Runtime running;
+- with it, it calls the same `runtime.stop_desktop_runtime` with that observed
+ id, and exits 3 if the stop is refused and 2 if it fails;
+- it also exits 3 if the UI pidfile still names a running UI afterwards: that
+ UI is not the superseded Runtime's, and the start would otherwise reuse it or
+ replace it with an unscoped stop.
+
+Exit 3 means this start did not take the home over; exit 2 means the superseded
+Runtime may be left partly running. `runtime.stop_desktop_runtime` never stops
+the tunnel connector, so the successor adopts it. These errors go through
+`vibe/i18n/` (`desktopRuntime.handover*`).
## Backend installer ownership (#2131)
@@ -214,11 +227,23 @@ These errors go through `vibe/i18n/` (`desktopRuntime.handover*`).
## Known-by-design ledger
-- Programs without a role that carry the id, such as agent CLIs and the tunnel
- connector, are listed in `left_running` and never signalled. They are either
- children of a stopped role process or, like the connector, kept for adoption.
-- The scoped stop does not stop remote access: that path acts on the
- connector's files. The handover leaves the tunnel for the successor.
+- Programs without a role that carry the id, such as agent CLIs, are listed in
+ `left_running` and never signalled; they are children of a stopped role
+ process.
+- The tunnel connector serves the home, not one Runtime. After a successful
+ scoped stop it is stopped through its own files, and only while the stop holds
+ the free service lock and no UI of the home is running. A held lock leaves it
+ to that service. A handover inside `vibe start` never stops it, so the
+ successor adopts the tunnel, and the next UI start's
+ `remote_access.reconcile()` brings a stopped tunnel back after Quit.
+- argparse usage errors also exit 2, so a `vibe start` too old to know
+ `--hand-over` reads as a handover that may have left the predecessor partly
+ running. The bundled launcher is always the same version, so this cannot
+ happen, and the reading fails closed. No other `vibe start` path exits 2 or 3.
+- A `vibe restart` or plain `vibe stop` run by a process a superseded Runtime
+ left running still acts on the Controller unscoped, because its desktop
+ identity was stripped with its old root. Claiming by the caller's own id
+ belongs at the start and restart boundary, tracked in #2135 for PR 3.
- A role process in the stop's own lineage is never signalled and fails the
stop; a program without a role in the lineage is not listed.
- The scoped stop path reads no file: no pidfile, lock record or installer
@@ -257,15 +282,35 @@ These errors go through `vibe/i18n/` (`desktopRuntime.handover*`).
landing on a UI. An owner launched outside the UI's `-c` shape, which Avibe
never does, reads as reused on a shifted create time, as before this rule.
-## Consumer notes for the desktop host (PR2)
+## Desktop host (PR 2b)
+
+`HealthProbe::presence` classifies the origin: `Mine{ready}` (this bundle's id),
+`Foreign{id, ready}`, `Unmanaged` (no id), `Absent` (connection refused) or
+`Unknown` (any other failure). Each probe has 5 s, because Windows refuses a
+loopback connect only after about 2 s of SYN resends. The host runs one stop verb,
+`vibe stop --expect-runtime-id <id>`, mapped as exit 0 → `Completed`, 3 →
+`Refused{reason}`, 2 → `Failed{part}`, any other exit → `Failed{unknown}`, and a
+spawn error → `Unrunnable`. The host never stops a predecessor itself.
-- Pass `--expect-runtime-id` for handover, Quit and uninstall. Exit 3 means
- nothing was touched; parse the JSON reason. `service_runtime_id_mismatch` is
- Foreign; `service_identity_unavailable` is Unknown, to be retried and never
- treated as Absent.
-- Exit 2 means a process or installer tree of this Runtime may still be
- running: do not replace or remove the bundle. `remaining` names each one.
-- `left_running` lists the other programs carrying the id. For Quit and
- uninstall the tunnel connector is among them; stop it separately if the
- tunnel should not outlive the app.
-- Uninstall should take the backend's `.install.lock` before removing its root.
+- B1, initial: `Mine{ready}` → adopt; `Mine{!ready}`, `Absent`, `Unknown` and
+ `Foreign` → launch; `Unmanaged` → adopt as external. The host owns only the
+ handover policy: its launch passes `--hand-over` on app launch or a user
+ Retry, never from monitor recovery. Recovery that sees `Foreign` shows
+ `runtime_ownership_lost` and launches nothing.
+- The start helper's exit decides a handover: 3 → `runtime_ownership_lost`,
+ 2 after `--hand-over` → `runtime_stop_failed`, any other non-zero exit →
+ `launcher_exited`.
+- B4, polling: `Mine{ready}` → Ready; `Unmanaged` → Adopted. B5: `Foreign` is
+ judged only once this app's helper has exited, because until then it may be
+ the predecessor the helper is replacing. One still serving after that was not
+ replaced, and shows `runtime_ownership_lost`.
+- B6, monitor: the Runtime is serving while presence stays the adopted class.
+- B7, uninstall: only `Mine`, or `Absent` with no launch in flight, is stopped
+ by the bundle's id, then its backends and bundle are removed. Any other
+ presence, a refusal or a failure keeps every file. When the CLI cannot run
+ at all and presence is `Absent` with no launch in flight, a native dialog
+ offers "Delete Anyway" or "Keep Files".
+- B8, Stop and Quit: offered only while the last presence is `Mine`. A refusal
+ shows `runtime_ownership_lost`; a failure shows `runtime_stop_failed`.
+- `Unknown` → launch relies on the start boundary, tracked in
+ https://github.com/avibe-bot/avibe/issues/2135#issuecomment-5877263657.
diff --git a/docs/plans/desktop-start-receipt.md b/docs/plans/desktop-start-receipt.md
index b3b52642e..47878eacf 100644
--- a/docs/plans/desktop-start-receipt.md
+++ b/docs/plans/desktop-start-receipt.md
@@ -1,5 +1,9 @@
# Desktop startup receipt and service-owner stop gate
+> Superseded. PR 2b of #2135 removed the startup receipt and `vibe stop
+> --receipt`; the desktop host now proves provenance with its Runtime id. See
+> `desktop-runtime-scoped-stop.md`. This file records the retired design.
+
## Outcome and boundaries
The desktop shell needs to distinguish a Runtime it started from one it adopted.
diff --git a/docs/plans/desktop-tray-lifecycle.md b/docs/plans/desktop-tray-lifecycle.md
index 85c8b9beb..daa68d9c8 100644
--- a/docs/plans/desktop-tray-lifecycle.md
+++ b/docs/plans/desktop-tray-lifecycle.md
@@ -10,11 +10,11 @@ another endpoint or Webview-provided signal. Serving includes the proved
listener; transient probe failures show unreachable while the existing
three-failure recovery threshold remains unchanged.
-Stop is offered only for a shell-started Runtime. Confirmation stops it without
+Stop is offered only for this app's own Runtime. Confirmation stops it without
exiting the shell. The bootstrap then shows a localized stopped notice and an
explicit Retry action; automatic recovery must not undo a user's Stop.
-Quit with launch ownership offers stop-and-quit, keep-running-and-quit, or
-cancel. Quit without ownership leaves the adopted Runtime alone. Startup and
+Quit while this app's Runtime serves offers stop-and-quit, keep-running-and-quit,
+or cancel. Quit otherwise leaves the adopted Runtime alone. Startup and
uninstall serialize against lifecycle actions; no stop may race a launch.
Start at Login is a native checkable menu item backed by
@@ -23,38 +23,23 @@ The OS registration is authoritative and is read back after every toggle.
There are no new webview commands or permissions. Workbench and Show Pages
remain unprivileged.
-## Frozen stop semantics
+## Stop semantics
+
+PR 2b of #2135 retired the startup receipt this section used to freeze.
+`desktop-runtime-scoped-stop.md` owns the stop rules; the sections below that
+mention receipts record the receipt-era lane.
- `avibe-runtime-host` owns the Tauri-free operation.
- A retained launch attempt only deduplicates starts; it is never stop authority.
- Only a successful launcher exit plus a valid schema-v1 `started` receipt grants
- authority. `reused`, absent/malformed/duplicate receipts, failed helpers, and
- helpers still running grant none. Readiness alone never grants authority.
-- The producer contract is `docs/plans/desktop-start-receipt.md` in the separate
- `feat/desktop-start-receipt` lane. Its receipt is sourced from the service
- startup function's actual spawn/reuse branch, never before/after snapshots.
- UI reuse does not change the service's provenance outcome.
-- Startup stdout is drained without forwarding it to a webview. At most 64 KiB
- is retained; oversized output is drained and discards authority. Exactly one
- line beginning `@avibe-start-receipt:` is accepted. Schema, positive PIDs, and
- finite positive creation timestamps are validated, including fractional ms.
-- Missing proven ownership is an error, never a best-effort stop.
-- The host retains the exact resolved launcher/interpreter that launched the
- Runtime. Stopping does not resolve an executable, search PATH, or invoke a
- shell interpreter.
-- The Runtime's own `stop --receipt <JSON>` command owns shutdown. The helper
- uses the same process isolation as startup and null standard streams. This
- path never falls back to an unscoped stop or re-resolves an executable.
-- Python validates the current service PID and creation time (2 ms tolerance)
- at its service-owner gate. Exit 3, including invalid receipt, replaced PID,
- unavailable identity, and changed creation time, revokes authority and returns
- a localized `runtime_ownership_lost` bootstrap screen with explicit Retry.
- Retry uses the existing endpoint discovery and `/ready` state machine; no
- second status channel or automatic stop/restart is introduced.
-- Successful stop releases ownership. Other stop failures preserve it for an
- explicit retry. Confirmed Runtime loss releases ownership as before.
-- Tests prove adopted refusal, launch/stop executable identity, argument shape,
- failure retention, and stop/monitor/bootstrap exclusion.
+ Authority is the last presence: Stop is offered only while the Controller
+ serving the origin carries this bundle's Runtime id (`Mine`). Readiness alone
+ never grants authority.
+- The host stops through the Runtime's own `vibe stop --expect-runtime-id <id>`,
+ run by the exact resolved launcher. Stopping does not resolve an executable,
+ search PATH, or fall back to an unscoped stop.
+- Exit 0 releases authority. Exit 3 revokes it and shows the retryable
+ `runtime_ownership_lost`. Exit 2 or a CLI that cannot run keeps it and shows
+ `runtime_stop_failed`. No stop runs while a launch or another stop is pending.
## Scope and dependencies
@@ -85,17 +70,10 @@ it does not copy or stack on that lane's Python implementation.
- Workbench Settings integration is deferred; the native toggle is the only
login-item control in this slice.
-- A Runtime deliberately kept running is adopted on the next shell launch and
- cannot then be stopped via this session's tray ownership path.
-- Receipt v1 is a service-owner gate, not a per-process capability: a matching
- service identity invokes today's full graceful stop, including UI, service
- sweep, OpenCode, and tunnel. UI reuse does not prevent this full stop. The
- gate does not prevent replacement after validation or independently authorize
- each auxiliary process. The orchestrator explicitly accepted these v1 limits
- on 2026-09-10; no per-process guarantee is claimed.
-- Older Runtime packages without receipt support can still serve/adopt, but
- cannot gain tray stop authority. A ready Runtime whose helper has not finished
- is also treated conservatively until a successful receipt becomes available.
+- A Runtime deliberately kept running is adopted as this app's own on the next
+ shell launch, and Stop is offered for it again.
+- A Runtime without this bundle's id, including one without any desktop
+ identity, can be adopted but is never offered Stop.
- Runtime version reporting is not added to `/ready`; the tray shows the
already-proved listener and current readiness without creating a status API.
- Native GUI/login testing remains an integration acceptance step, not a claim
diff --git a/tests/test_cli_setup_status.py b/tests/test_cli_setup_status.py
index a29117cea..33beb1bd7 100644
--- a/tests/test_cli_setup_status.py
+++ b/tests/test_cli_setup_status.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import json
from functools import partial
from types import SimpleNamespace
from unittest.mock import patch
@@ -19,24 +18,10 @@ def _config_with_setup_state(*, ready: bool) -> SimpleNamespace:
def _start_process(pid: int, *args, start_info: ProcessStartInfo, **kwargs) -> int:
start_info.pid = pid
- start_info.create_unix_ms = 1789010100000.5 + pid
start_info.reused = False
return pid
-def _assert_start_receipt(output: str) -> None:
- receipts = [line for line in output.splitlines() if line.startswith("@avibe-start-receipt:")]
- assert len(receipts) == 1
- assert json.loads(receipts[0].split(":", 1)[1]) == {
- "schema_version": 1,
- "outcome": "started",
- "service_pid": 101,
- "ui_pid": 202,
- "service_create_unix_ms": 1789010100101.5,
- "ui_create_unix_ms": 1789010100202.5,
- }
-
-
def test_cmd_vibe_marks_setup_when_no_enabled_platform_has_credentials(capsys) -> None:
config = _config_with_setup_state(ready=False)
@@ -59,10 +44,9 @@ def test_cmd_vibe_marks_setup_when_no_enabled_platform_has_credentials(capsys) -
output = capsys.readouterr().out
assert "Run: vibe remote" in output
assert "SSH port forwarding" not in output
- _assert_start_receipt(output)
-def test_cmd_vibe_marks_starting_when_non_slack_platform_is_configured(capsys) -> None:
+def test_cmd_vibe_marks_starting_when_non_slack_platform_is_configured() -> None:
config = _config_with_setup_state(ready=True)
with (
@@ -81,4 +65,3 @@ def test_cmd_vibe_marks_starting_when_non_slack_platform_is_configured(capsys) -
stop_service.assert_not_called()
stop_ui.assert_not_called()
write_status.assert_called_once_with("starting")
- _assert_start_receipt(capsys.readouterr().out)
diff --git a/tests/test_desktop_runtime.py b/tests/test_desktop_runtime.py
index 9c50e3f62..5ce848bdb 100644
--- a/tests/test_desktop_runtime.py
+++ b/tests/test_desktop_runtime.py
@@ -1169,7 +1169,6 @@ def test_cmd_start_reused_controller_starts_missing_ui_and_emits_untagged_ready(
language="en",
)
spawned = []
- process_times = {1234: 1789010100.1235, 5678: 1789010100.4565}
monkeypatch.setenv("AVIBE_DESKTOP_RUNTIME_ID", "a" * 64)
monkeypatch.setattr(cli, "_guard_cli_default_state_migration", lambda: None)
@@ -1177,7 +1176,6 @@ def test_cmd_start_reused_controller_starts_missing_ui_and_emits_untagged_ready(
monkeypatch.setattr(cli, "_write_status", lambda *args: None)
monkeypatch.setattr(cli, "_in_ssh_session", lambda: False)
monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda _config: "127.0.0.1")
- monkeypatch.setattr(cli.runtime, "process_create_time", lambda pid: process_times[pid])
monkeypatch.setattr(cli.runtime, "resolve_service_owner_pid", lambda **_kwargs: 1234)
monkeypatch.setattr(cli.runtime, "wait_for_service_ready", lambda pid, timeout: pid)
monkeypatch.setattr(cli.runtime, "write_status", lambda *args: None)
@@ -1223,17 +1221,7 @@ def test_cmd_start_reused_controller_starts_missing_ui_and_emits_untagged_ready(
assert cli.cmd_start(open_browser=False) == 0
- receipt_line = next(
- line for line in capsys.readouterr().out.splitlines() if line.startswith("@avibe-start-receipt:")
- )
- assert json.loads(receipt_line.split(":", 1)[1]) == {
- "schema_version": 1,
- "outcome": "reused",
- "service_pid": 1234,
- "ui_pid": 5678,
- "service_create_unix_ms": process_times[1234] * 1000,
- "ui_create_unix_ms": process_times[5678] * 1000,
- }
+ assert " http://127.0.0.1:5123" in capsys.readouterr().out.splitlines()
assert len(spawned) == 1
diff --git a/tests/test_desktop_runtime_stop.py b/tests/test_desktop_runtime_stop.py
index 8f3fecd7d..1cbe087b5 100644
--- a/tests/test_desktop_runtime_stop.py
+++ b/tests/test_desktop_runtime_stop.py
@@ -422,15 +422,13 @@ def test_no_service_can_take_the_lock_before_the_stop_s_connector_and_status_lan
assert lock_free_at == expected
[email protected]("keeper", ["keep_remote_access", "a_ui_of_this_home"])
-def test_the_tunnel_connector_is_left_to_what_still_serves_it(spawn, stop_env, keeper):
+def test_the_tunnel_connector_is_left_to_a_ui_that_still_serves_it(spawn, stop_env):
service = spawn(RUNTIME_ID)
- if keeper == "a_ui_of_this_home":
- # Whoever started it, a running UI of this home serves the tunnel.
- other_ui = spawn(None, "ui")
- paths.get_runtime_ui_pid_path().write_text(str(other_ui.pid), encoding="utf-8")
+ # Whoever started it, a running UI of this home serves the tunnel.
+ other_ui = spawn(None, "ui")
+ paths.get_runtime_ui_pid_path().write_text(str(other_ui.pid), encoding="utf-8")
- assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID, keep_remote_access=keeper == "keep_remote_access") == 0
+ assert cli.cmd_stop(expect_runtime_id=RUNTIME_ID) == 0
service.wait(timeout=10)
assert stop_env["remote_access"] == []
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 4f454b286..f17ec32a6 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -1078,152 +1078,6 @@ def test_cmd_restart_schedules_supervisor_by_default(monkeypatch):
assert calls == [{"delay_seconds": 0.0, "vibe_path": "/usr/local/bin/vibe", "trigger": "cli"}]
-def _startup_receipt_payload():
- return {
- "schema_version": 1, "outcome": "started",
- "service_pid": 1234, "ui_pid": 5678,
- "service_create_unix_ms": 1789010100.1235 * 1000,
- "ui_create_unix_ms": 1789010100.4565 * 1000,
- }
-
-
-def receipt_shutdown(monkeypatch):
- pid_path = paths.get_runtime_pid_path()
- pid_path.parent.mkdir(parents=True, exist_ok=True)
- pid_path.write_text("1234\n", encoding="utf-8")
- calls = []
- monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)
- monkeypatch.setattr(runtime, "process_create_time", lambda pid: 1789010100.1235)
- monkeypatch.setattr(cli, "_pid_file_points_to_live_process", lambda path: True)
- monkeypatch.setattr(runtime, "stop_service", lambda: calls.append("service") or True)
- monkeypatch.setattr(runtime, "stop_ui", lambda: calls.append("ui") or True)
- monkeypatch.setattr(cli, "_stop_opencode_server", lambda: calls.append("opencode") or True)
- monkeypatch.setattr(cli, "_write_status", lambda *args: calls.append(args))
- return SimpleNamespace(pid_path=pid_path, calls=calls)
-
-
[email protected]("delta_ms", [-2, -1.999, 0, 1.999, 2])
[email protected]("outcome", ["started", "reused"])
-def test_cmd_stop_receipt_matches_with_inclusive_tolerance(capsys, receipt_shutdown, delta_ms, outcome):
- receipt = _startup_receipt_payload()
- receipt["service_create_unix_ms"] += delta_ms
- receipt["outcome"] = outcome
-
- assert cli.cmd_stop(receipt=json.dumps(receipt)) == 0
-
- assert receipt_shutdown.calls == ["service", "ui", "opencode", ("stopped",)]
- output = capsys.readouterr()
- assert output.out == "OpenCode server stopped\n"
- assert output.err == ""
-
-
- ("state", "reason"),
- [
- ("replaced", "service_pid_mismatch"),
- ("missing", "service_pid_mismatch"),
- ("unreadable_pid", "service_pid_mismatch"),
- ("recycled", "service_create_time_mismatch"),
- ("older_time", "service_create_time_mismatch"),
- ("dead", "service_identity_unavailable"),
- ("unreadable_time", "service_identity_unavailable"),
- ("invalid_live_time", "service_create_time_mismatch"),
- ],
-)
-def test_cmd_stop_receipt_refuses_without_any_shutdown_side_effect(
- monkeypatch, capsys, receipt_shutdown, state, reason,
-):
- receipt = _startup_receipt_payload()
- if state == "replaced":
- receipt_shutdown.pid_path.write_text("9012\n", encoding="utf-8")
- elif state == "missing":
- receipt_shutdown.pid_path.unlink()
- elif state == "unreadable_pid":
- receipt_shutdown.pid_path.write_bytes(b"\xff")
- elif state in ("recycled", "older_time"):
- receipt["service_create_unix_ms"] += 2.001 if state == "recycled" else -2.001
- elif state == "dead":
- monkeypatch.setattr(runtime, "pid_alive", lambda pid: False)
- else:
- monkeypatch.setattr(runtime, "process_create_time", lambda pid: None if state == "unreadable_time" else float("nan"))
- before = receipt_shutdown.pid_path.read_bytes() if receipt_shutdown.pid_path.exists() else None
-
- assert cli.cmd_stop(receipt=json.dumps(receipt)) == 3
-
- output = capsys.readouterr()
- assert output.out == ""
- assert json.loads(output.err) == {"reason": reason}
- assert receipt_shutdown.calls == []
- assert (receipt_shutdown.pid_path.read_bytes() if receipt_shutdown.pid_path.exists() else None) == before
-
-
[email protected]("field", list(_startup_receipt_payload()))
-def test_cmd_stop_rejects_incomplete_receipt(capsys, receipt_shutdown, field):
- receipt = _startup_receipt_payload()
- del receipt[field]
-
- assert cli.cmd_stop(receipt=json.dumps(receipt)) == 3
-
- assert json.loads(capsys.readouterr().err) == {"reason": "invalid_receipt"}
- assert receipt_shutdown.calls == []
-
-
- ("field", "value"),
- [
- ("schema_version", True), ("schema_version", 1.0), ("schema_version", 2),
- ("outcome", "unknown"), ("outcome", ["started"]),
- ("service_pid", True), ("service_pid", -1234), ("service_pid", 1234.0),
- ("ui_pid", 0), ("ui_pid", "5678"),
- ("service_create_unix_ms", None), ("service_create_unix_ms", "1789010100123.5"),
- ("service_create_unix_ms", float("nan")), ("service_create_unix_ms", float("inf")),
- ("ui_create_unix_ms", -1), ("ui_create_unix_ms", True),
- ("ui_create_unix_ms", float("-inf")), ("ui_create_unix_ms", 10 ** 400),
- ],
-)
-def test_cmd_stop_rejects_invalid_receipt_values(capsys, receipt_shutdown, field, value):
- receipt = _startup_receipt_payload()
- receipt[field] = value
-
- assert cli.cmd_stop(receipt=json.dumps(receipt)) == 3
-
- assert json.loads(capsys.readouterr().err) == {"reason": "invalid_receipt"}
- assert receipt_shutdown.calls == []
-
-
[email protected]("receipt", ["", "{", "null", "[]", '"receipt"', "[" * 2000 + "]" * 2000])
-def test_cmd_stop_rejects_malformed_receipt(capsys, receipt_shutdown, receipt):
- assert cli.cmd_stop(receipt=receipt) == 3
-
- assert json.loads(capsys.readouterr().err) == {"reason": "invalid_receipt"}
- assert receipt_shutdown.calls == []
-
-
-def test_cmd_stop_without_receipt_keeps_legacy_full_stop(monkeypatch, capsys, receipt_shutdown):
- def unexpected_identity_read(pid):
- raise AssertionError("Unscoped stop must not inspect receipt identity")
-
- monkeypatch.setattr(runtime, "process_create_time", unexpected_identity_read)
- receipt_shutdown.pid_path.unlink()
-
- assert cli.cmd_stop() == 0
-
- assert receipt_shutdown.calls == ["service", "ui", "opencode", ("stopped",)]
- output = capsys.readouterr()
- assert output.out == "OpenCode server stopped\n"
- assert output.err == ""
-
-
-def test_cmd_stop_matched_receipt_preserves_stop_failure_exit_code(monkeypatch, capsys, receipt_shutdown):
- monkeypatch.setattr(runtime, "stop_service", lambda: receipt_shutdown.calls.append("service") or False)
-
- assert cli.cmd_stop(receipt=json.dumps(_startup_receipt_payload())) == 2
-
- assert receipt_shutdown.calls == ["service", "ui", "opencode", ("error", "service stop failed")]
- assert capsys.readouterr().err == "ERROR: Avibe service did not stop; preserving pidfile and aborting.\n"
-
-
def test_cmd_stop_ignores_absent_services(monkeypatch):
status = []
@@ -1393,24 +1247,21 @@ def _fake_start_result(pid, kwargs, *, reused=False):
start_info = kwargs.get("start_info")
if start_info is not None:
start_info.pid = pid
- start_info.create_unix_ms = 1789010100000.5 + pid
start_info.reused = reused
return pid
@pytest.fixture
-def receipt_runtime(monkeypatch):
+def start_runtime(monkeypatch):
service_path = paths.get_runtime_pid_path()
ui_path = paths.get_runtime_ui_pid_path()
service_path.parent.mkdir(parents=True, exist_ok=True)
process_times = {1234: 1789010100.1235, 5678: 1789010100.4565, 9012: 1789010100.7895}
spawned = []
- captured = []
opened = []
stopped = []
def fake_process(pid):
- captured.append(pid)
return SimpleNamespace(create_time=lambda: process_times[pid])
# Both stand in for the spawn primitives, so both honour their contract:
@@ -1429,7 +1280,7 @@ def receipt_runtime(monkeypatch):
return 5678
monkeypatch.setattr(cli, "_guard_cli_default_state_migration", lambda: None)
- monkeypatch.setattr(cli, "_handover_superseded_desktop_runtime", lambda: None)
+ monkeypatch.setattr(cli, "_handover_superseded_desktop_runtime", lambda **kwargs: 0)
monkeypatch.setattr(cli, "_ensure_config", lambda: SimpleNamespace(
has_configured_platform_credentials=lambda: True,
ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=True),
@@ -1461,57 +1312,45 @@ def receipt_runtime(monkeypatch):
monkeypatch.setattr(runtime, "stop_ui", lambda **kwargs: stopped.append("stop_ui") or True)
monkeypatch.setattr(runtime, "stop_service", lambda: stopped.append("stop_service") or True)
return SimpleNamespace(
- service_path=service_path, ui_path=ui_path, process_times=process_times,
- spawned=spawned, captured=captured, opened=opened, stopped=stopped,
+ service_path=service_path, ui_path=ui_path, spawned=spawned, opened=opened, stopped=stopped,
)
@pytest.mark.parametrize("reused", [False, True])
@pytest.mark.parametrize("open_browser", [None, False])
-def test_cmd_start_receipt_uses_launch_provenance_and_psutil_identity(
- monkeypatch, capsys, receipt_runtime, reused, open_browser,
+def test_cmd_start_reports_the_web_ui_whether_it_spawned_or_reused_the_runtime(
+ monkeypatch, capsys, start_runtime, reused, open_browser,
):
if reused:
- receipt_runtime.service_path.write_text("1234", encoding="utf-8")
- receipt_runtime.ui_path.write_text("5678", encoding="utf-8")
+ start_runtime.service_path.write_text("1234", encoding="utf-8")
+ start_runtime.ui_path.write_text("5678", encoding="utf-8")
monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **kwargs: None if reused else 1234)
assert cli.cmd_start(open_browser=open_browser) == 0
output = capsys.readouterr().out
- receipts = [line for line in output.splitlines() if line.startswith("@avibe-start-receipt:")]
- assert len(receipts) == 1
- assert json.loads(receipts[0].split(":", 1)[1]) == {
- "schema_version": 1, "outcome": "reused" if reused else "started",
- "service_pid": 1234, "ui_pid": 5678,
- "service_create_unix_ms": receipt_runtime.process_times[1234] * 1000,
- "ui_create_unix_ms": receipt_runtime.process_times[5678] * 1000,
- }
- assert receipt_runtime.spawned == ([] if reused else ["service", "ui"])
- assert receipt_runtime.captured == [1234, 5678]
- assert bool(receipt_runtime.opened) == (open_browser is None)
+ assert start_runtime.spawned == ([] if reused else ["service", "ui"])
+ assert bool(start_runtime.opened) == (open_browser is None)
assert "Web UI:\n http://127.0.0.1:5123\n" in output
assert "Run: vibe remote" in output
@pytest.mark.parametrize("reused", [False, True])
-def test_start_ui_captures_its_own_provenance_before_readiness(monkeypatch, receipt_runtime, reused):
+def test_start_ui_records_whether_it_reused_the_ui(start_runtime, reused):
if reused:
- receipt_runtime.ui_path.write_text("5678", encoding="utf-8")
- before = receipt_runtime.process_times[5678] * 1000
- monkeypatch.setattr(runtime, "wait_for_ui_server", lambda host, port: receipt_runtime.process_times.update({5678: 9999}) or True)
+ start_runtime.ui_path.write_text("5678", encoding="utf-8")
info = runtime.ProcessStartInfo()
assert runtime.start_ui("127.0.0.1", 5123, start_info=info) == 5678
+ assert info.pid == 5678
assert info.reused is reused
- assert info.create_unix_ms == before
- assert receipt_runtime.spawned == ([] if reused else ["ui"])
+ assert start_runtime.spawned == ([] if reused else ["ui"])
@pytest.mark.parametrize("branch", ["recorded", "starting", "ready_owner", "mismatched_command", "lock_owner"])
-def test_start_service_receipt_marks_every_existing_return_as_reused(monkeypatch, receipt_runtime, branch):
- receipt_runtime.service_path.write_text("1234", encoding="utf-8")
+def test_start_service_marks_every_existing_return_as_reused(monkeypatch, start_runtime, branch):
+ start_runtime.service_path.write_text("1234", encoding="utf-8")
alive_checks = iter([False, True]) if branch == "lock_owner" else None
if alive_checks is not None:
monkeypatch.setattr(runtime, "pid_alive", lambda pid: next(alive_checks))
@@ -1527,63 +1366,19 @@ def test_start_service_receipt_marks_every_existing_return_as_reused(monkeypatch
assert info.reused is True
assert info.pid == expected_pid
- assert info.create_unix_ms == receipt_runtime.process_times[expected_pid] * 1000
- assert receipt_runtime.spawned == []
+ assert start_runtime.spawned == []
-def test_start_service_receipt_adopts_scoped_owner(monkeypatch, receipt_runtime):
+def test_start_service_adopts_scoped_owner(monkeypatch, start_runtime):
monkeypatch.setattr(runtime, "maybe_systemd_scope_prefix", lambda: ["systemd-run", "--scope"])
monkeypatch.setattr(runtime, "_start_scoped_service_result", lambda *args, **kwargs: 9012)
info = runtime.ProcessStartInfo()
assert runtime.start_service(start_info=info) == 9012
+ assert info.pid == 9012
assert info.reused is False
- assert info.create_unix_ms == receipt_runtime.process_times[9012] * 1000
- assert receipt_runtime.captured == [1234, 9012]
- assert receipt_runtime.spawned == ["service"]
-
-
-def test_start_service_receipt_keeps_identity_captured_before_readiness(monkeypatch, receipt_runtime):
- before = receipt_runtime.process_times[1234] * 1000
- monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, timeout: receipt_runtime.process_times.update({1234: 9999}) or True)
- info = runtime.ProcessStartInfo()
-
- assert runtime.start_service(start_info=info) == 1234
-
- assert info.reused is False
- assert info.create_unix_ms == before
- assert receipt_runtime.captured == [1234]
-
-
-def test_cmd_start_receipt_tracks_late_authoritative_service_pid(monkeypatch, capsys, receipt_runtime):
- monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: False)
- monkeypatch.setattr(runtime, "wait_for_service_pid", lambda pid, timeout: False)
- monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: 9012)
-
- assert cli.cmd_start(open_browser=False) == 0
-
- receipt_line = next(line for line in capsys.readouterr().out.splitlines() if line.startswith("@avibe-start-receipt:"))
- receipt = json.loads(receipt_line.split(":", 1)[1])
- assert receipt["service_pid"] == 9012
- assert receipt["service_create_unix_ms"] == receipt_runtime.process_times[9012] * 1000
- assert receipt["outcome"] == "started"
- assert receipt_runtime.captured == [1234, 5678, 9012]
-
-
-def test_cmd_start_does_not_emit_a_receipt_with_unreadable_identity(monkeypatch, capsys, receipt_runtime):
- monkeypatch.setattr(runtime, "process_create_time", lambda pid: None)
-
- with pytest.raises(ValueError, match="service_create_unix_ms"):
- cli.cmd_start(open_browser=False)
-
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
- # The far end of the pre-receipt region, and the only failure in it that
- # needs no monkeypatched failure to reach: the receipt builder rejects an
- # identity it cannot read, with the service this command started already up.
- assert receipt_runtime.stopped == ["stop_ui", "stop_service"], (
- f"a start that could not build its receipt must stop its UI, then its service: {receipt_runtime.stopped}"
- )
+ assert start_runtime.spawned == ["service"]
def test_cmd_start_ensures_services_without_stopping(monkeypatch):
@@ -1599,7 +1394,7 @@ def test_cmd_start_ensures_services_without_stopping(monkeypatch):
monkeypatch.setattr(
cli,
"_handover_superseded_desktop_runtime",
- lambda: calls.append(("handover",)),
+ lambda **kwargs: calls.append(("handover", kwargs)) or 0,
)
monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: calls.append(("status", args)))
monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: calls.append(("start_service", kwargs)) or _fake_start_result(1234, kwargs))
@@ -1616,7 +1411,7 @@ def test_cmd_start_ensures_services_without_stopping(monkeypatch):
service_call = next(call for call in calls if call[0] == "start_service")
ui_call = next(call for call in calls if call[0] == "start_ui")
- assert calls.index(("handover",)) < calls.index(service_call)
+ assert calls.index(("handover", {"allowed": False})) < calls.index(service_call)
assert service_call[1]["wait_for_ready"] is False
assert ui_call[1:3] == ("127.0.0.1", 5123)
assert not any(call == "stop" for call in calls)
@@ -1642,33 +1437,46 @@ def _superseded_controller(monkeypatch, result, *, ui_running=False):
def test_desktop_start_hands_over_a_superseded_controller(monkeypatch):
calls = _superseded_controller(monkeypatch, cli.runtime.DesktopRuntimeStopResult())
- cli._handover_superseded_desktop_runtime()
+ assert cli._handover_superseded_desktop_runtime(allowed=True) == 0
# The Runtime health named is the one stopped, through the scoped stop.
assert calls == [("a" * 64, {})]
+def test_a_start_not_asked_to_hand_over_leaves_the_superseded_controller_running(monkeypatch):
+ # Only the desktop host, for a user's launch or retry, may replace another
+ # desktop Runtime; a recovery launch or a terminal start refuses instead.
+ calls = _superseded_controller(monkeypatch, cli.runtime.DesktopRuntimeStopResult())
+ monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)
+ monkeypatch.setattr(cli, "_guard_cli_default_state_migration", lambda: None)
+ monkeypatch.setattr(cli, "_ensure_config", lambda: SimpleNamespace())
+ monkeypatch.setattr(cli, "_write_status", lambda *args: pytest.fail("the start must not begin"))
+
+ assert cli.cmd_start(open_browser=False) == 3
+ assert calls == []
+
+
def _left(role):
return (cli.runtime.DesktopRuntimeProcess(pid=4242, role=role, name="python"),)
@pytest.mark.parametrize(
- ("result", "ui_running"),
+ ("result", "ui_running", "status"),
[
- (cli.runtime.DesktopRuntimeStopResult(refusal="service_runtime_id_mismatch"), False),
- (cli.runtime.DesktopRuntimeStopResult(remaining=_left("service")), False),
- (cli.runtime.DesktopRuntimeStopResult(remaining=_left("installer")), False),
- (cli.runtime.DesktopRuntimeStopResult(remaining=_left("opencode")), False),
- (cli.runtime.DesktopRuntimeStopResult(remaining=_left("unknown")), False),
+ (cli.runtime.DesktopRuntimeStopResult(refusal="service_runtime_id_mismatch"), False, 3),
+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("service")), False, 2),
+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("installer")), False, 2),
+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("opencode")), False, 2),
+ (cli.runtime.DesktopRuntimeStopResult(remaining=_left("unknown")), False, 2),
# Stopped, but a UI of some other Runtime still holds the pidfile.
- (cli.runtime.DesktopRuntimeStopResult(), True),
+ (cli.runtime.DesktopRuntimeStopResult(), True, 3),
],
)
-def test_desktop_start_fails_when_the_superseded_controller_is_not_stopped(monkeypatch, result, ui_running):
+def test_desktop_start_fails_when_the_superseded_controller_is_not_stopped(monkeypatch, result, ui_running, status):
_superseded_controller(monkeypatch, result, ui_running=ui_running)
- with pytest.raises(RuntimeError):
- cli._handover_superseded_desktop_runtime()
+ # 3: this start does not take the home over; 2: part of it may still run.
+ assert cli._handover_superseded_desktop_runtime(allowed=True) == status
@pytest.mark.parametrize("controller_runtime_id", [None, "b" * 64])
@@ -1690,7 +1498,8 @@ def test_desktop_start_preserves_external_or_matching_controllers(
lambda *_args, **_kwargs: pytest.fail("controller must be preserved"),
)
- cli._handover_superseded_desktop_runtime()
+ # Nothing to hand over, so a start the desktop did not ask to hand over still proceeds.
+ assert cli._handover_superseded_desktop_runtime(allowed=False) == 0
def test_cmd_start_can_suppress_configured_browser_open(monkeypatch):
@@ -1917,7 +1726,6 @@ def _ui_refuses_to_start(
ui_outcome=None,
on_wait=None,
ui_reused: bool = False,
- on_receipt=None,
):
"""Wire cmd_start for a start that cannot finish, with every stop recorded.
@@ -1928,8 +1736,7 @@ def _ui_refuses_to_start(
stale process kept serving -- and keeps the pid record naming the process
that has to be stopped. An exception instance is raised instead, which is
what an unwritable or malformed ``vibe-ui.pid`` or a failing process spawn
- does. ``on_wait`` fails later still, once the UI is already up, and
- ``on_receipt`` fails last of all, inside the receipt builder.
+ does. ``on_wait`` fails later still, once the UI is already up.
``ui_reused`` is the other half of the picture: ``start_ui`` returns a pid
both when it spawns one and when it adopts a live, compatible UI, and only
@@ -1940,8 +1747,6 @@ def _ui_refuses_to_start(
own UI and its remote access from a unit test.
"""
- from vibe.desktop_runtime import start_receipt_line as real_receipt_line
-
calls: list[str] = []
statuses: list[tuple] = []
stop_ui_kwargs: list[dict] = []
@@ -1975,13 +1780,6 @@ def _ui_refuses_to_start(
raise on_wait
return pid
- def build_receipt(payload):
- calls.append("start_receipt_line")
- if on_receipt is not None:
- raise on_receipt
- return real_receipt_line(payload)
-
- monkeypatch.setattr("vibe.desktop_runtime.start_receipt_line", build_receipt)
monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)
monkeypatch.setattr(cli, "_ensure_config", lambda: config)
monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: None)
@@ -1996,14 +1794,13 @@ def _ui_refuses_to_start(
return SimpleNamespace(calls=calls, statuses=statuses, stop_ui_kwargs=stop_ui_kwargs)
-def test_cmd_start_does_not_leave_its_own_service_running_when_the_ui_refuses(monkeypatch, capsys):
+def test_cmd_start_does_not_leave_its_own_service_running_when_the_ui_refuses(monkeypatch):
"""A start that cannot finish must not leave a service nobody can stop.
- No UI pid ends the start: the status writes carry that pid and
- ``validate_start_receipt`` rejects a receipt without one. Carrying on
- regardless left the service this command had just started alive with no
- receipt ever printed -- and an unreceipted service is adopted as ``reused``
- on the next attempt, so the desktop shell never owns the stop again.
+ No UI pid ends the start: the status writes carry that pid. Carrying on
+ regardless left the service this command had just started alive after a
+ start that failed -- and a service left behind is adopted as ``reused`` on
+ the next attempt, so nothing ever undoes it.
Deliberately fix-agnostic: rolling the service back and refusing to start it
at all both satisfy the invariant below.
@@ -2018,9 +1815,8 @@ def test_cmd_start_does_not_leave_its_own_service_running_when_the_ui_refuses(mo
failure = error
assert failure is not None, "cmd_start reported success after the UI refused to start"
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
assert "start_service" not in started.calls or "stop_service" in started.calls, (
- f"cmd_start left the service it started running with no start receipt: {started.calls}"
+ f"cmd_start left the service it started running after a failed start: {started.calls}"
)
assert started.calls.count("stop_service") <= 1, (
f"cmd_start rolled the same failed start back more than once: {started.calls}"
@@ -2030,11 +1826,11 @@ def test_cmd_start_does_not_leave_its_own_service_running_when_the_ui_refuses(mo
)
-def test_cmd_start_never_stops_a_service_it_did_not_start_when_the_ui_refuses(monkeypatch, capsys):
+def test_cmd_start_never_stops_a_service_it_did_not_start_when_the_ui_refuses(monkeypatch):
"""The rollback is scoped to this command's own start, and nothing else.
A reused service belongs to whoever started it. The UI refusing still fails
- the command, because there is no pid to receipt, but it must not touch the
+ the command, because the start cannot finish without a UI, but it must not touch the
service and must not restate the pair's status -- the stale UI is still
running with its pid record preserved, so a write naming no UI pid would
contradict it.
@@ -2047,17 +1843,16 @@ def test_cmd_start_never_stops_a_service_it_did_not_start_when_the_ui_refuses(mo
assert "stop_service" not in started.calls, "cmd_start stopped a service it did not start"
assert started.statuses == [], f"cmd_start restated the status of a reused pair: {started.statuses}"
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
@pytest.mark.parametrize("reused", [False, True])
-def test_cmd_start_rolls_its_own_service_back_when_the_ui_start_raises(monkeypatch, capsys, reused):
+def test_cmd_start_rolls_its_own_service_back_when_the_ui_start_raises(monkeypatch, reused):
"""The refusal is not the only way the UI start ends without a pid.
``start_ui`` also raises -- an unwritable or malformed ``vibe-ui.pid`` fails
while it cleans or writes that record, and the process spawn itself can fail.
The orphan is identical either way, so the rollback cannot belong to the
- ``None`` branch; it belongs to the whole pre-receipt region. And it stays
+ ``None`` branch; it belongs to the whole start region. And it stays
scoped: a reused service belongs to whoever started it.
"""
@@ -2071,18 +1866,17 @@ def test_cmd_start_rolls_its_own_service_back_when_the_ui_start_raises(monkeypat
assert started.calls.count("stop_service") == (0 if reused else 1), (
f"a raising UI start left the wrong service state behind (reused={reused}): {started.calls}"
)
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
-def test_cmd_start_rolls_back_when_an_interrupt_arrives_before_the_receipt(monkeypatch, capsys):
+def test_cmd_start_rolls_back_when_an_interrupt_arrives_before_the_start_finishes(monkeypatch):
"""Ctrl-C during the readiness wait orphans both processes, not just one.
The wait is the longest thing in the region -- it runs to
``SERVICE_SLOW_START_TIMEOUT_SECONDS`` against a service that is still
migrating its database -- so it is the likeliest moment for a user to give
up. ``KeyboardInterrupt`` is not an ``Exception``, which is why the guard
- catches ``BaseException``: an interrupted start that leaves a running,
- unreceipted service is adopted as ``reused`` next time just the same, and a
+ catches ``BaseException``: an interrupted start that leaves a running
+ service behind is adopted as ``reused`` next time just the same, and a
UI left behind keeps its pid file, its listener and the port that the next
attempt then has to fight.
@@ -2111,10 +1905,9 @@ def test_cmd_start_rolls_back_when_an_interrupt_arrives_before_the_receipt(monke
assert started.stop_ui_kwargs == [{"stop_remote_access": False}], (
f"the rollback destroyed a remote URL it did not create: {started.stop_ui_kwargs}"
)
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
-def test_cmd_start_leaves_a_ui_and_service_it_only_adopted_alone(monkeypatch, capsys):
+def test_cmd_start_leaves_a_ui_and_service_it_only_adopted_alone(monkeypatch):
"""Adoption is not creation, and the same failure must undo nothing.
``start_ui`` returns a pid both when it spawns a UI and when it finds a live,
@@ -2139,34 +1932,34 @@ def test_cmd_start_leaves_a_ui_and_service_it_only_adopted_alone(monkeypatch, ca
assert "stop_service" not in started.calls, (
f"cmd_start stopped a service it did not start: {started.calls}"
)
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
-def test_cmd_start_rolls_both_back_when_the_receipt_builder_fails(monkeypatch, capsys):
+def test_cmd_start_rolls_both_back_when_opening_the_browser_is_interrupted(monkeypatch):
"""The last statement of the region can fail too, and it orphans the most.
- By this point both processes are up and the status says ``running``; only the
- receipt is missing. That is the worst orphan of the set, because everything
- except the one line the desktop shell needs to own the stop succeeded.
+ By this point both processes are up and the status says ``running``; only
+ the browser is still opening. A Ctrl-C there ends a start that never
+ finished, so it must undo both processes like any earlier failure.
"""
- started = _ui_refuses_to_start(
- monkeypatch,
- reused=False,
- ui_outcome=5678,
- on_receipt=RuntimeError("receipt payload is not serializable"),
- )
+ started = _ui_refuses_to_start(monkeypatch, reused=False, ui_outcome=5678)
+ monkeypatch.setattr(cli, "_in_ssh_session", lambda: False)
- with pytest.raises(RuntimeError, match="receipt payload"):
- cli.cmd_start()
+ def interrupted_open(url):
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(cli, "_open_browser", interrupted_open)
+
+ with pytest.raises(KeyboardInterrupt):
+ cli.cmd_start(open_browser=True)
+ assert ("running", "pid=1234", 1234, 5678) in started.statuses, started.statuses
assert started.calls.count("stop_ui") == 1, (
- f"a failed receipt left the UI this command started running: {started.calls}"
+ f"an interrupted browser open left the UI this command started running: {started.calls}"
)
assert started.calls.count("stop_service") == 1, (
- f"a failed receipt left the service this command started running: {started.calls}"
+ f"an interrupted browser open left the service this command started running: {started.calls}"
)
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
@pytest.mark.parametrize(
@@ -2181,7 +1974,7 @@ def test_cmd_start_rolls_both_back_when_the_receipt_builder_fails(monkeypatch, c
],
)
def test_cmd_start_undoes_a_service_it_created_even_when_start_service_itself_raises(
- monkeypatch, capsys, captured, reused, expected
+ monkeypatch, captured, reused, expected
):
"""`start_service` spawns and then waits, and the wait can be interrupted.
@@ -2204,7 +1997,6 @@ def test_cmd_start_undoes_a_service_it_created_even_when_start_service_itself_ra
cli.cmd_start()
assert started.calls == expected
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
def test_cmd_start_leaves_no_ui_running_when_the_ui_pid_record_cannot_be_written(monkeypatch, tmp_path):
@@ -2273,7 +2065,7 @@ def _kill_children(children) -> None:
def test_cmd_start_leaves_no_ui_running_when_interrupted_between_the_ui_record_and_its_capture(
- monkeypatch, capsys, tmp_path
+ monkeypatch, tmp_path
):
"""The last gap in the UI handover, end to end, with a real UI child.
@@ -2309,13 +2101,12 @@ def test_cmd_start_leaves_no_ui_running_when_interrupted_between_the_ui_record_a
# The service this start created is still undone, and nothing claims success.
assert started.calls.count("stop_service") == 1, started.calls
assert "running" not in [entry[0] for entry in started.statuses], started.statuses
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
finally:
_kill_children(children)
def test_cmd_start_leaves_no_service_running_when_interrupted_between_its_reservation_and_its_capture(
- monkeypatch, capsys, tmp_path
+ monkeypatch, tmp_path
):
"""The service side of the same boundary, through the real `start_service`.
@@ -2367,12 +2158,11 @@ def test_cmd_start_leaves_no_service_running_when_interrupted_between_its_reserv
# Nothing was captured, so nothing is left for the rollback, and the UI
# was never reached.
assert started.calls == [], started.calls
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
finally:
_kill_children(children)
-def test_cmd_start_rolls_back_a_real_ui_it_captured_through_its_record(monkeypatch, capsys, tmp_path):
+def test_cmd_start_rolls_back_a_real_ui_it_captured_through_its_record(monkeypatch, tmp_path):
"""Once captured, the UI is the rollback's to stop, and the rollback finds it.
The other side of the handover boundary: a Ctrl-C after `start_ui` returned
@@ -2402,17 +2192,15 @@ def test_cmd_start_rolls_back_a_real_ui_it_captured_through_its_record(monkeypat
assert children[0].wait(timeout=5) == -signal.SIGTERM
assert not ui_pid_path.exists()
assert started.calls.index("stop_ui") < started.calls.index("stop_service"), started.calls
- assert "@avibe-start-receipt:" not in capsys.readouterr().out
finally:
_kill_children(children)
-def test_cmd_start_keeps_the_service_it_started_once_the_receipt_is_out(monkeypatch, capsys):
- """The region ends at the receipt, and a finished start is never undone.
+def test_cmd_start_keeps_the_service_it_started_once_the_start_finished(monkeypatch):
+ """The region ends with the start, and a finished start is never undone.
- This is the boundary the guard must not overrun: the receipt is the last
- statement in the region, so a start that printed one has handed the desktop
- shell everything it needs to own the stop itself -- both processes stay up.
+ This is the boundary the guard must not overrun: a start that returned has
+ handed its Runtime over to whoever asked for it -- both processes stay up.
"""
started = _ui_refuses_to_start(monkeypatch, reused=False, ui_outcome=5678)
@@ -2432,7 +2220,6 @@ def test_cmd_start_keeps_the_service_it_started_once_the_receipt_is_out(monkeypa
assert "stop_ui" not in started.calls, (
f"cmd_start stopped the UI of a start that had already succeeded: {started.calls}"
)
- assert "@avibe-start-receipt:" in capsys.readouterr().out
assert len(collected) == 1
@@ -4333,12 +4120,7 @@ def test_start_parser_accepts_no_open_browser():
("arguments", "expected"),
[
(["stop"], {}),
- (["stop", "--receipt", json.dumps(_startup_receipt_payload())], {"receipt": json.dumps(_startup_receipt_payload())}),
- (["stop", "--expect-runtime-id", "a" * 64], {"expect_runtime_id": "a" * 64, "keep_remote_access": False}),
- (
- ["stop", "--expect-runtime-id", "a" * 64, "--keep-remote-access"],
- {"expect_runtime_id": "a" * 64, "keep_remote_access": True},
- ),
+ (["stop", "--expect-runtime-id", "a" * 64], {"expect_runtime_id": "a" * 64}),
],
)
def test_stop_parser_and_main_route_each_stop_mode(monkeypatch, arguments, expected):
@@ -4354,25 +4136,19 @@ def test_stop_parser_and_main_route_each_stop_mode(monkeypatch, arguments, expec
assert calls == [expected]
-def test_stop_parser_rejects_a_receipt_with_an_expected_runtime_id():
- with pytest.raises(SystemExit):
- cli.build_parser().parse_args(
- ["stop", "--receipt", json.dumps(_startup_receipt_payload()), "--expect-runtime-id", "a" * 64]
- )
-
-
-def test_only_a_scoped_stop_can_keep_remote_access(monkeypatch):
- # A full stop always stops the tunnel with the UI.
[email protected](("arguments", "hand_over"), [(["start"], False), (["start", "--hand-over"], True)])
+def test_only_a_start_asked_to_hand_over_may_replace_another_desktop_runtime(monkeypatch, arguments, hand_over):
calls = []
- monkeypatch.setattr(cli.sys, "argv", ["vibe", "stop", "--keep-remote-access"])
+ monkeypatch.setattr(cli.sys, "argv", ["vibe", *arguments])
monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)
- monkeypatch.setattr(cli, "cmd_stop", lambda **kwargs: calls.append(kwargs) or 0)
+ monkeypatch.setattr(cli, "_generation_downgrade_blocks", lambda *args, **kwargs: False)
+ monkeypatch.setattr(cli, "cmd_start", lambda **kwargs: calls.append(kwargs) or 0)
with pytest.raises(SystemExit) as exited:
cli.main()
- assert exited.value.code == 2
- assert calls == []
+ assert exited.value.code == 0
+ assert calls == [{"open_browser": None, "hand_over": hand_over}]
def test_remote_parser_accepts_pairing_command():
diff --git a/ui/src/components/VersionBadge.test.tsx b/ui/src/components/VersionBadge.test.tsx
index c21b8e31f..30fc1406d 100644
--- a/ui/src/components/VersionBadge.test.tsx
+++ b/ui/src/components/VersionBadge.test.tsx
@@ -19,17 +19,33 @@ afterEach(() => {
delete (window as { __AVIBE_DESKTOP_VERSION__?: string }).__AVIBE_DESKTOP_VERSION__;
});
+function renderInShell(appVersion: string, runtimeVersion: string) {
+ Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
+ Object.defineProperty(window, '__AVIBE_DESKTOP_VERSION__', { value: appVersion, configurable: true });
+ api.getVersion.mockResolvedValueOnce({ current: runtimeVersion, latest: null, has_update: false, managed_by: 'desktop' });
+ render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
+}
+
describe('desktop version ownership', () => {
- it('uses the stamped app version and never starts the Python updater', () => {
- Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { value: true, configurable: true });
- Object.defineProperty(window, '__AVIBE_DESKTOP_VERSION__', { value: '3.1.2-rc.15', configurable: true });
- render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
- expect(screen.getByTitle('v3.1.2-rc.15')).toBeTruthy();
- expect(api.getVersion).not.toHaveBeenCalled();
+ it('uses the stamped app version and never starts the Python updater', async () => {
+ renderInShell('3.1.2-rc.15', '3.1.2rc15');
+ await vi.waitFor(() => expect(api.getVersion).toHaveBeenCalledOnce());
+ const entry = screen.getByTitle('v3.1.2-rc.15');
+ expect(entry.className).not.toContain('text-gold-ink');
expect(api.getConfig).not.toHaveBeenCalled();
expect(screen.queryByRole('dialog')).toBeNull();
});
+ it('shows and flags the Runtime version when the shell serves another one', async () => {
+ renderInShell('3.1.2-rc.3', '3.1.2rc2');
+ const entry = await screen.findByTitle(
+ i18n.t('dashboard.runtimeVersionSkew', { app: '3.1.2-rc.3', runtime: '3.1.2rc2' }),
+ );
+ expect(entry.textContent).toBe('v3.1.2rc2');
+ expect(entry.className).toContain('text-gold-ink');
+ expect(api.getConfig).not.toHaveBeenCalled();
+ });
+
it('retains the browser version entry and its existing managed-runtime guidance', async () => {
render(<I18nextProvider i18n={i18n}><VersionBadge /></I18nextProvider>);
const entry = await screen.findByTitle('v9.9.9');
diff --git a/ui/src/components/VersionBadge.tsx b/ui/src/components/VersionBadge.tsx
index 4d862045e..a4c6a3fcb 100644
--- a/ui/src/components/VersionBadge.tsx
+++ b/ui/src/components/VersionBadge.tsx
@@ -28,6 +28,25 @@ function shortenVersion(value: string, tail = 4): string {
return `${core}…${value.slice(-tail)}`;
}
+// The shell stamps SemVer (`3.1.2-rc.3`) and the Runtime reports PEP 440
+// (`3.1.2rc3`). Normalize both to PEP 440 so only a real difference is flagged.
+const PEP440 = /^v?(\d+(?:\.\d+)*)(?:[-_.]?(a|b|c|rc|alpha|beta|pre|preview)[-_.]?(\d*))?(?:[-_.]?(post|rev|r)[-_.]?(\d*))?(?:[-_.]?(dev)[-_.]?(\d*))?(?:\+([a-z0-9]+(?:[-_.][a-z0-9]+)*))?$/;
+const PRE_RELEASE: Record<string, string> = { alpha: 'a', beta: 'b', c: 'rc', pre: 'rc', preview: 'rc' };
+
+function normalizeVersion(value: string): string {
+ const version = value.trim().toLowerCase();
+ const match = PEP440.exec(version);
+ if (!match) return version;
+ const [, release, pre, preNumber, post, postNumber, dev, devNumber, local] = match;
+ return [
+ release,
+ pre ? `${PRE_RELEASE[pre] ?? pre}${preNumber || '0'}` : '',
+ post ? `.post${postNumber || '0'}` : '',
+ dev ? `.dev${devNumber || '0'}` : '',
+ local ? `+${local.replace(/[-_]/g, '.')}` : '',
+ ].join('');
+}
+
export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward = false }) => {
const { t } = useTranslation();
const api = useApi();
@@ -45,8 +64,9 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
const popupId = React.useId();
React.useEffect(() => {
- if (inDesktopShell) return;
checkVersion();
+ // The shell owns updates; it reads the Runtime's version only to show skew.
+ if (inDesktopShell) return;
loadAutoUpdateSetting();
}, []);
@@ -120,7 +140,13 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
const hasUpdate = !inDesktopShell && versionInfo?.managed_by !== 'desktop' && versionInfo?.has_update === true;
const isDesktopManaged = versionInfo?.managed_by === 'desktop';
- const currentVersion = (inDesktopShell ? window.__AVIBE_DESKTOP_VERSION__ : versionInfo?.current) || '...';
+ const shellVersion = inDesktopShell ? window.__AVIBE_DESKTOP_VERSION__ : undefined;
+ const runtimeVersion = versionInfo?.current;
+ // A shell can serve a Runtime it did not start, such as one it adopted.
+ const hasVersionSkew = Boolean(
+ shellVersion && runtimeVersion && normalizeVersion(shellVersion) !== normalizeVersion(runtimeVersion),
+ );
+ const currentVersion = (hasVersionSkew ? runtimeVersion : shellVersion ?? runtimeVersion) || '...';
const isSourceBuild = !inDesktopShell && versionInfo?.build?.kind === 'source';
const sourceRevision = versionInfo?.build?.revision;
const shortSourceRevision = sourceRevision?.slice(0, 12) || t('dashboard.unknownRevision');
@@ -128,9 +154,11 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
const refreshLabel = checking
? t('dashboard.checking')
: t(isSourceBuild ? 'dashboard.refreshBuildInfo' : 'dashboard.checkUpdate');
- const badgeTitle = isSourceBuild
- ? `${t('dashboard.sourceRevision')}: ${sourceRevision || t('dashboard.unknownRevision')}${versionInfo?.build?.dirty ? ` (${t('dashboard.dirtySource')})` : ''}`
- : `v${currentVersion}`;
+ const badgeTitle = hasVersionSkew
+ ? t('dashboard.runtimeVersionSkew', { app: shellVersion, runtime: runtimeVersion })
+ : isSourceBuild
+ ? `${t('dashboard.sourceRevision')}: ${sourceRevision || t('dashboard.unknownRevision')}${versionInfo?.build?.dirty ? ` (${t('dashboard.dirtySource')})` : ''}`
+ : `v${currentVersion}`;
// Desktop details belong in the shared floating layer, outside the sidebar.
// Phones retain their fixed panel below the header.
const Popup = isDesktop ? PopoverContent : 'div';
@@ -143,7 +171,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
<button
type="button"
className={cn(
- badgeVariants({ variant: hasUpdate ? 'warning' : 'secondary' }),
+ badgeVariants({ variant: hasUpdate || hasVersionSkew ? 'warning' : 'secondary' }),
interactiveBadgeTriggerClassName,
'relative rounded-md font-medium tracking-normal hover:brightness-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
)}
@@ -154,6 +182,7 @@ export const VersionBadge: React.FC<{ openUpward?: boolean }> = ({ openUpward =
window.location.href = 'avibe://updates';
} : undefined}
>
+ {hasVersionSkew && <AlertCircle size={12} aria-hidden="true" />}
{isSourceBuild ? <GitCommitHorizontal size={12} /> : 'v'}
{displayVersion}
{hasUpdate && (
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fa6dd5f3e..7b83915fb 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -16,7 +16,8 @@
"runtime_discovery_failed": "Avibe could not determine the local Runtime address.",
"runtime_spawn_failed": "Avibe could not start the installed Runtime.",
"runtime_stopped": "The Runtime was stopped. Choose Try again to start it when you are ready.",
- "runtime_ownership_lost": "The Runtime changed and this app can no longer stop it. Choose Try again to check the current Runtime.",
+ "runtime_ownership_lost": "The Runtime at this address changed, so this app left it running. Choose Try again to check the current Runtime and reconnect.",
+ "runtime_stop_failed": "Avibe could not confirm that the Runtime stopped, so some or all of it may still be running. Choose Try again to reconnect to it, then stop it again if you need to.",
"launcher_exited": "The Avibe Runtime stopped instead of starting. Update Avibe, then try again.",
"ready_timeout": "The Avibe Runtime did not become ready within {{seconds}} seconds.",
"workbench_navigation_failed": "Avibe could not open the Workbench in this window."
@@ -29,7 +30,7 @@
"stopped": "Runtime: stopped",
"stopping": "Runtime: stopping…",
"stop": "Stop Runtime…",
- "quit": "Quit",
+ "quit": "Quit Avibe",
"login": "Start at Login",
"settings": "Settings…",
"stopTitle": "Stop Runtime",
@@ -43,7 +44,6 @@
"busyTitle": "Avibe Is Busy",
"busyMessage": "The Runtime is starting or another lifecycle action is in progress. Please try again when it finishes.",
"failureTitle": "Action Could Not Be Completed",
- "stopFailure": "The Runtime could not be stopped safely. Avibe remains open. Try again after checking the Runtime.",
"loginFailure": "The login setting could not be read or changed. Check your operating system's login settings and try again."
},
"notifications": {
@@ -76,7 +76,13 @@
"successTitle": "Avibe Private Files Removed",
"successMessage": "The private Runtime and agent backends were removed. Avibe will now quit. You can delete the application or run the system uninstaller.",
"failureTitle": "Uninstall Failed",
- "failureMessage": "Avibe could not remove all private Runtime and backend files. The desktop app remains installed and your user data was not changed."
+ "failureMessage": "Avibe could not remove all private Runtime and backend files. The desktop app remains installed and your user data was not changed.",
+ "blockedTitle": "Private Files Kept",
+ "blockedMessage": "Avibe kept the private Runtime and backend files because something still running may use them: a Runtime this app did not start, a Runtime that is still starting, or a backend install that has not finished. Stop that Runtime or wait for it to finish, then choose Uninstall Avibe again. Your user data was not changed.",
+ "unverifiedTitle": "Stop Could Not Be Verified",
+ "unverifiedMessage": "Avibe could not run its Runtime to confirm that background installs have stopped. If you delete the private files anyway, an install that is still running may fail or leave files behind. Your user data is not changed either way.",
+ "unverifiedDelete": "Delete Anyway",
+ "unverifiedKeep": "Keep Files"
},
"updater": {
"menu": "Check for Desktop Updates…",
@@ -3684,7 +3690,8 @@
"restarting": "Restarting...",
"autoUpdate": "Auto Update",
"autoUpdateHint": "Auto-install when idle",
- "desktopManagedUpdate": "Updates are delivered with the Avibe desktop app"
+ "desktopManagedUpdate": "Updates are delivered with the Avibe desktop app",
+ "runtimeVersionSkew": "This app is v{{app}}, but it is connected to an Avibe Runtime at v{{runtime}}"
},
"doctor": {
"title": "System Status",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index cc2c64846..5d319f2ad 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -16,7 +16,8 @@
"runtime_discovery_failed": "Avibe 无法确定本地 Runtime 地址。",
"runtime_spawn_failed": "Avibe 无法启动已安装的 Runtime。",
"runtime_stopped": "运行时已停止。准备就绪后,点击“重试”即可启动。",
- "runtime_ownership_lost": "运行时已更换,此应用已无法停止它。点击“重试”以检查当前运行时。",
+ "runtime_ownership_lost": "此地址上的运行时已更换,本应用未停止它。点击“重试”以检查当前运行时并重新连接。",
+ "runtime_stop_failed": "Avibe 无法确认运行时已停止,其部分或全部组件可能仍在运行。点击“重试”重新连接,如有需要可再次停止它。",
"launcher_exited": "Avibe Runtime 未能启动。请更新 Avibe 后重试。",
"ready_timeout": "Avibe Runtime 未能在 {{seconds}} 秒内就绪。",
"workbench_navigation_failed": "Avibe 无法在当前窗口中打开工作台。"
@@ -29,7 +30,7 @@
"stopped": "运行时:已停止",
"stopping": "运行时:正在停止…",
"stop": "停止运行时…",
- "quit": "退出",
+ "quit": "退出 Avibe",
"login": "登录时启动",
"settings": "设置…",
"stopTitle": "停止运行时",
@@ -43,7 +44,6 @@
"busyTitle": "应用正忙",
"busyMessage": "运行时正在启动,或另一个生命周期操作正在进行。请等待完成后重试。",
"failureTitle": "无法完成操作",
- "stopFailure": "无法安全停止运行时,应用将保持打开。请检查运行时后重试。",
"loginFailure": "无法读取或更改登录启动设置。请检查操作系统的登录设置后重试。"
},
"notifications": {
@@ -76,7 +76,13 @@
"successTitle": "Avibe 私有文件已移除",
"successMessage": "私有 Runtime 和 Agent 后端已移除,Avibe 现在将退出。你可以删除应用或运行系统卸载程序。",
"failureTitle": "卸载失败",
- "failureMessage": "Avibe 无法完整移除私有 Runtime 和后端文件。桌面应用仍保持安装状态,你的用户数据没有发生变化。"
+ "failureMessage": "Avibe 无法完整移除私有 Runtime 和后端文件。桌面应用仍保持安装状态,你的用户数据没有发生变化。",
+ "blockedTitle": "私有文件已保留",
+ "blockedMessage": "Avibe 保留了私有 Runtime 和后端文件,因为仍在运行的程序可能正在使用它们:不是本应用启动的 Runtime、仍在启动的 Runtime,或尚未完成的后端安装。请停止该 Runtime 或等待其完成,然后再次选择“卸载 Avibe”。你的用户数据没有发生变化。",
+ "unverifiedTitle": "无法确认已停止",
+ "unverifiedMessage": "Avibe 无法运行其 Runtime 来确认后台安装已停止。如果仍然删除私有文件,仍在运行的安装可能会失败或残留文件。无论如何选择,你的用户数据都不会改变。",
+ "unverifiedDelete": "仍然删除",
+ "unverifiedKeep": "保留文件"
},
"updater": {
"menu": "检查桌面应用更新…",
@@ -3684,7 +3690,8 @@
"restarting": "正在重启...",
"autoUpdate": "自动更新",
"autoUpdateHint": "空闲时自动安装",
- "desktopManagedUpdate": "更新将随 Avibe 桌面应用提供"
+ "desktopManagedUpdate": "更新将随 Avibe 桌面应用提供",
+ "runtimeVersionSkew": "本应用为 v{{app}},但连接的 Avibe 运行时为 v{{runtime}}"
},
"doctor": {
"title": "系统状态",
diff --git a/vibe/cli.py b/vibe/cli.py
index 0919b9bab..1c9a2cca6 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -13635,41 +13635,56 @@ def _confirm_doctor_repair(targets: list[str]) -> bool:
return answer.strip().lower() == "yes"
-def _handover_superseded_desktop_runtime() -> None:
- """Replace a different desktop-managed Controller before service reuse."""
+def _handover_superseded_desktop_runtime(*, allowed: bool) -> int:
+ """Replace a different desktop-managed Controller before service reuse.
+
+ Returns 0 to go on starting, 3 when this start does not take the home over,
+ and 2 when the superseded Runtime may be left partly running.
+ """
from vibe import internal_client
from vibe.desktop_runtime import desktop_runtime_id
expected_runtime_id = desktop_runtime_id()
if expected_runtime_id is None:
- return
+ return 0
controller_identity = internal_client.health_identity_sync()
if controller_identity is None:
- return
+ return 0
actual_runtime_id = controller_identity.get("desktop_runtime_id")
if actual_runtime_id is None or actual_runtime_id == expected_runtime_id:
- return
+ return 0
+ language = _configured_cli_language()
+ # Only the desktop host asks for a handover, when a user launches or
+ # retries its app; any other start leaves another desktop Runtime alone.
+ if not allowed:
+ print(i18n_t("desktopRuntime.handoverNotRequested", language), file=sys.stderr)
+ return 3
# Health names the Runtime that answered; the stop signals only processes
# that carry its id.
result = runtime.stop_desktop_runtime(actual_runtime_id)
- language = _configured_cli_language()
if result.refusal is not None:
- raise RuntimeError(i18n_t("desktopRuntime.handoverRefused", language, reason=result.refusal))
+ print(i18n_t("desktopRuntime.handoverRefused", language, reason=result.refusal), file=sys.stderr)
+ return 3
if result.failure is not None:
- raise RuntimeError(i18n_t("desktopRuntime.handoverFailed", language, part=result.failure))
+ print(i18n_t("desktopRuntime.handoverFailed", language, part=result.failure), file=sys.stderr)
+ return 2
# A UI still running is not the superseded Runtime's. Starting would reuse
# it, or replace it with an unscoped stop.
if runtime.ui_pid_file_points_to_running_ui():
- raise RuntimeError(i18n_t("desktopRuntime.handoverForeignUi", language))
+ print(i18n_t("desktopRuntime.handoverForeignUi", language), file=sys.stderr)
+ return 3
+ return 0
-def cmd_start(*, open_browser: bool | None = None):
+def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):
_guard_cli_default_state_migration()
paths.ensure_data_dirs()
config = _ensure_config()
- _handover_superseded_desktop_runtime()
+ handover_status = _handover_superseded_desktop_runtime(allowed=hand_over)
+ if handover_status:
+ return handover_status
has_configured_platform_credentials = getattr(config, "has_configured_platform_credentials", None)
if callable(has_configured_platform_credentials):
@@ -13684,13 +13699,12 @@ def cmd_start(*, open_browser: bool | None = None):
service_start = runtime.ProcessStartInfo()
ui_start = runtime.ProcessStartInfo()
- # Everything from here to the receipt line is one region under one invariant:
- # nothing THIS invocation created may survive a start that never printed a
- # receipt. Both processes count. An unreceipted service is adopted as
- # `reused` on the next attempt, so the desktop shell never owns its stop
- # again; an unreceipted UI keeps its pid file and its listener, which the
- # next attempt then has to fight. Every failure in the region produces those
- # orphans, whichever line raised.
+ # Everything from here to the end of the start is one region under one
+ # invariant: nothing THIS invocation created may survive a start that did not
+ # finish. Both processes count. A service left behind is adopted as `reused`
+ # on the next attempt, so nothing ever undoes it; a UI left behind keeps its
+ # pid file and its listener, which the next attempt then has to fight. Every
+ # failure in the region produces those orphans, whichever line raised.
#
# The guard is regional on purpose. Undoing one named failure inside its own
# branch -- which is what the `ui_pid is None` refusal below used to do --
@@ -13701,8 +13715,8 @@ def cmd_start(*, open_browser: bool | None = None):
# `BaseException`, not `Exception`: a Ctrl-C during the readiness wait, the
# longest thing in here, orphans the service exactly like a crash does.
# `SystemExit` is included deliberately -- nothing in the region exits on
- # purpose, and an exit before the receipt is indistinguishable, to the next
- # launch, from any other start that never finished. The bare `raise` keeps
+ # purpose, and an exit before the start finished is indistinguishable, to
+ # the next launch, from any other start that never finished. The bare `raise` keeps
# the original failure and its traceback unchanged.
#
# The region opens before `start_service`, not after it: that call spawns
@@ -13723,10 +13737,8 @@ def cmd_start(*, open_browser: bool | None = None):
if ui_pid is None:
# No pid means start_ui found a stale UI it could not stop and refused
# to start a replacement that would only die on bind. Nothing below can
- # complete without that pid: the status writes carry it and
- # validate_start_receipt rejects a receipt missing it. Fail here rather
- # than further down in the receipt builder, and let the region's guard
- # undo the start.
+ # complete without that pid: the status writes carry it. Fail here and
+ # let the region's guard undo the start.
raise RuntimeError("Vibe UI could not be started because a stale UI process could not be stopped")
# The WAIT below is asked unconditionally. The predicate that used to guard
# it is the lock, which is taken before the database is migrated -- so it is
@@ -13753,7 +13765,6 @@ def cmd_start(*, open_browser: bool | None = None):
service_ready = resolved_pid is not None
if resolved_pid is not None:
service_pid = resolved_pid
- service_start.capture(service_pid, reused=service_reused)
if service_ready:
runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)
elif runtime.pid_alive(service_pid):
@@ -13762,18 +13773,6 @@ def cmd_start(*, open_browser: bool | None = None):
runtime.write_status("error", "service process exited before startup completed", service_pid, ui_pid)
raise RuntimeError(f"Vibe service process pid={service_pid} exited before acquiring the service lock")
- from vibe.desktop_runtime import start_receipt_line
-
- receipt_line = start_receipt_line(
- {
- "schema_version": 1,
- "outcome": "reused" if service_reused else "started",
- "service_pid": service_pid,
- "ui_pid": ui_pid,
- "service_create_unix_ms": service_start.create_unix_ms,
- "ui_create_unix_ms": ui_start.create_unix_ms,
- }
- )
ui_url = "http://{}:{}".format(config.ui.setup_host, config.ui.setup_port)
# Always print Web UI access instructions.
@@ -13792,8 +13791,6 @@ def cmd_start(*, open_browser: bool | None = None):
if not opened:
print(f"(Tip) Could not auto-open a browser. Open this URL manually: {ui_url}")
print("")
-
- print(receipt_line, flush=True)
except BaseException:
# The invariant is that this invocation leaves running nothing it
# created -- not just the service. The region starts two processes, and
@@ -13923,29 +13920,6 @@ def _runtime_process_was_running() -> bool:
return runtime.service_process_running() or runtime.ui_pid_file_points_to_running_ui()
-def _stop_receipt_refusal(receipt_json: str) -> str | None:
- from vibe.desktop_runtime import START_RECEIPT_TIME_TOLERANCE_MS, validate_start_receipt
-
- try:
- receipt = validate_start_receipt(json.loads(receipt_json))
- except (ValueError, RecursionError):
- return "invalid_receipt"
- try:
- recorded_pid = int(paths.get_runtime_pid_path().read_text(encoding="utf-8").strip())
- except (OSError, ValueError):
- return "service_pid_mismatch"
- if recorded_pid != receipt["service_pid"]:
- return "service_pid_mismatch"
- if not runtime.pid_alive(recorded_pid):
- return "service_identity_unavailable"
- created = runtime.process_create_time(recorded_pid)
- if created is None:
- return "service_identity_unavailable"
- if not abs(created * 1000 - receipt["service_create_unix_ms"]) <= START_RECEIPT_TIME_TOLERANCE_MS:
- return "service_create_time_mismatch"
- return None
-
-
# The part of a stop that did not stop: its localized diagnostic and the
# status detail, which stays English for machine readers.
_STOP_FAILURES = {
@@ -13988,7 +13962,7 @@ def _print_left_running(result: runtime.DesktopRuntimeStopResult) -> None:
_print_stop_json({"left_running": [{"pid": item.pid, "name": item.name} for item in left_running]})
-def _stop_expected_desktop_runtime(runtime_id: str, *, keep_remote_access: bool = False) -> int:
+def _stop_expected_desktop_runtime(runtime_id: str) -> int:
result = runtime.stop_desktop_runtime(runtime_id)
if result.outcome is runtime.DesktopRuntimeStopOutcome.NOT_OURS:
_print_stop_json({"reason": result.refusal})
@@ -14003,11 +13977,7 @@ def _stop_expected_desktop_runtime(runtime_id: str, *, keep_remote_access: bool
remaining = [{"pid": item.pid, "role": item.role} for item in result.remaining]
_print_stop_json({"failed": result.failure, "remaining": remaining})
return status
- if keep_remote_access:
- _write_status_unless_a_service_holds_the_lock("stopped")
- status = 0
- else:
- status = _stop_the_home_s_connector()
+ status = _stop_the_home_s_connector()
_print_left_running(result)
if status:
_print_stop_json({"failed": "remote_access", "remaining": []})
@@ -14037,14 +14007,9 @@ def _stop_the_home_s_connector() -> int:
return outcome[0]
-def cmd_stop(*, receipt: str | None = None, expect_runtime_id: str | None = None, keep_remote_access: bool = False):
+def cmd_stop(*, expect_runtime_id: str | None = None):
if expect_runtime_id is not None:
- return _stop_expected_desktop_runtime(expect_runtime_id, keep_remote_access=keep_remote_access)
- if receipt is not None:
- reason = _stop_receipt_refusal(receipt)
- if reason is not None:
- print(json.dumps({"reason": reason}, separators=(",", ":")), file=sys.stderr)
- return 3
+ return _stop_expected_desktop_runtime(expect_runtime_id)
service_was_running = _pid_file_points_to_live_process(paths.get_runtime_pid_path())
ui_was_running = _pid_file_points_to_live_process(paths.get_runtime_ui_pid_path())
@@ -16639,21 +16604,11 @@ def build_parser():
subparsers = parser.add_subparsers(dest="command")
stop_parser = subparsers.add_parser("stop", help="Stop all services")
- stop_scope = stop_parser.add_mutually_exclusive_group()
- stop_scope.add_argument(
- "--receipt",
- help="Stop only if the service identity matches this startup receipt JSON.",
- )
- stop_scope.add_argument(
+ stop_parser.add_argument(
"--expect-runtime-id",
metavar="RUNTIME_ID",
help="Stop only the processes the desktop Runtime with this id started.",
)
- stop_parser.add_argument(
- "--keep-remote-access",
- action="store_true",
- help="With --expect-runtime-id, leave the remote access tunnel running.",
- )
start_parser = subparsers.add_parser("start", help="Start services if needed without stopping running processes")
start_parser.add_argument(
"--no-open-browser",
@@ -16667,6 +16622,7 @@ def build_parser():
action="store_true",
help="Start this install even though a newer one was activated since.",
)
+ start_parser.add_argument("--hand-over", action="store_true", help=argparse.SUPPRESS)
desktop_parser = subparsers.add_parser("desktop", help=argparse.SUPPRESS)
desktop_subparsers = desktop_parser.add_subparsers(dest="desktop_command", required=True)
desktop_endpoint_parser = desktop_subparsers.add_parser("endpoint", help=argparse.SUPPRESS)
@@ -18799,19 +18755,13 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:
"""Run the admitted command. Every branch exits; nothing returns to ``main``."""
if args.command == "stop":
- if args.keep_remote_access and args.expect_runtime_id is None:
- parser.error("--keep-remote-access requires --expect-runtime-id")
- if args.receipt is not None:
- sys.exit(cmd_stop(receipt=args.receipt))
if args.expect_runtime_id is not None:
- sys.exit(
- cmd_stop(expect_runtime_id=args.expect_runtime_id, keep_remote_access=args.keep_remote_access)
- )
+ sys.exit(cmd_stop(expect_runtime_id=args.expect_runtime_id))
sys.exit(cmd_stop())
if args.command == "start":
if _generation_downgrade_blocks("start", allow_downgrade=args.allow_downgrade):
sys.exit(1)
- sys.exit(cmd_start(open_browser=args.open_browser))
+ sys.exit(cmd_start(open_browser=args.open_browser, hand_over=args.hand_over))
if args.command == "desktop" and args.desktop_command == "endpoint":
sys.exit(cmd_desktop_endpoint())
if args.command == "desktop" and args.desktop_command == "remove-backends":
diff --git a/vibe/desktop_runtime.py b/vibe/desktop_runtime.py
index 59cbe4769..507915a3d 100644
--- a/vibe/desktop_runtime.py
+++ b/vibe/desktop_runtime.py
@@ -9,13 +9,11 @@ configuration or broaden its navigation policy.
from __future__ import annotations
import ipaddress
-import json
-import math
import os
import socket
from collections.abc import Mapping
from pathlib import Path
-from typing import Literal, TypedDict, cast
+from typing import Literal, TypedDict
DESKTOP_ENDPOINT_SCHEMA_VERSION: Literal[1] = 1
DESKTOP_RUNTIME_ID_ENV = "AVIBE_DESKTOP_RUNTIME_ID"
@@ -38,46 +36,6 @@ DESKTOP_OPENCODE_ROLE = "opencode"
# different one is a reused pid only when the process holding it is readable and
# is not a UI of the tree's Runtime; when it cannot be read, nobody can tell.
DESKTOP_INSTALLER_OWNER_ENV = "AVIBE_DESKTOP_INSTALLER_OWNER"
-START_RECEIPT_PREFIX = "@avibe-start-receipt:"
-START_RECEIPT_TIME_TOLERANCE_MS = 2.0
-
-
-class StartReceipt(TypedDict):
- schema_version: Literal[1]
- outcome: Literal["started", "reused"]
- service_pid: int
- ui_pid: int
- service_create_unix_ms: float
- ui_create_unix_ms: float
-
-
-def validate_start_receipt(payload: object) -> StartReceipt:
- if not isinstance(payload, dict):
- raise ValueError("Startup receipt must be an object")
- if type(payload.get("schema_version")) is not int or payload["schema_version"] != 1:
- raise ValueError("Unsupported startup receipt schema")
- if payload.get("outcome") not in ("started", "reused"):
- raise ValueError("Invalid startup receipt outcome")
- for field in ("service_pid", "ui_pid"):
- value = payload.get(field)
- if type(value) is not int or value <= 0:
- raise ValueError(f"Invalid startup receipt {field}")
- for field in ("service_create_unix_ms", "ui_create_unix_ms"):
- value = payload.get(field)
- if type(value) not in (int, float) or value <= 0:
- raise ValueError(f"Invalid startup receipt {field}")
- try:
- finite = math.isfinite(value)
- except OverflowError:
- finite = False
- if not finite:
- raise ValueError(f"Invalid startup receipt {field}")
- return cast(StartReceipt, payload)
-
-
-def start_receipt_line(payload: object) -> str:
- receipt = validate_start_receipt(payload)
- return START_RECEIPT_PREFIX + json.dumps(receipt, separators=(",", ":"), allow_nan=False)
class DesktopEndpointPayload(TypedDict):
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index e6cadd5c4..d93c8d07d 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -843,6 +843,7 @@
"upgrade": "This Runtime is managed by the Avibe desktop app. Update the app to update Avibe.",
"apiUpgrade": "This Runtime is managed by the Avibe desktop app.",
"backendUpgrade": "This Codex backend belongs to an older Avibe desktop Runtime and cannot be updated in place. Reopen the current desktop app to install it privately.",
+ "handoverNotRequested": "Another desktop-managed Avibe Runtime is running here; this start does not replace it.",
"handoverRefused": "Refused to stop the superseded desktop-managed Avibe Runtime: {reason}",
"handoverFailed": "Failed to stop the superseded desktop-managed Avibe Runtime: {part}",
"handoverForeignUi": "A UI server that is not the superseded desktop-managed Avibe Runtime's is still running."
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index a014da29e..80500d653 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -843,6 +843,7 @@
"upgrade": "此 Runtime 由 Avibe 桌面应用管理。请更新桌面应用来更新 Avibe。",
"apiUpgrade": "此 Runtime 由 Avibe 桌面应用管理。",
"backendUpgrade": "此 Codex 后端属于旧版 Avibe 桌面 Runtime,无法原地更新。请重新打开当前桌面应用,将其安装为私有后端。",
+ "handoverNotRequested": "此处正在运行另一个桌面托管的 Avibe Runtime;本次启动不会替换它。",
"handoverRefused": "已拒绝停止被取代的桌面托管 Avibe Runtime:{reason}",
"handoverFailed": "未能停止被取代的桌面托管 Avibe Runtime:{part}",
"handoverForeignUi": "仍有一个不属于被取代的桌面托管 Avibe Runtime 的 UI 服务在运行。"
diff --git a/vibe/runtime.py b/vibe/runtime.py
index b80e1f7d7..b401bd185 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -59,14 +59,10 @@ SERVICE_PHASE_RUNNING = "running"
@dataclass
class ProcessStartInfo:
pid: int | None = None
- create_unix_ms: float | None = None
reused: bool = False
def capture(self, pid: int, *, reused: bool) -> int:
- if self.pid != pid:
- created = process_create_time(pid)
- self.pid = pid
- self.create_unix_ms = created * 1000 if created is not None else None
+ self.pid = pid
self.reused = reused
return pid