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.

feat(desktop): use startup readiness receipt (#3100)

Max6f178e2c9b1a
diff --git a/.github/workflows/desktop-shell.yml b/.github/workflows/desktop-shell.yml
index daa572d38..e3d481664 100644
--- a/.github/workflows/desktop-shell.yml
+++ b/.github/workflows/desktop-shell.yml
@@ -133,6 +133,27 @@ jobs:
- name: Test Rust
run: cargo test --workspace --all-features
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+ with:
+ python-version: "3.12"
+
+ - name: Install startup fixture dependencies
+ working-directory: .
+ run: |
+ python -m pip install --disable-pip-version-check --only-binary=:all: --no-deps uv==0.12.10
+ uv sync --frozen --no-install-project --no-dev
+
+ - name: Verify launcher stdout closes while Runtime children stay alive
+ env:
+ AVIBE_TEST_PYTHON: ${{ github.workspace }}/.venv/${{ runner.os == 'Windows' && 'Scripts/python.exe' || 'bin/python' }}
+ run: cargo test -p avibe-runtime-host cmd_start_stdout_reaches_eof -- --ignored --nocapture
+
+ - name: Verify shell timeout reaches the real startup producer
+ env:
+ AVIBE_TEST_PYTHON: ${{ github.workspace }}/.venv/${{ runner.os == 'Windows' && 'Scripts/python.exe' || 'bin/python' }}
+ AVIBE_DESKTOP_READY_TIMEOUT_SECONDS: "1"
+ run: cargo test -p avibe-runtime-host cmd_start_receipt_timeout_override -- --ignored --nocapture
+
- name: Verify Windows installer transaction with isolated native fixtures
if: runner.os == 'Windows'
shell: powershell
diff --git a/desktop/README.md b/desktop/README.md
index d9241ff25..1f7f9eba9 100644
--- a/desktop/README.md
+++ b/desktop/README.md
@@ -41,11 +41,59 @@ product logic.
a concurrent Stop is not held for that budget. A successful lookup lets the
shell finish its logout hooks within the remaining time; only a fallback
(or a logout that itself hangs) ends the process group.
-5. Polls until the Runtime is ready or the bound expires, then navigates. The
+5. Observes readiness until the bound expires, then navigates. The
window never leaves the bootstrap page before combined readiness succeeds.
If the launcher it started exits non-zero, it gives up immediately instead of
waiting out the timeout: nothing is coming, and the user is asked to update
Avibe rather than watching a spinner for two minutes.
+
+ Bundled product builds use an opt-in `vibe start --desktop-receipt` mode.
+ Python remains the owner of config, process startup, ownership, rollback, and
+ the combined UI/Controller readiness predicate. It writes one bounded
+ `@avibe-desktop-start:` JSON line after all failure-prone startup work has
+ completed. The frame is version `1`, is at most 4096 UTF-8 bytes including
+ its prefix and newline, and has `outcome: "ready"` or `outcome: "failed"`.
+ A failed start before the endpoint origin is resolved emits no frame and
+ keeps the existing nonzero exit behavior. External launchers,
+ `AVIBE_DESKTOP_VIBE_PATH`, and `AVIBE_DESKTOP_ORIGIN` continue through the
+ legacy startup path.
+
+ The bundled shell accepts a ready frame only after validating its canonical
+ loopback origin and then performs one final direct, redirect-free `/ready`
+ probe against the exact endpoint. The probe still verifies the expected
+ Runtime identity and usable Controller/UI state. A valid frame is an
+ irreversible startup observation: later helper exit or ordinary stdout
+ cleanup cannot revoke it, while a final probe contradiction still refuses
+ navigation. Admission stops at that temporal acceptance boundary and does
+ not wait for stdout EOF; malformed,
+ oversized, duplicate, or contradictory protocol data in the read batch
+ containing the first frame fails closed. Later bytes are outside that
+ acceptance boundary. The dedicated reader uses ordinary blocking reads and
+ sends a verdict over a bounded channel. Admission spends the remaining
+ deadline and allows a short drain after helper exit. Current service/UI
+ spawns redirect output to separate log sinks and close unrelated handles.
+ A future descendant that incorrectly inherits receipt stdout could leave
+ one idle reader thread blocked until it exits; admission, rollback and
+ navigation remain unaffected. Both desktop CI platforms verify real stdout
+ EOF after helper exit while the fixture Runtime children stay alive.
+
+ Python's desktop readiness requests also bypass configured proxies and refuse
+ redirects. Only the exact loopback `/ready` is required; LAN `/health` is
+ not a desktop readiness gate. Each complete HTTP response, including its
+ UTF-8 body (at most 1 KiB), is limited to the smaller of five seconds and
+ the remaining startup deadline. The shell passes its validated
+ `AVIBE_DESKTOP_READY_TIMEOUT_SECONDS` setting to the bundled CLI using
+ `--desktop-ready-timeout`; Python shares that budget across startup and its
+ readiness observations. The UI starts without waiting
+ for service readiness so the existing startup
+ parallelism remains. Optional install-generation cleanup runs after the
+ receipt is flushed and cannot delay Workbench admission. This receipt removes
+ duplicate Rust readiness polling; it does not promise a cold-start time
+ reduction on Windows. Packaged Windows acceptance still needs the release
+ artifact and manual launch checks.
+ After a failed receipt is displayed, a still-running helper is retained to
+ prevent overlapping starts. Once it exits, the first Try again starts a new
+ attempt without displaying that old failure a second time.
6. After navigation, probes the same exact origin every two seconds. Three
consecutive failures return the WebView to the bundled bootstrap and rerun
adoption/startup; a transient miss does not replace the Workbench.
diff --git a/desktop/runtime-host/src/bootstrap.rs b/desktop/runtime-host/src/bootstrap.rs
index 623c4f7fc..a6fea857c 100644
--- a/desktop/runtime-host/src/bootstrap.rs
+++ b/desktop/runtime-host/src/bootstrap.rs
@@ -13,6 +13,7 @@ use tokio::time::{sleep, Instant};
use crate::health::{HealthProbe, Presence};
use crate::launcher::{CliOutcome, LaunchError, LaunchExit, LaunchedRuntime, ResolvedRuntimeLauncher, RuntimeLauncher};
use crate::origin::LoopbackOrigin;
+use crate::receipt::{ReceiptEvent, StartupReceiptOutcome, StartupReceiptReason};
use crate::status::{BootstrapNotice, BootstrapNoticeCode, BootstrapStatus};
/// Overrides the origin the shell probes and navigates to. Still validated as a
@@ -422,7 +423,7 @@ impl RuntimeHost {
.adopt(
sink,
&origin,
- attempt,
+ (run, attempt),
presence,
resolved_launcher.as_ref(),
BootstrapNoticeCode::Adopted,
@@ -434,7 +435,7 @@ impl RuntimeHost {
.adopt(
sink,
&origin,
- attempt,
+ (run, attempt),
presence,
resolved_launcher.as_ref(),
BootstrapNoticeCode::Adopted,
@@ -504,6 +505,18 @@ impl RuntimeHost {
publish(sink, BootstrapStatus::starting(&origin, attempt));
+ let receipt_watch = self
+ .launched_runtime()
+ .attempt
+ .as_ref()
+ .map(|attempt| attempt.watch.clone())
+ .filter(|watch| watch.receipt_capable());
+ if let Some(watch) = receipt_watch {
+ return self
+ .wait_for_startup_receipt(sink, run, origin, launcher, attempt, watch)
+ .await;
+ }
+
let deadline = Instant::now() + self.settings.ready_timeout;
while Instant::now() < deadline {
sleep(self.settings.poll_interval).await;
@@ -518,7 +531,7 @@ impl RuntimeHost {
.adopt(
sink,
&origin,
- attempt,
+ (run, attempt),
presence,
Some(&launcher),
BootstrapNoticeCode::Ready,
@@ -530,7 +543,7 @@ impl RuntimeHost {
.adopt(
sink,
&origin,
- attempt,
+ (run, attempt),
presence,
Some(&launcher),
BootstrapNoticeCode::Adopted,
@@ -542,7 +555,7 @@ impl RuntimeHost {
.adopt(
sink,
&origin,
- attempt,
+ (run, attempt),
presence,
Some(&launcher),
BootstrapNoticeCode::Adopted,
@@ -583,6 +596,142 @@ impl RuntimeHost {
)
}
+ async fn wait_for_startup_receipt(
+ &self,
+ sink: &dyn StatusSink,
+ run: u64,
+ origin: LoopbackOrigin,
+ launcher: Arc<dyn ResolvedRuntimeLauncher>,
+ mut attempt: u32,
+ watch: crate::launcher::LaunchWatch,
+ ) -> BootstrapStatus {
+ let identified = launcher.expected_runtime_id().is_some();
+ let deadline = Instant::now() + self.settings.ready_timeout;
+ loop {
+ if !self.receipt_run_current(run) {
+ return publish(sink, receipt_invalid(&origin, attempt));
+ }
+ if Instant::now() >= deadline {
+ watch.cancel_receipt();
+ self.clear_successful_launch();
+ return publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::timeout(self.settings.ready_timeout.as_secs()),
+ true,
+ ),
+ );
+ }
+ let receipt = match watch.receipt_event() {
+ Some(ReceiptEvent::Receipt(receipt)) => Some(receipt),
+ Some(ReceiptEvent::Invalid | ReceiptEvent::TransportError | ReceiptEvent::Eof) => {
+ let code = self
+ .clear_failed_launch()
+ .unwrap_or(BootstrapNoticeCode::RuntimeDiscoveryFailed);
+ return publish(
+ sink,
+ BootstrapStatus::failed(&origin, attempt, BootstrapNotice::new(code), true),
+ );
+ }
+ None => None,
+ };
+ if let Some(receipt) = receipt {
+ if !receipt_matches_origin(&receipt, &origin) {
+ return publish(sink, receipt_invalid(&origin, attempt));
+ }
+ if receipt.outcome == StartupReceiptOutcome::Failed {
+ let status = publish(
+ sink,
+ BootstrapStatus::failed(
+ &origin,
+ attempt,
+ BootstrapNotice::new(receipt_failure_notice(receipt.reason)),
+ true,
+ ),
+ );
+ // Keep the live helper's retry slot, but do not display the
+ // same terminal failure again when its exit is reaped.
+ watch.acknowledge_receipt_failure();
+ return status;
+ }
+ if let Some(code) = self.clear_failed_launch() {
+ return publish(
+ sink,
+ BootstrapStatus::failed(&origin, attempt, BootstrapNotice::new(code), true),
+ );
+ }
+ // Receipt acceptance is the startup commit observation. The
+ // final probe below is still authoritative for the exact
+ // endpoint and Runtime identity, but helper output and exit
+ // events observed after this point belong to the monitor.
+ launcher.record_bootstrap_event("runtime.start.receipt.accepted");
+ attempt += 1;
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ let presence =
+ match tokio::time::timeout(remaining, self.observe_presence(run, &origin, Some(&launcher))).await {
+ Ok(presence) if Instant::now() < deadline => presence,
+ _ => Presence::Unknown,
+ };
+ if !self.receipt_run_current(run) {
+ return publish(sink, receipt_invalid(&origin, attempt));
+ }
+ launcher.record_bootstrap_event("runtime.start.final_presence");
+ return match presence {
+ Presence::Mine { ready: true } => {
+ self.adopt(
+ sink,
+ &origin,
+ (run, attempt),
+ presence,
+ Some(&launcher),
+ BootstrapNoticeCode::Ready,
+ )
+ .await
+ }
+ Presence::Unmanaged => {
+ self.adopt(
+ sink,
+ &origin,
+ (run, attempt),
+ presence,
+ Some(&launcher),
+ BootstrapNoticeCode::Adopted,
+ )
+ .await
+ }
+ Presence::Foreign { ready: true, .. } if !identified => {
+ self.adopt(
+ sink,
+ &origin,
+ (run, attempt),
+ presence,
+ Some(&launcher),
+ BootstrapNoticeCode::Adopted,
+ )
+ .await
+ }
+ Presence::Foreign { .. } if identified => publish(sink, ownership_lost(&origin, attempt)),
+ _ => publish(sink, receipt_invalid(&origin, attempt)),
+ };
+ }
+ if let Some(code) = self.clear_failed_launch() {
+ return publish(
+ sink,
+ BootstrapStatus::failed(&origin, attempt, BootstrapNotice::new(code), true),
+ );
+ }
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ let _ = tokio::time::timeout(remaining, watch.receipt_changed(remaining)).await;
+ }
+ }
+
+ fn receipt_run_current(&self, run: u64) -> bool {
+ let state = self.launched_runtime();
+ !state.stopping && state.epoch == run
+ }
+
async fn resolve_origin(&self) -> Result<(LoopbackOrigin, Option<Arc<dyn ResolvedRuntimeLauncher>>), LaunchError> {
if let Some(origin) = self.settings.origin_override.as_deref() {
return LoopbackOrigin::parse(origin)
@@ -617,20 +766,30 @@ impl RuntimeHost {
&self,
sink: &dyn StatusSink,
origin: &LoopbackOrigin,
- attempt: u32,
+ run_attempt: (u64, u32),
presence: Presence,
launcher: Option<&Arc<dyn ResolvedRuntimeLauncher>>,
notice: BootstrapNoticeCode,
) -> BootstrapStatus {
+ let (run, attempt) = run_attempt;
+ if !self.receipt_run_current(run) {
+ return publish(sink, receipt_invalid(origin, attempt));
+ }
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;
}
+ {
+ let mut state = self.launched_runtime();
+ if state.stopping || state.epoch != run {
+ return publish(sink, receipt_invalid(origin, attempt));
+ }
+ state.adoption = Some(Adoption {
+ presence,
+ launcher: launcher.cloned(),
+ });
+ }
publish(sink, BootstrapStatus::ready(origin, attempt, notice))
}
@@ -752,14 +911,14 @@ impl RuntimeHost {
// Spawning the helper is evidence that a Runtime may exist even
// when the helper later reports failure. Keep that fact separate
// from retry deduplication and stop authority.
- state.attempt = Some(launcher.launch(hand_over)?);
+ state.attempt = Some(launcher.launch_with_ready_timeout(hand_over, self.settings.ready_timeout)?);
state.runtime_may_be_running = true;
}
Ok(())
}
- /// A failed helper releases its retry slot and nothing else. Returns the
- /// notice its exit calls for.
+ /// A failed helper releases its retry slot and nothing else. Report its
+ /// exit only when this attempt has not already published a valid FAILED.
fn clear_failed_launch(&self) -> Option<BootstrapNoticeCode> {
let mut state = self.launched_runtime();
let code = match state.attempt.as_ref()?.watch.exit()? {
@@ -768,8 +927,9 @@ impl RuntimeHost {
LaunchExit::HandoverFailed => BootstrapNoticeCode::RuntimeStopFailed,
LaunchExit::Failed => BootstrapNoticeCode::LauncherExited,
};
+ let presented = state.attempt.as_ref()?.watch.receipt_failure_presented();
state.attempt = None;
- Some(code)
+ (!presented).then_some(code)
}
/// Readiness timeout releases only a completed helper, never the liveness
@@ -803,6 +963,30 @@ fn ownership_lost(origin: &LoopbackOrigin, attempt: u32) -> BootstrapStatus {
)
}
+fn receipt_invalid(origin: &LoopbackOrigin, attempt: u32) -> BootstrapStatus {
+ BootstrapStatus::failed(
+ origin,
+ attempt,
+ BootstrapNotice::new(BootstrapNoticeCode::RuntimeDiscoveryFailed),
+ true,
+ )
+}
+
+fn receipt_matches_origin(receipt: &crate::receipt::StartupReceipt, origin: &LoopbackOrigin) -> bool {
+ LoopbackOrigin::parse(&receipt.origin).is_ok_and(|receipt_origin| receipt_origin.as_str() == origin.as_str())
+}
+
+fn receipt_failure_notice(reason: Option<StartupReceiptReason>) -> BootstrapNoticeCode {
+ match reason {
+ Some(StartupReceiptReason::HandoverRefused | StartupReceiptReason::RuntimeClaimRefused) => {
+ BootstrapNoticeCode::RuntimeOwnershipLost
+ }
+ Some(StartupReceiptReason::HandoverFailed) => BootstrapNoticeCode::RuntimeStopFailed,
+ Some(StartupReceiptReason::RuntimeNotReady) => BootstrapNoticeCode::RuntimeDiscoveryFailed,
+ Some(StartupReceiptReason::StartupFailed) | None => BootstrapNoticeCode::RuntimeSpawnFailed,
+ }
+}
+
fn publish(sink: &dyn StatusSink, status: BootstrapStatus) -> BootstrapStatus {
sink.publish(status.clone());
status
@@ -812,7 +996,9 @@ fn publish(sink: &dyn StatusSink, status: BootstrapStatus) -> BootstrapStatus {
mod tests {
use super::*;
use crate::launcher::LaunchWatch;
+ use crate::receipt::{ReceiptEvent, StartupReceipt, StartupReceiptOutcome, StartupReceiptStream};
use crate::status::BootstrapPhase;
+ use std::collections::VecDeque;
use std::sync::atomic::{AtomicUsize, Ordering};
const ORIGIN: &str = "http://127.0.0.1:5123";
@@ -920,6 +1106,124 @@ mod tests {
inner: Arc<CountingLauncher>,
}
+ #[derive(Clone)]
+ struct ReceiptLauncher {
+ state: Arc<ReceiptLauncherState>,
+ }
+
+ struct ReceiptLauncherState {
+ events: Vec<ReceiptEvent>,
+ launches: AtomicUsize,
+ runtime_id: String,
+ exit: Option<LaunchExit>,
+ }
+
+ impl ReceiptLauncher {
+ fn new(events: impl IntoIterator<Item = ReceiptEvent>) -> Self {
+ Self {
+ state: Arc::new(ReceiptLauncherState {
+ events: events.into_iter().collect(),
+ launches: AtomicUsize::new(0),
+ runtime_id: "b".repeat(64),
+ exit: None,
+ }),
+ }
+ }
+
+ fn ready(events: impl IntoIterator<Item = ReceiptEvent>) -> Self {
+ Self::new(events)
+ }
+
+ fn failed_before_acceptance(events: impl IntoIterator<Item = ReceiptEvent>) -> Self {
+ let mut launcher = Self::new(events);
+ Arc::get_mut(&mut launcher.state)
+ .expect("unique receipt launcher state")
+ .exit = Some(LaunchExit::Failed);
+ launcher
+ }
+
+ fn launches(&self) -> usize {
+ self.state.launches.load(Ordering::SeqCst)
+ }
+ }
+
+ impl RuntimeLauncher for ReceiptLauncher {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ Ok(Arc::new(self.clone()))
+ }
+ }
+
+ impl ResolvedRuntimeLauncher for ReceiptLauncher {
+ fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
+ Ok(LoopbackOrigin::parse(ORIGIN).expect("test origin"))
+ }
+
+ fn launch(&self, _hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
+ self.state.launches.fetch_add(1, Ordering::SeqCst);
+ let watch = if let Some(exit) = self.state.exit {
+ LaunchWatch::with_receipt_and_exit(StartupReceiptStream::from_events(self.state.events.clone()), exit)
+ } else {
+ LaunchWatch::with_receipt(StartupReceiptStream::from_events(self.state.events.clone()))
+ };
+ Ok(LaunchedRuntime { pid: 4242, watch })
+ }
+
+ fn expected_runtime_id(&self) -> Option<&str> {
+ Some(&self.state.runtime_id)
+ }
+
+ fn stop(&self, runtime_id: &str) -> CliOutcome {
+ assert_eq!(runtime_id, self.state.runtime_id);
+ CliOutcome::Completed
+ }
+ }
+
+ fn ready_receipt(origin: &str) -> ReceiptEvent {
+ ReceiptEvent::Receipt(StartupReceipt {
+ schema_version: 1,
+ outcome: StartupReceiptOutcome::Ready,
+ origin: origin.to_owned(),
+ reason: None,
+ })
+ }
+
+ struct ReceiptProbe {
+ calls: AtomicUsize,
+ }
+
+ impl ReceiptProbe {
+ fn calls(&self) -> usize {
+ self.calls.load(Ordering::SeqCst)
+ }
+ }
+
+ struct SequenceProbe {
+ responses: Mutex<VecDeque<Presence>>,
+ }
+
+ #[async_trait::async_trait]
+ impl HealthProbe for SequenceProbe {
+ async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
+ self.responses
+ .lock()
+ .expect("sequence probe lock")
+ .pop_front()
+ .unwrap_or(Presence::Unknown)
+ }
+ }
+
+ #[async_trait::async_trait]
+ impl HealthProbe for ReceiptProbe {
+ async fn presence(&self, _origin: &LoopbackOrigin, expected: Option<&str>) -> Presence {
+ if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
+ return Presence::Absent;
+ }
+ Presence::Mine {
+ ready: expected == Some("b".repeat(64).as_str()),
+ }
+ }
+ }
+
impl RuntimeLauncher for PreparingLauncher {
fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
Ok(Arc::new(self.inner.clone()))
@@ -983,6 +1287,346 @@ mod tests {
assert_eq!(counting.launches.load(Ordering::SeqCst), 0);
}
+ #[tokio::test(start_paused = true)]
+ async fn a_ready_receipt_is_followed_by_one_final_presence_check() {
+ let probe = Arc::new(ReceiptProbe {
+ calls: AtomicUsize::new(0),
+ });
+ let launcher = ReceiptLauncher::ready([ready_receipt(ORIGIN)]);
+ let host = RuntimeHost::new(
+ probe.clone(),
+ Arc::new(launcher.clone()),
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_secs(2),
+ poll_interval: Duration::from_secs(1),
+ ..RuntimeHostSettings::default()
+ },
+ );
+
+ let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Ready);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::Ready);
+ assert_eq!(probe.calls(), 2, "initial adoption plus one final receipt check");
+ assert_eq!(launcher.launches(), 1);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_terminal_invalid_receipt_event_refuses_navigation() {
+ let probe = Arc::new(ReceiptProbe {
+ calls: AtomicUsize::new(0),
+ });
+ let launcher = ReceiptLauncher::ready([ReceiptEvent::Invalid]);
+ let host = RuntimeHost::new(
+ probe,
+ Arc::new(launcher),
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_secs(2),
+ poll_interval: Duration::from_secs(1),
+ ..RuntimeHostSettings::default()
+ },
+ );
+
+ let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeDiscoveryFailed);
+ }
+
+ #[test]
+ fn receipt_origin_comparison_uses_the_loopback_canonical_form() {
+ for host in ["127.0.0.1", "[::1]"] {
+ let expected = LoopbackOrigin::parse(&format!("http://{host}")).expect("default HTTP port");
+ let explicit_default = ready_receipt(&format!("http://{host}:80"));
+ let distinct = ready_receipt(&format!("http://{host}:81"));
+
+ let ReceiptEvent::Receipt(explicit_default) = explicit_default else {
+ unreachable!("test receipt is a receipt event");
+ };
+ let ReceiptEvent::Receipt(distinct) = distinct else {
+ unreachable!("test receipt is a receipt event");
+ };
+
+ assert!(receipt_matches_origin(&explicit_default, &expected));
+ assert!(!receipt_matches_origin(&distinct, &expected));
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_receipt_for_another_origin_refuses_navigation() {
+ let probe = Arc::new(ReceiptProbe {
+ calls: AtomicUsize::new(0),
+ });
+ let launcher = ReceiptLauncher::ready([ready_receipt("http://127.0.0.1:5124")]);
+ let host = RuntimeHost::new(
+ probe.clone(),
+ Arc::new(launcher),
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_secs(2),
+ poll_interval: Duration::from_secs(1),
+ ..RuntimeHostSettings::default()
+ },
+ );
+
+ let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeDiscoveryFailed);
+ assert_eq!(probe.calls(), 1, "wrong origin precedes the final probe");
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_receipt_transport_failure_before_publication_refuses_navigation() {
+ let probe = Arc::new(ReceiptProbe {
+ calls: AtomicUsize::new(0),
+ });
+ let launcher = ReceiptLauncher::ready([ReceiptEvent::TransportError]);
+ let host = RuntimeHost::new(
+ probe.clone(),
+ Arc::new(launcher),
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_secs(2),
+ poll_interval: Duration::from_secs(1),
+ ..RuntimeHostSettings::default()
+ },
+ );
+
+ let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::RuntimeDiscoveryFailed);
+ assert_eq!(probe.calls(), 1, "transport failure precedes the final probe");
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_failed_helper_before_receipt_acceptance_refuses_navigation() {
+ let launcher = ReceiptLauncher::failed_before_acceptance([ready_receipt(ORIGIN)]);
+ let host = RuntimeHost::new(
+ Arc::new(ReceiptProbe {
+ calls: AtomicUsize::new(0),
+ }),
+ Arc::new(launcher),
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_secs(2),
+ poll_interval: Duration::from_secs(1),
+ ..RuntimeHostSettings::default()
+ },
+ );
+
+ let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_eq!(status.notice.code, BootstrapNoticeCode::LauncherExited);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn the_final_presence_probe_remains_authoritative_after_a_ready_receipt() {
+ for final_presence in [
+ Presence::Absent,
+ Presence::Unknown,
+ Presence::Mine { ready: false },
+ Presence::Foreign {
+ runtime_id: "c".repeat(64),
+ ready: true,
+ },
+ ] {
+ let probe = Arc::new(SequenceProbe {
+ responses: Mutex::new(VecDeque::from([Presence::Absent, final_presence])),
+ });
+ let host = RuntimeHost::new(
+ probe,
+ Arc::new(ReceiptLauncher::ready([ready_receipt(ORIGIN)])),
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_secs(2),
+ poll_interval: Duration::from_secs(1),
+ ..RuntimeHostSettings::default()
+ },
+ );
+
+ let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+
+ assert_eq!(status.phase, BootstrapPhase::Failed);
+ assert_ne!(status.notice.code, BootstrapNoticeCode::Ready);
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn an_in_flight_receipt_helper_is_retained_after_observation_timeout() {
+ struct NeverReadyProbe;
+
+ #[async_trait::async_trait]
+ impl HealthProbe for NeverReadyProbe {
+ async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
+ Presence::Absent
+ }
+ }
+
+ let launcher = ReceiptLauncher::ready([]);
+ let host = RuntimeHost::new(
+ Arc::new(NeverReadyProbe),
+ Arc::new(launcher.clone()),
+ RuntimeHostSettings {
+ ready_timeout: Duration::ZERO,
+ poll_interval: Duration::from_secs(1),
+ ..RuntimeHostSettings::default()
+ },
+ );
+
+ let first = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+ let second = host.bootstrap(&DiscardStatus, BootstrapTrigger::Retry).await;
+
+ assert_eq!(first.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ assert_eq!(second.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ assert_eq!(launcher.launches(), 1, "Retry must not start a duplicate helper");
+ assert!(host.has_launched());
+ }
+
+ #[tokio::test]
+ async fn a_newer_attempt_or_stop_fences_a_receipts_in_flight_final_probe() {
+ struct PausedFinalProbe {
+ calls: AtomicUsize,
+ entered: tokio::sync::Notify,
+ release: tokio::sync::Notify,
+ initial: Presence,
+ }
+ #[async_trait::async_trait]
+ impl HealthProbe for PausedFinalProbe {
+ async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
+ match self.calls.fetch_add(1, Ordering::SeqCst) {
+ 0 => self.initial.clone(),
+ 1 => {
+ self.entered.notify_one();
+ self.release.notified().await;
+ Presence::Mine { ready: true }
+ }
+ _ => Presence::Mine { ready: true },
+ }
+ }
+ }
+ for stop in [false, true] {
+ let probe = Arc::new(PausedFinalProbe {
+ calls: AtomicUsize::new(0),
+ entered: tokio::sync::Notify::new(),
+ release: tokio::sync::Notify::new(),
+ initial: if stop {
+ Presence::Mine { ready: false }
+ } else {
+ Presence::Absent
+ },
+ });
+ let mut launcher = ReceiptLauncher::ready([ready_receipt(ORIGIN)]);
+ // Stop is permitted only once the helper has settled and actual
+ // presence established this Runtime's ownership.
+ if stop {
+ Arc::get_mut(&mut launcher.state).unwrap().exit = Some(LaunchExit::Started);
+ }
+ let host = RuntimeHost::new(
+ probe.clone(),
+ Arc::new(launcher.clone()),
+ RuntimeHostSettings::default(),
+ );
+ let (stale, ()) = tokio::join!(host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch), async {
+ probe.entered.notified().await;
+ if stop {
+ assert_eq!(host.stop_owned_runtime().await, CliOutcome::Completed);
+ } else {
+ assert_eq!(
+ host.bootstrap(&DiscardStatus, BootstrapTrigger::Retry).await.phase,
+ BootstrapPhase::Ready
+ );
+ }
+ probe.release.notify_one();
+ });
+ assert_eq!(stale.phase, BootstrapPhase::Failed);
+ assert_eq!(launcher.launches(), 1);
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_ready_frame_cannot_extend_the_deadline_for_final_verification() {
+ struct SlowFinalProbe(AtomicUsize);
+ #[async_trait::async_trait]
+ impl HealthProbe for SlowFinalProbe {
+ async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
+ if self.0.fetch_add(1, Ordering::SeqCst) == 0 {
+ return Presence::Absent;
+ }
+ sleep(Duration::from_secs(5)).await;
+ Presence::Mine { ready: true }
+ }
+ }
+ for budget in [Duration::ZERO, Duration::from_secs(1)] {
+ let host = RuntimeHost::new(
+ Arc::new(SlowFinalProbe(AtomicUsize::new(0))),
+ Arc::new(ReceiptLauncher::ready([ready_receipt(ORIGIN)])),
+ RuntimeHostSettings {
+ ready_timeout: budget,
+ ..RuntimeHostSettings::default()
+ },
+ );
+ let started = Instant::now();
+ assert_eq!(
+ host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await.phase,
+ BootstrapPhase::Failed
+ );
+ assert!(started.elapsed() <= budget);
+ }
+ }
+
+ #[tokio::test]
+ async fn receipt_timeout_does_not_run_a_second_http_polling_loop() {
+ struct CountingAbsentProbe {
+ calls: AtomicUsize,
+ }
+
+ #[async_trait::async_trait]
+ impl HealthProbe for CountingAbsentProbe {
+ async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Presence::Absent
+ }
+ }
+
+ let receipt_probe = Arc::new(CountingAbsentProbe {
+ calls: AtomicUsize::new(0),
+ });
+ let receipt_host = RuntimeHost::new(
+ receipt_probe.clone(),
+ Arc::new(ReceiptLauncher::ready([])),
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_millis(30),
+ poll_interval: Duration::from_millis(5),
+ ..RuntimeHostSettings::default()
+ },
+ );
+ let receipt_status = receipt_host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+
+ let legacy_probe = Arc::new(CountingAbsentProbe {
+ calls: AtomicUsize::new(0),
+ });
+ let legacy_launcher = Arc::new(CountingLauncher::default());
+ let legacy_host = RuntimeHost::new(
+ legacy_probe.clone(),
+ Arc::new(PreparingLauncher { inner: legacy_launcher }),
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_millis(30),
+ poll_interval: Duration::from_millis(5),
+ ..RuntimeHostSettings::default()
+ },
+ );
+ let legacy_status = legacy_host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+
+ assert_eq!(receipt_status.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ assert_eq!(legacy_status.notice.code, BootstrapNoticeCode::ReadyTimeout);
+ let receipt_calls = receipt_probe.calls.load(Ordering::SeqCst);
+ let legacy_calls = legacy_probe.calls.load(Ordering::SeqCst);
+ assert_eq!(receipt_calls, 1, "receipt waiting does not poll /ready");
+ assert!(
+ legacy_calls > receipt_calls,
+ "legacy Rust polling should exceed the receipt path"
+ );
+ }
+
/// A launcher whose login-shell lookup blocks until the test releases it.
struct BlockedLookup {
started: std::sync::mpsc::SyncSender<()>,
@@ -1094,10 +1738,16 @@ mod tests {
#[test]
fn a_timeout_override_must_be_a_positive_bounded_number_of_seconds() {
+ assert_eq!(parse_timeout("1"), Some(Duration::from_secs(1)));
assert_eq!(parse_timeout("30"), Some(Duration::from_secs(30)));
+ assert_eq!(parse_timeout("600"), Some(Duration::from_secs(600)));
assert_eq!(parse_timeout(" 30 "), Some(Duration::from_secs(30)));
for rejected in ["", "0", "-1", "abc", "30s", "1e3", "601", "18446744073709551616"] {
assert_eq!(parse_timeout(rejected), None, "override {rejected:?}");
}
}
}
+
+#[cfg(test)]
+#[path = "bootstrap_receipt_tests.rs"]
+mod receipt_integration;
diff --git a/desktop/runtime-host/src/bootstrap_receipt_tests.rs b/desktop/runtime-host/src/bootstrap_receipt_tests.rs
new file mode 100644
index 000000000..1c8f294cb
--- /dev/null
+++ b/desktop/runtime-host/src/bootstrap_receipt_tests.rs
@@ -0,0 +1,362 @@
+//! Real cmd_start -> local HTTP -> stdout -> RuntimeHost admission.
+//! Run with AVIBE_TEST_PYTHON pointing at the repository test environment and
+//! `cargo test -p avibe-runtime-host cmd_start_receipt_admission -- --ignored --nocapture`.
+use super::*;
+use crate::bootstrap_log::BootstrapLog;
+use crate::health::HttpHealthProbe;
+use crate::launcher::LaunchWatch;
+use crate::receipt::StartupReceiptStream;
+use crate::status::BootstrapPhase;
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+struct Fixture {
+ child: Mutex<Child>,
+ origin: LoopbackOrigin,
+ scratch: PathBuf,
+ receipt: bool,
+ launches: AtomicUsize,
+ descendants: bool,
+ expected_failure: bool,
+}
+
+impl Fixture {
+ fn start(root: &Path, case: &str, receipt: bool, delay: f64, housekeeping: f64, sample: usize) -> Arc<Self> {
+ let scratch = std::env::temp_dir().join(format!(
+ "avibe startup 非 ASCII {} {case} {receipt} {sample}",
+ std::process::id()
+ ));
+ std::fs::create_dir_all(&scratch).unwrap();
+ let stderr_path = scratch.join("stderr.log");
+ let stderr = std::fs::File::create(&stderr_path).unwrap();
+ let python =
+ std::env::var_os("AVIBE_TEST_PYTHON").expect("set absolute AVIBE_TEST_PYTHON to project test Python");
+ let mut command = Command::new(python);
+ command
+ .env_clear()
+ .env("PYTHONIOENCODING", "utf-8")
+ .env("PYTHONDONTWRITEBYTECODE", "1");
+ for key in ["SYSTEMROOT", "WINDIR"] {
+ if let Some(value) = std::env::var_os(key) {
+ command.env(key, value);
+ }
+ }
+ for key in [
+ "HOME",
+ "USERPROFILE",
+ "TEMP",
+ "TMP",
+ "TMPDIR",
+ "XDG_CONFIG_HOME",
+ "XDG_CACHE_HOME",
+ "XDG_DATA_HOME",
+ "XDG_STATE_HOME",
+ "AVIBE_HOME",
+ "CODEX_HOME",
+ "CLAUDE_CONFIG_DIR",
+ "APPDATA",
+ "LOCALAPPDATA",
+ ] {
+ let home = scratch.join(key);
+ std::fs::create_dir_all(&home).unwrap();
+ command.env(key, home);
+ }
+ let mut child = command
+ .current_dir(&scratch)
+ .arg(root.join("tests/fixtures/desktop_startup_process.py"))
+ .arg(&scratch)
+ .arg(if receipt { "receipt" } else { "legacy" })
+ .arg(delay.to_string())
+ .arg(housekeeping.to_string())
+ .arg(case)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::from(stderr))
+ .spawn()
+ .expect("fixture Python starts");
+ let deadline = std::time::Instant::now() + Duration::from_secs(15);
+ let endpoint = scratch.join("endpoint");
+ while !endpoint.exists() {
+ if let Some(status) = child.try_wait().unwrap() {
+ panic!("fixture exited {status}: {}", diagnostic_tail(&stderr_path));
+ }
+ if std::time::Instant::now() >= deadline {
+ child.kill().ok();
+ child.wait().ok();
+ panic!("fixture initialization timed out: {}", diagnostic_tail(&stderr_path));
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ Arc::new(Self {
+ origin: LoopbackOrigin::parse(&std::fs::read_to_string(endpoint).unwrap()).unwrap(),
+ child: Mutex::new(child),
+ scratch,
+ receipt,
+ launches: AtomicUsize::new(0),
+ descendants: case == "eof",
+ expected_failure: case == "budget",
+ })
+ }
+
+ fn finish(&self) -> serde_json::Value {
+ let mut child = self.child.lock().unwrap();
+ writeln!(child.stdin.as_mut().unwrap(), "done").unwrap();
+ let deadline = std::time::Instant::now() + Duration::from_secs(10);
+ loop {
+ if let Some(status) = child.try_wait().unwrap() {
+ assert_eq!(
+ status.success(),
+ !self.expected_failure,
+ "{}",
+ diagnostic_tail(&self.scratch.join("stderr.log"))
+ );
+ break;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "fixture exits after bounded housekeeping"
+ );
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ serde_json::from_slice(&std::fs::read(self.scratch.join("trace.json")).unwrap()).unwrap()
+ }
+}
+impl Drop for Fixture {
+ fn drop(&mut self) {
+ if self.descendants {
+ std::fs::write(self.scratch.join("children-stop"), "").ok();
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ while ["service-done", "ui-done"]
+ .iter()
+ .any(|name| !self.scratch.join(name).exists())
+ && std::time::Instant::now() < deadline
+ {
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ }
+ if let Ok(child) = self.child.get_mut() {
+ if child.try_wait().ok().flatten().is_none() {
+ child.kill().ok();
+ }
+ child.wait().ok();
+ }
+ std::fs::remove_dir_all(&self.scratch).ok();
+ }
+}
+
+fn diagnostic_tail(path: &Path) -> String {
+ use std::io::{Seek, SeekFrom};
+ let mut file = std::fs::File::open(path).unwrap();
+ let size = file.metadata().unwrap().len();
+ file.seek(SeekFrom::Start(size.saturating_sub(8192))).unwrap();
+ let mut tail = Vec::new();
+ file.take(8192).read_to_end(&mut tail).unwrap();
+ String::from_utf8_lossy(&tail).into_owned()
+}
+
+#[test]
+#[ignore = "requires repository Python dependencies; run on both desktop CI platforms"]
+fn cmd_start_stdout_reaches_eof_while_runtime_children_remain_alive() {
+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .parent()
+ .unwrap()
+ .parent()
+ .unwrap()
+ .to_owned();
+ let fixture = Fixture::start(&root, "eof", true, 0.0, 0.0, 0);
+ let mut stdout = {
+ let mut child = fixture.child.lock().unwrap();
+ let stdout = child.stdout.take().unwrap();
+ writeln!(child.stdin.as_mut().unwrap(), "start").unwrap();
+ stdout
+ };
+ let (sender, receiver) = std::sync::mpsc::sync_channel(1);
+ let reader = std::thread::spawn(move || {
+ let mut bytes = Vec::new();
+ // This is the real launcher pipe, with no transport/spawn mocks.
+ let result = stdout.read_to_end(&mut bytes).map(|_| bytes);
+ let _ = sender.send(result);
+ });
+ fixture.finish(); // waits for actual cmd_start and the launcher process exit
+ let bytes = receiver
+ .recv_timeout(Duration::from_secs(1))
+ .expect("reader sees EOF after helper exit")
+ .unwrap();
+ reader.join().unwrap();
+ assert!(String::from_utf8(bytes).unwrap().contains("\"outcome\":\"ready\""));
+ // These acknowledgements are written after the helper exited: the actual
+ // service/UI spawn primitives and their log sinks did not inherit stdout.
+ std::fs::write(fixture.scratch.join("prove-alive"), "").unwrap();
+ let deadline = std::time::Instant::now() + Duration::from_secs(2);
+ while ["service-alive", "ui-alive"]
+ .iter()
+ .any(|name| !fixture.scratch.join(name).exists())
+ {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "both Runtime fixture children outlive the helper"
+ );
+ std::thread::sleep(Duration::from_millis(10));
+ }
+}
+impl RuntimeLauncher for Arc<Fixture> {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ Ok(Arc::new(self.clone()))
+ }
+}
+impl ResolvedRuntimeLauncher for Arc<Fixture> {
+ fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
+ Ok(self.origin.clone())
+ }
+ fn launch(&self, _hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
+ self.launch_with_ready_timeout(false, DEFAULT_READY_TIMEOUT)
+ }
+ fn launch_with_ready_timeout(
+ &self,
+ _hand_over: bool,
+ ready_timeout: Duration,
+ ) -> Result<LaunchedRuntime, LaunchError> {
+ self.launches.fetch_add(1, Ordering::SeqCst);
+ let mut child = self.child.lock().unwrap();
+ let watch = if self.receipt {
+ LaunchWatch::with_receipt(StartupReceiptStream::spawn(
+ child.stdout.take().unwrap(),
+ BootstrapLog::at(self.scratch.join("bootstrap.log")),
+ ))
+ } else {
+ LaunchWatch::default()
+ };
+ if self.receipt {
+ // Use the exact argument builder used by the bundled launcher, then
+ // let the actual Python parser and cmd_start consume its budget.
+ let args = crate::launcher::desktop_start_arguments(ready_timeout);
+ writeln!(
+ child.stdin.as_mut().unwrap(),
+ "{}",
+ serde_json::to_string(&args).unwrap()
+ )
+ .unwrap();
+ } else {
+ writeln!(child.stdin.as_mut().unwrap(), "start").unwrap();
+ }
+ Ok(LaunchedRuntime { pid: child.id(), watch })
+ }
+ fn expected_runtime_id(&self) -> Option<&str> {
+ Some("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
+ }
+ fn record_bootstrap_event(&self, event: &str) {
+ BootstrapLog::at(self.scratch.join("bootstrap.log")).record(event, &[]);
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires repository Python and AVIBE_DESKTOP_READY_TIMEOUT_SECONDS=1"]
+async fn cmd_start_receipt_timeout_override() {
+ let settings = RuntimeHostSettings::from_env();
+ assert_eq!(
+ settings.ready_timeout,
+ Duration::from_secs(1),
+ "run with the documented shell override"
+ );
+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .parent()
+ .unwrap()
+ .parent()
+ .unwrap()
+ .to_owned();
+ let fixture = Fixture::start(&root, "budget", true, 2.5, 0.0, 0);
+ let probe = Arc::new(HttpHealthProbe::new(settings.probe_timeout).unwrap());
+ let host = RuntimeHost::new(probe, Arc::new(fixture.clone()), settings);
+ let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+ assert_eq!(
+ status.phase,
+ BootstrapPhase::Failed,
+ "the override expires before Controller readiness"
+ );
+ let trace = fixture.finish();
+ assert_eq!(trace["ready_timeout"], 1.0);
+ assert_eq!(
+ trace["result"], 1,
+ "the producer also expires, rather than keeping its old 120s budget"
+ );
+ assert!(trace["helper_work_ms"].as_f64().unwrap() < 1800.0);
+ assert_eq!(fixture.launches.load(Ordering::SeqCst), 1);
+}
+struct CountProbe {
+ inner: HttpHealthProbe,
+ calls: AtomicUsize,
+}
+#[async_trait::async_trait]
+impl HealthProbe for CountProbe {
+ async fn presence(&self, origin: &LoopbackOrigin, expected: Option<&str>) -> Presence {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.inner.presence(origin, expected).await
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires repository Python dependencies; explicit cross-language acceptance gate"]
+async fn cmd_start_receipt_admission() {
+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .parent()
+ .unwrap()
+ .parent()
+ .unwrap()
+ .to_owned();
+ for (case, delay, housekeeping) in [
+ ("early", 0.0, 0.0),
+ ("controller", 1.1, 0.0),
+ ("housekeeping", 0.0, 1.2),
+ ] {
+ for sample in 0..3 {
+ let mut elapsed = Vec::new();
+ for receipt in [false, true] {
+ let fixture = Fixture::start(&root, case, receipt, delay, housekeeping, sample);
+ let probe = Arc::new(CountProbe {
+ inner: HttpHealthProbe::new(Duration::from_secs(1)).unwrap(),
+ calls: AtomicUsize::new(0),
+ });
+ let host = RuntimeHost::new(probe.clone(), Arc::new(fixture.clone()), RuntimeHostSettings::default());
+ let start = std::time::Instant::now();
+ let status = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+ let ready_ms = start.elapsed().as_secs_f64() * 1000.0;
+ assert_eq!(status.phase, BootstrapPhase::Ready, "{case}, receipt={receipt}");
+ let probes = probe.calls.load(Ordering::SeqCst);
+ if receipt {
+ assert_eq!(probes, 2, "initial adoption and one final real HTTP probe");
+ if housekeeping > 0.0 {
+ assert!(
+ !fixture.scratch.join("housekeeping-finished").exists(),
+ "admission must precede housekeeping completion"
+ );
+ }
+ }
+ // A subsequent live adoption never asks the fixture to start twice.
+ assert_eq!(
+ host.bootstrap(&DiscardStatus, BootstrapTrigger::Retry).await.phase,
+ BootstrapPhase::Ready
+ );
+ assert_eq!(fixture.launches.load(Ordering::SeqCst), 1);
+ let trace = fixture.finish();
+ assert_eq!(trace["service_starts"], 1);
+ assert_eq!(trace["ui_starts"], 1);
+ eprintln!("startup fixture case={case} sample={sample} receipt={receipt} shell_probes={probes} admission_ms={ready_ms:.1} trace={trace}");
+ if receipt {
+ eprintln!(
+ "{}",
+ std::fs::read_to_string(fixture.scratch.join("bootstrap.log")).unwrap()
+ );
+ }
+ elapsed.push(ready_ms);
+ }
+ // Same process fixture and production poll interval. This allowance
+ // covers scheduling noise, not a claimed native Windows speedup.
+ assert!(
+ elapsed[1] <= elapsed[0] + 100.0,
+ "receipt admission regressed: {elapsed:?}"
+ );
+ }
+ }
+}
diff --git a/desktop/runtime-host/src/launcher.rs b/desktop/runtime-host/src/launcher.rs
index dee3342fb..1fc31d0df 100644
--- a/desktop/runtime-host/src/launcher.rs
+++ b/desktop/runtime-host/src/launcher.rs
@@ -12,10 +12,11 @@
use std::env;
use std::ffi::{OsStr, OsString};
+use std::fmt;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
-use std::sync::{mpsc, Arc, OnceLock};
+use std::sync::{mpsc, Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use serde::Deserialize;
@@ -24,6 +25,7 @@ use crate::bootstrap_log::BootstrapLog;
use crate::login_path::{login_shell_path, LoginPath};
use crate::origin::LoopbackOrigin;
use crate::private_runtime::{InstalledPrivateRuntime, PrivateRuntimeBundle, PrivateRuntimeError};
+use crate::receipt::{ReceiptEvent, StartupReceiptStream};
use crate::status::BootstrapNoticeCode;
/// Environment variable that points the shell at a specific `vibe` executable.
///
@@ -59,6 +61,20 @@ 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 DESKTOP_START_ARGS: [&str; 3] = ["start", "--no-open-browser", "--desktop-receipt"];
+
+/// Only the bundled CLI shares this interface. The shell has already validated
+/// its environment override; Python consumes this attempt's explicit budget.
+pub(crate) fn desktop_start_arguments(ready_timeout: Duration) -> Vec<String> {
+ DESKTOP_START_ARGS
+ .iter()
+ .map(|arg| (*arg).to_owned())
+ .chain([
+ "--desktop-ready-timeout".to_owned(),
+ ready_timeout.as_secs_f64().to_string(),
+ ])
+ .collect()
+}
/// 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";
@@ -219,6 +235,15 @@ pub trait ResolvedRuntimeLauncher: Send + Sync {
/// `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>;
+ /// Legacy/external launchers retain their CLI; bundled launchers pass the
+ /// shell-owned readiness budget to the producer.
+ fn launch_with_ready_timeout(
+ &self,
+ hand_over: bool,
+ _ready_timeout: Duration,
+ ) -> Result<LaunchedRuntime, LaunchError> {
+ self.launch(hand_over)
+ }
/// The provenance id of the Runtime this launcher starts, if it has one.
/// Only a Runtime serving this id is this launcher's own.
@@ -236,6 +261,9 @@ pub trait ResolvedRuntimeLauncher: Send + Sync {
CliOutcome::Unrunnable
}
+ /// Records a bounded bootstrap milestone without affecting the outcome.
+ fn record_bootstrap_event(&self, _event: &str) {}
+
fn prune_superseded(&self) {}
}
@@ -273,8 +301,24 @@ impl LaunchExit {
/// Whether the launcher process itself survived long enough to do its job.
/// Empty means "still running, or not observable".
-#[derive(Debug, Clone, Default)]
-pub struct LaunchWatch(Arc<OnceLock<LaunchExit>>);
+#[derive(Clone)]
+pub struct LaunchWatch(Arc<LaunchWatchState>);
+
+struct LaunchWatchState {
+ exit: OnceLock<LaunchExit>,
+ receipt: Mutex<Option<StartupReceiptStream>>,
+ presented_receipt_failure: OnceLock<()>,
+}
+
+impl Default for LaunchWatch {
+ fn default() -> Self {
+ Self(Arc::new(LaunchWatchState {
+ exit: OnceLock::new(),
+ receipt: Mutex::new(None),
+ presented_receipt_failure: OnceLock::new(),
+ }))
+ }
+}
impl LaunchWatch {
/// A watch that has already seen the launcher exit. For launchers that learn
@@ -287,7 +331,7 @@ impl LaunchWatch {
/// The exit seen, if the launcher has exited.
pub fn exit(&self) -> Option<LaunchExit> {
- self.0.get().copied()
+ self.0.exit.get().copied()
}
/// True only once the launcher has been *seen* to exit non-zero.
@@ -302,11 +346,71 @@ impl LaunchWatch {
/// Neither outcome has been seen: the launcher may still be starting pieces.
pub fn pending(&self) -> bool {
- self.0.get().is_none()
+ self.0.exit.get().is_none()
+ }
+
+ pub fn receipt_capable(&self) -> bool {
+ self.0.receipt.lock().map(|receipt| receipt.is_some()).unwrap_or(false)
+ }
+
+ pub fn receipt_event(&self) -> Option<ReceiptEvent> {
+ self.0
+ .receipt
+ .lock()
+ .ok()?
+ .as_ref()
+ .and_then(StartupReceiptStream::try_next)
+ }
+
+ pub async fn receipt_changed(&self, remaining: Duration) {
+ let receipt = self.0.receipt.lock().ok().and_then(|receipt| receipt.clone());
+ if let Some(receipt) = receipt {
+ receipt.changed(remaining).await;
+ }
+ }
+
+ pub fn cancel_receipt(&self) {
+ if let Some(receipt) = self.0.receipt.lock().ok().and_then(|receipt| receipt.clone()) {
+ receipt.cancel();
+ }
+ }
+
+ pub(crate) fn acknowledge_receipt_failure(&self) {
+ let _ = self.0.presented_receipt_failure.set(());
+ }
+
+ pub(crate) fn receipt_failure_presented(&self) -> bool {
+ self.0.presented_receipt_failure.get().is_some()
+ }
+
+ pub(crate) fn with_receipt(receipt: StartupReceiptStream) -> Self {
+ let watch = Self::default();
+ *watch.0.receipt.lock().expect("launch receipt lock") = Some(receipt);
+ watch
+ }
+
+ #[cfg(test)]
+ pub(crate) fn with_receipt_and_exit(receipt: StartupReceiptStream, exit: LaunchExit) -> Self {
+ let watch = Self::with_receipt(receipt);
+ watch.record(exit);
+ watch
}
fn record(&self, exit: LaunchExit) {
- let _ = self.0.set(exit);
+ let _ = self.0.exit.set(exit);
+ if let Some(receipt) = self.0.receipt.lock().ok().and_then(|receipt| receipt.clone()) {
+ receipt.finish();
+ }
+ }
+}
+
+impl fmt::Debug for LaunchWatch {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter
+ .debug_struct("LaunchWatch")
+ .field("exit", &self.exit())
+ .field("receipt_capable", &self.receipt_capable())
+ .finish()
}
}
@@ -501,15 +605,37 @@ impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
}
fn launch(&self, hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
+ self.launch_with_ready_timeout(hand_over, crate::bootstrap::DEFAULT_READY_TIMEOUT)
+ }
+
+ fn launch_with_ready_timeout(
+ &self,
+ hand_over: bool,
+ ready_timeout: Duration,
+ ) -> 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 login_path = self.login_path();
let started = Instant::now();
- let child = spawn_detached(&self.command, hand_over, login_path).map_err(LaunchError::Spawn)?;
+ let mut child = if identified {
+ spawn_detached_with_receipt(&self.command, hand_over, login_path, Some(ready_timeout))
+ } else {
+ spawn_detached(&self.command, hand_over, login_path)
+ }
+ .map_err(LaunchError::Spawn)?;
let pid = child.id();
- let watch = LaunchWatch::default();
+ let watch = if identified {
+ let stdout = child.stdout.take().ok_or_else(|| {
+ let _ = child.kill();
+ let _ = child.wait();
+ LaunchError::Spawn(std::io::Error::other("desktop startup receipt pipe was not created"))
+ })?;
+ LaunchWatch::with_receipt(StartupReceiptStream::spawn(stdout, self.log.clone()))
+ } else {
+ LaunchWatch::default()
+ };
// Reap the launcher process so it cannot linger as a zombie. `vibe start`
// returns once the Runtime daemons are up; those daemons are grandchildren
@@ -557,6 +683,10 @@ impl ResolvedRuntimeLauncher for ResolvedVibeExecutable {
)
}
+ fn record_bootstrap_event(&self, event: &str) {
+ self.log.record(event, &[]);
+ }
+
fn prune_superseded(&self) {
if let Some((bundle, active_root)) = &self.cleanup {
let _ = bundle.prune_superseded(active_root);
@@ -1081,12 +1211,28 @@ fn spawn_detached(
runtime: &RuntimeCommand,
hand_over: bool,
login_path: &LoginPath,
+) -> std::io::Result<std::process::Child> {
+ spawn_detached_with_receipt(runtime, hand_over, login_path, None)
+}
+
+fn spawn_detached_with_receipt(
+ runtime: &RuntimeCommand,
+ hand_over: bool,
+ login_path: &LoginPath,
+ receipt_timeout: Option<Duration>,
) -> std::io::Result<std::process::Child> {
let inherited_path = match login_path {
LoginPath::Resolved(path) => Some(path.as_os_str()),
LoginPath::Inherited(_) => None,
};
- let mut command = lifecycle_command(runtime, &START_ARGS, inherited_path);
+ let receipt_args = receipt_timeout.map(desktop_start_arguments);
+ let args: Vec<&str> = receipt_args
+ .as_ref()
+ .map_or_else(|| START_ARGS.to_vec(), |args| args.iter().map(String::as_str).collect());
+ let mut command = lifecycle_command(runtime, &args, inherited_path);
+ if receipt_timeout.is_some() {
+ command.stdout(Stdio::piped());
+ }
if hand_over {
command.arg(HAND_OVER_ARG);
}
@@ -1203,6 +1349,177 @@ mod tests {
use super::*;
use std::ffi::OsStr;
+ /// FAILED is already visible before reaping; transport loss/timeouts are
+ /// not a substitute for that verdict. Only the former acknowledges failure.
+ #[tokio::test]
+ async fn retained_receipt_attempt_transitions_preserve_first_retry_and_live_deduplication() {
+ use crate::bootstrap::{BootstrapTrigger, DiscardStatus, RuntimeHost, RuntimeHostSettings};
+ use crate::health::{HealthProbe, Presence};
+ use crate::receipt::{StartupReceipt, StartupReceiptOutcome, StartupReceiptReason};
+ use crate::status::BootstrapPhase;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ #[derive(Clone)]
+ struct Launcher {
+ first: LaunchWatch,
+ launches: Arc<AtomicUsize>,
+ }
+ impl RuntimeLauncher for Launcher {
+ fn resolve(&self) -> Result<Arc<dyn ResolvedRuntimeLauncher>, LaunchError> {
+ Ok(Arc::new(self.clone()))
+ }
+ }
+ impl ResolvedRuntimeLauncher for Launcher {
+ fn endpoint(&self) -> Result<LoopbackOrigin, LaunchError> {
+ Ok(LoopbackOrigin::parse("http://127.0.0.1:5123").unwrap())
+ }
+ fn launch(&self, _hand_over: bool) -> Result<LaunchedRuntime, LaunchError> {
+ let first = self.launches.fetch_add(1, Ordering::SeqCst) == 0;
+ Ok(LaunchedRuntime {
+ pid: 42,
+ watch: if first {
+ self.first.clone()
+ } else {
+ LaunchWatch::exited(LaunchExit::Failed)
+ },
+ })
+ }
+ }
+ struct Probe {
+ healthy: bool,
+ calls: AtomicUsize,
+ }
+ #[async_trait::async_trait]
+ impl HealthProbe for Probe {
+ async fn presence(&self, _origin: &LoopbackOrigin, _expected: Option<&str>) -> Presence {
+ if self.healthy && self.calls.fetch_add(1, Ordering::SeqCst) > 0 {
+ Presence::Unmanaged
+ } else {
+ Presence::Absent
+ }
+ }
+ }
+ for scenario in [
+ "failed",
+ "wrong-origin",
+ "eof",
+ "timeout",
+ "cancel",
+ "healthy",
+ "legacy",
+ ] {
+ for exit in [
+ LaunchExit::Failed,
+ LaunchExit::HandoverRefused,
+ LaunchExit::HandoverFailed,
+ ] {
+ let events = match scenario {
+ "failed" | "wrong-origin" | "healthy" => vec![ReceiptEvent::Receipt(StartupReceipt {
+ schema_version: 1,
+ outcome: if scenario == "healthy" {
+ StartupReceiptOutcome::Ready
+ } else {
+ StartupReceiptOutcome::Failed
+ },
+ origin: if scenario == "wrong-origin" {
+ "http://127.0.0.1:5124"
+ } else {
+ "http://127.0.0.1:5123"
+ }
+ .to_owned(),
+ reason: (scenario != "healthy").then_some(match exit {
+ LaunchExit::HandoverRefused => StartupReceiptReason::HandoverRefused,
+ LaunchExit::HandoverFailed => StartupReceiptReason::HandoverFailed,
+ _ => StartupReceiptReason::RuntimeNotReady,
+ }),
+ })],
+ "eof" => vec![ReceiptEvent::Eof],
+ _ => vec![],
+ };
+ let watch = if scenario == "legacy" {
+ LaunchWatch::default()
+ } else {
+ LaunchWatch::with_receipt(StartupReceiptStream::from_events(events))
+ };
+ if scenario == "cancel" {
+ watch.cancel_receipt();
+ }
+ let launcher = Launcher {
+ first: watch.clone(),
+ launches: Arc::new(AtomicUsize::new(0)),
+ };
+ let host = RuntimeHost::new(
+ Arc::new(Probe {
+ healthy: scenario == "healthy",
+ calls: AtomicUsize::new(0),
+ }),
+ Arc::new(launcher.clone()),
+ RuntimeHostSettings {
+ ready_timeout: Duration::from_millis(20),
+ poll_interval: Duration::from_millis(1),
+ ..RuntimeHostSettings::default()
+ },
+ );
+ let first = host.bootstrap(&DiscardStatus, BootstrapTrigger::Launch).await;
+ assert_eq!(
+ first.phase,
+ if scenario == "healthy" {
+ BootstrapPhase::Ready
+ } else {
+ BootstrapPhase::Failed
+ },
+ "{scenario}"
+ );
+ if scenario == "failed" {
+ assert_eq!(
+ first.notice.code,
+ match exit {
+ LaunchExit::HandoverRefused => BootstrapNoticeCode::RuntimeOwnershipLost,
+ LaunchExit::HandoverFailed => BootstrapNoticeCode::RuntimeStopFailed,
+ _ => BootstrapNoticeCode::RuntimeDiscoveryFailed,
+ }
+ );
+ }
+ host.bootstrap(&DiscardStatus, BootstrapTrigger::Retry).await;
+ assert_eq!(
+ launcher.launches.load(Ordering::SeqCst),
+ 1,
+ "{scenario}: live helper is retained"
+ );
+ watch.record(exit); // the same observation the actual reaper records
+ let retry = host.bootstrap(&DiscardStatus, BootstrapTrigger::Retry).await;
+ let expected_launches = if scenario == "failed" { 2 } else { 1 };
+ assert_eq!(
+ launcher.launches.load(Ordering::SeqCst),
+ expected_launches,
+ "{scenario}: {exit:?}"
+ );
+ if scenario == "healthy" {
+ assert_eq!(retry.phase, BootstrapPhase::Ready, "live Runtime is adopted");
+ } else if scenario == "failed" {
+ assert_eq!(
+ retry.notice.code,
+ BootstrapNoticeCode::LauncherExited,
+ "a new attempt's failure is not acknowledged by the old attempt"
+ );
+ } else {
+ let code = match exit {
+ LaunchExit::HandoverRefused => BootstrapNoticeCode::RuntimeOwnershipLost,
+ LaunchExit::HandoverFailed => BootstrapNoticeCode::RuntimeStopFailed,
+ _ => BootstrapNoticeCode::LauncherExited,
+ };
+ assert_eq!(retry.notice.code, code, "{scenario}: unreported exit is shown once");
+ host.bootstrap(&DiscardStatus, BootstrapTrigger::Retry).await;
+ assert_eq!(
+ launcher.launches.load(Ordering::SeqCst),
+ 2,
+ "{scenario}: next retry launches"
+ );
+ }
+ }
+ }
+ }
+
/// 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
@@ -1758,11 +2075,30 @@ mod tests {
// 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,
+ false,
+ &[
+ "start",
+ "--no-open-browser",
+ "--desktop-receipt",
+ "--desktop-ready-timeout",
+ "37",
+ "shell=1",
+ ][..],
+ ),
(
true,
true,
- &["start", "--no-open-browser", "--hand-over", "shell=1"][..],
+ &[
+ "start",
+ "--no-open-browser",
+ "--desktop-receipt",
+ "--desktop-ready-timeout",
+ "37",
+ "--hand-over",
+ "shell=1",
+ ][..],
),
] {
let dir = scratch_dir("launch");
@@ -1784,7 +2120,9 @@ mod tests {
.resolve()
.expect("the fake runtime resolves")
};
- let launched = resolved.launch(hand_over).expect("the fake runtime starts");
+ let launched = resolved
+ .launch_with_ready_timeout(hand_over, Duration::from_secs(37))
+ .expect("the fake runtime starts");
assert!(launched.pid > 0);
let recorded = wait_for_file(&recording);
diff --git a/desktop/runtime-host/src/lib.rs b/desktop/runtime-host/src/lib.rs
index f88bb731d..9868cf9e5 100644
--- a/desktop/runtime-host/src/lib.rs
+++ b/desktop/runtime-host/src/lib.rs
@@ -33,6 +33,7 @@ pub mod notifications;
pub mod origin;
pub mod pet;
pub mod private_runtime;
+pub mod receipt;
pub mod status;
pub mod window_frame;
diff --git a/desktop/runtime-host/src/receipt.rs b/desktop/runtime-host/src/receipt.rs
new file mode 100644
index 000000000..cf4a5e082
--- /dev/null
+++ b/desktop/runtime-host/src/receipt.rs
@@ -0,0 +1,471 @@
+//! The bounded stdout protocol for the bundled desktop startup command.
+
+use std::io::{self, Read};
+use std::process::ChildStdout;
+use std::sync::{mpsc, Arc, Mutex, OnceLock};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use serde::Deserialize;
+
+use crate::bootstrap_log::BootstrapLog;
+
+pub const START_RECEIPT_PREFIX: &str = "@avibe-desktop-start:";
+pub const START_RECEIPT_MAX_BYTES: usize = 4096;
+
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum StartupReceiptOutcome {
+ Ready,
+ Failed,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum StartupReceiptReason {
+ StartupFailed,
+ HandoverRefused,
+ HandoverFailed,
+ RuntimeClaimRefused,
+ RuntimeNotReady,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct StartupReceipt {
+ pub schema_version: u32,
+ pub outcome: StartupReceiptOutcome,
+ pub origin: String,
+ #[serde(default)]
+ pub reason: Option<StartupReceiptReason>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ReceiptEvent {
+ Receipt(StartupReceipt),
+ Invalid,
+ Eof,
+ TransportError,
+}
+
+const EXIT_DRAIN: Duration = Duration::from_millis(100);
+
+// At most three messages: one verdict, EOF after a verdict, and helper exit.
+enum TransportEvent {
+ Verdict(ReceiptEvent),
+ Exited(Instant),
+}
+
+#[derive(Clone)]
+pub struct StartupReceiptStream {
+ sender: mpsc::SyncSender<TransportEvent>,
+ receiver: Arc<Mutex<mpsc::Receiver<TransportEvent>>>,
+ terminal: Arc<OnceLock<ReceiptEvent>>,
+ exited: Arc<OnceLock<Instant>>,
+}
+
+impl Default for StartupReceiptStream {
+ fn default() -> Self {
+ let (sender, receiver) = mpsc::sync_channel(3);
+ Self {
+ sender,
+ receiver: Arc::new(Mutex::new(receiver)),
+ terminal: Arc::new(OnceLock::new()),
+ exited: Arc::new(OnceLock::new()),
+ }
+ }
+}
+
+impl StartupReceiptStream {
+ #[cfg(test)]
+ pub(crate) fn from_events(events: impl IntoIterator<Item = ReceiptEvent>) -> Self {
+ let stream = Self::default();
+ for event in events {
+ stream.sender.try_send(TransportEvent::Verdict(event)).unwrap();
+ }
+ stream
+ }
+
+ pub fn spawn(mut stdout: ChildStdout, log: BootstrapLog) -> Self {
+ let stream = Self::default();
+ let sender = stream.sender.clone();
+ thread::spawn(move || {
+ let event = read_receipts(&mut stdout);
+ let drain = matches!(event, ReceiptEvent::Receipt(_));
+ if let ReceiptEvent::Receipt(receipt) = &event {
+ log.record(
+ "runtime.start.receipt",
+ &[("outcome", format!("{:?}", receipt.outcome))],
+ );
+ }
+ let _ = sender.try_send(TransportEvent::Verdict(event));
+ // Keep ordinary post-commit output from breaking the helper's pipe.
+ // The consumer has one terminal verdict and ignores later messages.
+ // A future descendant inheriting stdout can keep only this detached
+ // reader blocked; it cannot extend the admission deadline.
+ if drain {
+ let event = match io::copy(&mut stdout, &mut io::sink()) {
+ Ok(_) => ReceiptEvent::Eof,
+ Err(_) => ReceiptEvent::TransportError,
+ };
+ let _ = sender.try_send(TransportEvent::Verdict(event));
+ }
+ });
+ stream
+ }
+
+ fn record(&self, event: TransportEvent) {
+ match event {
+ TransportEvent::Verdict(verdict) => {
+ let _ = self.terminal.set(verdict);
+ }
+ TransportEvent::Exited(at) => {
+ let _ = self.exited.set(at);
+ }
+ }
+ }
+
+ pub fn try_next(&self) -> Option<ReceiptEvent> {
+ if self.terminal.get().is_none() {
+ // Another observer may be waiting on this retained attempt. Never
+ // block the async admission thread on its channel lock.
+ if let Ok(receiver) = self.receiver.try_lock() {
+ while let Ok(event) = receiver.try_recv() {
+ self.record(event);
+ }
+ }
+ if self.exited.get().is_some_and(|at| at.elapsed() >= EXIT_DRAIN) {
+ let _ = self.terminal.set(ReceiptEvent::Eof);
+ }
+ }
+ self.terminal.get().cloned()
+ }
+
+ pub fn finish(&self) {
+ let _ = self.sender.try_send(TransportEvent::Exited(Instant::now()));
+ }
+
+ pub fn cancel(&self) {
+ let _ = self.terminal.set(ReceiptEvent::TransportError);
+ }
+
+ pub async fn changed(&self, remaining: Duration) {
+ let stream = self.clone();
+ // Include time queued for the blocking pool/channel mutex in the same
+ // budget. The GUI thread never performs a blocking pipe or channel read.
+ let deadline = Instant::now() + remaining;
+ let _ = tokio::task::spawn_blocking(move || {
+ if stream.terminal.get().is_some() {
+ return;
+ }
+ if let Ok(receiver) = stream.receiver.lock() {
+ let deadline = stream
+ .exited
+ .get()
+ .map_or(deadline, |at| deadline.min(*at + EXIT_DRAIN));
+ if let Ok(event) = receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
+ stream.record(event);
+ }
+ }
+ })
+ .await;
+ }
+}
+
+/// One terminal result, at most 4096 retained line bytes and one 8 KiB read.
+/// Acceptance is the end of the read batch containing the first valid frame.
+/// A second protocol prefix in that batch rejects it; later bytes are outside
+/// the acceptance boundary. Only the dedicated reader thread may block on I/O.
+fn read_receipts(mut reader: impl Read) -> ReceiptEvent {
+ let mut line = Vec::new();
+ let mut oversized = false;
+ let mut chunk = [0_u8; 8192];
+ loop {
+ let count = match reader.read(&mut chunk) {
+ Ok(0) => {
+ return if line.starts_with(START_RECEIPT_PREFIX.as_bytes()) {
+ ReceiptEvent::Invalid
+ } else {
+ ReceiptEvent::Eof
+ }
+ }
+ Ok(count) => count,
+ Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
+ Err(_) => return ReceiptEvent::TransportError,
+ };
+ let mut candidate = None;
+ for byte in &chunk[..count] {
+ if line.len() < START_RECEIPT_MAX_BYTES {
+ line.push(*byte);
+ } else {
+ oversized = true;
+ }
+ let protocol = line.starts_with(START_RECEIPT_PREFIX.as_bytes());
+ if protocol && (oversized || (line.len() == START_RECEIPT_MAX_BYTES && *byte != b'\n')) {
+ return ReceiptEvent::Invalid;
+ }
+ if protocol && candidate.is_some() {
+ return ReceiptEvent::Invalid;
+ }
+ if *byte == b'\n' {
+ if protocol {
+ match parse_frame(&line) {
+ Ok(receipt) => candidate = Some(receipt),
+ Err(()) => return ReceiptEvent::Invalid,
+ }
+ }
+ line.clear();
+ oversized = false;
+ }
+ }
+ if let Some(receipt) = candidate {
+ return ReceiptEvent::Receipt(receipt);
+ }
+ }
+}
+
+fn parse_frame(frame: &[u8]) -> Result<StartupReceipt, ()> {
+ if frame.len() > START_RECEIPT_MAX_BYTES
+ || !frame.starts_with(START_RECEIPT_PREFIX.as_bytes())
+ || !frame.ends_with(b"\n")
+ {
+ return Err(());
+ }
+ let payload = &frame[START_RECEIPT_PREFIX.len()..frame.len() - 1];
+ let receipt: StartupReceipt = serde_json::from_slice(payload).map_err(|_| ())?;
+ if receipt.schema_version != 1 {
+ return Err(());
+ }
+ match (&receipt.outcome, &receipt.reason) {
+ (StartupReceiptOutcome::Ready, None) => Ok(receipt),
+ (StartupReceiptOutcome::Failed, Some(_)) => Ok(receipt),
+ _ => Err(()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Cursor;
+ use std::process::{Command, Stdio};
+ use std::time::{Duration, Instant};
+
+ #[test]
+ fn accepts_only_the_v1_ready_shape() {
+ let frame = format!(
+ "{START_RECEIPT_PREFIX}{{\"schema_version\":1,\"outcome\":\"ready\",\"origin\":\"http://127.0.0.1:5123\"}}\n"
+ );
+ let receipt = parse_frame(frame.as_bytes()).expect("valid ready frame");
+ assert_eq!(receipt.outcome, StartupReceiptOutcome::Ready);
+ assert_eq!(receipt.reason, None);
+ }
+
+ #[test]
+ fn requires_a_reason_for_failed_and_rejects_unknown_fields() {
+ for payload in [
+ r#"{"schema_version":1,"outcome":"failed","origin":"http://127.0.0.1:5123"}"#,
+ r#"{"schema_version":1,"outcome":"ready","origin":"http://127.0.0.1:5123","reason":"startup_failed"}"#,
+ r#"{"schema_version":1,"outcome":"failed","origin":"http://127.0.0.1:5123","reason":"unknown"}"#,
+ r#"{"schema_version":1,"outcome":"ready","origin":"http://127.0.0.1:5123","extra":true}"#,
+ ] {
+ let frame = format!("{START_RECEIPT_PREFIX}{payload}\n");
+ assert_eq!(parse_frame(frame.as_bytes()), Err(()));
+ }
+ }
+
+ #[test]
+ fn frame_limit_counts_prefix_json_and_newline() {
+ let payload = format!(
+ "{START_RECEIPT_PREFIX}{{\"schema_version\":1,\"outcome\":\"ready\",\"origin\":\"{}\"}}\n",
+ "a".repeat(START_RECEIPT_MAX_BYTES)
+ );
+ assert_eq!(parse_frame(payload.as_bytes()), Err(()));
+ }
+
+ #[test]
+ fn ordinary_output_is_not_a_protocol_event() {
+ assert_eq!(
+ read_receipts(Cursor::new(b"Web UI:\nordinary output\n"),),
+ ReceiptEvent::Eof,
+ );
+ }
+
+ #[test]
+ fn malformed_truncated_and_conflicting_batches_are_terminal() {
+ let ready = format!(
+ "{START_RECEIPT_PREFIX}{{\"schema_version\":1,\"outcome\":\"ready\",\"origin\":\"http://127.0.0.1:80\"}}\n"
+ );
+ for bytes in [
+ format!("{START_RECEIPT_PREFIX}{{}}invalid\n{ready}"),
+ format!("{ready}{ready}"),
+ format!("{ready}{START_RECEIPT_PREFIX}"),
+ ready.trim_end().to_owned(),
+ format!("{START_RECEIPT_PREFIX}{}", "x".repeat(4096)),
+ ] {
+ assert_eq!(read_receipts(Cursor::new(bytes)), ReceiptEvent::Invalid,);
+ }
+ }
+
+ #[test]
+ fn exited_helper_does_not_wait_for_an_inherited_stdout_writer() {
+ let python = std::env::var_os("PYTHON").unwrap_or_else(|| "python3".into());
+ let mut child = Command::new(python).arg("-c").arg(
+ "import subprocess,sys; subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(0.8)'], stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL)"
+ ).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
+ let stream = StartupReceiptStream::spawn(child.stdout.take().unwrap(), BootstrapLog::disabled());
+ assert!(child.wait().unwrap().success());
+ let started = Instant::now();
+ stream.finish();
+ while stream.try_next().is_none() && started.elapsed() < Duration::from_millis(300) {
+ thread::sleep(Duration::from_millis(5));
+ }
+ assert_eq!(stream.try_next(), Some(ReceiptEvent::Eof));
+ assert!(started.elapsed() < Duration::from_millis(300));
+ // The controlled writer has a bounded lifetime and owns no Runtime.
+ thread::sleep(Duration::from_millis(800));
+ }
+
+ #[test]
+ fn python_producer_reaches_the_rust_stream_with_real_bytes() {
+ let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ let root = manifest_dir
+ .parent()
+ .and_then(std::path::Path::parent)
+ .expect("repository root");
+ let scratch = std::env::temp_dir().join(format!("avibe receipt with spaces 非 ASCII {}", std::process::id()));
+ std::fs::create_dir_all(&scratch).expect("scratch directory");
+ let python = std::env::var_os("PYTHON").unwrap_or_else(|| "python3".into());
+ let mut child = Command::new(&python)
+ .current_dir(&scratch)
+ .arg("-c")
+ .arg(
+ "import sys; print('x' * 5120); \
+ sys.path.insert(0, sys.argv[1]); \
+ from vibe.desktop_startup import emit_desktop_start_receipt; \
+ emit_desktop_start_receipt(origin='http://127.0.0.1:5123', outcome='ready')",
+ )
+ .arg(root)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .or_else(|_| {
+ Command::new("python")
+ .current_dir(&scratch)
+ .arg("-c")
+ .arg(
+ "import sys; print('x' * 5120); \
+ sys.path.insert(0, sys.argv[1]); \
+ from vibe.desktop_startup import emit_desktop_start_receipt; \
+ emit_desktop_start_receipt(origin='http://127.0.0.1:5123', outcome='ready')",
+ )
+ .arg(root)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ })
+ .expect("a Python interpreter is available");
+ let stdout = child.stdout.take().expect("receipt stdout pipe");
+ let stream = StartupReceiptStream::spawn(stdout, BootstrapLog::disabled());
+ let status = child.wait().expect("Python producer exits");
+ assert!(status.success());
+
+ let deadline = Instant::now() + Duration::from_secs(2);
+ let mut receipt = None;
+ while Instant::now() < deadline {
+ if let Some(ReceiptEvent::Receipt(value)) = stream.try_next() {
+ receipt = Some(value);
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ let receipt = receipt.expect("Python receipt reaches the Rust parser");
+ assert_eq!(receipt.schema_version, 1);
+ assert_eq!(receipt.outcome, StartupReceiptOutcome::Ready);
+ assert_eq!(receipt.origin, "http://127.0.0.1:5123");
+ std::fs::remove_dir_all(scratch).ok();
+ }
+
+ #[test]
+ fn real_stdout_batch_rejects_a_second_receipt_before_acceptance() {
+ let frame = format!(
+ "{START_RECEIPT_PREFIX}{{\"schema_version\":1,\"outcome\":\"ready\",\"origin\":\"http://127.0.0.1:5123\"}}\n"
+ );
+ let python = std::env::var_os("PYTHON").unwrap_or_else(|| "python3".into());
+ let mut child = Command::new(&python)
+ .arg("-c")
+ .arg(format!(
+ "import sys; sys.stdout.write({frame:?} + {frame:?}); sys.stdout.flush()"
+ ))
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .or_else(|_| {
+ Command::new("python")
+ .arg("-c")
+ .arg(format!(
+ "import sys; sys.stdout.write({frame:?} + {frame:?}); sys.stdout.flush()"
+ ))
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ })
+ .expect("a Python interpreter is available");
+ let stdout = child.stdout.take().expect("receipt stdout pipe");
+ let stream = StartupReceiptStream::spawn(stdout, BootstrapLog::disabled());
+
+ let deadline = Instant::now() + Duration::from_secs(2);
+ let mut event = None;
+ while Instant::now() < deadline {
+ if let Some(next) = stream.try_next() {
+ event = Some(next);
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ assert_eq!(event, Some(ReceiptEvent::Invalid));
+ assert!(child.wait().expect("Python producer exits").success());
+ }
+
+ #[test]
+ fn real_stdout_reports_an_oversized_prefixed_frame_without_waiting_for_newline() {
+ let python = std::env::var_os("PYTHON").unwrap_or_else(|| "python3".into());
+ let script = format!(
+ "import sys,time; sys.stdout.write({prefix:?} + 'x' * 4096); sys.stdout.flush(); time.sleep(1)",
+ prefix = START_RECEIPT_PREFIX,
+ );
+ let mut child = Command::new(&python)
+ .arg("-c")
+ .arg(&script)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .or_else(|_| {
+ Command::new("python")
+ .arg("-c")
+ .arg(&script)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ })
+ .expect("a Python interpreter is available");
+ let stdout = child.stdout.take().expect("receipt stdout pipe");
+ let stream = StartupReceiptStream::spawn(stdout, BootstrapLog::disabled());
+
+ let deadline = Instant::now() + Duration::from_secs(2);
+ let mut event = None;
+ while Instant::now() < deadline {
+ if let Some(next) = stream.try_next() {
+ event = Some(next);
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ assert_eq!(event, Some(ReceiptEvent::Invalid));
+ assert!(
+ child.try_wait().unwrap().is_none(),
+ "oversize is terminal before newline or child exit"
+ );
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+}
diff --git a/desktop/runtime-host/tests/bootstrap.rs b/desktop/runtime-host/tests/bootstrap.rs
index b991ad5ca..23e0a992a 100644
--- a/desktop/runtime-host/tests/bootstrap.rs
+++ b/desktop/runtime-host/tests/bootstrap.rs
@@ -1470,7 +1470,9 @@ async fn concurrent_bootstraps_start_at_most_one_runtime() {
let (left, right) = (Recorder::default(), Recorder::default());
let (first, second) = tokio::join!(host.bootstrap(&left, Launch), host.bootstrap(&right, Launch));
- assert_eq!(first.phase, BootstrapPhase::Ready);
+ // The newer run owns admission. An older in-flight probe must not publish
+ // Ready after that run has replaced its epoch, even for the same endpoint.
+ assert_eq!(first.phase, BootstrapPhase::Failed);
assert_eq!(second.phase, BootstrapPhase::Ready);
assert_eq!(launcher.calls(), 1, "two racing runs must not start two Runtimes");
assert_eq!(
diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs
index 89f44aaa8..21047b69a 100644
--- a/desktop/src-tauri/src/lib.rs
+++ b/desktop/src-tauri/src/lib.rs
@@ -43,10 +43,10 @@ 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, RemovalOutcome, BOOTSTRAP_LOG_NAME};
+use avibe_runtime_host::{bundled_runtime_host, RemovalOutcome, BOOTSTRAP_LOG_NAME};
use avibe_runtime_host::{
- is_shell_ui_url, wait_for_shell_ui_url, BootstrapNotice, BootstrapNoticeCode, BootstrapPhase, BootstrapStatus,
- BootstrapTrigger, CliOutcome, LoopbackOrigin, RuntimeHost, StatusSink, SHELL_UI_URL_TIMEOUT,
+ is_shell_ui_url, wait_for_shell_ui_url, BootstrapLog, BootstrapNotice, BootstrapNoticeCode, BootstrapPhase,
+ BootstrapStatus, BootstrapTrigger, CliOutcome, LoopbackOrigin, RuntimeHost, StatusSink, SHELL_UI_URL_TIMEOUT,
};
use serde::Deserialize;
use tauri::menu::{CheckMenuItem, Menu, MenuItem, MenuItemKind, PredefinedMenuItem, Submenu};
@@ -315,6 +315,7 @@ fn native_uninstall_catalog() -> NativeUninstallCatalog {
/// needs without borrowing from the managed state across an await point.
struct Shell {
host: Arc<RuntimeHost>,
+ diagnostics: BootstrapLog,
latest: Arc<Mutex<Option<BootstrapStatus>>>,
activity: Arc<AtomicU8>,
active_origin: Arc<Mutex<Option<LoopbackOrigin>>>,
@@ -327,9 +328,10 @@ struct Shell {
}
impl Shell {
- fn new(host: RuntimeHost) -> Self {
+ fn new(host: RuntimeHost, diagnostics: BootstrapLog) -> Self {
Self {
host: Arc::new(host),
+ diagnostics,
latest: Arc::new(Mutex::new(None)),
activity: Arc::new(AtomicU8::new(ACTIVITY_IDLE)),
active_origin: Arc::new(Mutex::new(None)),
@@ -1493,6 +1495,9 @@ fn open_workbench(app: &AppHandle, ready: &BootstrapStatus, activity: Arc<Atomic
.publish(workbench_navigation_failure_status(ready, &origin));
return;
}
+ app.state::<Shell>()
+ .diagnostics
+ .record("runtime.start.navigation", &[("outcome", "success".to_owned())]);
match complete_workbench_handoff(&activity, &window_generation, observed_generation) {
WorkbenchHandoff::Monitor => {
commit_deep_link_navigation(app, &navigation, true, observed_generation);
@@ -2450,7 +2455,9 @@ pub fn run() {
default_runtime_host()?
}
};
- app.manage(Shell::new(host));
+ #[cfg(not(feature = "bundled-runtime"))]
+ let bootstrap_log = BootstrapLog::disabled();
+ app.manage(Shell::new(host, bootstrap_log.clone()));
#[cfg(target_os = "macos")]
app.manage(computer_use::Controller::start(app.handle()));
app.manage(notifications::Notifications::new(
diff --git a/desktop/src-tauri/tests/shell_boundaries.rs b/desktop/src-tauri/tests/shell_boundaries.rs
index c7adf991a..422d37401 100644
--- a/desktop/src-tauri/tests/shell_boundaries.rs
+++ b/desktop/src-tauri/tests/shell_boundaries.rs
@@ -42,7 +42,8 @@ fn shipping_source(relative: &str) -> String {
/// every check here must read the same text on every platform.
fn shipping_text(source: &str) -> String {
let source = source.replace("\r\n", "\n");
- match source.find("#[cfg(test)]") {
+ // Individual test-only methods may occur before more shipping code.
+ match source.find("#[cfg(test)]\nmod tests") {
Some(offset) => source[..offset].to_owned(),
None => source,
}
diff --git a/docs/plans/2026-10-31-desktop-ready-receipt.md b/docs/plans/2026-10-31-desktop-ready-receipt.md
new file mode 100644
index 000000000..edfbae3a7
--- /dev/null
+++ b/docs/plans/2026-10-31-desktop-ready-receipt.md
@@ -0,0 +1,274 @@
+# Desktop startup readiness receipt
+
+## Outcome
+
+The bundled desktop shell will launch the Runtime through an opt-in startup
+mode that returns one bounded, machine-readable result when Python has proved
+both the Controller and the UI usable. The shell will use that result to avoid
+running a second full `/ready` polling loop, then perform one bounded final
+identity/presence check against the exact endpoint before navigation.
+
+Ordinary `vibe start`, external launchers, `AVIBE_DESKTOP_ORIGIN`, Runtime
+identity/provenance, scoped stop, handover, rollback, and the NSIS preparation
+path retain their existing contracts.
+
+## Change contract
+
+- **CLI:** `vibe start --desktop-receipt` is hidden and opt-in. The bundled
+ Runtime uses it together with `--no-open-browser` and hidden
+ `--desktop-ready-timeout <seconds>` carrying the shell-validated budget; ordinary callers do not
+ receive or depend on the new line.
+- **Wire framing:** Python writes at most one line beginning with
+ `@avibe-desktop-start:` followed by compact UTF-8 JSON and `\n` on stdout.
+ The complete UTF-8 frame, including the prefix and newline, is bounded to
+ 4096 bytes by both producer and consumer. Byte length, rather than character
+ count, is the contract.
+- **Schema:** version `1` contains `schema_version`, `outcome`, and `origin`.
+ `outcome` is `ready` or `failed`; `reason` is required only for `failed` and
+ is one of the stable bounded startup/refusal codes documented below.
+ `origin` is the validated loopback origin computed by Python from the
+ existing V2 config/listener owner. A pre-resolution failure, including a
+ claim or handover failure before a validated origin exists, emits no receipt
+ and exits through its existing nonzero mapping. Once the origin is known, a
+ failed receipt is emitted after rollback has finished.
+- **Startup commit boundary:** `ready` is an irreversible observation of the
+ startup commit. Python completes all failure-prone startup and ownership
+ work, including the shared service/UI readiness check, status publication,
+ identity claim, and any rollback decision, before writing the ready frame.
+ Python marks the startup committed immediately before publishing the ready
+ frame. Optional install-generation housekeeping runs after that publication
+ and is warning-only; it cannot delay Workbench admission or revoke the
+ committed Runtime. A broken pipe or other ordinary output failure after that
+ point cannot roll back the Runtime or emit a failed frame.
+ The reader validates the entire read batch (at most 8192 bytes) containing
+ the first complete frame. A second protocol prefix in that batch rejects it.
+ Rust accepts that one terminal result only after checking origin and any
+ already observed helper failure. A malformed frame or oversized prefixed
+ line is terminal immediately, even without a newline. The verdict is sent
+ after this batch; admission does not wait for the reader's subsequent drain
+ to EOF. Acceptance is a temporal
+ boundary: a helper exit or additional output racing after it cannot
+ retroactively defeat startup. The final exact-origin presence/identity check
+ remains authoritative and may still reject navigation; later Runtime loss
+ belongs to the existing monitor and is not converted into a second startup
+ verdict. This deliberately does not claim that a stream reader can reject
+ events that occur after navigation.
+- **Readiness owner:** Python owns startup readiness and cleanup. The
+ receipt-capable path starts the service and UI through the existing
+ `runtime` primitives, launches the UI without waiting for service readiness,
+ and checks the UI and Controller together under one shared remaining startup
+ deadline. The Python desktop readiness probe uses the existing httpx
+ dependency with `trust_env=False` and `follow_redirects=False`, and probes
+ only the exact loopback `/ready`. LAN `/health` is not a desktop gate.
+ Each entire response (including its body, bounded to 1024 bytes) is bounded
+ by the smaller of 5 seconds and the remaining deadline; streamed bytes cannot
+ reset that budget. Service provenance still passes through the existing
+ `claim_ready_service`. Rust owns desktop policy, receipt validation, the bounded
+ attempt budget, adoption/handover rules, and the final `/ready`
+ identity/presence check. If Rust's observation budget expires while the
+ helper is still in-flight, the helper remains retained by the existing launch
+ state so Retry cannot launch a duplicate.
+- **Transport lifetime (2026-11-01 source decision):** use ordinary blocking
+ `std::io::Read` on the existing dedicated thread, with a bounded channel to
+ the admission state machine. No platform pipe adapter or added dependency.
+ Channel waits spend only the shared remaining deadline. The helper reaper
+ signals exit; a successful exit allows at most 100 ms to receive an already
+ written frame. Accept/fail/timeout is final for that observer; later results
+ cannot change it. After its first frame the reader discards remaining stdout
+ through EOF without affecting admission. Current service/UI spawn primitives
+ redirect stdout/stderr to log sinks and close unrelated handles; the sinks
+ also redirect their output and close unrelated handles. A real cmd_start
+ fixture must prove EOF after helper exit while its child is still alive, on
+ both macOS and Windows CI. Residual: a future descendant incorrectly inheriting
+ receipt stdout can leave one idle reader thread blocked until it exits.
+ Admission, rollback, navigation and Retry deduplication remain bounded and
+ unaffected. This is an explicit accepted limitation, not a claim that EOF is
+ guaranteed for arbitrary descendants.
+- **Rust consumer:** bundled launch reads the actual child stdout while it is
+ running, drains it without waiting for pipe EOF, rejects malformed,
+ oversized, stale, or wrong-origin receipts, plus duplicate/contradictory
+ prefixes within the documented read batch, and navigates only after a
+ `ready` receipt plus a final
+ `Presence::Mine` or allowed unmanaged/adopted result. A missing receipt while
+ the helper is alive is pending; helper failure, timeout, broken output, or a
+ failed receipt is terminal failure. A final probe contradiction never falls
+ back to receipt success. The endpoint helper remains for endpoint discovery
+ and is not replaced by an unsafe Rust config guess.
+- **Exit mapping:** `ready` requires helper success or an observed still-running
+ helper plus the final readiness check; a nonzero exit observed before
+ acceptance is failure.
+ Receipt `failed` is failure and preserves existing retryability. Legacy
+ launchers continue using the existing `vibe start` plus Rust readiness path.
+- **Failure reasons:** after origin resolution, Python emits only
+ `startup_failed`, `handover_refused`, `handover_failed`,
+ `runtime_claim_refused`, or `runtime_not_ready`. The Rust consumer maps
+ `failed` to the existing retryable startup failure notices and preserves
+ exit/refusal distinctions from the helper. A `RuntimeError` raised inside the
+ guarded service/UI/readiness region maps to `runtime_not_ready`; other
+ unexpected failures map to `startup_failed`. Pre-resolution failures carry no
+ receipt, so Rust never has to trust a guessed origin.
+- **Ownership:** the receipt is an observation/transport optimization. It does
+ not grant stop, quit, uninstall, handover, or process ownership authority.
+ The expected Runtime ID and the final exact-origin `/ready` identity/presence
+ check remain authoritative; the receipt intentionally does not duplicate
+ identity fields.
+
+## Removed wait and evidence
+
+The bundled path removes the Rust full startup `/ready` polling loop that
+duplicates Python's service/UI readiness work. The remaining Rust probe is a
+single final check immediately before navigation. This removes duplicate
+probes, not helper processes, and may or may not reduce elapsed cold-start time; it does not
+promise a Windows speedup from historical Mac measurements. Existing bounded
+bootstrap diagnostics now mark receipt arrival, receipt acceptance, final
+presence verification, and successful navigation alongside the existing
+endpoint/start records. Helper/probe counts and elapsed time can therefore be
+compared on identical hermetic fixtures. Early-ready and slow-controller
+fixtures must show that navigation does not move later than the current path.
+The timing report separates time to Python readiness, receipt acceptance, the
+final probe, and navigation; a timeout comparison alone is not startup-speed
+evidence.
+
+## Verification
+
+### Review breaker scope (2026-11-01)
+
+The orchestrator independently confirmed the second findings-bearing head and
+authorized one combined correction: preserve the replaced Rust probe's 5-second
+whole-response allowance, pass the shell's validated startup timeout to Python,
+and acknowledge an already-presented FAILED result on its retained attempt.
+No identity, stop authority, ownership, rollback, or platform transport changes
+are part of this correction. Tests must cover healthy 700 ms / 2.5 s responses,
+one non-resetting total deadline, the shell override reaching actual cmd_start,
+and retained-attempt transitions before and after helper exit. The compatibility
+inventory below will record every preserved or intentional difference against
+master `bc6cd410ccb26cacc5fbd422f8198371bd272892`.
+
+
+### Replaced-wait compatibility inventory
+
+All old locations below refer to that frozen master commit, not this branch's
+moving line numbers. The final Rust presence probe and its identity classifier
+remain in place; Python supplies readiness observation, never ownership.
+
+| Property | Old Rust behavior / master source | New producer and consumer behavior | Status / reason | Pinning evidence |
+| --- | --- | --- | --- | --- |
+| Whole-response request budget | 5 s, `desktop/runtime-host/src/bootstrap.rs:40`; reqwest total timeout in `health.rs:48` | `min(5 s, remaining)` around the entire HTTP response, including streamed body | Preserved; the accidental 500 ms cap is removed | `test_desktop_startup_readiness_uses_direct_no_redirect_http` real 700 ms and 2.5 s healthy responses; drip case below |
+| Poll cadence / first probe | Sleep 500 ms before each Rust request, `bootstrap.rs:507` | Immediate Python observation, then 100 ms between incomplete observations; the existing Python readiness cadence remains | Intentionally changed: consolidate onto Python's existing cadence without delaying early readiness behind a new 500 ms sleep | Repeated actual `cmd_start_receipt_admission`; `starting` and transport-error cases require multiple requests under one budget |
+| Default total budget / override | 120 s; `AVIBE_DESKTOP_READY_TIMEOUT_SECONDS`, integer 1..600; invalid values ignored, `bootstrap.rs:24`, `:33`, `:80`, `:94` | Shell still parses/validates it. `launch_with_ready_timeout` passes the resolved duration using `--desktop-ready-timeout`; actual CLI parser routes it to cmd_start | Preserved, including overrides above 120 s. Python no longer silently hard-codes 120 s for a shell-selected duration | `a_timeout_override_must_be_a_positive_bounded_number_of_seconds`; real `cmd_start_receipt_timeout_override` (env → shell settings → host → production argv builder → Python parser/actual wait), CLI 1/600 s remaining-budget cases; OS argv contract |
+| Deadline across retries / phases | One outer deadline; checked before sleep/probe, `bootstrap.rs:507` (a final probe could overrun it) | One producer deadline covers service/UI launch and remaining HTTP wait. Each request/sleep is capped by remaining time. Shell observation and final verification also cannot reset their deadline; a still-live helper is retained when shell observation expires | Preserved non-resetting budget, intentionally stricter bound on the last request. Interpreter/config/handover work retains its existing lifecycle limits; observation timeout grants no kill authority | `test_desktop_ready_request_body_has_one_deadline_and_size_bound`; CLI shared-readiness test; final-probe deadline and retained-helper tests |
+| Proxy / redirects | `.no_proxy()`, redirect policy none, `health.rs:49` | `trust_env=False`, `follow_redirects=False`; only exact loopback `/ready`, not LAN `/health` | Preserved | Real inherited-proxy traps and redirect listener tests |
+| Refused connection / timeout / incomplete response | Refused → Absent; other errors → Unknown, `health.rs:65`; both keep waiting while helper is viable, `bootstrap.rs:514` | HTTP failure or non-affirmative payload keeps waiting while the service is viable, spending remaining budget. Service death still fails via existing Python cleanup | Preserved retry classification, with existing Python service-death cleanup retained | Controlled HTTPX connection/timeout errors; `starting`, `malformed`, `drip` body cases; cmd_start created/reused rollback tests |
+| HTTP / payload / identity | Strict successful schema, product, boolean and identity format; 503 identity mismatch is non-ready, `health.rs:75`, `:135`, `:170` | Shared Python strict payload predicate; only affirmative `/ready` can produce READY. Initial/final Rust `Presence` checks still enforce Mine/Foreign/Unmanaged and recovery policy | Preserved. Receipt never substitutes for the final current endpoint/identity check | Existing payload/identity fixtures, malformed body, final-presence contradiction, adoption/recovery tests |
+| Origin | Literal safe loopback via `origin.rs:58`; URL origin canonicalization | Python supplies config-derived endpoint; receipt parsed through the same Rust boundary, including default port and IPv6 | Preserved | `receipt_origin_comparison_uses_the_loopback_canonical_form` (IPv4 + IPv6); Python origin tests; unsafe origin boundary tests |
+| Response encoding / size | UTF-8 only, maximum 1024 bytes; reject oversized Content-Length and streamed bodies, `health.rs:9`, `:106` | Raw identity-encoded bytes and explicit UTF-8 decode (no implicit decompression), 1024-byte header/body bound before accumulation; same whole-response timeout even with drip output | Preserved; inventory also closed Python bytes-JSON auto-detection and missing early Content-Length rejection | `utf16`, `compressed`, `oversized`, `oversized-stream`, `drip` cases in the real HTTP body-bound test |
+| Attempt failure / Retry | A previously unseen nonzero exit is reported once; live helper retained, `bootstrap.rs:557`, `:571` | Origin-valid FAILED is acknowledged on that attempt after publication. A live helper remains deduped; once it exits, first Retry releases its slot and launches exactly once. Unreported exits retain their old notice/Retry semantics | Preserved user-visible Retry behavior with receipt-before-exit ordering accounted for | `retained_receipt_attempt_transitions_preserve_first_retry_and_live_deduplication` |
+
+The only intentional differences in the moved wait are the existing Python
+100 ms cadence / immediate observation, and stricter enforcement of the last
+request's remaining deadline. Neither weakens usable-state evidence or makes
+an observation timeout authority to stop reused state.
+
+### Retained-attempt transition inventory
+
+The table test covers each exit as generic failure, handover refusal, and
+handover failure; the acknowledgement lives on the attempt's LaunchWatch and
+cannot transfer to a newer attempt. Origin validation precedes acknowledgement.
+
+| First observation | Retry while helper is live | First Retry after nonzero exit |
+| --- | --- | --- |
+| Valid FAILED receipt, already published | Same failure, no duplicate launcher | Release slot and launch once in this Retry |
+| Wrong-origin FAILED | Refuse, no duplicate launcher | Report previously unseen exit; following Retry may launch |
+| EOF without receipt | Refuse, no duplicate launcher | Report previously unseen exit once |
+| Observation deadline / cancelled receipt observation | No overlapping helper | Report previously unseen exit once |
+| Healthy attempt, Runtime still ready | Adopt live Runtime | Adopt live Runtime; late helper exit cannot revoke readiness |
+| Legacy helper without receipts | Retain while pending | Preserve old notice and subsequent-Retry behavior |
+
+Explicit Stop/newer-run races continue to be pinned separately by
+`a_newer_attempt_or_stop_fences_a_receipts_in_flight_final_probe` and the existing
+stop/ownership fence tests. A cancelled observation is not Runtime Stop.
+
+### Verification gates
+
+1. Parser-backed Python CLI tests cover the hidden invocation and preserve
+ ordinary `vibe start` semantics.
+2. Python tests exercise complete, failed, duplicate, and cleanup outcomes.
+3. Rust tests cover the receipt parser and bootstrap state transitions,
+ including wrong origin/identity, Retry/Stop during final verification, malformed
+ or oversized output, helper
+ failure, delayed output, retry, close, handover, and reuse.
+4. A hermetic cross-language fixture sends real Python-produced stdout through
+ the Rust parser/state-machine boundary, including spaces and non-ASCII paths.
+5. Temporal tests cover transport failure before successful publication, the
+ ready commit boundary, terminal malformed/oversized output, duplicate output
+ already buffered in one real stdout batch, helper observation timeout with
+ retry deduplication, canonical default-port origins, and final probe
+ contradiction.
+6. The hermetic timing fixture has early-ready and delayed-controller outcomes
+ with repeated samples and real Python stdout consumption. Baseline and
+ candidate traces report helper/probe counts and time to each startup
+ milestone separately. The report distinguishes actual reductions from
+ remaining Windows packaged/manual acceptance.
+7. Focused Python tests, Ruff, Rust tests, and desktop shell boundary checks
+ run before the PR. Windows packaged/manual acceptance remains a handoff item.
+
+## Local integration evidence (2026-11-01)
+
+The explicit cross-language gate runs actual `cmd_start` and its parser,
+readiness HTTP, private status writes and stdout through the production Rust
+reader and `RuntimeHost` with `HttpHealthProbe`, including the expected identity.
+The bootstrap log records receipt arrival/acceptance and final verification. Process creation and Controller
+scheduling use controlled fixture seams; this is not a full installed Runtime
+or native Windows benchmark. Every subprocess has an empty inherited environment
+and private HOME/XDG/Avibe/credential directories under a path with spaces and
+non-ASCII characters. It never contacts user services. No endpoint helper is
+removed: production still uses one discovery helper and one start helper.
+
+Three fresh helper processes per mode and scenario (after fixture Python imports
+and endpoint initialization), same debug build and
+production 500 ms legacy polling interval, all reached successful admission:
+
+| Scenario | Legacy admission (ms) | Receipt admission (ms) | Rust probes, legacy → receipt |
+| --- | --- | --- | --- |
+| Early ready | 505.0, 507.1, 510.7 | 106.8, 94.7, 93.5 | 2 → 2 |
+| Controller delayed 1.1 s | 1526.6, 1517.0, 1516.5 | 1158.2, 1160.9, 1157.4 | 4 → 2 |
+| Housekeeping delayed 1.2 s | 505.3, 504.4, 504.5 | 93.5, 92.2, 96.9 | 2 → 2 |
+
+Admission means `RuntimeHost` permits navigation, not rendered WebView latency.
+The initial adoption probe is included. Python used one `/ready` for early and
+housekeeping cases; delayed Controller used 11–12 baseline and 11 candidate
+probes. Baseline additionally called `/health` on each Python poll; candidate
+made zero `/health` requests. All cases started one fixture service and one
+fixture UI, then reused the live endpoint on Retry without another launch.
+Candidate admission preceded housekeeping completion in every delayed sample
+(the helper completed around 1293.1–1311.2 ms). The former 30 ms comparison is a
+**timeout/probe-count test only**, not time-to-ready performance evidence.
+
+Run the integration gate explicitly (ignored in ordinary Cargo tests because it
+needs the repository Python dependencies):
+
+```sh
+AVIBE_TEST_PYTHON="$PWD/.venv/bin/python" cargo test \
+ --manifest-path desktop/Cargo.toml -p avibe-runtime-host \
+ cmd_start_receipt_admission -- --ignored --nocapture
+```
+
+Both desktop CI platforms install the existing locked Python dependencies
+without an editable project build and explicitly run
+`cmd_start_stdout_reaches_eof_while_runtime_children_remain_alive`. This uses
+actual `cmd_start` and the service/UI spawn primitives plus their real log
+sinks, then proves receipt-pipe EOF after launcher exit while both spawned
+children acknowledge a later liveness request. The fixture owns all child
+state and stops them with bounded test controls. It does not mock pipe reads,
+Popen, log-sink setup, descriptor inheritance, or process isolation.
+Its HTTP listener binds a numeric loopback address without reverse DNS.
+The macOS CI initialization stack exposed `HTTPServer.server_bind` waiting in
+`socket.getfqdn`; a DNS trap reproduces the original fixture failure and the
+corrected fixture reaches READY and EOF with that lookup forbidden. This
+changes fixture setup only, outside the measured startup interval, and leaves
+the 15-second initialization and 1-second post-exit EOF checks intact.
+
+Windows CI covers the native pipe reader and shell build. Packaged cold/warm
+NSIS launch, release-matched identity/handover, UI/controller failures, and
+close/retry acceptance still require the Windows artifact. These local results
+make no Windows elapsed-time claim.
diff --git a/tests/fixtures/desktop_startup_process.py b/tests/fixtures/desktop_startup_process.py
new file mode 100644
index 000000000..34b9c7f30
--- /dev/null
+++ b/tests/fixtures/desktop_startup_process.py
@@ -0,0 +1,184 @@
+"""Hermetic cmd_start producer for the Rust startup admission integration test.
+
+Only process creation/controller ownership and optional housekeeping are controlled.
+cmd_start, both readiness paths, status writes, wire serialization, HTTP and stdout
+are production code. No backend, keychain, browser, or user service is contacted.
+The Rust parent supplies an empty environment with private homes before imports.
+"""
+from __future__ import annotations
+
+import faulthandler
+import json
+import os
+from pathlib import Path
+import sys
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from socketserver import TCPServer
+from types import SimpleNamespace
+
+# A slow import or listener initialization must identify its blocking call in
+# CI before the Rust parent's 15-second fixture initialization deadline.
+faulthandler.dump_traceback_later(10, file=sys.stderr)
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+from vibe import cli, runtime # noqa: E402
+from vibe import install_generations # noqa: E402
+
+scratch = Path(sys.argv[1])
+mode, delay, housekeeping = sys.argv[2], float(sys.argv[3]), float(sys.argv[4])
+case = sys.argv[5]
+controller_ready = threading.Event()
+trace = {"python_ready_probes": 0, "health_probes": 0, "service_starts": 0, "ui_starts": 0}
+started = 0.0
+service_pid = os.getpid()
+
+# In the EOF case these children and their real log sinks outlive cmd_start.
+# Their bounded lifetime and explicit stop file also cover assertion failures.
+child_script = """
+import os,sys,time
+from pathlib import Path
+root, role = Path(sys.argv[1]), sys.argv[2]
+deadline = time.monotonic() + 30
+while not (root / 'children-stop').exists() and time.monotonic() < deadline:
+ if (root / 'prove-alive').exists():
+ (root / (role + '-alive')).write_text(str(os.getpid()))
+ print(role, flush=True)
+ time.sleep(0.02)
+(root / (role + '-done')).touch()
+"""
+
+
+class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ ready = controller_ready.is_set()
+ if self.path == "/health":
+ trace["health_probes"] += 1
+ body, status = b"{}", 200
+ elif self.path == "/ready":
+ if self.headers.get("User-Agent", "").lower().startswith("python"):
+ trace["python_ready_probes"] += 1
+ payload = {"schema_version": 1, "product": "avibe", "ready": ready}
+ if ready:
+ payload["desktop_runtime_id"] = "b" * 64
+ else:
+ payload["code"] = "controller_unavailable"
+ body, status = json.dumps(payload).encode(), 200 if ready else 503
+ else:
+ body, status = b"", 404
+ self.send_response(status)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_args):
+ pass
+
+
+class LoopbackHTTPServer(ThreadingHTTPServer):
+ def server_bind(self):
+ # HTTPServer's display-name lookup performs reverse DNS even for
+ # 127.0.0.1. The fixture needs only the numeric bound address.
+ TCPServer.server_bind(self)
+ self.server_name, self.server_port = self.server_address[:2]
+
+
+server = LoopbackHTTPServer(("127.0.0.1", 0), Handler)
+thread = threading.Thread(target=server.serve_forever, daemon=True)
+thread.start()
+port = server.server_address[1]
+config = SimpleNamespace(
+ has_configured_platform_credentials=lambda: True,
+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=port, open_browser=False),
+)
+cli._ensure_config = lambda: config
+cli._guard_cli_default_state_migration = lambda: None
+cli.cache_running_vibe_path = lambda: None
+runtime.resolve_service_owner_pid = lambda **kwargs: service_pid if controller_ready.is_set() else None
+runtime.service_instance_started = lambda _pid: controller_ready.is_set()
+
+
+def start_service(*, start_info, **kwargs):
+ global service_pid
+ trace["service_starts"] += 1
+ if case == "eof":
+ child = runtime.spawn_service_background_process(
+ [sys.executable, "-c", child_script, str(scratch), "service"],
+ "service-stdout.log", "service-stderr.log",
+ )
+ service_pid = child.pid
+ start_info.capture(child.pid, reused=False)
+ else:
+ start_info.capture(service_pid, reused=True)
+
+ def become_ready():
+ time.sleep(delay)
+ trace["controller_ms"] = (time.monotonic() - started) * 1000
+ controller_ready.set()
+
+ threading.Thread(target=become_ready, daemon=True).start()
+ return service_pid
+
+
+def start_ui(host, port, *, start_info, wait_for_ready=True):
+ trace["ui_starts"] += 1
+ if case == "eof":
+ pid = runtime.spawn_background(
+ [sys.executable, "-c", child_script, str(scratch), "ui"],
+ scratch / "ui.pid", "ui-stdout.log", "ui-stderr.log",
+ start_info=start_info,
+ )
+ else:
+ pid = os.getpid()
+ start_info.capture(pid, reused=True)
+ if wait_for_ready:
+ runtime.wait_for_ui_server(host, port)
+ return pid
+
+
+def wait_service(pid, timeout):
+ return pid if controller_ready.wait(timeout) else None
+
+
+def housekeeping_work(*_args):
+ trace["housekeeping_start_ms"] = (time.monotonic() - started) * 1000
+ (scratch / "housekeeping-started").touch()
+ time.sleep(housekeeping)
+ (scratch / "housekeeping-finished").touch()
+
+
+runtime.start_service = start_service
+runtime.start_ui = start_ui
+runtime.wait_for_service_ready = wait_service
+install_generations.collect_install_generations = housekeeping_work
+(scratch / "endpoint.tmp").write_text(f"http://127.0.0.1:{port}", encoding="utf-8")
+(scratch / "endpoint.tmp").replace(scratch / "endpoint")
+faulthandler.cancel_dump_traceback_later()
+try:
+ invocation = sys.stdin.readline().strip()
+ started = time.monotonic()
+ args = cli.build_parser().parse_args(
+ ["start", "--no-open-browser"] + (["--desktop-receipt"] if mode == "receipt" else [])
+ if invocation == "start" else json.loads(invocation)
+ )
+ try:
+ result = cli.cmd_start(
+ open_browser=args.open_browser,
+ desktop_receipt=args.desktop_receipt,
+ desktop_ready_timeout=args.desktop_ready_timeout,
+ )
+ except RuntimeError:
+ if case != "budget":
+ raise
+ result = 1
+ trace["result"] = result
+ trace["ready_timeout"] = args.desktop_ready_timeout
+ trace["helper_work_ms"] = (time.monotonic() - started) * 1000
+ (scratch / "trace.json").write_text(json.dumps(trace), encoding="utf-8")
+ assert result == (1 if case == "budget" else 0)
+ assert sys.stdin.readline().strip() == "done"
+ sys.exit(result)
+finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
diff --git a/tests/test_desktop_runtime.py b/tests/test_desktop_runtime.py
index eb76f657f..06748f8b1 100644
--- a/tests/test_desktop_runtime.py
+++ b/tests/test_desktop_runtime.py
@@ -9,6 +9,7 @@ import subprocess
import sys
import threading
import urllib.error
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
@@ -526,6 +527,217 @@ def test_ui_server_readiness_reuses_wildcard_listener(monkeypatch):
]
[email protected]("response_delay", [0.0, 0.7, 2.5])
+def test_desktop_startup_readiness_uses_direct_no_redirect_http(monkeypatch, response_delay):
+ """Healthy Controller responses may use the former Rust probe's budget."""
+ import time
+
+ requests = []
+ proxy_requests = []
+
+ class RuntimeHandler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ requests.append(self.path)
+ time.sleep(response_delay)
+ if self.path == "/health":
+ body = b""
+ elif self.path == "/ready":
+ body = b'{"schema_version":1,"product":"avibe","ready":true}'
+ else:
+ self.send_response(404)
+ self.end_headers()
+ return
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ try:
+ self.wfile.write(body)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+ def log_message(self, *_args):
+ return
+
+ class ProxyTrapHandler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ proxy_requests.append(self.path)
+ self.send_response(502)
+ self.end_headers()
+
+ def log_message(self, *_args):
+ return
+
+ runtime_server = ThreadingHTTPServer(("127.0.0.1", 0), RuntimeHandler)
+ proxy_server = ThreadingHTTPServer(("127.0.0.1", 0), ProxyTrapHandler)
+ runtime_thread = threading.Thread(target=runtime_server.serve_forever, daemon=True)
+ proxy_thread = threading.Thread(target=proxy_server.serve_forever, daemon=True)
+ runtime_thread.start()
+ proxy_thread.start()
+ try:
+ runtime_port = runtime_server.server_address[1]
+ proxy_port = proxy_server.server_address[1]
+ monkeypatch.setenv("NO_PROXY", "")
+ monkeypatch.setenv("no_proxy", "")
+ monkeypatch.setenv("http_proxy", f"http://127.0.0.1:{proxy_port}")
+ monkeypatch.setenv("HTTP_PROXY", f"http://127.0.0.1:{proxy_port}")
+ monkeypatch.setenv("HTTPS_PROXY", f"http://127.0.0.1:{proxy_port}")
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **kwargs: None)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda _pid: True)
+ monkeypatch.setattr(runtime, "pid_alive", lambda _pid: True)
+
+ assert runtime.wait_for_desktop_startup_ready(
+ 1234,
+ "127.0.0.1",
+ runtime_port,
+ timeout=4.0,
+ ) == 1234
+ finally:
+ runtime_server.shutdown()
+ proxy_server.shutdown()
+ runtime_server.server_close()
+ proxy_server.server_close()
+ runtime_thread.join(timeout=2)
+ proxy_thread.join(timeout=2)
+
+ assert requests == ["/ready"]
+ assert proxy_requests == []
+
+
+def test_desktop_startup_readiness_rejects_redirects(monkeypatch):
+ requests = []
+
+ class RedirectHandler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ requests.append(self.path)
+ self.send_response(302)
+ self.send_header("Location", f"http://127.0.0.1:{self.server.server_address[1]}/ready")
+ self.end_headers()
+
+ def log_message(self, *_args):
+ return
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), RedirectHandler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **kwargs: None)
+ monkeypatch.setattr(runtime, "service_instance_started", lambda _pid: True)
+ monkeypatch.setattr(runtime, "pid_alive", lambda _pid: True)
+ assert (
+ runtime.wait_for_desktop_startup_ready(
+ 1234,
+ "127.0.0.1",
+ server.server_address[1],
+ timeout=0.1,
+ )
+ is None
+ )
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+ assert requests == ["/ready"]
+
+
[email protected]("error_type", ["ConnectError", "ReadTimeout"])
+def test_desktop_readiness_retries_transport_errors_within_one_budget(monkeypatch, error_type):
+ import httpx
+ import time
+
+ observations = []
+
+ def fail_request(request):
+ observations.append(request.url.path)
+ raise getattr(httpx, error_type)("test transport failure", request=request)
+
+ client = httpx.AsyncClient
+ monkeypatch.setattr(
+ httpx, "AsyncClient",
+ lambda **kwargs: client(transport=httpx.MockTransport(fail_request), **kwargs),
+ )
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **_kwargs: 1234)
+ monkeypatch.setattr(runtime, "pid_alive", lambda _pid: True)
+ started = time.monotonic()
+ assert runtime.wait_for_desktop_startup_ready(
+ 1234, "127.0.0.1", 5123, timeout=0.2,
+ ) is None
+ assert time.monotonic() - started < 0.5
+ assert len(observations) >= 2
+ assert set(observations) == {"/ready"}
+
+
+ "response_kind", ["drip", "oversized", "oversized-stream", "starting", "utf16", "compressed", "malformed"],
+)
+def test_desktop_ready_request_body_has_one_deadline_and_size_bound(monkeypatch, response_kind):
+ """A peer sending bytes must not restart the whole observation budget."""
+ import time
+
+ completed = threading.Event()
+ requests = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ requests.append(time.monotonic())
+ body = (
+ b'{"schema_version":1,"product":"avibe","ready":true}' + b" " * 1100
+ if response_kind in {"oversized", "oversized-stream"}
+ else b'{"schema_version":1,"product":"avibe","ready":true}'
+ )
+ if response_kind == "starting":
+ time.sleep(0.02)
+ body = b'{"schema_version":1,"product":"avibe","ready":false,"code":"controller_unavailable"}'
+ elif response_kind == "utf16":
+ body = body.decode().encode("utf-16")
+ elif response_kind == "malformed":
+ body = b'{"ready":true}'
+ elif response_kind == "compressed":
+ import gzip
+
+ body = gzip.compress(body)
+ self.send_response(503 if response_kind == "starting" else 200)
+ if response_kind == "compressed":
+ self.send_header("Content-Encoding", "gzip")
+ if response_kind != "oversized-stream":
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ try:
+ if response_kind != "drip":
+ self.wfile.write(body)
+ else:
+ for byte in body:
+ self.wfile.write(bytes([byte]))
+ self.wfile.flush()
+ time.sleep(0.02)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+ finally:
+ completed.set()
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **kwargs: 1234)
+ monkeypatch.setattr(runtime, "pid_alive", lambda _pid: True)
+ started = time.monotonic()
+ assert runtime.wait_for_desktop_startup_ready(
+ 1234, "127.0.0.1", server.server_address[1], timeout=0.2,
+ ) is None
+ assert time.monotonic() - started < 0.5
+ if response_kind == "starting":
+ assert len(requests) >= 2, "retries consume the original total deadline"
+ assert completed.wait(2)
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+
def test_ui_server_health_fails_when_old_specific_bind_lacks_desktop_listener(monkeypatch):
calls = []
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 1bcaec516..9c4a460e7 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -4301,6 +4301,196 @@ def test_start_parser_accepts_no_open_browser():
assert args.open_browser is False
+def test_start_parser_accepts_hidden_desktop_receipt():
+ parser = cli.build_parser()
+ args = parser.parse_args(["start", "--desktop-receipt"])
+
+ assert args.command == "start"
+ assert args.desktop_receipt is True
+
+
+def test_desktop_receipt_frame_has_bounded_utf8_schema():
+ from vibe.desktop_startup import desktop_start_receipt_line
+
+ frame = desktop_start_receipt_line(
+ origin="http://127.0.0.1:5123",
+ outcome="failed",
+ reason="startup_failed",
+ )
+
+ assert frame.startswith("@avibe-desktop-start:")
+ assert frame.endswith("\n")
+ assert len(frame.encode("utf-8")) <= 4096
+ assert json.loads(frame.removeprefix("@avibe-desktop-start:")) == {
+ "schema_version": 1,
+ "outcome": "failed",
+ "origin": "http://127.0.0.1:5123",
+ "reason": "startup_failed",
+ }
+
+
[email protected]("ready_timeout", [None, 1.0, 600.0])
+def test_desktop_receipt_start_shares_readiness_and_does_not_wait_twice(monkeypatch, capsys, ready_timeout):
+ config = SimpleNamespace(
+ has_configured_platform_credentials=lambda: True,
+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),
+ )
+ calls = []
+
+ 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: config)
+ monkeypatch.setattr(cli, "_handover_superseded_desktop_runtime", lambda **kwargs: 0)
+ monkeypatch.setattr(cli.runtime, "claim_desktop_runtime_start", lambda: None)
+ monkeypatch.setattr(cli, "_write_status", lambda *args: None)
+ monkeypatch.setattr(cli.runtime, "write_status", lambda *args: None)
+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda _config: "127.0.0.1")
+ monkeypatch.setattr(cli, "_in_ssh_session", lambda: False)
+ monkeypatch.setattr(cli, "_open_browser", lambda _url: pytest.fail("desktop mode must not open a browser"))
+ monkeypatch.setattr(cli.runtime, "claim_ready_service", lambda *args, **kwargs: None)
+ monkeypatch.setattr("vibe.install_generations.collect_install_generations", lambda *_args: None)
+
+ def start_service(**kwargs):
+ calls.append(("service", kwargs))
+ kwargs["start_info"].capture(1234, reused=False)
+ return 1234
+
+ def start_ui(host, port, **kwargs):
+ calls.append(("ui", host, port, kwargs))
+ kwargs["start_info"].capture(5678, reused=False)
+ return 5678
+
+ def wait_ready(pid, host, port, *, timeout):
+ calls.append(("ready", pid, host, port, timeout))
+ return 1234
+
+ monkeypatch.setattr(cli.runtime, "start_service", start_service)
+ monkeypatch.setattr(cli.runtime, "start_ui", start_ui)
+ monkeypatch.setattr(cli.runtime, "wait_for_desktop_startup_ready", wait_ready)
+
+ assert cli.cmd_start(open_browser=False, desktop_receipt=True, desktop_ready_timeout=ready_timeout) == 0
+
+ service_call = calls[0][1]
+ ui_call = calls[1][3]
+ ready_call = calls[2]
+ assert service_call["wait_for_ready"] is False
+ assert service_call["initial_ready_timeout"] == 0
+ assert ui_call["wait_for_ready"] is False
+ assert ready_call[:4] == ("ready", 1234, "127.0.0.1", 5123)
+ expected_budget = 120.0 if ready_timeout is None else ready_timeout
+ assert expected_budget - 0.5 < ready_call[4] <= expected_budget
+ assert "@avibe-desktop-start:" in capsys.readouterr().out
+
+
[email protected]("service_reused", [False, True])
[email protected]("ui_reused", [False, True])
+def test_desktop_receipt_requires_combined_readiness_even_when_service_is_alive(
+ monkeypatch, capsys, service_reused, ui_reused,
+):
+ """A live timeout must fail; actual rollback stops only created children."""
+ state = _ui_refuses_to_start(
+ monkeypatch, reused=service_reused, ui_outcome=5678, ui_reused=ui_reused,
+ )
+ monkeypatch.setattr(cli.runtime, "pid_alive", lambda pid: True)
+ monkeypatch.setattr(cli.runtime, "wait_for_desktop_startup_ready", lambda *args, **kwargs: None)
+ with pytest.raises(RuntimeError, match="did not become ready"):
+ cli.cmd_start(open_browser=False, desktop_receipt=True)
+ output = capsys.readouterr().out
+ assert '"outcome":"ready"' not in output
+ assert '"reason":"runtime_not_ready"' in output
+ assert ("stop_ui" in state.calls) is (not ui_reused)
+ assert ("stop_service" in state.calls) is (not service_reused)
+ if not ui_reused:
+ assert state.stop_ui_kwargs == [{"stop_remote_access": False}]
+
+
+def test_desktop_receipt_failure_is_emitted_after_rollback(monkeypatch, capsys):
+ config = SimpleNamespace(
+ has_configured_platform_credentials=lambda: True,
+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),
+ )
+ stopped = []
+
+ 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: config)
+ monkeypatch.setattr(cli, "_handover_superseded_desktop_runtime", lambda **kwargs: 0)
+ monkeypatch.setattr(cli.runtime, "claim_desktop_runtime_start", lambda: None)
+ monkeypatch.setattr(cli, "_write_status", lambda *args: None)
+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda _config: "127.0.0.1")
+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: 1234)
+ monkeypatch.setattr(
+ cli.runtime,
+ "start_ui",
+ lambda host, port, **kwargs: (_ for _ in ()).throw(RuntimeError("ui failed")),
+ )
+ monkeypatch.setattr(
+ cli.runtime,
+ "roll_back_start",
+ lambda service, ui: stopped.append((service, ui)),
+ )
+
+ with pytest.raises(RuntimeError, match="ui failed"):
+ cli.cmd_start(open_browser=False, desktop_receipt=True)
+
+ output = capsys.readouterr().out
+ assert '"outcome":"failed"' in output
+ assert '"reason":"runtime_not_ready"' in output
+ assert len(stopped) == 1
+
+
[email protected]("failure", ["transport", "housekeeping"])
+def test_desktop_receipt_failure_after_commit_keeps_runtime(monkeypatch, capsys, failure):
+ config = SimpleNamespace(
+ has_configured_platform_credentials=lambda: True,
+ ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),
+ )
+ rolled_back = []
+
+ 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: config)
+ monkeypatch.setattr(cli, "_handover_superseded_desktop_runtime", lambda **kwargs: 0)
+ monkeypatch.setattr(cli.runtime, "claim_desktop_runtime_start", lambda: None)
+ monkeypatch.setattr(cli, "_write_status", lambda *args: None)
+ monkeypatch.setattr(cli.runtime, "write_status", lambda *args: None)
+ monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda _config: "127.0.0.1")
+ monkeypatch.setattr(cli, "_in_ssh_session", lambda: True)
+ monkeypatch.setattr(cli.runtime, "start_service", lambda **kwargs: 1234)
+ monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port, **kwargs: 5678)
+ monkeypatch.setattr(cli.runtime, "wait_for_desktop_startup_ready", lambda *args, **kwargs: 1234)
+ monkeypatch.setattr(cli.runtime, "claim_ready_service", lambda *args, **kwargs: None)
+ monkeypatch.setattr("vibe.install_generations.collect_install_generations", lambda *_args: None)
+ monkeypatch.setattr(cli.runtime, "roll_back_start", lambda *args: rolled_back.append(args))
+ if failure == "transport":
+ monkeypatch.setattr(
+ "vibe.desktop_startup.emit_desktop_start_receipt",
+ lambda **kwargs: (_ for _ in ()).throw(BrokenPipeError()),
+ )
+ with pytest.raises(BrokenPipeError):
+ cli.cmd_start(open_browser=False, desktop_receipt=True)
+ else:
+ def fail_housekeeping(*_args):
+ assert '"outcome":"ready"' in capsys.readouterr().out
+ raise RuntimeError("housekeeping failed after publication")
+
+ monkeypatch.setattr("vibe.install_generations.collect_install_generations", fail_housekeeping)
+ assert cli.cmd_start(open_browser=False, desktop_receipt=True) == 0
+ assert '"outcome":"failed"' not in capsys.readouterr().out
+ assert rolled_back == []
+
+
+def test_desktop_receipt_pre_resolution_failure_has_no_receipt(monkeypatch, capsys):
+ 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: (_ for _ in ()).throw(RuntimeError("config failed")))
+
+ with pytest.raises(RuntimeError, match="config failed"):
+ cli.cmd_start(open_browser=False, desktop_receipt=True)
+
+ assert "@avibe-desktop-start:" not in capsys.readouterr().out
+
+
@pytest.mark.parametrize(
("arguments", "expected"),
[
@@ -4321,8 +4511,22 @@ def test_stop_parser_and_main_route_each_stop_mode(monkeypatch, arguments, expec
assert calls == [expected]
[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):
+ ("arguments", "expected"),
+ [
+ (["start"], {"open_browser": None, "hand_over": False}),
+ (["start", "--hand-over"], {"open_browser": None, "hand_over": True}),
+ (
+ ["start", "--desktop-receipt"],
+ {"open_browser": None, "hand_over": False, "desktop_receipt": True},
+ ),
+ (
+ ["start", "--no-open-browser", "--desktop-receipt", "--desktop-ready-timeout", "600"],
+ {"open_browser": False, "hand_over": False, "desktop_receipt": True, "desktop_ready_timeout": 600.0},
+ ),
+ ],
+)
+def test_start_parser_and_main_route_desktop_modes(monkeypatch, arguments, expected):
calls = []
monkeypatch.setattr(cli.sys, "argv", ["vibe", *arguments])
monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)
@@ -4333,7 +4537,7 @@ def test_only_a_start_asked_to_hand_over_may_replace_another_desktop_runtime(mon
cli.main()
assert exited.value.code == 0
- assert calls == [{"open_browser": None, "hand_over": hand_over}]
+ assert calls == [expected]
def test_remote_parser_accepts_pairing_command():
diff --git a/vibe/cli.py b/vibe/cli.py
index 24db7f62d..cb2b3f159 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -14300,12 +14300,39 @@ def _handover_superseded_desktop_runtime(*, allowed: bool) -> int:
return 0
-def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):
+def cmd_start(
+ *,
+ open_browser: bool | None = None,
+ hand_over: bool = False,
+ desktop_receipt: bool = False,
+ desktop_ready_timeout: float | None = None,
+):
_guard_cli_default_state_migration()
paths.ensure_data_dirs()
config = _ensure_config()
+ receipt_origin = None
+ receipt_bind_host = None
+ if desktop_receipt:
+ from vibe.desktop_runtime import desktop_origin
+
+ receipt_bind_host = runtime.effective_ui_bind_host(config)
+ receipt_origin = desktop_origin(receipt_bind_host, config.ui.setup_port)
+
+ def emit_receipt(outcome: str, reason: str | None = None) -> None:
+ if receipt_origin is None:
+ return
+ from vibe.desktop_startup import emit_desktop_start_receipt
+
+ emit_desktop_start_receipt(
+ origin=receipt_origin,
+ outcome=outcome, # type: ignore[arg-type]
+ reason=reason,
+ )
+
handover_status = _handover_superseded_desktop_runtime(allowed=hand_over)
if handover_status:
+ if desktop_receipt:
+ emit_receipt("failed", "handover_refused" if handover_status == 3 else "handover_failed")
return handover_status
# Before anything is announced: a start refused here leaves the status, and
# everything running, as it found them. The start below claims again what
@@ -14314,6 +14341,8 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):
runtime.claim_desktop_runtime_start()
except runtime.DesktopRuntimeClaimRefused as refusal:
_print_provenance_refusal("claim", refusal)
+ if desktop_receipt:
+ emit_receipt("failed", "runtime_claim_refused")
return 3
has_configured_platform_credentials = getattr(config, "has_configured_platform_credentials", None)
@@ -14329,6 +14358,7 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):
service_start = runtime.ProcessStartInfo()
ui_start = runtime.ProcessStartInfo()
+ startup_committed = False
# 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`
@@ -14353,17 +14383,24 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):
# the service and then waits for it to take the lock, and a Ctrl-C in that
# wait left a live, reserved service that no rollback had been asked about.
try:
- service_pid = runtime.start_service(
- wait_for_ready=False,
- start_info=service_start,
- )
+ service_kwargs = {
+ "wait_for_ready": False,
+ "start_info": service_start,
+ }
+ startup_deadline = None
+ if desktop_receipt:
+ service_kwargs["initial_ready_timeout"] = 0
+ startup_deadline = time.monotonic() + (
+ runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS
+ if desktop_ready_timeout is None else desktop_ready_timeout
+ )
+ service_pid = runtime.start_service(**service_kwargs)
service_reused = service_start.reused
- bind_host = runtime.effective_ui_bind_host(config)
- ui_pid = runtime.start_ui(
- bind_host,
- config.ui.setup_port,
- start_info=ui_start,
- )
+ bind_host = receipt_bind_host if receipt_bind_host is not None else runtime.effective_ui_bind_host(config)
+ ui_kwargs = {"start_info": ui_start}
+ if desktop_receipt:
+ ui_kwargs["wait_for_ready"] = False
+ ui_pid = runtime.start_ui(bind_host, config.ui.setup_port, **ui_kwargs)
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
@@ -14388,16 +14425,39 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):
# on the raw pid start_service handed back: under a delegated user scope that
# pid can be a launcher that never takes the lock, so wait_for_service_ready
# adopts and returns the real owner instead of stalling the full timeout.
- resolved_pid = runtime.wait_for_service_ready(
- service_pid,
- timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
- )
+ if desktop_receipt:
+ assert startup_deadline is not None
+ resolved_pid = runtime.wait_for_desktop_startup_ready(
+ service_pid,
+ bind_host,
+ config.ui.setup_port,
+ timeout=max(0.0, startup_deadline - time.monotonic()),
+ )
+ else:
+ resolved_pid = runtime.wait_for_service_ready(
+ service_pid,
+ timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS,
+ )
service_ready = resolved_pid is not None
if resolved_pid is not None:
runtime.claim_ready_service(resolved_pid, started_pid=service_pid)
service_pid = resolved_pid
if service_ready:
runtime.write_status("running", "pid={}".format(service_pid), service_pid, ui_pid)
+ elif desktop_receipt:
+ alive = runtime.pid_alive(service_pid)
+ detail = (
+ "service process is still starting"
+ if alive
+ else "service process exited before startup completed"
+ )
+ runtime.write_status(
+ "starting" if alive else "error",
+ detail,
+ service_pid,
+ ui_pid,
+ )
+ raise RuntimeError("Vibe service and UI did not become ready before startup deadline")
elif runtime.pid_alive(service_pid):
runtime.write_status("starting", "service process is still starting", service_pid, ui_pid)
else:
@@ -14422,6 +14482,20 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):
if not opened:
print(f"(Tip) Could not auto-open a browser. Open this URL manually: {ui_url}")
print("")
+ if desktop_receipt:
+ # Readiness and ownership are complete here. From this point on,
+ # stdout transport is only an observation channel for the shell;
+ # closing that channel must never roll back a Runtime that this
+ # invocation has already started or adopted.
+ startup_committed = True
+ emit_receipt("ready")
+ try:
+ from vibe.install_generations import collect_install_generations
+
+ collect_install_generations(cache_running_vibe_path())
+ except Exception:
+ logger.warning("Desktop startup housekeeping failed after Runtime became ready", exc_info=True)
+ return 0
except BaseException as exc:
# The invariant is that this invocation leaves running nothing it
# created -- not just the service. The region starts two processes, and
@@ -14458,12 +14532,23 @@ def cmd_start(*, open_browser: bool | None = None, hand_over: bool = False):
# leaves evidence; either way the start has failed. Under a desktop
# Runtime id only the processes this start created are stopped, so one
# another Runtime started meanwhile is left running.
- runtime.roll_back_start(service_start, ui_start)
+ if not startup_committed:
+ runtime.roll_back_start(service_start, ui_start)
+ if desktop_receipt and not startup_committed:
+ reason = (
+ "runtime_claim_refused" if isinstance(exc, runtime.DesktopRuntimeClaimRefused)
+ else "runtime_not_ready" if isinstance(exc, RuntimeError)
+ else "startup_failed"
+ )
+ try:
+ emit_receipt("failed", reason)
+ except Exception:
+ logger.warning("Could not write the desktop startup failure receipt", exc_info=True)
if isinstance(exc, runtime.DesktopRuntimeClaimRefused):
_print_provenance_refusal("claim", exc)
return 3
raise
- if service_ready:
+ if service_ready and not desktop_receipt:
from vibe.install_generations import collect_install_generations
collect_install_generations(cache_running_vibe_path())
@@ -17242,6 +17327,8 @@ def build_parser():
help="Start this install even though a newer one was activated since.",
)
start_parser.add_argument("--hand-over", action="store_true", help=argparse.SUPPRESS)
+ start_parser.add_argument("--desktop-receipt", action="store_true", help=argparse.SUPPRESS)
+ start_parser.add_argument("--desktop-ready-timeout", type=_non_negative_float, help=argparse.SUPPRESS)
# The desktop shell's own entry points: runnable, but never listed.
desktop_parser = subparsers.add_parser("desktop")
desktop_subparsers = desktop_parser.add_subparsers(dest="desktop_command", required=True)
@@ -19676,7 +19763,12 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:
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, hand_over=args.hand_over))
+ start_kwargs = {"open_browser": args.open_browser, "hand_over": args.hand_over}
+ if args.desktop_receipt:
+ start_kwargs["desktop_receipt"] = True
+ if args.desktop_ready_timeout is not None:
+ start_kwargs["desktop_ready_timeout"] = args.desktop_ready_timeout
+ sys.exit(cmd_start(**start_kwargs))
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_startup.py b/vibe/desktop_startup.py
new file mode 100644
index 000000000..c6df95bbd
--- /dev/null
+++ b/vibe/desktop_startup.py
@@ -0,0 +1,56 @@
+"""The opt-in desktop startup receipt written by ``vibe start``."""
+
+from __future__ import annotations
+
+import json
+import sys
+from typing import Literal, TypedDict
+
+DESKTOP_START_RECEIPT_PREFIX = "@avibe-desktop-start:"
+DESKTOP_START_RECEIPT_SCHEMA_VERSION: Literal[1] = 1
+DESKTOP_START_RECEIPT_MAX_BYTES = 4096
+
+
+class DesktopStartReceipt(TypedDict, total=False):
+ schema_version: Literal[1]
+ outcome: Literal["ready", "failed"]
+ origin: str
+ reason: str
+
+
+def desktop_start_receipt_line(
+ *,
+ origin: str,
+ outcome: Literal["ready", "failed"],
+ reason: str | None = None,
+) -> str:
+ """Build one bounded receipt frame for the bundled desktop shell."""
+
+ if outcome == "ready" and reason is not None:
+ raise ValueError("a ready receipt cannot carry a failure reason")
+ if outcome == "failed" and not reason:
+ raise ValueError("a failed receipt requires a reason")
+ payload: DesktopStartReceipt = {
+ "schema_version": DESKTOP_START_RECEIPT_SCHEMA_VERSION,
+ "outcome": outcome,
+ "origin": origin,
+ }
+ if reason is not None:
+ payload["reason"] = reason
+ encoded = json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode("utf-8")
+ frame = DESKTOP_START_RECEIPT_PREFIX.encode("ascii") + encoded + b"\n"
+ if len(frame) > DESKTOP_START_RECEIPT_MAX_BYTES:
+ raise ValueError("desktop startup receipt exceeds its byte limit")
+ return frame.decode("utf-8")
+
+
+def emit_desktop_start_receipt(
+ *,
+ origin: str,
+ outcome: Literal["ready", "failed"],
+ reason: str | None = None,
+) -> None:
+ """Write and flush one receipt frame without changing normal CLI output."""
+
+ sys.stdout.write(desktop_start_receipt_line(origin=origin, outcome=outcome, reason=reason))
+ sys.stdout.flush()
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 8235a0906..c0c3f6f23 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -159,6 +159,8 @@ _PENDING_SQLITE_BACKUP_READINESS: tuple[Path, str, tuple[str, ...], datetime] |
_SERVICE_START_PROCESSES: dict[int, subprocess.Popen] = {}
# /ready can spend up to two seconds in the Controller health probe.
UI_ADOPTION_PROBE_TIMEOUT_SECONDS = 3.0
+# Preserve the desktop host's DEFAULT_PROBE_TIMEOUT when Python owns the wait.
+DESKTOP_READY_PROBE_TIMEOUT_SECONDS = 5.0
def _rounded_seconds(seconds: float) -> float:
@@ -2394,6 +2396,10 @@ def _ui_ready_identity_state(response) -> bool | None:
except (AttributeError, OSError, UnicodeDecodeError, json.JSONDecodeError):
return None
+ return _ui_ready_payload_state(response.status, payload)
+
+
+def _ui_ready_payload_state(status: int, payload) -> bool | None:
if not isinstance(payload, dict):
return None
if type(payload.get("schema_version")) is not int or payload["schema_version"] != 1:
@@ -2419,12 +2425,12 @@ def _ui_ready_identity_state(response) -> bool | None:
):
return None
expected_ready.add(field)
- if response.status == 200 and set(payload) == expected_ready and payload["ready"] is True:
+ if status == 200 and set(payload) == expected_ready and payload["ready"] is True:
return True
code = payload.get("code")
if (
- response.status == 503
+ status == 503
and isinstance(code, str)
and bool(code)
and payload
@@ -2477,6 +2483,79 @@ def wait_for_ui_server(host: str, port: int, timeout: float = 5.0) -> bool:
return ui_server_healthy(host, port)
+def wait_for_desktop_startup_ready(
+ service_pid: int,
+ host: str,
+ port: int,
+ *,
+ timeout: float = SERVICE_SLOW_START_TIMEOUT_SECONDS,
+) -> int | None:
+ """Wait for the UI and Controller together under one startup deadline.
+
+ ``/ready`` is the existing combined UI/Controller readiness contract. The
+ service owner lookup is still required to return the authoritative process
+ for status and rollback; it never becomes a second readiness predicate.
+ """
+
+ import asyncio
+
+ import httpx
+
+ from vibe.desktop_runtime import desktop_origin
+
+ deadline = time.monotonic() + max(0.0, timeout)
+ origin = desktop_origin(host, port)
+
+ async def observe(client):
+ # The combined exact-origin /ready predicate includes the usable UI,
+ # service owner and Controller IPC. LAN /health is not a desktop gate.
+ async with client.stream("GET", f"{origin}/ready", headers={"Accept-Encoding": "identity"}) as response:
+ length = response.headers.get("content-length")
+ if length is not None:
+ try:
+ if int(length) > 1024:
+ return False
+ except ValueError:
+ return False
+ body = bytearray()
+ async for chunk in response.aiter_raw():
+ if len(body) + len(chunk) > 1024:
+ return False
+ body.extend(chunk)
+ try:
+ return _ui_ready_payload_state(response.status_code, json.loads(body.decode("utf-8"))) is True
+ except (ValueError, UnicodeDecodeError):
+ return False
+
+ async def wait():
+ current_pid = service_pid
+ async with httpx.AsyncClient(trust_env=False, follow_redirects=False) as client:
+ while time.monotonic() < deadline:
+ owner_pid = resolve_service_owner_pid(include_starting=False)
+ if owner_pid is not None:
+ current_pid = owner_pid
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return None
+ try:
+ # Bound the entire request including headers and streamed
+ # body, not a fresh socket timeout for each received byte.
+ ready = await asyncio.wait_for(
+ observe(client), min(DESKTOP_READY_PROBE_TIMEOUT_SECONDS, remaining),
+ )
+ except (httpx.HTTPError, TimeoutError, OSError):
+ ready = False
+ if ready and time.monotonic() < deadline:
+ if owner_pid is not None or service_instance_started(current_pid):
+ return current_pid
+ if not pid_alive(current_pid) and owner_pid is None:
+ return None
+ await asyncio.sleep(min(0.1, max(0.0, deadline - time.monotonic())))
+ return None
+
+ return asyncio.run(wait())
+
+
def _is_ui_server_command(command: str) -> bool:
return "vibe.ui_server" in command and "run_ui_server" in command