@@ -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::*;
@@ -32,74 +33,46 @@ const DEBIAN_COMPRESSED_DISK_URL: &str = "https://cloud.debian.org/images/cloud/
3233const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
3334const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
3435const SHARED_DIRECTORIES_TAG: &str = "shared";
36+pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
3537
36−const BYTES_PER_MB: u64 = 1024 * 1024;
37−const DEFAULT_CPU_COUNT: usize = 2;
38−const DEFAULT_RAM_MB: u64 = 2048;
39−const DEFAULT_RAM_BYTES: u64 = DEFAULT_RAM_MB * BYTES_PER_MB;
4038const START_TIMEOUT: Duration = Duration::from_secs(60);
4139const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
40+const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
4241
43−struct StatusFile {
44− path: PathBuf,
45− cleared: AtomicBool,
46−}
47−
48−impl StatusFile {
49− fn new(path: PathBuf) -> Self {
50− Self {
51− path,
52− cleared: AtomicBool::new(false),
53− }
54− }
55−
56− fn update(&self, message: &str) {
57− let _ = fs::write(&self.path, message);
58− }
59−
60− fn clear(&self) {
61− if !self.cleared.swap(true, Ordering::SeqCst) {
62− let _ = fs::remove_file(&self.path);
63− }
64− }
65−}
66−
67−impl Drop for StatusFile {
68− fn drop(&mut self) {
69− if !self.cleared.load(Ordering::SeqCst) {
70− let _ = fs::remove_file(&self.path);
71− self.cleared.store(true, Ordering::SeqCst);
72− }
73− }
74−}
42+const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
7543const PROVISION_SCRIPT: &str = include_str!("provision.sh");
76−const PROVISION_SCRIPT_NAME: &str = "provision.sh";
44+const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
7745const DEFAULT_RAW_NAME: &str = "default.raw";
7846const INSTANCE_RAW_NAME: &str = "instance.raw";
7947const BASE_DISK_RAW_NAME: &str = "disk.raw";
8048
8149#[derive(Clone)]
82−pub(crate) enum LoginAction {
83− 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+ },
8460 Send(String),
8561}
62+use crate::config::BoxConfig;
8663use LoginAction::*;
8764
8865#[derive(Clone)]
89−pub(crate) struct DirectoryShare {
66+pub struct DirectoryShare {
9067 host: PathBuf,
9168 guest: PathBuf,
9269 read_only: bool,
9370}
9471
9572impl DirectoryShare {
96− pub(crate) fn new(
97− host: PathBuf,
98− mut guest: PathBuf,
99− read_only: bool,
100− ) -> Result<Self, Box<dyn std::error::Error>> {
73+ pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
10174 if !host.exists() {
102− return Err(format!("Host path does not exist: {}", host.display()).into());
75+ bail!(format!("host path does not exist: {}", host.display()));
10376 }
10477 if !guest.is_absolute() {
10578 guest = PathBuf::from("/root").join(guest);
@@ -111,10 +84,10 @@ impl DirectoryShare {
11184 })
11285 }
11386
114− 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> {
11588 let parts: Vec<&str> = spec.split(':').collect();
11689 if parts.len() < 2 || parts.len() > 3 {
117− return Err(format!("Invalid mount spec: {spec}").into());
90+ bail!(format!("invalid mount spec: {spec}"));
11891 }
11992 let host = expand_tilde_path(parts[0]);
12093 let guest = PathBuf::from(parts[1]);
@@ -123,11 +96,10 @@ impl DirectoryShare {
12396 "read-only" => true,
12497 "read-write" => false,
12598 _ => {
126− return Err(format!(
99+ bail!(format!(
127100 "Invalid mount mode '{}'; expected read-only or read-write",
128101 parts[2]
129− )
130− .into());
102+ ));
131103 }
132104 }
133105 } else {
@@ -166,23 +138,33 @@ fn expand_tilde_path(value: &str) -> PathBuf {
166138pub struct VmArg {
167139 pub cpu_count: usize,
168140 pub ram_bytes: u64,
141+ pub disk_bytes: u64,
169142 pub no_default_mounts: bool,
170143 pub mounts: Vec<String>,
171144}
172145
173−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<()>
174155where
175156 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
176157{
177− 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)
178159}
179160
180−pub(crate) fn run_with_args_and_extras<F>(
161+pub fn run_with_args_and_extras<F>(
181162 args: VmArg,
182163 io_handler: F,
183164 extra_login_actions: Vec<LoginAction>,
184165 extra_directory_shares: Vec<DirectoryShare>,
185−) -> Result<(), Box<dyn std::error::Error>>
166+ status: Option<&StatusEmitter<'_>>,
167+) -> Result<()>
186168where
187169 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
188170{
@@ -191,7 +173,7 @@ where
191173 let project_root = env::current_dir()?;
192174 let project_name = project_root
193175 .file_name()
194− .ok_or("Project directory has no name")?
176+ .with_context(|| "Project directory has no name")?
195177 .to_string_lossy()
196178 .into_owned();
197179
@@ -203,8 +185,10 @@ where
203185 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
204186
205187 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
206− let status_file = StatusFile::new(instance_dir.join(STATUS_FILE_NAME));
207− 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");
208192
209193 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
210194 let base_compressed = cache_dir.join(basename_compressed);
@@ -228,16 +212,26 @@ where
228212 &base_compressed,
229213 &default_raw,
230214 std::slice::from_ref(&mise_directory_share),
231− Some(&status_file),
215+ Some(&provision_log),
216+ status,
232217 )?;
233− ensure_instance_disk(&instance_raw, &default_raw, Some(&status_file))?;
218+ let _ = ensure_instance_disk(
219+ &instance_raw,
220+ &default_raw,
221+ ByteSize(args.disk_bytes),
222+ status,
223+ )?;
224+ let base_size = fs::metadata(&default_raw)?.len();
225+ let instance_size = fs::metadata(&instance_raw)?.len();
226+ let needs_resize = instance_size > base_size;
234227 let disk_path = instance_raw;
235228
236229 let mut login_actions = Vec::new();
237230 let mut directory_shares = Vec::new();
238231
239232 if !args.no_default_mounts {
240− login_actions.push(Send(format!("cd {project_name}")));
233+ let project_guest_dir = PathBuf::from(PROJECT_GUEST_BASE).join(project_name);
234+ login_actions.push(Send(format!("cd {}", project_guest_dir.display())));
241235
242236 // discourage read/write of .git folder from within the VM. note that this isn't secure, since the VM runs as root and could unmount this.
243237 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
@@ -245,15 +239,6 @@ where
245239 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
246240 }
247241
248− directory_shares.push(
249− DirectoryShare::new(
250− project_root,
251− PathBuf::from("/root/").join(project_name),
252− false,
253− )
254− .expect("Project directory must exist"),
255− );
256−
257242 directory_shares.push(mise_directory_share);
258243 }
259244
@@ -263,6 +248,11 @@ where
263248 directory_shares.push(DirectoryShare::from_mount_spec(spec)?);
264249 }
265250
251+ if needs_resize {
252+ let resize_cmd = script_command_from_content("resize_disk.sh", RESIZE_DISK_SCRIPT)?;
253+ login_actions.push(Send(resize_cmd));
254+ }
255+
266256 if let Some(motd_action) = motd_login_action(&directory_shares) {
267257 login_actions.push(motd_action);
268258 }
@@ -275,25 +265,29 @@ where
275265 &directory_shares[..],
276266 args.cpu_count,
277267 args.ram_bytes,
278− Some(&status_file),
268+ status,
279269 io_handler,
280270 )
281271}
282272
283−pub(crate) fn script_command_from_content(
284− label: &str,
285− script: &str,
286−) -> Result<String, Box<dyn std::error::Error>> {
273+pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
287274 let marker = "VIBE_SCRIPT_EOF";
288275 let guest_dir = "/tmp/vibe-scripts";
289276 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);
290284 let command = format!(
291− "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}"
292286 );
293287 if script.contains(marker) {
294− return Err(
295− format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
296− );
288+ bail!(format!(
289+ "Script '{label}' contains marker '{marker}', cannot safely upload"
290+ ));
297291 }
298292 Ok(command)
299293}
@@ -357,6 +351,12 @@ enum WaitResult {
357351 Found,
358352}
359353
354+#[derive(PartialEq, Eq)]
355+enum WaitAnyResult {
356+ Timeout,
357+ Found(usize),
358+}
359+
360360pub enum VmInput {
361361 Bytes(Vec<u8>),
362362 Shutdown,
@@ -364,6 +364,7 @@ pub enum VmInput {
364364
365365enum VmOutput {
366366 LoginActionTimeout { action: String, timeout: Duration },
367+ LoginActionFailed { action: String, reason: String },
367368}
368369
369370#[derive(Default)]
@@ -400,6 +401,41 @@ impl OutputMonitor {
400401 WaitResult::Found
401402 }
402403 }
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
403439}
404440
405441#[derive(Debug)]
@@ -448,18 +484,16 @@ impl IoControl {
448484fn ensure_base_image(
449485 base_raw: &Path,
450486 base_compressed: &Path,
451− status: Option<&StatusFile>,
452−) -> Result<(), Box<dyn std::error::Error>> {
487+ status: Option<&StatusEmitter<'_>>,
488+) -> Result<()> {
453489 if base_raw.exists() {
454490 return Ok(());
455491 }
456492
457493 if !base_compressed.exists()
458− || 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
459495 {
460− if let Some(status) = status {
461− status.update("downloading base image...");
462− }
496+ emit_status(status, "downloading base image...");
463497 tracing::info!("downloading base image");
464498 let status = Command::new("curl")
465499 .args([
@@ -474,15 +508,14 @@ fn ensure_base_image(
474508 ])
475509 .status()?;
476510 if !status.success() {
477− return Err("Failed to download base image".into());
511+ bail!("failed to download base image");
478512 }
479513 }
480514
481515 // Check SHA
482516 {
483− if let Some(status) = status {
484− status.update("verifying base image...");
485− }
517+ emit_status(status, "verifying base image...");
518+ tracing::info!("verifying base image...");
486519 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
487520
488521 let mut child = Command::new("/usr/bin/shasum")
@@ -500,25 +533,25 @@ fn ensure_base_image(
500533
501534 let status = child.wait().expect("failed to wait on child");
502535 if !status.success() {
503− 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+ ));
504539 }
505540 }
506541
507− if let Some(status) = status {
508− status.update("decompressing base image...");
509− }
510− tracing::info!("decompressing base image");
542+ emit_status(status, "decompressing base image...");
543+ tracing::info!("decompressing base image...");
511544 let status = Command::new("tar")
512545 .args([
513546 "-xOf",
514547 &base_compressed.to_string_lossy(),
515548 BASE_DISK_RAW_NAME,
516549 ])
517− .stdout(std::fs::File::create(base_raw)?)
550+ .stdout(fs::File::create(base_raw)?)
518551 .status()?;
519552
520553 if !status.success() {
521− return Err("Failed to decompress base image".into());
554+ bail!("Failed to decompress base image");
522555 }
523556
524557 Ok(())
@@ -529,29 +562,56 @@ fn ensure_default_image(
529562 base_compressed: &Path,
530563 default_raw: &Path,
531564 directory_shares: &[DirectoryShare],
532− status: Option<&StatusFile>,
533−) -> Result<(), Box<dyn std::error::Error>> {
565+ provision_log: Option<&Path>,
566+ status: Option<&StatusEmitter<'_>>,
567+) -> Result<()> {
534568 if default_raw.exists() {
535569 return Ok(());
536570 }
537571
538572 ensure_base_image(base_raw, base_compressed, status)?;
539573
540− if let Some(status) = status {
541− status.update("configuring base image...");
542− }
543− tracing::info!("configuring base image");
574+ emit_status(status, "configuring base image...");
575+ tracing::info!("configuring base image...");
544576 fs::copy(base_raw, default_raw)?;
545577
546− let provision_command = script_command_from_content(PROVISION_SCRIPT_NAME, PROVISION_SCRIPT)?;
547− run_vm(
548− default_raw,
549− &[Send(provision_command)],
550− directory_shares,
551− DEFAULT_CPU_COUNT,
552− DEFAULT_RAM_BYTES,
553− None,
554− )?;
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+ }
555615
556616 Ok(())
557617}
@@ -559,19 +619,47 @@ fn ensure_default_image(
559619fn ensure_instance_disk(
560620 instance_raw: &Path,
561621 template_raw: &Path,
562− status: Option<&StatusFile>,
563−) -> Result<(), Box<dyn std::error::Error>> {
622+ target_bytes: ByteSize,
623+ status: Option<&StatusEmitter<'_>>,
624+) -> Result<bool> {
564625 if instance_raw.exists() {
565− return Ok(());
626+ let current_size = ByteSize(fs::metadata(instance_raw)?.len());
627+ if current_size != target_bytes {
628+ let current_gb = current_size;
629+ let target_gb = target_bytes;
630+ 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.",
632+ current_gb,
633+ target_gb
634+ );
635+ }
636+ return Ok(false);
566637 }
567638
568− if let Some(status) = status {
569− status.update("creating instance disk...");
639+ let template_size = ByteSize(fs::metadata(template_raw)?.len());
640+ if target_bytes < template_size {
641+ bail!(format!(
642+ "Requested disk size {} is smaller than base image size {}",
643+ target_bytes, template_size
644+ ));
570645 }
646+ let target_size = target_bytes;
647+ let needs_resize = target_size > template_size;
648+
649+ emit_status(status, "creating instance disk...");
650+ tracing::info!("creating instance disk...");
571651 tracing::info!(path = %template_raw.display(), "creating instance disk");
572− std::fs::create_dir_all(instance_raw.parent().unwrap())?;
573− fs::copy(template_raw, instance_raw)?;
574− Ok(())
652+ fs::create_dir_all(instance_raw.parent().unwrap())?;
653+ if target_size == template_size {
654+ fs::copy(template_raw, instance_raw)?;
655+ return Ok(needs_resize);
656+ }
657+
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)?;
661+ std::io::copy(&mut src, &mut dst)?;
662+ Ok(needs_resize)
575663}
576664
577665pub struct IoContext {
@@ -587,18 +675,17 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
587675 (read_stream.into(), write_stream.into())
588676}
589677
590−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+>(
591682 output_monitor: Arc<OutputMonitor>,
592683 vm_output_fd: OwnedFd,
593684 vm_input_fd: OwnedFd,
594685 io_control: Arc<IoControl>,
595686 mut on_line: F,
596687 mut on_output: G,
597−) -> IoContext
598−where
599− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
600− G: FnMut(&[u8]) + ::std::marker::Send + 'static,
601−{
688+) -> IoContext {
602689 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
603690
604691 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
@@ -746,14 +833,14 @@ where
746833 PollResult::Spurious => continue,
747834 PollResult::Ready(bytes) => {
748835 if io_control.forward_output() {
749− // enable raw mode, if we haven't already
836+ // enable raw mode if we haven't already
750837 if raw_guard.lock().unwrap().is_none()
751838 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
752839 {
753840 *raw_guard.lock().unwrap() = Some(guard);
754841 }
755842
756− let mut stdout = std::io::stdout().lock();
843+ let mut stdout = io::stdout().lock();
757844 if stdout.write_all(bytes).is_err() {
758845 break;
759846 }
@@ -769,7 +856,7 @@ where
769856
770857 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
771858 let mux_thread = thread::spawn(move || {
772− let mut vm_writer = std::fs::File::from(vm_input_fd);
859+ let mut vm_writer = fs::File::from(vm_input_fd);
773860 loop {
774861 match input_rx.recv() {
775862 Ok(VmInput::Bytes(data)) => {
@@ -799,7 +886,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
799886 on_line: F,
800887) -> IoContext
801888where
802− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
889+ F: FnMut(&str) -> bool + std::marker::Send + 'static,
803890{
804891 spawn_vm_io_with_hooks(
805892 output_monitor,
@@ -819,6 +906,36 @@ pub fn spawn_vm_io(
819906 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
820907}
821908
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+
822939impl IoContext {
823940 pub fn shutdown(self) {
824941 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -836,7 +953,7 @@ fn create_vm_configuration(
836953 vm_writes_to_fd: OwnedFd,
837954 cpu_count: usize,
838955 ram_bytes: u64,
839−) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
956+) -> Result<Retained<VZVirtualMachineConfiguration>> {
840957 unsafe {
841958 let platform =
842959 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -870,7 +987,7 @@ fn create_vm_configuration(
870987 false,
871988 VZDiskImageCachingMode::Automatic,
872989 VZDiskImageSynchronizationMode::Full,
873− ).unwrap();
990+ )?;
874991
875992 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
876993 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -957,7 +1074,7 @@ fn create_vm_configuration(
9571074 // Validate
9581075 config.validateWithError().map_err(|e| {
9591076 io::Error::other(format!(
960− "Invalid VM configuration: {:?}",
1077+ "invalid VM configuration: {:?}",
9611078 e.localizedDescription()
9621079 ))
9631080 })?;
@@ -966,9 +1083,9 @@ fn create_vm_configuration(
9661083 }
9671084}
9681085
969−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1086+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
9701087 unsafe {
971− let temp_dir = std::env::temp_dir();
1088+ let temp_dir = env::temp_dir();
9721089 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
9731090 let url = nsurl_from_path(&temp_path)?;
9741091 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -984,8 +1101,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std
9841101fn spawn_login_actions_thread(
9851102 login_actions: Vec<LoginAction>,
9861103 output_monitor: Arc<OutputMonitor>,
987− input_tx: mpsc::Sender<VmInput>,
988− vm_output_tx: mpsc::Sender<VmOutput>,
1104+ input_tx: Sender<VmInput>,
1105+ vm_output_tx: Sender<VmOutput>,
9891106) -> thread::JoinHandle<()> {
9901107 thread::spawn(move || {
9911108 for a in login_actions {
@@ -999,6 +1116,27 @@ fn spawn_login_actions_thread(
9991116 return;
10001117 }
10011118 }
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+ },
10021140 Send(mut text) => {
10031141 text.push('\n'); // Type the newline so the command is actually submitted.
10041142 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
@@ -1014,9 +1152,9 @@ fn run_vm_with_io<F>(
10141152 directory_shares: &[DirectoryShare],
10151153 cpu_count: usize,
10161154 ram_bytes: u64,
1017− status: Option<&StatusFile>,
1155+ status: Option<&StatusEmitter<'_>>,
10181156 io_handler: F,
1019−) -> Result<(), Box<dyn std::error::Error>>
1157+) -> Result<()>
10201158where
10211159 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
10221160{
@@ -1063,24 +1201,22 @@ where
10631201
10641202 match rx.try_recv() {
10651203 Ok(result) => {
1066− result.map_err(|e| format!("Failed to start VM: {}", e))?;
1204+ result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
10671205 break;
10681206 }
10691207 Err(mpsc::TryRecvError::Empty) => continue,
10701208 Err(mpsc::TryRecvError::Disconnected) => {
1071− return Err("VM start channel disconnected".into());
1209+ bail!("VM start channel disconnected");
10721210 }
10731211 }
10741212 }
10751213
10761214 if Instant::now() >= start_deadline {
1077− return Err("Timed out waiting for VM to start".into());
1215+ bail!("Timed out waiting for VM to start");
10781216 }
10791217
1080− if let Some(status) = status {
1081− status.update("vm booting... go vibecoder!");
1082− status.clear();
1083− }
1218+ emit_status(status, "vm booting... go vibecoder!");
1219+ tracing::info!("vm booting... go vibecoder!");
10841220 tracing::info!("vm booting");
10851221
10861222 let output_monitor = Arc::new(OutputMonitor::default());
@@ -1126,7 +1262,7 @@ where
11261262 );
11271263
11281264 let mut last_state = None;
1129− let mut exit_result = Ok(());
1265+ let mut exit_result: Result<(), String> = Ok(());
11301266 loop {
11311267 unsafe {
11321268 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1145,8 +1281,24 @@ where
11451281 exit_result = Err(format!(
11461282 "Login action ({}) timed out after {:?}; shutting down.",
11471283 action, timeout
1148− )
1149− .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+ ));
11501302 unsafe {
11511303 if vm.canRequestStop() {
11521304 if let Err(err) = vm.requestStopWithError() {
@@ -1162,7 +1314,7 @@ where
11621314 Err(mpsc::TryRecvError::Empty) => {}
11631315 Err(mpsc::TryRecvError::Disconnected) => {}
11641316 }
1165− if state != objc2_virtualization::VZVirtualMachineState::Running {
1317+ if state != VZVirtualMachineState::Running {
11661318 //eprintln!("VM stopped with state: {:?}", state);
11671319 break;
11681320 }
@@ -1172,7 +1324,7 @@ where
11721324
11731325 io_ctx.shutdown();
11741326
1175− exit_result
1327+ exit_result.map_err(Error::msg)
11761328}
11771329
11781330fn run_vm(
@@ -1181,8 +1333,8 @@ fn run_vm(
11811333 directory_shares: &[DirectoryShare],
11821334 cpu_count: usize,
11831335 ram_bytes: u64,
1184− status: Option<&StatusFile>,
1185−) -> Result<(), Box<dyn std::error::Error>> {
1336+ status: Option<&StatusEmitter<'_>>,
1337+) -> Result<()> {
11861338 run_vm_with_io(
11871339 disk_path,
11881340 login_actions,
@@ -1194,7 +1346,7 @@ fn run_vm(
11941346 )
11951347}
11961348
1197−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
1349+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
11981350 let abs_path = if path.is_absolute() {
11991351 path.to_path_buf()
12001352 } else {
@@ -1203,7 +1355,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::E
12031355 let ns_path = NSString::from_str(
12041356 abs_path
12051357 .to_str()
1206− .ok_or("Non-UTF8 path encountered while building NSURL")?,
1358+ .with_context(|| "non-UTF8 path encountered while building NSURL")?,
12071359 );
12081360 Ok(NSURL::fileURLWithPath(&ns_path))
12091361}
@@ -1218,7 +1370,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
12181370 let original = attributes;
12191371
12201372 // Disable translation of carriage return to newline on input
1221− attributes.c_iflag &= !(libc::ICRNL);
1373+ attributes.c_iflag &= !libc::ICRNL;
12221374 // Disable canonical mode (line buffering), echo, and signal generation
12231375 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
12241376 attributes.c_cc[libc::VMIN] = 0;
@@ -1246,10 +1398,10 @@ impl Drop for RawModeGuard {
12461398
12471399// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
12481400pub fn ensure_signed() {
1249− if std::env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1401+ if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
12501402 return;
12511403 }
1252− 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");
12531405 let exe_str = exe.to_str().expect("exe path not valid utf-8");
12541406
12551407 let has_required_entitlements = {
@@ -1271,8 +1423,8 @@ pub fn ensure_signed() {
12711423 }
12721424
12731425 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1274− let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1275− 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");
12761428
12771429 let output = Command::new("codesign")
12781430 .args([
@@ -1285,7 +1437,7 @@ pub fn ensure_signed() {
12851437 ])
12861438 .output();
12871439
1288− let _ = std::fs::remove_file(&entitlements_path);
1440+ let _ = fs::remove_file(&entitlements_path);
12891441
12901442 match output {
12911443 Ok(o) if o.status.success() => {
@@ -1293,7 +1445,7 @@ pub fn ensure_signed() {
12931445 if !stderr.trim().is_empty() {
12941446 tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
12951447 }
1296− 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();
12971449 tracing::error!(error = %err, "failed to re-exec after signing");
12981450 std::process::exit(1);
12991451 }