@@ -1,5 +1,5 @@
1+use crate::instance::STATUS_FILE_NAME;
12use 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,7 +23,6 @@ use std::{
2323};
2424
2525use block2::RcBlock;
26−use bytesize::ByteSize;
2726use dispatch2::DispatchQueue;
2827use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
2928use objc2_foundation::*;
@@ -35,19 +34,49 @@ const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
3534const SHARED_DIRECTORIES_TAG: &str = "shared";
3635pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
3736
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;
3841const START_TIMEOUT: Duration = Duration::from_secs(60);
3942const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
4043const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
4144
42−const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
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+}
4371const PROVISION_SCRIPT: &str = include_str!("provision.sh");
72+const PROVISION_SCRIPT_NAME: &str = "provision.sh";
4473const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
4574const DEFAULT_RAW_NAME: &str = "default.raw";
4675const INSTANCE_RAW_NAME: &str = "instance.raw";
4776const BASE_DISK_RAW_NAME: &str = "disk.raw";
4877
4978#[derive(Clone)]
50−pub enum LoginAction {
79+pub(crate) enum LoginAction {
5180 Expect {
5281 text: String,
5382 timeout: Duration,
@@ -59,20 +88,23 @@ pub enum LoginAction {
5988 },
6089 Send(String),
6190}
62−use crate::config::BoxConfig;
6391use LoginAction::*;
6492
6593#[derive(Clone)]
66−pub struct DirectoryShare {
94+pub(crate) struct DirectoryShare {
6795 host: PathBuf,
6896 guest: PathBuf,
6997 read_only: bool,
7098}
7199
72100impl DirectoryShare {
73− pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
101+ pub(crate) fn new(
102+ host: PathBuf,
103+ mut guest: PathBuf,
104+ read_only: bool,
105+ ) -> Result<Self, Box<dyn std::error::Error>> {
74106 if !host.exists() {
75− bail!(format!("host path does not exist: {}", host.display()));
107+ return Err(format!("Host path does not exist: {}", host.display()).into());
76108 }
77109 if !guest.is_absolute() {
78110 guest = PathBuf::from("/root").join(guest);
@@ -84,10 +116,10 @@ impl DirectoryShare {
84116 })
85117 }
86118
87− pub fn from_mount_spec(spec: &str) -> Result<Self> {
119+ pub(crate) fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
88120 let parts: Vec<&str> = spec.split(':').collect();
89121 if parts.len() < 2 || parts.len() > 3 {
90− bail!(format!("invalid mount spec: {spec}"));
122+ return Err(format!("Invalid mount spec: {spec}").into());
91123 }
92124 let host = expand_tilde_path(parts[0]);
93125 let guest = PathBuf::from(parts[1]);
@@ -96,10 +128,11 @@ impl DirectoryShare {
96128 "read-only" => true,
97129 "read-write" => false,
98130 _ => {
99− bail!(format!(
131+ return Err(format!(
100132 "Invalid mount mode '{}'; expected read-only or read-write",
101133 parts[2]
102− ));
134+ )
135+ .into());
103136 }
104137 }
105138 } else {
@@ -143,28 +176,19 @@ pub struct VmArg {
143176 pub mounts: Vec<String>,
144177}
145178
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<()>
179+pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<(), Box<dyn std::error::Error>>
155180where
156181 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
157182{
158− run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new(), None)
183+ run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new())
159184}
160185
161−pub fn run_with_args_and_extras<F>(
186+pub(crate) fn run_with_args_and_extras<F>(
162187 args: VmArg,
163188 io_handler: F,
164189 extra_login_actions: Vec<LoginAction>,
165190 extra_directory_shares: Vec<DirectoryShare>,
166− status: Option<&StatusEmitter<'_>>,
167−) -> Result<()>
191+) -> Result<(), Box<dyn std::error::Error>>
168192where
169193 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
170194{
@@ -173,7 +197,7 @@ where
173197 let project_root = env::current_dir()?;
174198 let project_name = project_root
175199 .file_name()
176− .with_context(|| "Project directory has no name")?
200+ .ok_or("Project directory has no name")?
177201 .to_string_lossy()
178202 .into_owned();
179203
@@ -185,10 +209,8 @@ where
185209 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
186210
187211 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
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");
212+ let status_file = StatusFile::new(instance_dir.join(STATUS_FILE_NAME));
213+ status_file.update("preparing VM image...");
192214
193215 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
194216 let base_compressed = cache_dir.join(basename_compressed);
@@ -212,14 +234,13 @@ where
212234 &base_compressed,
213235 &default_raw,
214236 std::slice::from_ref(&mise_directory_share),
215− Some(&provision_log),
216− status,
237+ Some(&status_file),
217238 )?;
218239 let _ = ensure_instance_disk(
219240 &instance_raw,
220241 &default_raw,
221− ByteSize(args.disk_bytes),
222− status,
242+ args.disk_bytes,
243+ Some(&status_file),
223244 )?;
224245 let base_size = fs::metadata(&default_raw)?.len();
225246 let instance_size = fs::metadata(&instance_raw)?.len();
@@ -249,7 +270,7 @@ where
249270 }
250271
251272 if needs_resize {
252− let resize_cmd = script_command_from_content("resize_disk.sh", RESIZE_DISK_SCRIPT)?;
273+ let resize_cmd = script_command_from_content("resize_disk", RESIZE_DISK_SCRIPT)?;
253274 login_actions.push(Send(resize_cmd));
254275 }
255276
@@ -265,29 +286,25 @@ where
265286 &directory_shares[..],
266287 args.cpu_count,
267288 args.ram_bytes,
268− status,
289+ Some(&status_file),
269290 io_handler,
270291 )
271292}
272293
273−pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
294+pub(crate) fn script_command_from_content(
295+ label: &str,
296+ script: &str,
297+) -> Result<String, Box<dyn std::error::Error>> {
274298 let marker = "VIBE_SCRIPT_EOF";
275299 let guest_dir = "/tmp/vibe-scripts";
276300 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);
284301 let command = format!(
285− "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{wrapped_script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
302+ "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
286303 );
287304 if script.contains(marker) {
288− bail!(format!(
289− "Script '{label}' contains marker '{marker}', cannot safely upload"
290− ));
305+ return Err(
306+ format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
307+ );
291308 }
292309 Ok(command)
293310}
@@ -484,16 +501,18 @@ impl IoControl {
484501fn ensure_base_image(
485502 base_raw: &Path,
486503 base_compressed: &Path,
487− status: Option<&StatusEmitter<'_>>,
488−) -> Result<()> {
504+ status: Option<&StatusFile>,
505+) -> Result<(), Box<dyn std::error::Error>> {
489506 if base_raw.exists() {
490507 return Ok(());
491508 }
492509
493510 if !base_compressed.exists()
494− || fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
511+ || std::fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
495512 {
496− emit_status(status, "downloading base image...");
513+ if let Some(status) = status {
514+ status.update("downloading base image...");
515+ }
497516 tracing::info!("downloading base image");
498517 let status = Command::new("curl")
499518 .args([
@@ -508,14 +527,15 @@ fn ensure_base_image(
508527 ])
509528 .status()?;
510529 if !status.success() {
511− bail!("failed to download base image");
530+ return Err("Failed to download base image".into());
512531 }
513532 }
514533
515534 // Check SHA
516535 {
517− emit_status(status, "verifying base image...");
518− tracing::info!("verifying base image...");
536+ if let Some(status) = status {
537+ status.update("verifying base image...");
538+ }
519539 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
520540
521541 let mut child = Command::new("/usr/bin/shasum")
@@ -533,25 +553,25 @@ fn ensure_base_image(
533553
534554 let status = child.wait().expect("failed to wait on child");
535555 if !status.success() {
536− bail!(format!(
537− "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
538− ));
556+ return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
539557 }
540558 }
541559
542− emit_status(status, "decompressing base image...");
543− tracing::info!("decompressing base image...");
560+ if let Some(status) = status {
561+ status.update("decompressing base image...");
562+ }
563+ tracing::info!("decompressing base image");
544564 let status = Command::new("tar")
545565 .args([
546566 "-xOf",
547567 &base_compressed.to_string_lossy(),
548568 BASE_DISK_RAW_NAME,
549569 ])
550− .stdout(fs::File::create(base_raw)?)
570+ .stdout(std::fs::File::create(base_raw)?)
551571 .status()?;
552572
553573 if !status.success() {
554− bail!("Failed to decompress base image");
574+ return Err("Failed to decompress base image".into());
555575 }
556576
557577 Ok(())
@@ -562,20 +582,21 @@ fn ensure_default_image(
562582 base_compressed: &Path,
563583 default_raw: &Path,
564584 directory_shares: &[DirectoryShare],
565− provision_log: Option<&Path>,
566− status: Option<&StatusEmitter<'_>>,
567−) -> Result<()> {
585+ status: Option<&StatusFile>,
586+) -> Result<(), Box<dyn std::error::Error>> {
568587 if default_raw.exists() {
569588 return Ok(());
570589 }
571590
572591 ensure_base_image(base_raw, base_compressed, status)?;
573592
574− emit_status(status, "configuring base image...");
575− tracing::info!("configuring base image...");
593+ if let Some(status) = status {
594+ status.update("configuring base image...");
595+ }
596+ tracing::info!("configuring base image");
576597 fs::copy(base_raw, default_raw)?;
577598
578− let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
599+ let provision_command = script_command_from_content(PROVISION_SCRIPT_NAME, PROVISION_SCRIPT)?;
579600 let provision_actions = [
580601 Send(provision_command),
581602 ExpectEither {
@@ -584,31 +605,14 @@ fn ensure_default_image(
584605 timeout: PROVISION_EXPECT_TIMEOUT,
585606 },
586607 ];
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 {
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+ ) {
612616 let _ = fs::remove_file(default_raw);
613617 return Err(err);
614618 }
@@ -619,16 +623,18 @@ fn ensure_default_image(
619623fn ensure_instance_disk(
620624 instance_raw: &Path,
621625 template_raw: &Path,
622− target_bytes: ByteSize,
623− status: Option<&StatusEmitter<'_>>,
624−) -> Result<bool> {
626+ target_bytes: u64,
627+ status: Option<&StatusFile>,
628+) -> Result<bool, Box<dyn std::error::Error>> {
625629 if instance_raw.exists() {
626− let current_size = ByteSize(fs::metadata(instance_raw)?.len());
630+ let current_size = fs::metadata(instance_raw)?.len();
627631 if current_size != target_bytes {
628− let current_gb = current_size;
629− let target_gb = 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);
630634 tracing::warn!(
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.",
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.",
632638 current_gb,
633639 target_gb
634640 );
@@ -636,28 +642,30 @@ fn ensure_instance_disk(
636642 return Ok(false);
637643 }
638644
639− let template_size = ByteSize(fs::metadata(template_raw)?.len());
645+ let template_size = fs::metadata(template_raw)?.len();
640646 if target_bytes < template_size {
641− bail!(format!(
642− "Requested disk size {} is smaller than base image size {}",
647+ return Err(format!(
648+ "Requested disk size {} bytes is smaller than base image size {} bytes",
643649 target_bytes, template_size
644− ));
650+ )
651+ .into());
645652 }
646653 let target_size = target_bytes;
647654 let needs_resize = target_size > template_size;
648655
649− emit_status(status, "creating instance disk...");
650− tracing::info!("creating instance disk...");
656+ if let Some(status) = status {
657+ status.update("creating instance disk...");
658+ }
651659 tracing::info!(path = %template_raw.display(), "creating instance disk");
652− fs::create_dir_all(instance_raw.parent().unwrap())?;
660+ std::fs::create_dir_all(instance_raw.parent().unwrap())?;
653661 if target_size == template_size {
654662 fs::copy(template_raw, instance_raw)?;
655663 return Ok(needs_resize);
656664 }
657665
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)?;
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)?;
661669 std::io::copy(&mut src, &mut dst)?;
662670 Ok(needs_resize)
663671}
@@ -675,17 +683,18 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
675683 (read_stream.into(), write_stream.into())
676684}
677685
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−>(
686+pub fn spawn_vm_io_with_hooks<F, G>(
682687 output_monitor: Arc<OutputMonitor>,
683688 vm_output_fd: OwnedFd,
684689 vm_input_fd: OwnedFd,
685690 io_control: Arc<IoControl>,
686691 mut on_line: F,
687692 mut on_output: G,
688−) -> IoContext {
693+) -> IoContext
694+where
695+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
696+ G: FnMut(&[u8]) + ::std::marker::Send + 'static,
697+{
689698 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
690699
691700 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
@@ -833,14 +842,14 @@ pub fn spawn_vm_io_with_hooks<
833842 PollResult::Spurious => continue,
834843 PollResult::Ready(bytes) => {
835844 if io_control.forward_output() {
836− // enable raw mode if we haven't already
845+ // enable raw mode, if we haven't already
837846 if raw_guard.lock().unwrap().is_none()
838847 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
839848 {
840849 *raw_guard.lock().unwrap() = Some(guard);
841850 }
842851
843− let mut stdout = io::stdout().lock();
852+ let mut stdout = std::io::stdout().lock();
844853 if stdout.write_all(bytes).is_err() {
845854 break;
846855 }
@@ -856,7 +865,7 @@ pub fn spawn_vm_io_with_hooks<
856865
857866 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
858867 let mux_thread = thread::spawn(move || {
859− let mut vm_writer = fs::File::from(vm_input_fd);
868+ let mut vm_writer = std::fs::File::from(vm_input_fd);
860869 loop {
861870 match input_rx.recv() {
862871 Ok(VmInput::Bytes(data)) => {
@@ -886,7 +895,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
886895 on_line: F,
887896) -> IoContext
888897where
889− F: FnMut(&str) -> bool + std::marker::Send + 'static,
898+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
890899{
891900 spawn_vm_io_with_hooks(
892901 output_monitor,
@@ -906,36 +915,6 @@ pub fn spawn_vm_io(
906915 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
907916}
908917
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−
939918impl IoContext {
940919 pub fn shutdown(self) {
941920 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -953,7 +932,7 @@ fn create_vm_configuration(
953932 vm_writes_to_fd: OwnedFd,
954933 cpu_count: usize,
955934 ram_bytes: u64,
956−) -> Result<Retained<VZVirtualMachineConfiguration>> {
935+) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
957936 unsafe {
958937 let platform =
959938 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -987,7 +966,7 @@ fn create_vm_configuration(
987966 false,
988967 VZDiskImageCachingMode::Automatic,
989968 VZDiskImageSynchronizationMode::Full,
990− )?;
969+ ).unwrap();
991970
992971 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
993972 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1074,7 +1053,7 @@ fn create_vm_configuration(
10741053 // Validate
10751054 config.validateWithError().map_err(|e| {
10761055 io::Error::other(format!(
1077− "invalid VM configuration: {:?}",
1056+ "Invalid VM configuration: {:?}",
10781057 e.localizedDescription()
10791058 ))
10801059 })?;
@@ -1083,9 +1062,9 @@ fn create_vm_configuration(
10831062 }
10841063}
10851064
1086−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
1065+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
10871066 unsafe {
1088− let temp_dir = env::temp_dir();
1067+ let temp_dir = std::env::temp_dir();
10891068 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
10901069 let url = nsurl_from_path(&temp_path)?;
10911070 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1101,8 +1080,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
11011080fn spawn_login_actions_thread(
11021081 login_actions: Vec<LoginAction>,
11031082 output_monitor: Arc<OutputMonitor>,
1104− input_tx: Sender<VmInput>,
1105− vm_output_tx: Sender<VmOutput>,
1083+ input_tx: mpsc::Sender<VmInput>,
1084+ vm_output_tx: mpsc::Sender<VmOutput>,
11061085) -> thread::JoinHandle<()> {
11071086 thread::spawn(move || {
11081087 for a in login_actions {
@@ -1152,9 +1131,9 @@ fn run_vm_with_io<F>(
11521131 directory_shares: &[DirectoryShare],
11531132 cpu_count: usize,
11541133 ram_bytes: u64,
1155− status: Option<&StatusEmitter<'_>>,
1134+ status: Option<&StatusFile>,
11561135 io_handler: F,
1157−) -> Result<()>
1136+) -> Result<(), Box<dyn std::error::Error>>
11581137where
11591138 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
11601139{
@@ -1201,22 +1180,23 @@ where
12011180
12021181 match rx.try_recv() {
12031182 Ok(result) => {
1204− result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
1183+ result.map_err(|e| format!("Failed to start VM: {}", e))?;
12051184 break;
12061185 }
12071186 Err(mpsc::TryRecvError::Empty) => continue,
12081187 Err(mpsc::TryRecvError::Disconnected) => {
1209− bail!("VM start channel disconnected");
1188+ return Err("VM start channel disconnected".into());
12101189 }
12111190 }
12121191 }
12131192
12141193 if Instant::now() >= start_deadline {
1215− bail!("Timed out waiting for VM to start");
1194+ return Err("Timed out waiting for VM to start".into());
12161195 }
12171196
1218− emit_status(status, "vm booting... go vibecoder!");
1219− tracing::info!("vm booting... go vibecoder!");
1197+ if let Some(status) = status {
1198+ status.update("vm booting... go vibecoder!");
1199+ }
12201200 tracing::info!("vm booting");
12211201
12221202 let output_monitor = Arc::new(OutputMonitor::default());
@@ -1262,7 +1242,7 @@ where
12621242 );
12631243
12641244 let mut last_state = None;
1265− let mut exit_result: Result<(), String> = Ok(());
1245+ let mut exit_result = Ok(());
12661246 loop {
12671247 unsafe {
12681248 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1281,7 +1261,8 @@ where
12811261 exit_result = Err(format!(
12821262 "Login action ({}) timed out after {:?}; shutting down.",
12831263 action, timeout
1284− ));
1264+ )
1265+ .into());
12851266 unsafe {
12861267 if vm.canRequestStop() {
12871268 if let Err(err) = vm.requestStopWithError() {
@@ -1298,7 +1279,8 @@ where
12981279 exit_result = Err(format!(
12991280 "Login action ({}) failed: {}; shutting down.",
13001281 action, reason
1301− ));
1282+ )
1283+ .into());
13021284 unsafe {
13031285 if vm.canRequestStop() {
13041286 if let Err(err) = vm.requestStopWithError() {
@@ -1314,7 +1296,7 @@ where
13141296 Err(mpsc::TryRecvError::Empty) => {}
13151297 Err(mpsc::TryRecvError::Disconnected) => {}
13161298 }
1317− if state != VZVirtualMachineState::Running {
1299+ if state != objc2_virtualization::VZVirtualMachineState::Running {
13181300 //eprintln!("VM stopped with state: {:?}", state);
13191301 break;
13201302 }
@@ -1324,7 +1306,7 @@ where
13241306
13251307 io_ctx.shutdown();
13261308
1327− exit_result.map_err(Error::msg)
1309+ exit_result
13281310}
13291311
13301312fn run_vm(
@@ -1333,8 +1315,8 @@ fn run_vm(
13331315 directory_shares: &[DirectoryShare],
13341316 cpu_count: usize,
13351317 ram_bytes: u64,
1336− status: Option<&StatusEmitter<'_>>,
1337−) -> Result<()> {
1318+ status: Option<&StatusFile>,
1319+) -> Result<(), Box<dyn std::error::Error>> {
13381320 run_vm_with_io(
13391321 disk_path,
13401322 login_actions,
@@ -1346,7 +1328,7 @@ fn run_vm(
13461328 )
13471329}
13481330
1349−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
1331+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
13501332 let abs_path = if path.is_absolute() {
13511333 path.to_path_buf()
13521334 } else {
@@ -1355,7 +1337,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
13551337 let ns_path = NSString::from_str(
13561338 abs_path
13571339 .to_str()
1358− .with_context(|| "non-UTF8 path encountered while building NSURL")?,
1340+ .ok_or("Non-UTF8 path encountered while building NSURL")?,
13591341 );
13601342 Ok(NSURL::fileURLWithPath(&ns_path))
13611343}
@@ -1370,7 +1352,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
13701352 let original = attributes;
13711353
13721354 // Disable translation of carriage return to newline on input
1373− attributes.c_iflag &= !libc::ICRNL;
1355+ attributes.c_iflag &= !(libc::ICRNL);
13741356 // Disable canonical mode (line buffering), echo, and signal generation
13751357 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
13761358 attributes.c_cc[libc::VMIN] = 0;
@@ -1398,10 +1380,10 @@ impl Drop for RawModeGuard {
13981380
13991381// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
14001382pub fn ensure_signed() {
1401− if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1383+ if std::env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
14021384 return;
14031385 }
1404− let exe = env::current_exe().expect("failed to get current exe path");
1386+ let exe = std::env::current_exe().expect("failed to get current exe path");
14051387 let exe_str = exe.to_str().expect("exe path not valid utf-8");
14061388
14071389 let has_required_entitlements = {
@@ -1423,8 +1405,8 @@ pub fn ensure_signed() {
14231405 }
14241406
14251407 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1426− let entitlements_path = env::temp_dir().join("entitlements.plist");
1427− fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1408+ let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1409+ std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
14281410
14291411 let output = Command::new("codesign")
14301412 .args([
@@ -1437,7 +1419,7 @@ pub fn ensure_signed() {
14371419 ])
14381420 .output();
14391421
1440− let _ = fs::remove_file(&entitlements_path);
1422+ let _ = std::fs::remove_file(&entitlements_path);
14411423
14421424 match output {
14431425 Ok(o) if o.status.success() => {
@@ -1445,7 +1427,7 @@ pub fn ensure_signed() {
14451427 if !stderr.trim().is_empty() {
14461428 tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
14471429 }
1448− let err = Command::new(&exe).args(env::args_os().skip(1)).exec();
1430+ let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
14491431 tracing::error!(error = %err, "failed to re-exec after signing");
14501432 std::process::exit(1);
14511433 }