@@ -1,5 +1,5 @@
1−use crate::instance::STATUS_FILE_NAME;
21use crate::session_manager::{GLOBAL_CACHE_DIR_NAME, INSTANCE_DIR_NAME};
2+use anyhow::{Context, Error, Result, bail};
33use std::{
44 env, fs,
55 io::{self, Write},
@@ -23,6 +23,7 @@ use std::{
2323};
2424
2525use block2::RcBlock;
26+use bytesize::ByteSize;
2627use dispatch2::DispatchQueue;
2728use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
2829use objc2_foundation::*;
@@ -34,68 +35,44 @@ const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
3435const SHARED_DIRECTORIES_TAG: &str = "shared";
3536pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
3637
37−const BYTES_PER_MB: u64 = 1024 * 1024;
38−const DEFAULT_CPU_COUNT: usize = 2;
39−const DEFAULT_RAM_MB: u64 = 2048;
40−const DEFAULT_RAM_BYTES: u64 = DEFAULT_RAM_MB * BYTES_PER_MB;
4138const START_TIMEOUT: Duration = Duration::from_secs(60);
4239const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
40+const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
4341
44−struct StatusFile {
45− path: PathBuf,
46− cleared: AtomicBool,
47−}
48−
49−impl StatusFile {
50− fn new(path: PathBuf) -> Self {
51− Self {
52− path,
53− cleared: AtomicBool::new(false),
54− }
55− }
56−
57− fn update(&self, message: &str) {
58− let _ = fs::write(&self.path, message);
59− }
60−}
61−
62−impl Drop for StatusFile {
63− fn drop(&mut self) {
64− if !self.cleared.load(Ordering::SeqCst) {
65− let _ = fs::remove_file(&self.path);
66− self.cleared.store(true, Ordering::SeqCst);
67− }
68− }
69−}
42+const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
7043const PROVISION_SCRIPT: &str = include_str!("provision.sh");
71−const PROVISION_SCRIPT_NAME: &str = "provision.sh";
7244const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
7345const DEFAULT_RAW_NAME: &str = "default.raw";
7446const INSTANCE_RAW_NAME: &str = "instance.raw";
7547const BASE_DISK_RAW_NAME: &str = "disk.raw";
7648
7749#[derive(Clone)]
78−pub(crate) enum LoginAction {
79− Expect { text: String, timeout: Duration },
50+pub enum LoginAction {
51+ Expect {
52+ text: String,
53+ timeout: Duration,
54+ },
55+ ExpectEither {
56+ success: String,
57+ failure: String,
58+ timeout: Duration,
59+ },
8060 Send(String),
8161}
62+use crate::config::BoxConfig;
8263use LoginAction::*;
8364
8465#[derive(Clone)]
85−pub(crate) struct DirectoryShare {
66+pub struct DirectoryShare {
8667 host: PathBuf,
8768 guest: PathBuf,
8869 read_only: bool,
8970}
9071
9172impl DirectoryShare {
92− pub(crate) fn new(
93− host: PathBuf,
94− mut guest: PathBuf,
95− read_only: bool,
96− ) -> Result<Self, Box<dyn std::error::Error>> {
73+ pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
9774 if !host.exists() {
98− return Err(format!("Host path does not exist: {}", host.display()).into());
75+ bail!(format!("host path does not exist: {}", host.display()));
9976 }
10077 if !guest.is_absolute() {
10178 guest = PathBuf::from("/root").join(guest);
@@ -107,10 +84,10 @@ impl DirectoryShare {
10784 })
10885 }
10986
110− pub(crate) fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
87+ pub fn from_mount_spec(spec: &str) -> Result<Self> {
11188 let parts: Vec<&str> = spec.split(':').collect();
11289 if parts.len() < 2 || parts.len() > 3 {
113− return Err(format!("Invalid mount spec: {spec}").into());
90+ bail!(format!("invalid mount spec: {spec}"));
11491 }
11592 let host = expand_tilde_path(parts[0]);
11693 let guest = PathBuf::from(parts[1]);
@@ -119,11 +96,10 @@ impl DirectoryShare {
11996 "read-only" => true,
12097 "read-write" => false,
12198 _ => {
122− return Err(format!(
99+ bail!(format!(
123100 "Invalid mount mode '{}'; expected read-only or read-write",
124101 parts[2]
125− )
126− .into());
102+ ));
127103 }
128104 }
129105 } else {
@@ -167,19 +143,28 @@ pub struct VmArg {
167143 pub mounts: Vec<String>,
168144}
169145
170−pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<(), Box<dyn std::error::Error>>
146+type StatusEmitter<'a> = dyn Fn(&str) + std::marker::Send + Sync + 'a;
147+
148+fn emit_status(status: Option<&StatusEmitter<'_>>, message: &str) {
149+ if let Some(status) = status {
150+ status(message);
151+ }
152+}
153+
154+pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<()>
171155where
172156 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
173157{
174− run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new())
158+ run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new(), None)
175159}
176160
177−pub(crate) fn run_with_args_and_extras<F>(
161+pub fn run_with_args_and_extras<F>(
178162 args: VmArg,
179163 io_handler: F,
180164 extra_login_actions: Vec<LoginAction>,
181165 extra_directory_shares: Vec<DirectoryShare>,
182−) -> Result<(), Box<dyn std::error::Error>>
166+ status: Option<&StatusEmitter<'_>>,
167+) -> Result<()>
183168where
184169 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
185170{
@@ -188,7 +173,7 @@ where
188173 let project_root = env::current_dir()?;
189174 let project_name = project_root
190175 .file_name()
191− .ok_or("Project directory has no name")?
176+ .with_context(|| "Project directory has no name")?
192177 .to_string_lossy()
193178 .into_owned();
194179
@@ -200,8 +185,10 @@ where
200185 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
201186
202187 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
203− let status_file = StatusFile::new(instance_dir.join(STATUS_FILE_NAME));
204− status_file.update("preparing VM image...");
188+ fs::create_dir_all(&instance_dir)?;
189+ emit_status(status, "preparing VM image...");
190+ tracing::info!("preparing VM image...");
191+ let provision_log = instance_dir.join("provision.log");
205192
206193 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
207194 let base_compressed = cache_dir.join(basename_compressed);
@@ -225,13 +212,14 @@ where
225212 &base_compressed,
226213 &default_raw,
227214 std::slice::from_ref(&mise_directory_share),
228− Some(&status_file),
215+ Some(&provision_log),
216+ status,
229217 )?;
230218 let _ = ensure_instance_disk(
231219 &instance_raw,
232220 &default_raw,
233− args.disk_bytes,
234− Some(&status_file),
221+ ByteSize(args.disk_bytes),
222+ status,
235223 )?;
236224 let base_size = fs::metadata(&default_raw)?.len();
237225 let instance_size = fs::metadata(&instance_raw)?.len();
@@ -261,7 +249,7 @@ where
261249 }
262250
263251 if needs_resize {
264− let resize_cmd = script_command_from_content("resize_disk", RESIZE_DISK_SCRIPT)?;
252+ let resize_cmd = script_command_from_content("resize_disk.sh", RESIZE_DISK_SCRIPT)?;
265253 login_actions.push(Send(resize_cmd));
266254 }
267255
@@ -277,25 +265,29 @@ where
277265 &directory_shares[..],
278266 args.cpu_count,
279267 args.ram_bytes,
280− Some(&status_file),
268+ status,
281269 io_handler,
282270 )
283271}
284272
285−pub(crate) fn script_command_from_content(
286− label: &str,
287− script: &str,
288−) -> Result<String, Box<dyn std::error::Error>> {
273+pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
289274 let marker = "VIBE_SCRIPT_EOF";
290275 let guest_dir = "/tmp/vibe-scripts";
291276 let guest_path = format!("{guest_dir}/{label}.sh");
277+ let script_body = match script.split_once('\n') {
278+ Some((first, rest)) if first.starts_with("#!") => rest,
279+ _ => script,
280+ };
281+ let wrapped_script = ERROR_REPORT_SCRIPT
282+ .replace("__LABEL__", label)
283+ .replace("__SCRIPT_BODY__", script_body);
292284 let command = format!(
293− "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
285+ "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{wrapped_script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
294286 );
295287 if script.contains(marker) {
296− return Err(
297− format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
298− );
288+ bail!(format!(
289+ "Script '{label}' contains marker '{marker}', cannot safely upload"
290+ ));
299291 }
300292 Ok(command)
301293}
@@ -359,6 +351,12 @@ enum WaitResult {
359351 Found,
360352}
361353
354+#[derive(PartialEq, Eq)]
355+enum WaitAnyResult {
356+ Timeout,
357+ Found(usize),
358+}
359+
362360pub enum VmInput {
363361 Bytes(Vec<u8>),
364362 Shutdown,
@@ -366,6 +364,7 @@ pub enum VmInput {
366364
367365enum VmOutput {
368366 LoginActionTimeout { action: String, timeout: Duration },
367+ LoginActionFailed { action: String, reason: String },
369368}
370369
371370#[derive(Default)]
@@ -402,6 +401,41 @@ impl OutputMonitor {
402401 WaitResult::Found
403402 }
404403 }
404+
405+ fn wait_for_any(&self, needles: &[&str], timeout: Duration) -> WaitAnyResult {
406+ let mut found: Option<usize> = None;
407+ let (_unused, timeout_result) = self
408+ .condvar
409+ .wait_timeout_while(self.buffer.lock().unwrap(), timeout, |buf| {
410+ if let Some((pos, idx, len)) = find_any(buf, needles) {
411+ *buf = buf[(pos + len)..].to_string();
412+ found = Some(idx);
413+ false
414+ } else {
415+ true
416+ }
417+ })
418+ .unwrap();
419+
420+ if timeout_result.timed_out() {
421+ WaitAnyResult::Timeout
422+ } else {
423+ WaitAnyResult::Found(found.unwrap_or(0))
424+ }
425+ }
426+}
427+
428+fn find_any(buf: &str, needles: &[&str]) -> Option<(usize, usize, usize)> {
429+ let mut best: Option<(usize, usize, usize)> = None; // (pos, idx, len)
430+ for (idx, needle) in needles.iter().enumerate() {
431+ if let Some(pos) = buf.find(needle) {
432+ let candidate = (pos, idx, needle.len());
433+ if best.is_none_or(|b| candidate.0 < b.0) {
434+ best = Some(candidate);
435+ }
436+ }
437+ }
438+ best
405439}
406440
407441#[derive(Debug)]
@@ -450,18 +484,16 @@ impl IoControl {
450484fn ensure_base_image(
451485 base_raw: &Path,
452486 base_compressed: &Path,
453− status: Option<&StatusFile>,
454−) -> Result<(), Box<dyn std::error::Error>> {
487+ status: Option<&StatusEmitter<'_>>,
488+) -> Result<()> {
455489 if base_raw.exists() {
456490 return Ok(());
457491 }
458492
459493 if !base_compressed.exists()
460− || std::fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
494+ || fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
461495 {
462− if let Some(status) = status {
463− status.update("downloading base image...");
464− }
496+ emit_status(status, "downloading base image...");
465497 tracing::info!("downloading base image");
466498 let status = Command::new("curl")
467499 .args([
@@ -476,15 +508,14 @@ fn ensure_base_image(
476508 ])
477509 .status()?;
478510 if !status.success() {
479− return Err("Failed to download base image".into());
511+ bail!("failed to download base image");
480512 }
481513 }
482514
483515 // Check SHA
484516 {
485− if let Some(status) = status {
486− status.update("verifying base image...");
487− }
517+ emit_status(status, "verifying base image...");
518+ tracing::info!("verifying base image...");
488519 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
489520
490521 let mut child = Command::new("/usr/bin/shasum")
@@ -502,25 +533,25 @@ fn ensure_base_image(
502533
503534 let status = child.wait().expect("failed to wait on child");
504535 if !status.success() {
505− return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
536+ bail!(format!(
537+ "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
538+ ));
506539 }
507540 }
508541
509− if let Some(status) = status {
510− status.update("decompressing base image...");
511− }
512− tracing::info!("decompressing base image");
542+ emit_status(status, "decompressing base image...");
543+ tracing::info!("decompressing base image...");
513544 let status = Command::new("tar")
514545 .args([
515546 "-xOf",
516547 &base_compressed.to_string_lossy(),
517548 BASE_DISK_RAW_NAME,
518549 ])
519− .stdout(std::fs::File::create(base_raw)?)
550+ .stdout(fs::File::create(base_raw)?)
520551 .status()?;
521552
522553 if !status.success() {
523− return Err("Failed to decompress base image".into());
554+ bail!("Failed to decompress base image");
524555 }
525556
526557 Ok(())
@@ -531,29 +562,56 @@ fn ensure_default_image(
531562 base_compressed: &Path,
532563 default_raw: &Path,
533564 directory_shares: &[DirectoryShare],
534− status: Option<&StatusFile>,
535−) -> Result<(), Box<dyn std::error::Error>> {
565+ provision_log: Option<&Path>,
566+ status: Option<&StatusEmitter<'_>>,
567+) -> Result<()> {
536568 if default_raw.exists() {
537569 return Ok(());
538570 }
539571
540572 ensure_base_image(base_raw, base_compressed, status)?;
541573
542− if let Some(status) = status {
543− status.update("configuring base image...");
544− }
545− tracing::info!("configuring base image");
574+ emit_status(status, "configuring base image...");
575+ tracing::info!("configuring base image...");
546576 fs::copy(base_raw, default_raw)?;
547577
548− let provision_command = script_command_from_content(PROVISION_SCRIPT_NAME, PROVISION_SCRIPT)?;
549− run_vm(
550− default_raw,
551− &[Send(provision_command)],
552− directory_shares,
553− DEFAULT_CPU_COUNT,
554− DEFAULT_RAM_BYTES,
555− None,
556− )?;
578+ let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
579+ let provision_actions = [
580+ Send(provision_command),
581+ ExpectEither {
582+ success: "VIBEBOX_PROVISION_OK".to_string(),
583+ failure: "VIBEBOX_PROVISION_FAILED".to_string(),
584+ timeout: PROVISION_EXPECT_TIMEOUT,
585+ },
586+ ];
587+ let provision_result = if let Some(log_path) = provision_log {
588+ let log_path = log_path.to_path_buf();
589+ run_vm_with_io(
590+ default_raw,
591+ &provision_actions,
592+ directory_shares,
593+ BoxConfig::default().cpu_count,
594+ BoxConfig::default().ram_size.as_u64(),
595+ status,
596+ move |output_monitor, vm_output_fd, vm_input_fd| {
597+ spawn_vm_io_with_log(output_monitor, vm_output_fd, vm_input_fd, log_path)
598+ },
599+ )
600+ } else {
601+ run_vm(
602+ default_raw,
603+ &provision_actions,
604+ directory_shares,
605+ BoxConfig::default().cpu_count,
606+ BoxConfig::default().ram_size.as_u64(),
607+ status,
608+ )
609+ };
610+
611+ if let Err(err) = provision_result {
612+ let _ = fs::remove_file(default_raw);
613+ return Err(err);
614+ }
557615
558616 Ok(())
559617}
@@ -561,18 +619,16 @@ fn ensure_default_image(
561619fn ensure_instance_disk(
562620 instance_raw: &Path,
563621 template_raw: &Path,
564− target_bytes: u64,
565− status: Option<&StatusFile>,
566−) -> Result<bool, Box<dyn std::error::Error>> {
622+ target_bytes: ByteSize,
623+ status: Option<&StatusEmitter<'_>>,
624+) -> Result<bool> {
567625 if instance_raw.exists() {
568− let current_size = fs::metadata(instance_raw)?.len();
626+ let current_size = ByteSize(fs::metadata(instance_raw)?.len());
569627 if current_size != target_bytes {
570− let current_gb = current_size as f64 / (1024.0 * 1024.0 * 1024.0);
571− let target_gb = target_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
628+ let current_gb = current_size;
629+ let target_gb = target_bytes;
572630 tracing::warn!(
573− current_bytes = current_size,
574− target_bytes,
575− "instance disk size does not match config (current {:.2} GB, config {:.2} GB); disk_gb applies only on init. Run `vibebox reset` to recreate or set disk_gb to match; using existing disk.",
631+ "instance disk size does not match config (current {}, config {}); disk_gb applies only on init. Run `vibebox reset` to recreate or set disk_gb to match; using existing disk.",
576632 current_gb,
577633 target_gb
578634 );
@@ -580,30 +636,28 @@ fn ensure_instance_disk(
580636 return Ok(false);
581637 }
582638
583− let template_size = fs::metadata(template_raw)?.len();
639+ let template_size = ByteSize(fs::metadata(template_raw)?.len());
584640 if target_bytes < template_size {
585− return Err(format!(
586− "Requested disk size {} bytes is smaller than base image size {} bytes",
641+ bail!(format!(
642+ "Requested disk size {} is smaller than base image size {}",
587643 target_bytes, template_size
588− )
589− .into());
644+ ));
590645 }
591646 let target_size = target_bytes;
592647 let needs_resize = target_size > template_size;
593648
594− if let Some(status) = status {
595− status.update("creating instance disk...");
596− }
649+ emit_status(status, "creating instance disk...");
650+ tracing::info!("creating instance disk...");
597651 tracing::info!(path = %template_raw.display(), "creating instance disk");
598− std::fs::create_dir_all(instance_raw.parent().unwrap())?;
652+ fs::create_dir_all(instance_raw.parent().unwrap())?;
599653 if target_size == template_size {
600654 fs::copy(template_raw, instance_raw)?;
601655 return Ok(needs_resize);
602656 }
603657
604− let mut dst = std::fs::File::create(instance_raw)?;
605− dst.set_len(target_size)?;
606− let mut src = std::fs::File::open(template_raw)?;
658+ let mut dst = fs::File::create(instance_raw)?;
659+ dst.set_len(target_size.as_u64())?;
660+ let mut src = fs::File::open(template_raw)?;
607661 std::io::copy(&mut src, &mut dst)?;
608662 Ok(needs_resize)
609663}
@@ -621,18 +675,17 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
621675 (read_stream.into(), write_stream.into())
622676}
623677
624−pub fn spawn_vm_io_with_hooks<F, G>(
678+pub fn spawn_vm_io_with_hooks<
679+ F: FnMut(&str) -> bool + std::marker::Send + 'static,
680+ G: FnMut(&[u8]) + std::marker::Send + 'static,
681+>(
625682 output_monitor: Arc<OutputMonitor>,
626683 vm_output_fd: OwnedFd,
627684 vm_input_fd: OwnedFd,
628685 io_control: Arc<IoControl>,
629686 mut on_line: F,
630687 mut on_output: G,
631−) -> IoContext
632−where
633− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
634− G: FnMut(&[u8]) + ::std::marker::Send + 'static,
635−{
688+) -> IoContext {
636689 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
637690
638691 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
@@ -780,14 +833,14 @@ where
780833 PollResult::Spurious => continue,
781834 PollResult::Ready(bytes) => {
782835 if io_control.forward_output() {
783− // enable raw mode, if we haven't already
836+ // enable raw mode if we haven't already
784837 if raw_guard.lock().unwrap().is_none()
785838 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
786839 {
787840 *raw_guard.lock().unwrap() = Some(guard);
788841 }
789842
790− let mut stdout = std::io::stdout().lock();
843+ let mut stdout = io::stdout().lock();
791844 if stdout.write_all(bytes).is_err() {
792845 break;
793846 }
@@ -803,7 +856,7 @@ where
803856
804857 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
805858 let mux_thread = thread::spawn(move || {
806− let mut vm_writer = std::fs::File::from(vm_input_fd);
859+ let mut vm_writer = fs::File::from(vm_input_fd);
807860 loop {
808861 match input_rx.recv() {
809862 Ok(VmInput::Bytes(data)) => {
@@ -833,7 +886,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
833886 on_line: F,
834887) -> IoContext
835888where
836− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
889+ F: FnMut(&str) -> bool + std::marker::Send + 'static,
837890{
838891 spawn_vm_io_with_hooks(
839892 output_monitor,
@@ -853,6 +906,36 @@ pub fn spawn_vm_io(
853906 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
854907}
855908
909+fn spawn_vm_io_with_log(
910+ output_monitor: Arc<OutputMonitor>,
911+ vm_output_fd: OwnedFd,
912+ vm_input_fd: OwnedFd,
913+ log_path: PathBuf,
914+) -> IoContext {
915+ let log_file = fs::OpenOptions::new()
916+ .create(true)
917+ .write(true)
918+ .truncate(true)
919+ .open(&log_path)
920+ .ok()
921+ .map(|file| Arc::new(Mutex::new(file)));
922+
923+ spawn_vm_io_with_hooks(
924+ output_monitor,
925+ vm_output_fd,
926+ vm_input_fd,
927+ IoControl::new(),
928+ |_| false,
929+ move |bytes| {
930+ if let Some(log) = &log_file
931+ && let Ok(mut file) = log.lock()
932+ {
933+ let _ = file.write_all(bytes);
934+ }
935+ },
936+ )
937+}
938+
856939impl IoContext {
857940 pub fn shutdown(self) {
858941 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -870,7 +953,7 @@ fn create_vm_configuration(
870953 vm_writes_to_fd: OwnedFd,
871954 cpu_count: usize,
872955 ram_bytes: u64,
873−) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
956+) -> Result<Retained<VZVirtualMachineConfiguration>> {
874957 unsafe {
875958 let platform =
876959 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -904,7 +987,7 @@ fn create_vm_configuration(
904987 false,
905988 VZDiskImageCachingMode::Automatic,
906989 VZDiskImageSynchronizationMode::Full,
907− ).unwrap();
990+ )?;
908991
909992 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
910993 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -991,7 +1074,7 @@ fn create_vm_configuration(
9911074 // Validate
9921075 config.validateWithError().map_err(|e| {
9931076 io::Error::other(format!(
994− "Invalid VM configuration: {:?}",
1077+ "invalid VM configuration: {:?}",
9951078 e.localizedDescription()
9961079 ))
9971080 })?;
@@ -1000,9 +1083,9 @@ fn create_vm_configuration(
10001083 }
10011084}
10021085
1003−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1086+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
10041087 unsafe {
1005− let temp_dir = std::env::temp_dir();
1088+ let temp_dir = env::temp_dir();
10061089 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
10071090 let url = nsurl_from_path(&temp_path)?;
10081091 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1018,8 +1101,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std
10181101fn spawn_login_actions_thread(
10191102 login_actions: Vec<LoginAction>,
10201103 output_monitor: Arc<OutputMonitor>,
1021− input_tx: mpsc::Sender<VmInput>,
1022− vm_output_tx: mpsc::Sender<VmOutput>,
1104+ input_tx: Sender<VmInput>,
1105+ vm_output_tx: Sender<VmOutput>,
10231106) -> thread::JoinHandle<()> {
10241107 thread::spawn(move || {
10251108 for a in login_actions {
@@ -1033,6 +1116,27 @@ fn spawn_login_actions_thread(
10331116 return;
10341117 }
10351118 }
1119+ ExpectEither {
1120+ success,
1121+ failure,
1122+ timeout,
1123+ } => match output_monitor.wait_for_any(&[&success, &failure], timeout) {
1124+ WaitAnyResult::Found(0) => {}
1125+ WaitAnyResult::Found(_) => {
1126+ let _ = vm_output_tx.send(VmOutput::LoginActionFailed {
1127+ action: format!("expect '{}'", success),
1128+ reason: format!("saw failure marker '{}'", failure),
1129+ });
1130+ return;
1131+ }
1132+ WaitAnyResult::Timeout => {
1133+ let _ = vm_output_tx.send(VmOutput::LoginActionTimeout {
1134+ action: format!("expect '{}'", success),
1135+ timeout,
1136+ });
1137+ return;
1138+ }
1139+ },
10361140 Send(mut text) => {
10371141 text.push('\n'); // Type the newline so the command is actually submitted.
10381142 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
@@ -1048,9 +1152,9 @@ fn run_vm_with_io<F>(
10481152 directory_shares: &[DirectoryShare],
10491153 cpu_count: usize,
10501154 ram_bytes: u64,
1051− status: Option<&StatusFile>,
1155+ status: Option<&StatusEmitter<'_>>,
10521156 io_handler: F,
1053−) -> Result<(), Box<dyn std::error::Error>>
1157+) -> Result<()>
10541158where
10551159 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
10561160{
@@ -1097,23 +1201,22 @@ where
10971201
10981202 match rx.try_recv() {
10991203 Ok(result) => {
1100− result.map_err(|e| format!("Failed to start VM: {}", e))?;
1204+ result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
11011205 break;
11021206 }
11031207 Err(mpsc::TryRecvError::Empty) => continue,
11041208 Err(mpsc::TryRecvError::Disconnected) => {
1105− return Err("VM start channel disconnected".into());
1209+ bail!("VM start channel disconnected");
11061210 }
11071211 }
11081212 }
11091213
11101214 if Instant::now() >= start_deadline {
1111− return Err("Timed out waiting for VM to start".into());
1215+ bail!("Timed out waiting for VM to start");
11121216 }
11131217
1114− if let Some(status) = status {
1115− status.update("vm booting... go vibecoder!");
1116− }
1218+ emit_status(status, "vm booting... go vibecoder!");
1219+ tracing::info!("vm booting... go vibecoder!");
11171220 tracing::info!("vm booting");
11181221
11191222 let output_monitor = Arc::new(OutputMonitor::default());
@@ -1159,7 +1262,7 @@ where
11591262 );
11601263
11611264 let mut last_state = None;
1162− let mut exit_result = Ok(());
1265+ let mut exit_result: Result<(), String> = Ok(());
11631266 loop {
11641267 unsafe {
11651268 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1178,8 +1281,24 @@ where
11781281 exit_result = Err(format!(
11791282 "Login action ({}) timed out after {:?}; shutting down.",
11801283 action, timeout
1181− )
1182− .into());
1284+ ));
1285+ unsafe {
1286+ if vm.canRequestStop() {
1287+ if let Err(err) = vm.requestStopWithError() {
1288+ tracing::error!(error = ?err, "failed to request VM stop");
1289+ }
1290+ } else if vm.canStop() {
1291+ let handler = RcBlock::new(|_error: *mut NSError| {});
1292+ vm.stopWithCompletionHandler(&handler);
1293+ }
1294+ }
1295+ break;
1296+ }
1297+ Ok(VmOutput::LoginActionFailed { action, reason }) => {
1298+ exit_result = Err(format!(
1299+ "Login action ({}) failed: {}; shutting down.",
1300+ action, reason
1301+ ));
11831302 unsafe {
11841303 if vm.canRequestStop() {
11851304 if let Err(err) = vm.requestStopWithError() {
@@ -1195,7 +1314,7 @@ where
11951314 Err(mpsc::TryRecvError::Empty) => {}
11961315 Err(mpsc::TryRecvError::Disconnected) => {}
11971316 }
1198− if state != objc2_virtualization::VZVirtualMachineState::Running {
1317+ if state != VZVirtualMachineState::Running {
11991318 //eprintln!("VM stopped with state: {:?}", state);
12001319 break;
12011320 }
@@ -1205,7 +1324,7 @@ where
12051324
12061325 io_ctx.shutdown();
12071326
1208− exit_result
1327+ exit_result.map_err(Error::msg)
12091328}
12101329
12111330fn run_vm(
@@ -1214,8 +1333,8 @@ fn run_vm(
12141333 directory_shares: &[DirectoryShare],
12151334 cpu_count: usize,
12161335 ram_bytes: u64,
1217− status: Option<&StatusFile>,
1218−) -> Result<(), Box<dyn std::error::Error>> {
1336+ status: Option<&StatusEmitter<'_>>,
1337+) -> Result<()> {
12191338 run_vm_with_io(
12201339 disk_path,
12211340 login_actions,
@@ -1227,7 +1346,7 @@ fn run_vm(
12271346 )
12281347}
12291348
1230−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
1349+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
12311350 let abs_path = if path.is_absolute() {
12321351 path.to_path_buf()
12331352 } else {
@@ -1236,7 +1355,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::E
12361355 let ns_path = NSString::from_str(
12371356 abs_path
12381357 .to_str()
1239− .ok_or("Non-UTF8 path encountered while building NSURL")?,
1358+ .with_context(|| "non-UTF8 path encountered while building NSURL")?,
12401359 );
12411360 Ok(NSURL::fileURLWithPath(&ns_path))
12421361}
@@ -1251,7 +1370,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
12511370 let original = attributes;
12521371
12531372 // Disable translation of carriage return to newline on input
1254− attributes.c_iflag &= !(libc::ICRNL);
1373+ attributes.c_iflag &= !libc::ICRNL;
12551374 // Disable canonical mode (line buffering), echo, and signal generation
12561375 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
12571376 attributes.c_cc[libc::VMIN] = 0;
@@ -1279,10 +1398,10 @@ impl Drop for RawModeGuard {
12791398
12801399// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
12811400pub fn ensure_signed() {
1282− if std::env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1401+ if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
12831402 return;
12841403 }
1285− let exe = std::env::current_exe().expect("failed to get current exe path");
1404+ let exe = env::current_exe().expect("failed to get current exe path");
12861405 let exe_str = exe.to_str().expect("exe path not valid utf-8");
12871406
12881407 let has_required_entitlements = {
@@ -1304,8 +1423,8 @@ pub fn ensure_signed() {
13041423 }
13051424
13061425 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1307− let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1308− std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1426+ let entitlements_path = env::temp_dir().join("entitlements.plist");
1427+ fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
13091428
13101429 let output = Command::new("codesign")
13111430 .args([
@@ -1318,7 +1437,7 @@ pub fn ensure_signed() {
13181437 ])
13191438 .output();
13201439
1321− let _ = std::fs::remove_file(&entitlements_path);
1440+ let _ = fs::remove_file(&entitlements_path);
13221441
13231442 match output {
13241443 Ok(o) if o.status.success() => {
@@ -1326,7 +1445,7 @@ pub fn ensure_signed() {
13261445 if !stderr.trim().is_empty() {
13271446 tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
13281447 }
1329− let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
1448+ let err = Command::new(&exe).args(env::args_os().skip(1)).exec();
13301449 tracing::error!(error = %err, "failed to re-exec after signing");
13311450 std::process::exit(1);
13321451 }