@@ -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,44 +34,74 @@ 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);
40−const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
4143
42−const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
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+ fn clear(&self) {
62+ if !self.cleared.swap(true, Ordering::SeqCst) {
63+ let _ = fs::remove_file(&self.path);
64+ }
65+ }
66+}
67+
68+impl Drop for StatusFile {
69+ fn drop(&mut self) {
70+ if !self.cleared.load(Ordering::SeqCst) {
71+ let _ = fs::remove_file(&self.path);
72+ self.cleared.store(true, Ordering::SeqCst);
73+ }
74+ }
75+}
4376const PROVISION_SCRIPT: &str = include_str!("provision.sh");
77+const PROVISION_SCRIPT_NAME: &str = "provision.sh";
4478const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
4579const DEFAULT_RAW_NAME: &str = "default.raw";
4680const INSTANCE_RAW_NAME: &str = "instance.raw";
4781const BASE_DISK_RAW_NAME: &str = "disk.raw";
4882
4983#[derive(Clone)]
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− },
84+pub(crate) enum LoginAction {
85+ Expect { text: String, timeout: Duration },
6086 Send(String),
6187}
62−use crate::config::BoxConfig;
6388use LoginAction::*;
6489
6590#[derive(Clone)]
66−pub struct DirectoryShare {
91+pub(crate) struct DirectoryShare {
6792 host: PathBuf,
6893 guest: PathBuf,
6994 read_only: bool,
7095}
7196
7297impl DirectoryShare {
73− pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
98+ pub(crate) fn new(
99+ host: PathBuf,
100+ mut guest: PathBuf,
101+ read_only: bool,
102+ ) -> Result<Self, Box<dyn std::error::Error>> {
74103 if !host.exists() {
75− bail!(format!("host path does not exist: {}", host.display()));
104+ return Err(format!("Host path does not exist: {}", host.display()).into());
76105 }
77106 if !guest.is_absolute() {
78107 guest = PathBuf::from("/root").join(guest);
@@ -84,10 +113,10 @@ impl DirectoryShare {
84113 })
85114 }
86115
87− pub fn from_mount_spec(spec: &str) -> Result<Self> {
116+ pub(crate) fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
88117 let parts: Vec<&str> = spec.split(':').collect();
89118 if parts.len() < 2 || parts.len() > 3 {
90− bail!(format!("invalid mount spec: {spec}"));
119+ return Err(format!("Invalid mount spec: {spec}").into());
91120 }
92121 let host = expand_tilde_path(parts[0]);
93122 let guest = PathBuf::from(parts[1]);
@@ -96,10 +125,11 @@ impl DirectoryShare {
96125 "read-only" => true,
97126 "read-write" => false,
98127 _ => {
99− bail!(format!(
128+ return Err(format!(
100129 "Invalid mount mode '{}'; expected read-only or read-write",
101130 parts[2]
102− ));
131+ )
132+ .into());
103133 }
104134 }
105135 } else {
@@ -143,28 +173,19 @@ pub struct VmArg {
143173 pub mounts: Vec<String>,
144174}
145175
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<()>
176+pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<(), Box<dyn std::error::Error>>
155177where
156178 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
157179{
158− run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new(), None)
180+ run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new())
159181}
160182
161−pub fn run_with_args_and_extras<F>(
183+pub(crate) fn run_with_args_and_extras<F>(
162184 args: VmArg,
163185 io_handler: F,
164186 extra_login_actions: Vec<LoginAction>,
165187 extra_directory_shares: Vec<DirectoryShare>,
166− status: Option<&StatusEmitter<'_>>,
167−) -> Result<()>
188+) -> Result<(), Box<dyn std::error::Error>>
168189where
169190 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
170191{
@@ -173,7 +194,7 @@ where
173194 let project_root = env::current_dir()?;
174195 let project_name = project_root
175196 .file_name()
176− .with_context(|| "Project directory has no name")?
197+ .ok_or("Project directory has no name")?
177198 .to_string_lossy()
178199 .into_owned();
179200
@@ -185,10 +206,8 @@ where
185206 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
186207
187208 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");
209+ let status_file = StatusFile::new(instance_dir.join(STATUS_FILE_NAME));
210+ status_file.update("preparing VM image...");
192211
193212 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
194213 let base_compressed = cache_dir.join(basename_compressed);
@@ -212,14 +231,13 @@ where
212231 &base_compressed,
213232 &default_raw,
214233 std::slice::from_ref(&mise_directory_share),
215− Some(&provision_log),
216− status,
234+ Some(&status_file),
217235 )?;
218236 let _ = ensure_instance_disk(
219237 &instance_raw,
220238 &default_raw,
221− ByteSize(args.disk_bytes),
222− status,
239+ args.disk_bytes,
240+ Some(&status_file),
223241 )?;
224242 let base_size = fs::metadata(&default_raw)?.len();
225243 let instance_size = fs::metadata(&instance_raw)?.len();
@@ -249,7 +267,7 @@ where
249267 }
250268
251269 if needs_resize {
252− let resize_cmd = script_command_from_content("resize_disk.sh", RESIZE_DISK_SCRIPT)?;
270+ let resize_cmd = script_command_from_content("resize_disk", RESIZE_DISK_SCRIPT)?;
253271 login_actions.push(Send(resize_cmd));
254272 }
255273
@@ -265,29 +283,25 @@ where
265283 &directory_shares[..],
266284 args.cpu_count,
267285 args.ram_bytes,
268− status,
286+ Some(&status_file),
269287 io_handler,
270288 )
271289}
272290
273−pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
291+pub(crate) fn script_command_from_content(
292+ label: &str,
293+ script: &str,
294+) -> Result<String, Box<dyn std::error::Error>> {
274295 let marker = "VIBE_SCRIPT_EOF";
275296 let guest_dir = "/tmp/vibe-scripts";
276297 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);
284298 let command = format!(
285− "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{wrapped_script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
299+ "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
286300 );
287301 if script.contains(marker) {
288− bail!(format!(
289− "Script '{label}' contains marker '{marker}', cannot safely upload"
290− ));
302+ return Err(
303+ format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
304+ );
291305 }
292306 Ok(command)
293307}
@@ -351,12 +365,6 @@ enum WaitResult {
351365 Found,
352366}
353367
354−#[derive(PartialEq, Eq)]
355−enum WaitAnyResult {
356− Timeout,
357− Found(usize),
358−}
359−
360368pub enum VmInput {
361369 Bytes(Vec<u8>),
362370 Shutdown,
@@ -364,7 +372,6 @@ pub enum VmInput {
364372
365373enum VmOutput {
366374 LoginActionTimeout { action: String, timeout: Duration },
367− LoginActionFailed { action: String, reason: String },
368375}
369376
370377#[derive(Default)]
@@ -401,41 +408,6 @@ impl OutputMonitor {
401408 WaitResult::Found
402409 }
403410 }
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
439411}
440412
441413#[derive(Debug)]
@@ -484,16 +456,18 @@ impl IoControl {
484456fn ensure_base_image(
485457 base_raw: &Path,
486458 base_compressed: &Path,
487− status: Option<&StatusEmitter<'_>>,
488−) -> Result<()> {
459+ status: Option<&StatusFile>,
460+) -> Result<(), Box<dyn std::error::Error>> {
489461 if base_raw.exists() {
490462 return Ok(());
491463 }
492464
493465 if !base_compressed.exists()
494− || fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
466+ || std::fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
495467 {
496− emit_status(status, "downloading base image...");
468+ if let Some(status) = status {
469+ status.update("downloading base image...");
470+ }
497471 tracing::info!("downloading base image");
498472 let status = Command::new("curl")
499473 .args([
@@ -508,14 +482,15 @@ fn ensure_base_image(
508482 ])
509483 .status()?;
510484 if !status.success() {
511− bail!("failed to download base image");
485+ return Err("Failed to download base image".into());
512486 }
513487 }
514488
515489 // Check SHA
516490 {
517− emit_status(status, "verifying base image...");
518− tracing::info!("verifying base image...");
491+ if let Some(status) = status {
492+ status.update("verifying base image...");
493+ }
519494 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
520495
521496 let mut child = Command::new("/usr/bin/shasum")
@@ -533,25 +508,25 @@ fn ensure_base_image(
533508
534509 let status = child.wait().expect("failed to wait on child");
535510 if !status.success() {
536− bail!(format!(
537− "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
538− ));
511+ return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
539512 }
540513 }
541514
542− emit_status(status, "decompressing base image...");
543− tracing::info!("decompressing base image...");
515+ if let Some(status) = status {
516+ status.update("decompressing base image...");
517+ }
518+ tracing::info!("decompressing base image");
544519 let status = Command::new("tar")
545520 .args([
546521 "-xOf",
547522 &base_compressed.to_string_lossy(),
548523 BASE_DISK_RAW_NAME,
549524 ])
550− .stdout(fs::File::create(base_raw)?)
525+ .stdout(std::fs::File::create(base_raw)?)
551526 .status()?;
552527
553528 if !status.success() {
554− bail!("Failed to decompress base image");
529+ return Err("Failed to decompress base image".into());
555530 }
556531
557532 Ok(())
@@ -562,56 +537,29 @@ fn ensure_default_image(
562537 base_compressed: &Path,
563538 default_raw: &Path,
564539 directory_shares: &[DirectoryShare],
565− provision_log: Option<&Path>,
566− status: Option<&StatusEmitter<'_>>,
567−) -> Result<()> {
540+ status: Option<&StatusFile>,
541+) -> Result<(), Box<dyn std::error::Error>> {
568542 if default_raw.exists() {
569543 return Ok(());
570544 }
571545
572546 ensure_base_image(base_raw, base_compressed, status)?;
573547
574− emit_status(status, "configuring base image...");
575− tracing::info!("configuring base image...");
548+ if let Some(status) = status {
549+ status.update("configuring base image...");
550+ }
551+ tracing::info!("configuring base image");
576552 fs::copy(base_raw, default_raw)?;
577553
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− }
554+ let provision_command = script_command_from_content(PROVISION_SCRIPT_NAME, PROVISION_SCRIPT)?;
555+ run_vm(
556+ default_raw,
557+ &[Send(provision_command)],
558+ directory_shares,
559+ DEFAULT_CPU_COUNT,
560+ DEFAULT_RAM_BYTES,
561+ None,
562+ )?;
615563
616564 Ok(())
617565}
@@ -619,16 +567,18 @@ fn ensure_default_image(
619567fn ensure_instance_disk(
620568 instance_raw: &Path,
621569 template_raw: &Path,
622− target_bytes: ByteSize,
623− status: Option<&StatusEmitter<'_>>,
624−) -> Result<bool> {
570+ target_bytes: u64,
571+ status: Option<&StatusFile>,
572+) -> Result<bool, Box<dyn std::error::Error>> {
625573 if instance_raw.exists() {
626− let current_size = ByteSize(fs::metadata(instance_raw)?.len());
574+ let current_size = fs::metadata(instance_raw)?.len();
627575 if current_size != target_bytes {
628− let current_gb = current_size;
629− let target_gb = target_bytes;
576+ let current_gb = current_size as f64 / (1024.0 * 1024.0 * 1024.0);
577+ let target_gb = target_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
630578 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.",
579+ current_bytes = current_size,
580+ target_bytes,
581+ "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.",
632582 current_gb,
633583 target_gb
634584 );
@@ -636,28 +586,30 @@ fn ensure_instance_disk(
636586 return Ok(false);
637587 }
638588
639− let template_size = ByteSize(fs::metadata(template_raw)?.len());
589+ let template_size = fs::metadata(template_raw)?.len();
640590 if target_bytes < template_size {
641− bail!(format!(
642− "Requested disk size {} is smaller than base image size {}",
591+ return Err(format!(
592+ "Requested disk size {} bytes is smaller than base image size {} bytes",
643593 target_bytes, template_size
644− ));
594+ )
595+ .into());
645596 }
646597 let target_size = target_bytes;
647598 let needs_resize = target_size > template_size;
648599
649− emit_status(status, "creating instance disk...");
650− tracing::info!("creating instance disk...");
600+ if let Some(status) = status {
601+ status.update("creating instance disk...");
602+ }
651603 tracing::info!(path = %template_raw.display(), "creating instance disk");
652− fs::create_dir_all(instance_raw.parent().unwrap())?;
604+ std::fs::create_dir_all(instance_raw.parent().unwrap())?;
653605 if target_size == template_size {
654606 fs::copy(template_raw, instance_raw)?;
655607 return Ok(needs_resize);
656608 }
657609
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)?;
610+ let mut dst = std::fs::File::create(instance_raw)?;
611+ dst.set_len(target_size)?;
612+ let mut src = std::fs::File::open(template_raw)?;
661613 std::io::copy(&mut src, &mut dst)?;
662614 Ok(needs_resize)
663615}
@@ -675,17 +627,18 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
675627 (read_stream.into(), write_stream.into())
676628}
677629
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−>(
630+pub fn spawn_vm_io_with_hooks<F, G>(
682631 output_monitor: Arc<OutputMonitor>,
683632 vm_output_fd: OwnedFd,
684633 vm_input_fd: OwnedFd,
685634 io_control: Arc<IoControl>,
686635 mut on_line: F,
687636 mut on_output: G,
688−) -> IoContext {
637+) -> IoContext
638+where
639+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
640+ G: FnMut(&[u8]) + ::std::marker::Send + 'static,
641+{
689642 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
690643
691644 // 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 +786,14 @@ pub fn spawn_vm_io_with_hooks<
833786 PollResult::Spurious => continue,
834787 PollResult::Ready(bytes) => {
835788 if io_control.forward_output() {
836− // enable raw mode if we haven't already
789+ // enable raw mode, if we haven't already
837790 if raw_guard.lock().unwrap().is_none()
838791 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
839792 {
840793 *raw_guard.lock().unwrap() = Some(guard);
841794 }
842795
843− let mut stdout = io::stdout().lock();
796+ let mut stdout = std::io::stdout().lock();
844797 if stdout.write_all(bytes).is_err() {
845798 break;
846799 }
@@ -856,7 +809,7 @@ pub fn spawn_vm_io_with_hooks<
856809
857810 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
858811 let mux_thread = thread::spawn(move || {
859− let mut vm_writer = fs::File::from(vm_input_fd);
812+ let mut vm_writer = std::fs::File::from(vm_input_fd);
860813 loop {
861814 match input_rx.recv() {
862815 Ok(VmInput::Bytes(data)) => {
@@ -886,7 +839,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
886839 on_line: F,
887840) -> IoContext
888841where
889− F: FnMut(&str) -> bool + std::marker::Send + 'static,
842+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
890843{
891844 spawn_vm_io_with_hooks(
892845 output_monitor,
@@ -906,36 +859,6 @@ pub fn spawn_vm_io(
906859 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
907860}
908861
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−
939862impl IoContext {
940863 pub fn shutdown(self) {
941864 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -953,7 +876,7 @@ fn create_vm_configuration(
953876 vm_writes_to_fd: OwnedFd,
954877 cpu_count: usize,
955878 ram_bytes: u64,
956−) -> Result<Retained<VZVirtualMachineConfiguration>> {
879+) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
957880 unsafe {
958881 let platform =
959882 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -987,7 +910,7 @@ fn create_vm_configuration(
987910 false,
988911 VZDiskImageCachingMode::Automatic,
989912 VZDiskImageSynchronizationMode::Full,
990− )?;
913+ ).unwrap();
991914
992915 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
993916 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1074,7 +997,7 @@ fn create_vm_configuration(
1074997 // Validate
1075998 config.validateWithError().map_err(|e| {
1076999 io::Error::other(format!(
1077− "invalid VM configuration: {:?}",
1000+ "Invalid VM configuration: {:?}",
10781001 e.localizedDescription()
10791002 ))
10801003 })?;
@@ -1083,9 +1006,9 @@ fn create_vm_configuration(
10831006 }
10841007}
10851008
1086−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
1009+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
10871010 unsafe {
1088− let temp_dir = env::temp_dir();
1011+ let temp_dir = std::env::temp_dir();
10891012 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
10901013 let url = nsurl_from_path(&temp_path)?;
10911014 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1101,8 +1024,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
11011024fn spawn_login_actions_thread(
11021025 login_actions: Vec<LoginAction>,
11031026 output_monitor: Arc<OutputMonitor>,
1104− input_tx: Sender<VmInput>,
1105− vm_output_tx: Sender<VmOutput>,
1027+ input_tx: mpsc::Sender<VmInput>,
1028+ vm_output_tx: mpsc::Sender<VmOutput>,
11061029) -> thread::JoinHandle<()> {
11071030 thread::spawn(move || {
11081031 for a in login_actions {
@@ -1116,27 +1039,6 @@ fn spawn_login_actions_thread(
11161039 return;
11171040 }
11181041 }
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− },
11401042 Send(mut text) => {
11411043 text.push('\n'); // Type the newline so the command is actually submitted.
11421044 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
@@ -1152,9 +1054,9 @@ fn run_vm_with_io<F>(
11521054 directory_shares: &[DirectoryShare],
11531055 cpu_count: usize,
11541056 ram_bytes: u64,
1155− status: Option<&StatusEmitter<'_>>,
1057+ status: Option<&StatusFile>,
11561058 io_handler: F,
1157−) -> Result<()>
1059+) -> Result<(), Box<dyn std::error::Error>>
11581060where
11591061 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
11601062{
@@ -1201,22 +1103,24 @@ where
12011103
12021104 match rx.try_recv() {
12031105 Ok(result) => {
1204− result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
1106+ result.map_err(|e| format!("Failed to start VM: {}", e))?;
12051107 break;
12061108 }
12071109 Err(mpsc::TryRecvError::Empty) => continue,
12081110 Err(mpsc::TryRecvError::Disconnected) => {
1209− bail!("VM start channel disconnected");
1111+ return Err("VM start channel disconnected".into());
12101112 }
12111113 }
12121114 }
12131115
12141116 if Instant::now() >= start_deadline {
1215− bail!("Timed out waiting for VM to start");
1117+ return Err("Timed out waiting for VM to start".into());
12161118 }
12171119
1218− emit_status(status, "vm booting... go vibecoder!");
1219− tracing::info!("vm booting... go vibecoder!");
1120+ if let Some(status) = status {
1121+ status.update("vm booting... go vibecoder!");
1122+ status.clear();
1123+ }
12201124 tracing::info!("vm booting");
12211125
12221126 let output_monitor = Arc::new(OutputMonitor::default());
@@ -1262,7 +1166,7 @@ where
12621166 );
12631167
12641168 let mut last_state = None;
1265− let mut exit_result: Result<(), String> = Ok(());
1169+ let mut exit_result = Ok(());
12661170 loop {
12671171 unsafe {
12681172 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1281,24 +1185,8 @@ where
12811185 exit_result = Err(format!(
12821186 "Login action ({}) timed out after {:?}; shutting down.",
12831187 action, timeout
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− ));
1188+ )
1189+ .into());
13021190 unsafe {
13031191 if vm.canRequestStop() {
13041192 if let Err(err) = vm.requestStopWithError() {
@@ -1314,7 +1202,7 @@ where
13141202 Err(mpsc::TryRecvError::Empty) => {}
13151203 Err(mpsc::TryRecvError::Disconnected) => {}
13161204 }
1317− if state != VZVirtualMachineState::Running {
1205+ if state != objc2_virtualization::VZVirtualMachineState::Running {
13181206 //eprintln!("VM stopped with state: {:?}", state);
13191207 break;
13201208 }
@@ -1324,7 +1212,7 @@ where
13241212
13251213 io_ctx.shutdown();
13261214
1327− exit_result.map_err(Error::msg)
1215+ exit_result
13281216}
13291217
13301218fn run_vm(
@@ -1333,8 +1221,8 @@ fn run_vm(
13331221 directory_shares: &[DirectoryShare],
13341222 cpu_count: usize,
13351223 ram_bytes: u64,
1336− status: Option<&StatusEmitter<'_>>,
1337−) -> Result<()> {
1224+ status: Option<&StatusFile>,
1225+) -> Result<(), Box<dyn std::error::Error>> {
13381226 run_vm_with_io(
13391227 disk_path,
13401228 login_actions,
@@ -1346,7 +1234,7 @@ fn run_vm(
13461234 )
13471235}
13481236
1349−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
1237+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
13501238 let abs_path = if path.is_absolute() {
13511239 path.to_path_buf()
13521240 } else {
@@ -1355,7 +1243,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
13551243 let ns_path = NSString::from_str(
13561244 abs_path
13571245 .to_str()
1358− .with_context(|| "non-UTF8 path encountered while building NSURL")?,
1246+ .ok_or("Non-UTF8 path encountered while building NSURL")?,
13591247 );
13601248 Ok(NSURL::fileURLWithPath(&ns_path))
13611249}
@@ -1370,7 +1258,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
13701258 let original = attributes;
13711259
13721260 // Disable translation of carriage return to newline on input
1373− attributes.c_iflag &= !libc::ICRNL;
1261+ attributes.c_iflag &= !(libc::ICRNL);
13741262 // Disable canonical mode (line buffering), echo, and signal generation
13751263 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
13761264 attributes.c_cc[libc::VMIN] = 0;
@@ -1398,10 +1286,10 @@ impl Drop for RawModeGuard {
13981286
13991287// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
14001288pub fn ensure_signed() {
1401− if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1289+ if std::env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
14021290 return;
14031291 }
1404− let exe = env::current_exe().expect("failed to get current exe path");
1292+ let exe = std::env::current_exe().expect("failed to get current exe path");
14051293 let exe_str = exe.to_str().expect("exe path not valid utf-8");
14061294
14071295 let has_required_entitlements = {
@@ -1423,8 +1311,8 @@ pub fn ensure_signed() {
14231311 }
14241312
14251313 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");
1314+ let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1315+ std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
14281316
14291317 let output = Command::new("codesign")
14301318 .args([
@@ -1437,7 +1325,7 @@ pub fn ensure_signed() {
14371325 ])
14381326 .output();
14391327
1440− let _ = fs::remove_file(&entitlements_path);
1328+ let _ = std::fs::remove_file(&entitlements_path);
14411329
14421330 match output {
14431331 Ok(o) if o.status.success() => {
@@ -1445,7 +1333,7 @@ pub fn ensure_signed() {
14451333 if !stderr.trim().is_empty() {
14461334 tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
14471335 }
1448− let err = Command::new(&exe).args(env::args_os().skip(1)).exec();
1336+ let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
14491337 tracing::error!(error = %err, "failed to re-exec after signing");
14501338 std::process::exit(1);
14511339 }