@@ -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,49 +35,19 @@ 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);
4340const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
4441
45−struct StatusFile {
46− path: PathBuf,
47− cleared: AtomicBool,
48−}
49−
50−impl StatusFile {
51− fn new(path: PathBuf) -> Self {
52− Self {
53− path,
54− cleared: AtomicBool::new(false),
55− }
56− }
57−
58− fn update(&self, message: &str) {
59− let _ = fs::write(&self.path, message);
60− }
61−}
62−
63−impl Drop for StatusFile {
64− fn drop(&mut self) {
65− if !self.cleared.load(Ordering::SeqCst) {
66− let _ = fs::remove_file(&self.path);
67− self.cleared.store(true, Ordering::SeqCst);
68− }
69− }
70−}
42+const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
7143const PROVISION_SCRIPT: &str = include_str!("provision.sh");
72−const PROVISION_SCRIPT_NAME: &str = "provision.sh";
7344const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
7445const DEFAULT_RAW_NAME: &str = "default.raw";
7546const INSTANCE_RAW_NAME: &str = "instance.raw";
7647const BASE_DISK_RAW_NAME: &str = "disk.raw";
7748
7849#[derive(Clone)]
79−pub(crate) enum LoginAction {
50+pub enum LoginAction {
8051 Expect {
8152 text: String,
8253 timeout: Duration,
@@ -88,23 +59,20 @@ pub(crate) enum LoginAction {
8859 },
8960 Send(String),
9061}
62+use crate::config::BoxConfig;
9163use LoginAction::*;
9264
9365#[derive(Clone)]
94−pub(crate) struct DirectoryShare {
66+pub struct DirectoryShare {
9567 host: PathBuf,
9668 guest: PathBuf,
9769 read_only: bool,
9870}
9971
10072impl DirectoryShare {
101− pub(crate) fn new(
102− host: PathBuf,
103− mut guest: PathBuf,
104− read_only: bool,
105− ) -> Result<Self, Box<dyn std::error::Error>> {
73+ pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
10674 if !host.exists() {
107− return Err(format!("Host path does not exist: {}", host.display()).into());
75+ bail!(format!("host path does not exist: {}", host.display()));
10876 }
10977 if !guest.is_absolute() {
11078 guest = PathBuf::from("/root").join(guest);
@@ -116,10 +84,10 @@ impl DirectoryShare {
11684 })
11785 }
11886
119− 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> {
12088 let parts: Vec<&str> = spec.split(':').collect();
12189 if parts.len() < 2 || parts.len() > 3 {
122− return Err(format!("Invalid mount spec: {spec}").into());
90+ bail!(format!("invalid mount spec: {spec}"));
12391 }
12492 let host = expand_tilde_path(parts[0]);
12593 let guest = PathBuf::from(parts[1]);
@@ -128,11 +96,10 @@ impl DirectoryShare {
12896 "read-only" => true,
12997 "read-write" => false,
13098 _ => {
131− return Err(format!(
99+ bail!(format!(
132100 "Invalid mount mode '{}'; expected read-only or read-write",
133101 parts[2]
134− )
135− .into());
102+ ));
136103 }
137104 }
138105 } else {
@@ -176,19 +143,28 @@ pub struct VmArg {
176143 pub mounts: Vec<String>,
177144}
178145
179−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<()>
180155where
181156 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
182157{
183− 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)
184159}
185160
186−pub(crate) fn run_with_args_and_extras<F>(
161+pub fn run_with_args_and_extras<F>(
187162 args: VmArg,
188163 io_handler: F,
189164 extra_login_actions: Vec<LoginAction>,
190165 extra_directory_shares: Vec<DirectoryShare>,
191−) -> Result<(), Box<dyn std::error::Error>>
166+ status: Option<&StatusEmitter<'_>>,
167+) -> Result<()>
192168where
193169 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
194170{
@@ -197,7 +173,7 @@ where
197173 let project_root = env::current_dir()?;
198174 let project_name = project_root
199175 .file_name()
200− .ok_or("Project directory has no name")?
176+ .with_context(|| "Project directory has no name")?
201177 .to_string_lossy()
202178 .into_owned();
203179
@@ -209,8 +185,10 @@ where
209185 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
210186
211187 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
212− let status_file = StatusFile::new(instance_dir.join(STATUS_FILE_NAME));
213− 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");
214192
215193 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
216194 let base_compressed = cache_dir.join(basename_compressed);
@@ -234,13 +212,14 @@ where
234212 &base_compressed,
235213 &default_raw,
236214 std::slice::from_ref(&mise_directory_share),
237− Some(&status_file),
215+ Some(&provision_log),
216+ status,
238217 )?;
239218 let _ = ensure_instance_disk(
240219 &instance_raw,
241220 &default_raw,
242− args.disk_bytes,
243− Some(&status_file),
221+ ByteSize(args.disk_bytes),
222+ status,
244223 )?;
245224 let base_size = fs::metadata(&default_raw)?.len();
246225 let instance_size = fs::metadata(&instance_raw)?.len();
@@ -270,7 +249,7 @@ where
270249 }
271250
272251 if needs_resize {
273− 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)?;
274253 login_actions.push(Send(resize_cmd));
275254 }
276255
@@ -286,25 +265,29 @@ where
286265 &directory_shares[..],
287266 args.cpu_count,
288267 args.ram_bytes,
289− Some(&status_file),
268+ status,
290269 io_handler,
291270 )
292271}
293272
294−pub(crate) fn script_command_from_content(
295− label: &str,
296− script: &str,
297−) -> Result<String, Box<dyn std::error::Error>> {
273+pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
298274 let marker = "VIBE_SCRIPT_EOF";
299275 let guest_dir = "/tmp/vibe-scripts";
300276 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);
301284 let command = format!(
302− "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}"
303286 );
304287 if script.contains(marker) {
305− return Err(
306− format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
307− );
288+ bail!(format!(
289+ "Script '{label}' contains marker '{marker}', cannot safely upload"
290+ ));
308291 }
309292 Ok(command)
310293}
@@ -501,18 +484,16 @@ impl IoControl {
501484fn ensure_base_image(
502485 base_raw: &Path,
503486 base_compressed: &Path,
504− status: Option<&StatusFile>,
505−) -> Result<(), Box<dyn std::error::Error>> {
487+ status: Option<&StatusEmitter<'_>>,
488+) -> Result<()> {
506489 if base_raw.exists() {
507490 return Ok(());
508491 }
509492
510493 if !base_compressed.exists()
511− || 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
512495 {
513− if let Some(status) = status {
514− status.update("downloading base image...");
515− }
496+ emit_status(status, "downloading base image...");
516497 tracing::info!("downloading base image");
517498 let status = Command::new("curl")
518499 .args([
@@ -527,15 +508,14 @@ fn ensure_base_image(
527508 ])
528509 .status()?;
529510 if !status.success() {
530− return Err("Failed to download base image".into());
511+ bail!("failed to download base image");
531512 }
532513 }
533514
534515 // Check SHA
535516 {
536− if let Some(status) = status {
537− status.update("verifying base image...");
538− }
517+ emit_status(status, "verifying base image...");
518+ tracing::info!("verifying base image...");
539519 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
540520
541521 let mut child = Command::new("/usr/bin/shasum")
@@ -553,25 +533,25 @@ fn ensure_base_image(
553533
554534 let status = child.wait().expect("failed to wait on child");
555535 if !status.success() {
556− 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+ ));
557539 }
558540 }
559541
560− if let Some(status) = status {
561− status.update("decompressing base image...");
562− }
563− tracing::info!("decompressing base image");
542+ emit_status(status, "decompressing base image...");
543+ tracing::info!("decompressing base image...");
564544 let status = Command::new("tar")
565545 .args([
566546 "-xOf",
567547 &base_compressed.to_string_lossy(),
568548 BASE_DISK_RAW_NAME,
569549 ])
570− .stdout(std::fs::File::create(base_raw)?)
550+ .stdout(fs::File::create(base_raw)?)
571551 .status()?;
572552
573553 if !status.success() {
574− return Err("Failed to decompress base image".into());
554+ bail!("Failed to decompress base image");
575555 }
576556
577557 Ok(())
@@ -582,21 +562,20 @@ fn ensure_default_image(
582562 base_compressed: &Path,
583563 default_raw: &Path,
584564 directory_shares: &[DirectoryShare],
585− status: Option<&StatusFile>,
586−) -> Result<(), Box<dyn std::error::Error>> {
565+ provision_log: Option<&Path>,
566+ status: Option<&StatusEmitter<'_>>,
567+) -> Result<()> {
587568 if default_raw.exists() {
588569 return Ok(());
589570 }
590571
591572 ensure_base_image(base_raw, base_compressed, status)?;
592573
593− if let Some(status) = status {
594− status.update("configuring base image...");
595− }
596− tracing::info!("configuring base image");
574+ emit_status(status, "configuring base image...");
575+ tracing::info!("configuring base image...");
597576 fs::copy(base_raw, default_raw)?;
598577
599− let provision_command = script_command_from_content(PROVISION_SCRIPT_NAME, PROVISION_SCRIPT)?;
578+ let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
600579 let provision_actions = [
601580 Send(provision_command),
602581 ExpectEither {
@@ -605,14 +584,31 @@ fn ensure_default_image(
605584 timeout: PROVISION_EXPECT_TIMEOUT,
606585 },
607586 ];
608− if let Err(err) = run_vm(
609− default_raw,
610− &provision_actions,
611− directory_shares,
612− DEFAULT_CPU_COUNT,
613− DEFAULT_RAM_BYTES,
614− None,
615− ) {
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 {
616612 let _ = fs::remove_file(default_raw);
617613 return Err(err);
618614 }
@@ -623,18 +619,16 @@ fn ensure_default_image(
623619fn ensure_instance_disk(
624620 instance_raw: &Path,
625621 template_raw: &Path,
626− target_bytes: u64,
627− status: Option<&StatusFile>,
628−) -> Result<bool, Box<dyn std::error::Error>> {
622+ target_bytes: ByteSize,
623+ status: Option<&StatusEmitter<'_>>,
624+) -> Result<bool> {
629625 if instance_raw.exists() {
630− let current_size = fs::metadata(instance_raw)?.len();
626+ let current_size = ByteSize(fs::metadata(instance_raw)?.len());
631627 if current_size != target_bytes {
632− let current_gb = current_size as f64 / (1024.0 * 1024.0 * 1024.0);
633− 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;
634630 tracing::warn!(
635− current_bytes = current_size,
636− target_bytes,
637− "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.",
638632 current_gb,
639633 target_gb
640634 );
@@ -642,30 +636,28 @@ fn ensure_instance_disk(
642636 return Ok(false);
643637 }
644638
645− let template_size = fs::metadata(template_raw)?.len();
639+ let template_size = ByteSize(fs::metadata(template_raw)?.len());
646640 if target_bytes < template_size {
647− return Err(format!(
648− "Requested disk size {} bytes is smaller than base image size {} bytes",
641+ bail!(format!(
642+ "Requested disk size {} is smaller than base image size {}",
649643 target_bytes, template_size
650− )
651− .into());
644+ ));
652645 }
653646 let target_size = target_bytes;
654647 let needs_resize = target_size > template_size;
655648
656− if let Some(status) = status {
657− status.update("creating instance disk...");
658− }
649+ emit_status(status, "creating instance disk...");
650+ tracing::info!("creating instance disk...");
659651 tracing::info!(path = %template_raw.display(), "creating instance disk");
660− std::fs::create_dir_all(instance_raw.parent().unwrap())?;
652+ fs::create_dir_all(instance_raw.parent().unwrap())?;
661653 if target_size == template_size {
662654 fs::copy(template_raw, instance_raw)?;
663655 return Ok(needs_resize);
664656 }
665657
666− let mut dst = std::fs::File::create(instance_raw)?;
667− dst.set_len(target_size)?;
668− 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)?;
669661 std::io::copy(&mut src, &mut dst)?;
670662 Ok(needs_resize)
671663}
@@ -683,18 +675,17 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
683675 (read_stream.into(), write_stream.into())
684676}
685677
686−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+>(
687682 output_monitor: Arc<OutputMonitor>,
688683 vm_output_fd: OwnedFd,
689684 vm_input_fd: OwnedFd,
690685 io_control: Arc<IoControl>,
691686 mut on_line: F,
692687 mut on_output: G,
693−) -> IoContext
694−where
695− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
696− G: FnMut(&[u8]) + ::std::marker::Send + 'static,
697−{
688+) -> IoContext {
698689 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
699690
700691 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
@@ -842,14 +833,14 @@ where
842833 PollResult::Spurious => continue,
843834 PollResult::Ready(bytes) => {
844835 if io_control.forward_output() {
845− // enable raw mode, if we haven't already
836+ // enable raw mode if we haven't already
846837 if raw_guard.lock().unwrap().is_none()
847838 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
848839 {
849840 *raw_guard.lock().unwrap() = Some(guard);
850841 }
851842
852− let mut stdout = std::io::stdout().lock();
843+ let mut stdout = io::stdout().lock();
853844 if stdout.write_all(bytes).is_err() {
854845 break;
855846 }
@@ -865,7 +856,7 @@ where
865856
866857 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
867858 let mux_thread = thread::spawn(move || {
868− let mut vm_writer = std::fs::File::from(vm_input_fd);
859+ let mut vm_writer = fs::File::from(vm_input_fd);
869860 loop {
870861 match input_rx.recv() {
871862 Ok(VmInput::Bytes(data)) => {
@@ -895,7 +886,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
895886 on_line: F,
896887) -> IoContext
897888where
898− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
889+ F: FnMut(&str) -> bool + std::marker::Send + 'static,
899890{
900891 spawn_vm_io_with_hooks(
901892 output_monitor,
@@ -915,6 +906,36 @@ pub fn spawn_vm_io(
915906 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
916907}
917908
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+
918939impl IoContext {
919940 pub fn shutdown(self) {
920941 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -932,7 +953,7 @@ fn create_vm_configuration(
932953 vm_writes_to_fd: OwnedFd,
933954 cpu_count: usize,
934955 ram_bytes: u64,
935−) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
956+) -> Result<Retained<VZVirtualMachineConfiguration>> {
936957 unsafe {
937958 let platform =
938959 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -966,7 +987,7 @@ fn create_vm_configuration(
966987 false,
967988 VZDiskImageCachingMode::Automatic,
968989 VZDiskImageSynchronizationMode::Full,
969− ).unwrap();
990+ )?;
970991
971992 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
972993 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1053,7 +1074,7 @@ fn create_vm_configuration(
10531074 // Validate
10541075 config.validateWithError().map_err(|e| {
10551076 io::Error::other(format!(
1056− "Invalid VM configuration: {:?}",
1077+ "invalid VM configuration: {:?}",
10571078 e.localizedDescription()
10581079 ))
10591080 })?;
@@ -1062,9 +1083,9 @@ fn create_vm_configuration(
10621083 }
10631084}
10641085
1065−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1086+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
10661087 unsafe {
1067− let temp_dir = std::env::temp_dir();
1088+ let temp_dir = env::temp_dir();
10681089 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
10691090 let url = nsurl_from_path(&temp_path)?;
10701091 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1080,8 +1101,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std
10801101fn spawn_login_actions_thread(
10811102 login_actions: Vec<LoginAction>,
10821103 output_monitor: Arc<OutputMonitor>,
1083− input_tx: mpsc::Sender<VmInput>,
1084− vm_output_tx: mpsc::Sender<VmOutput>,
1104+ input_tx: Sender<VmInput>,
1105+ vm_output_tx: Sender<VmOutput>,
10851106) -> thread::JoinHandle<()> {
10861107 thread::spawn(move || {
10871108 for a in login_actions {
@@ -1131,9 +1152,9 @@ fn run_vm_with_io<F>(
11311152 directory_shares: &[DirectoryShare],
11321153 cpu_count: usize,
11331154 ram_bytes: u64,
1134− status: Option<&StatusFile>,
1155+ status: Option<&StatusEmitter<'_>>,
11351156 io_handler: F,
1136−) -> Result<(), Box<dyn std::error::Error>>
1157+) -> Result<()>
11371158where
11381159 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
11391160{
@@ -1180,23 +1201,22 @@ where
11801201
11811202 match rx.try_recv() {
11821203 Ok(result) => {
1183− result.map_err(|e| format!("Failed to start VM: {}", e))?;
1204+ result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
11841205 break;
11851206 }
11861207 Err(mpsc::TryRecvError::Empty) => continue,
11871208 Err(mpsc::TryRecvError::Disconnected) => {
1188− return Err("VM start channel disconnected".into());
1209+ bail!("VM start channel disconnected");
11891210 }
11901211 }
11911212 }
11921213
11931214 if Instant::now() >= start_deadline {
1194− return Err("Timed out waiting for VM to start".into());
1215+ bail!("Timed out waiting for VM to start");
11951216 }
11961217
1197− if let Some(status) = status {
1198− status.update("vm booting... go vibecoder!");
1199− }
1218+ emit_status(status, "vm booting... go vibecoder!");
1219+ tracing::info!("vm booting... go vibecoder!");
12001220 tracing::info!("vm booting");
12011221
12021222 let output_monitor = Arc::new(OutputMonitor::default());
@@ -1242,7 +1262,7 @@ where
12421262 );
12431263
12441264 let mut last_state = None;
1245− let mut exit_result = Ok(());
1265+ let mut exit_result: Result<(), String> = Ok(());
12461266 loop {
12471267 unsafe {
12481268 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1261,8 +1281,7 @@ where
12611281 exit_result = Err(format!(
12621282 "Login action ({}) timed out after {:?}; shutting down.",
12631283 action, timeout
1264− )
1265− .into());
1284+ ));
12661285 unsafe {
12671286 if vm.canRequestStop() {
12681287 if let Err(err) = vm.requestStopWithError() {
@@ -1279,8 +1298,7 @@ where
12791298 exit_result = Err(format!(
12801299 "Login action ({}) failed: {}; shutting down.",
12811300 action, reason
1282− )
1283− .into());
1301+ ));
12841302 unsafe {
12851303 if vm.canRequestStop() {
12861304 if let Err(err) = vm.requestStopWithError() {
@@ -1296,7 +1314,7 @@ where
12961314 Err(mpsc::TryRecvError::Empty) => {}
12971315 Err(mpsc::TryRecvError::Disconnected) => {}
12981316 }
1299− if state != objc2_virtualization::VZVirtualMachineState::Running {
1317+ if state != VZVirtualMachineState::Running {
13001318 //eprintln!("VM stopped with state: {:?}", state);
13011319 break;
13021320 }
@@ -1306,7 +1324,7 @@ where
13061324
13071325 io_ctx.shutdown();
13081326
1309− exit_result
1327+ exit_result.map_err(Error::msg)
13101328}
13111329
13121330fn run_vm(
@@ -1315,8 +1333,8 @@ fn run_vm(
13151333 directory_shares: &[DirectoryShare],
13161334 cpu_count: usize,
13171335 ram_bytes: u64,
1318− status: Option<&StatusFile>,
1319−) -> Result<(), Box<dyn std::error::Error>> {
1336+ status: Option<&StatusEmitter<'_>>,
1337+) -> Result<()> {
13201338 run_vm_with_io(
13211339 disk_path,
13221340 login_actions,
@@ -1328,7 +1346,7 @@ fn run_vm(
13281346 )
13291347}
13301348
1331−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
1349+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
13321350 let abs_path = if path.is_absolute() {
13331351 path.to_path_buf()
13341352 } else {
@@ -1337,7 +1355,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::E
13371355 let ns_path = NSString::from_str(
13381356 abs_path
13391357 .to_str()
1340− .ok_or("Non-UTF8 path encountered while building NSURL")?,
1358+ .with_context(|| "non-UTF8 path encountered while building NSURL")?,
13411359 );
13421360 Ok(NSURL::fileURLWithPath(&ns_path))
13431361}
@@ -1352,7 +1370,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
13521370 let original = attributes;
13531371
13541372 // Disable translation of carriage return to newline on input
1355− attributes.c_iflag &= !(libc::ICRNL);
1373+ attributes.c_iflag &= !libc::ICRNL;
13561374 // Disable canonical mode (line buffering), echo, and signal generation
13571375 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
13581376 attributes.c_cc[libc::VMIN] = 0;
@@ -1380,10 +1398,10 @@ impl Drop for RawModeGuard {
13801398
13811399// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
13821400pub fn ensure_signed() {
1383− if std::env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1401+ if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
13841402 return;
13851403 }
1386− 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");
13871405 let exe_str = exe.to_str().expect("exe path not valid utf-8");
13881406
13891407 let has_required_entitlements = {
@@ -1405,8 +1423,8 @@ pub fn ensure_signed() {
14051423 }
14061424
14071425 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1408− let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1409− 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");
14101428
14111429 let output = Command::new("codesign")
14121430 .args([
@@ -1419,7 +1437,7 @@ pub fn ensure_signed() {
14191437 ])
14201438 .output();
14211439
1422− let _ = std::fs::remove_file(&entitlements_path);
1440+ let _ = fs::remove_file(&entitlements_path);
14231441
14241442 match output {
14251443 Ok(o) if o.status.success() => {
@@ -1427,7 +1445,7 @@ pub fn ensure_signed() {
14271445 if !stderr.trim().is_empty() {
14281446 tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
14291447 }
1430− 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();
14311449 tracing::error!(error = %err, "failed to re-exec after signing");
14321450 std::process::exit(1);
14331451 }