@@ -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::*;
@@ -33,46 +32,74 @@ const DEBIAN_COMPRESSED_DISK_URL: &str = "https://cloud.debian.org/images/cloud/
3332const DEBIAN_COMPRESSED_SHA: &str = "6ab9be9e6834adc975268367f2f0235251671184345c34ee13031749fdfbf66fe4c3aafd949a2d98550426090e9ac645e79009c51eb0eefc984c15786570bb38";
3433const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
3534const SHARED_DIRECTORIES_TAG: &str = "shared";
36−pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
3735
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;
3840const START_TIMEOUT: Duration = Duration::from_secs(60);
3941const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
40−const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
4142
42−const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
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+}
4375const PROVISION_SCRIPT: &str = include_str!("provision.sh");
44−const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
76+const PROVISION_SCRIPT_NAME: &str = "provision.sh";
4577const DEFAULT_RAW_NAME: &str = "default.raw";
4678const INSTANCE_RAW_NAME: &str = "instance.raw";
4779const BASE_DISK_RAW_NAME: &str = "disk.raw";
4880
4981#[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− },
82+pub(crate) enum LoginAction {
83+ Expect { text: String, timeout: Duration },
6084 Send(String),
6185}
62−use crate::config::BoxConfig;
6386use LoginAction::*;
6487
6588#[derive(Clone)]
66−pub struct DirectoryShare {
89+pub(crate) struct DirectoryShare {
6790 host: PathBuf,
6891 guest: PathBuf,
6992 read_only: bool,
7093}
7194
7295impl DirectoryShare {
73− pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
96+ pub(crate) fn new(
97+ host: PathBuf,
98+ mut guest: PathBuf,
99+ read_only: bool,
100+ ) -> Result<Self, Box<dyn std::error::Error>> {
74101 if !host.exists() {
75− bail!(format!("host path does not exist: {}", host.display()));
102+ return Err(format!("Host path does not exist: {}", host.display()).into());
76103 }
77104 if !guest.is_absolute() {
78105 guest = PathBuf::from("/root").join(guest);
@@ -84,10 +111,10 @@ impl DirectoryShare {
84111 })
85112 }
86113
87− pub fn from_mount_spec(spec: &str) -> Result<Self> {
114+ pub(crate) fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
88115 let parts: Vec<&str> = spec.split(':').collect();
89116 if parts.len() < 2 || parts.len() > 3 {
90− bail!(format!("invalid mount spec: {spec}"));
117+ return Err(format!("Invalid mount spec: {spec}").into());
91118 }
92119 let host = expand_tilde_path(parts[0]);
93120 let guest = PathBuf::from(parts[1]);
@@ -96,10 +123,11 @@ impl DirectoryShare {
96123 "read-only" => true,
97124 "read-write" => false,
98125 _ => {
99− bail!(format!(
126+ return Err(format!(
100127 "Invalid mount mode '{}'; expected read-only or read-write",
101128 parts[2]
102− ));
129+ )
130+ .into());
103131 }
104132 }
105133 } else {
@@ -138,33 +166,23 @@ fn expand_tilde_path(value: &str) -> PathBuf {
138166pub struct VmArg {
139167 pub cpu_count: usize,
140168 pub ram_bytes: u64,
141− pub disk_bytes: u64,
142169 pub no_default_mounts: bool,
143170 pub mounts: Vec<String>,
144171}
145172
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<()>
173+pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<(), Box<dyn std::error::Error>>
155174where
156175 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
157176{
158− run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new(), None)
177+ run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new())
159178}
160179
161−pub fn run_with_args_and_extras<F>(
180+pub(crate) fn run_with_args_and_extras<F>(
162181 args: VmArg,
163182 io_handler: F,
164183 extra_login_actions: Vec<LoginAction>,
165184 extra_directory_shares: Vec<DirectoryShare>,
166− status: Option<&StatusEmitter<'_>>,
167−) -> Result<()>
185+) -> Result<(), Box<dyn std::error::Error>>
168186where
169187 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
170188{
@@ -173,7 +191,7 @@ where
173191 let project_root = env::current_dir()?;
174192 let project_name = project_root
175193 .file_name()
176− .with_context(|| "Project directory has no name")?
194+ .ok_or("Project directory has no name")?
177195 .to_string_lossy()
178196 .into_owned();
179197
@@ -185,10 +203,8 @@ where
185203 let guest_mise_cache = cache_dir.join(".guest-mise-cache");
186204
187205 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");
206+ let status_file = StatusFile::new(instance_dir.join(STATUS_FILE_NAME));
207+ status_file.update("preparing VM image...");
192208
193209 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
194210 let base_compressed = cache_dir.join(basename_compressed);
@@ -212,26 +228,16 @@ where
212228 &base_compressed,
213229 &default_raw,
214230 std::slice::from_ref(&mise_directory_share),
215− Some(&provision_log),
216− status,
231+ Some(&status_file),
217232 )?;
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;
233+ ensure_instance_disk(&instance_raw, &default_raw, Some(&status_file))?;
227234 let disk_path = instance_raw;
228235
229236 let mut login_actions = Vec::new();
230237 let mut directory_shares = Vec::new();
231238
232239 if !args.no_default_mounts {
233− let project_guest_dir = PathBuf::from(PROJECT_GUEST_BASE).join(project_name);
234− login_actions.push(Send(format!("cd {}", project_guest_dir.display())));
240+ login_actions.push(Send(format!("cd {project_name}")));
235241
236242 // 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.
237243 // I couldn't find an alternative way to do this --- the MacOS sandbox doesn't apply to the Apple Virtualization system
@@ -239,6 +245,15 @@ where
239245 login_actions.push(Send(r"mount -t tmpfs tmpfs .git/".into()));
240246 }
241247
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+
242257 directory_shares.push(mise_directory_share);
243258 }
244259
@@ -248,11 +263,6 @@ where
248263 directory_shares.push(DirectoryShare::from_mount_spec(spec)?);
249264 }
250265
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−
256266 if let Some(motd_action) = motd_login_action(&directory_shares) {
257267 login_actions.push(motd_action);
258268 }
@@ -265,29 +275,25 @@ where
265275 &directory_shares[..],
266276 args.cpu_count,
267277 args.ram_bytes,
268− status,
278+ Some(&status_file),
269279 io_handler,
270280 )
271281}
272282
273−pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
283+pub(crate) fn script_command_from_content(
284+ label: &str,
285+ script: &str,
286+) -> Result<String, Box<dyn std::error::Error>> {
274287 let marker = "VIBE_SCRIPT_EOF";
275288 let guest_dir = "/tmp/vibe-scripts";
276289 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);
284290 let command = format!(
285− "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{wrapped_script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
291+ "mkdir -p {guest_dir}\ncat >{guest_path} <<'{marker}'\n{script}\n{marker}\nchmod +x {guest_path}\n{guest_path}"
286292 );
287293 if script.contains(marker) {
288− bail!(format!(
289− "Script '{label}' contains marker '{marker}', cannot safely upload"
290− ));
294+ return Err(
295+ format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
296+ );
291297 }
292298 Ok(command)
293299}
@@ -351,12 +357,6 @@ enum WaitResult {
351357 Found,
352358}
353359
354−#[derive(PartialEq, Eq)]
355−enum WaitAnyResult {
356− Timeout,
357− Found(usize),
358−}
359−
360360pub enum VmInput {
361361 Bytes(Vec<u8>),
362362 Shutdown,
@@ -364,7 +364,6 @@ pub enum VmInput {
364364
365365enum VmOutput {
366366 LoginActionTimeout { action: String, timeout: Duration },
367− LoginActionFailed { action: String, reason: String },
368367}
369368
370369#[derive(Default)]
@@ -401,41 +400,6 @@ impl OutputMonitor {
401400 WaitResult::Found
402401 }
403402 }
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
439403}
440404
441405#[derive(Debug)]
@@ -484,16 +448,18 @@ impl IoControl {
484448fn ensure_base_image(
485449 base_raw: &Path,
486450 base_compressed: &Path,
487− status: Option<&StatusEmitter<'_>>,
488−) -> Result<()> {
451+ status: Option<&StatusFile>,
452+) -> Result<(), Box<dyn std::error::Error>> {
489453 if base_raw.exists() {
490454 return Ok(());
491455 }
492456
493457 if !base_compressed.exists()
494− || fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
458+ || std::fs::metadata(base_compressed).map(|m| m.len())? < DEBIAN_COMPRESSED_SIZE_BYTES
495459 {
496− emit_status(status, "downloading base image...");
460+ if let Some(status) = status {
461+ status.update("downloading base image...");
462+ }
497463 tracing::info!("downloading base image");
498464 let status = Command::new("curl")
499465 .args([
@@ -508,14 +474,15 @@ fn ensure_base_image(
508474 ])
509475 .status()?;
510476 if !status.success() {
511− bail!("failed to download base image");
477+ return Err("Failed to download base image".into());
512478 }
513479 }
514480
515481 // Check SHA
516482 {
517− emit_status(status, "verifying base image...");
518− tracing::info!("verifying base image...");
483+ if let Some(status) = status {
484+ status.update("verifying base image...");
485+ }
519486 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
520487
521488 let mut child = Command::new("/usr/bin/shasum")
@@ -533,25 +500,25 @@ fn ensure_base_image(
533500
534501 let status = child.wait().expect("failed to wait on child");
535502 if !status.success() {
536− bail!(format!(
537− "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
538− ));
503+ return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
539504 }
540505 }
541506
542− emit_status(status, "decompressing base image...");
543− tracing::info!("decompressing base image...");
507+ if let Some(status) = status {
508+ status.update("decompressing base image...");
509+ }
510+ tracing::info!("decompressing base image");
544511 let status = Command::new("tar")
545512 .args([
546513 "-xOf",
547514 &base_compressed.to_string_lossy(),
548515 BASE_DISK_RAW_NAME,
549516 ])
550− .stdout(fs::File::create(base_raw)?)
517+ .stdout(std::fs::File::create(base_raw)?)
551518 .status()?;
552519
553520 if !status.success() {
554− bail!("Failed to decompress base image");
521+ return Err("Failed to decompress base image".into());
555522 }
556523
557524 Ok(())
@@ -562,56 +529,29 @@ fn ensure_default_image(
562529 base_compressed: &Path,
563530 default_raw: &Path,
564531 directory_shares: &[DirectoryShare],
565− provision_log: Option<&Path>,
566− status: Option<&StatusEmitter<'_>>,
567−) -> Result<()> {
532+ status: Option<&StatusFile>,
533+) -> Result<(), Box<dyn std::error::Error>> {
568534 if default_raw.exists() {
569535 return Ok(());
570536 }
571537
572538 ensure_base_image(base_raw, base_compressed, status)?;
573539
574− emit_status(status, "configuring base image...");
575− tracing::info!("configuring base image...");
540+ if let Some(status) = status {
541+ status.update("configuring base image...");
542+ }
543+ tracing::info!("configuring base image");
576544 fs::copy(base_raw, default_raw)?;
577545
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− }
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+ )?;
615555
616556 Ok(())
617557}
@@ -619,47 +559,19 @@ fn ensure_default_image(
619559fn ensure_instance_disk(
620560 instance_raw: &Path,
621561 template_raw: &Path,
622− target_bytes: ByteSize,
623− status: Option<&StatusEmitter<'_>>,
624−) -> Result<bool> {
562+ status: Option<&StatusFile>,
563+) -> Result<(), Box<dyn std::error::Error>> {
625564 if instance_raw.exists() {
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);
565+ return Ok(());
637566 }
638567
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− ));
568+ if let Some(status) = status {
569+ status.update("creating instance disk...");
645570 }
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...");
651571 tracing::info!(path = %template_raw.display(), "creating instance disk");
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)
572+ std::fs::create_dir_all(instance_raw.parent().unwrap())?;
573+ fs::copy(template_raw, instance_raw)?;
574+ Ok(())
663575}
664576
665577pub struct IoContext {
@@ -675,17 +587,18 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
675587 (read_stream.into(), write_stream.into())
676588}
677589
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−>(
590+pub fn spawn_vm_io_with_hooks<F, G>(
682591 output_monitor: Arc<OutputMonitor>,
683592 vm_output_fd: OwnedFd,
684593 vm_input_fd: OwnedFd,
685594 io_control: Arc<IoControl>,
686595 mut on_line: F,
687596 mut on_output: G,
688−) -> IoContext {
597+) -> IoContext
598+where
599+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
600+ G: FnMut(&[u8]) + ::std::marker::Send + 'static,
601+{
689602 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
690603
691604 // 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 +746,14 @@ pub fn spawn_vm_io_with_hooks<
833746 PollResult::Spurious => continue,
834747 PollResult::Ready(bytes) => {
835748 if io_control.forward_output() {
836− // enable raw mode if we haven't already
749+ // enable raw mode, if we haven't already
837750 if raw_guard.lock().unwrap().is_none()
838751 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
839752 {
840753 *raw_guard.lock().unwrap() = Some(guard);
841754 }
842755
843− let mut stdout = io::stdout().lock();
756+ let mut stdout = std::io::stdout().lock();
844757 if stdout.write_all(bytes).is_err() {
845758 break;
846759 }
@@ -856,7 +769,7 @@ pub fn spawn_vm_io_with_hooks<
856769
857770 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
858771 let mux_thread = thread::spawn(move || {
859− let mut vm_writer = fs::File::from(vm_input_fd);
772+ let mut vm_writer = std::fs::File::from(vm_input_fd);
860773 loop {
861774 match input_rx.recv() {
862775 Ok(VmInput::Bytes(data)) => {
@@ -886,7 +799,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
886799 on_line: F,
887800) -> IoContext
888801where
889− F: FnMut(&str) -> bool + std::marker::Send + 'static,
802+ F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
890803{
891804 spawn_vm_io_with_hooks(
892805 output_monitor,
@@ -906,36 +819,6 @@ pub fn spawn_vm_io(
906819 spawn_vm_io_with_line_handler(output_monitor, vm_output_fd, vm_input_fd, |_| false)
907820}
908821
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−
939822impl IoContext {
940823 pub fn shutdown(self) {
941824 let _ = self.input_tx.send(VmInput::Shutdown);
@@ -953,7 +836,7 @@ fn create_vm_configuration(
953836 vm_writes_to_fd: OwnedFd,
954837 cpu_count: usize,
955838 ram_bytes: u64,
956−) -> Result<Retained<VZVirtualMachineConfiguration>> {
839+) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
957840 unsafe {
958841 let platform =
959842 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -987,7 +870,7 @@ fn create_vm_configuration(
987870 false,
988871 VZDiskImageCachingMode::Automatic,
989872 VZDiskImageSynchronizationMode::Full,
990− )?;
873+ ).unwrap();
991874
992875 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
993876 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1074,7 +957,7 @@ fn create_vm_configuration(
1074957 // Validate
1075958 config.validateWithError().map_err(|e| {
1076959 io::Error::other(format!(
1077− "invalid VM configuration: {:?}",
960+ "Invalid VM configuration: {:?}",
1078961 e.localizedDescription()
1079962 ))
1080963 })?;
@@ -1083,9 +966,9 @@ fn create_vm_configuration(
1083966 }
1084967}
1085968
1086−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
969+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1087970 unsafe {
1088− let temp_dir = env::temp_dir();
971+ let temp_dir = std::env::temp_dir();
1089972 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
1090973 let url = nsurl_from_path(&temp_path)?;
1091974 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1101,8 +984,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
1101984fn spawn_login_actions_thread(
1102985 login_actions: Vec<LoginAction>,
1103986 output_monitor: Arc<OutputMonitor>,
1104− input_tx: Sender<VmInput>,
1105− vm_output_tx: Sender<VmOutput>,
987+ input_tx: mpsc::Sender<VmInput>,
988+ vm_output_tx: mpsc::Sender<VmOutput>,
1106989) -> thread::JoinHandle<()> {
1107990 thread::spawn(move || {
1108991 for a in login_actions {
@@ -1116,27 +999,6 @@ fn spawn_login_actions_thread(
1116999 return;
11171000 }
11181001 }
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− },
11401002 Send(mut text) => {
11411003 text.push('\n'); // Type the newline so the command is actually submitted.
11421004 input_tx.send(VmInput::Bytes(text.into_bytes())).unwrap();
@@ -1152,9 +1014,9 @@ fn run_vm_with_io<F>(
11521014 directory_shares: &[DirectoryShare],
11531015 cpu_count: usize,
11541016 ram_bytes: u64,
1155− status: Option<&StatusEmitter<'_>>,
1017+ status: Option<&StatusFile>,
11561018 io_handler: F,
1157−) -> Result<()>
1019+) -> Result<(), Box<dyn std::error::Error>>
11581020where
11591021 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
11601022{
@@ -1201,22 +1063,24 @@ where
12011063
12021064 match rx.try_recv() {
12031065 Ok(result) => {
1204− result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
1066+ result.map_err(|e| format!("Failed to start VM: {}", e))?;
12051067 break;
12061068 }
12071069 Err(mpsc::TryRecvError::Empty) => continue,
12081070 Err(mpsc::TryRecvError::Disconnected) => {
1209− bail!("VM start channel disconnected");
1071+ return Err("VM start channel disconnected".into());
12101072 }
12111073 }
12121074 }
12131075
12141076 if Instant::now() >= start_deadline {
1215− bail!("Timed out waiting for VM to start");
1077+ return Err("Timed out waiting for VM to start".into());
12161078 }
12171079
1218− emit_status(status, "vm booting... go vibecoder!");
1219− tracing::info!("vm booting... go vibecoder!");
1080+ if let Some(status) = status {
1081+ status.update("vm booting... go vibecoder!");
1082+ status.clear();
1083+ }
12201084 tracing::info!("vm booting");
12211085
12221086 let output_monitor = Arc::new(OutputMonitor::default());
@@ -1262,7 +1126,7 @@ where
12621126 );
12631127
12641128 let mut last_state = None;
1265− let mut exit_result: Result<(), String> = Ok(());
1129+ let mut exit_result = Ok(());
12661130 loop {
12671131 unsafe {
12681132 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1281,24 +1145,8 @@ where
12811145 exit_result = Err(format!(
12821146 "Login action ({}) timed out after {:?}; shutting down.",
12831147 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− ));
1148+ )
1149+ .into());
13021150 unsafe {
13031151 if vm.canRequestStop() {
13041152 if let Err(err) = vm.requestStopWithError() {
@@ -1314,7 +1162,7 @@ where
13141162 Err(mpsc::TryRecvError::Empty) => {}
13151163 Err(mpsc::TryRecvError::Disconnected) => {}
13161164 }
1317− if state != VZVirtualMachineState::Running {
1165+ if state != objc2_virtualization::VZVirtualMachineState::Running {
13181166 //eprintln!("VM stopped with state: {:?}", state);
13191167 break;
13201168 }
@@ -1324,7 +1172,7 @@ where
13241172
13251173 io_ctx.shutdown();
13261174
1327− exit_result.map_err(Error::msg)
1175+ exit_result
13281176}
13291177
13301178fn run_vm(
@@ -1333,8 +1181,8 @@ fn run_vm(
13331181 directory_shares: &[DirectoryShare],
13341182 cpu_count: usize,
13351183 ram_bytes: u64,
1336− status: Option<&StatusEmitter<'_>>,
1337−) -> Result<()> {
1184+ status: Option<&StatusFile>,
1185+) -> Result<(), Box<dyn std::error::Error>> {
13381186 run_vm_with_io(
13391187 disk_path,
13401188 login_actions,
@@ -1346,7 +1194,7 @@ fn run_vm(
13461194 )
13471195}
13481196
1349−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
1197+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
13501198 let abs_path = if path.is_absolute() {
13511199 path.to_path_buf()
13521200 } else {
@@ -1355,7 +1203,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
13551203 let ns_path = NSString::from_str(
13561204 abs_path
13571205 .to_str()
1358− .with_context(|| "non-UTF8 path encountered while building NSURL")?,
1206+ .ok_or("Non-UTF8 path encountered while building NSURL")?,
13591207 );
13601208 Ok(NSURL::fileURLWithPath(&ns_path))
13611209}
@@ -1370,7 +1218,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
13701218 let original = attributes;
13711219
13721220 // Disable translation of carriage return to newline on input
1373− attributes.c_iflag &= !libc::ICRNL;
1221+ attributes.c_iflag &= !(libc::ICRNL);
13741222 // Disable canonical mode (line buffering), echo, and signal generation
13751223 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
13761224 attributes.c_cc[libc::VMIN] = 0;
@@ -1398,10 +1246,10 @@ impl Drop for RawModeGuard {
13981246
13991247// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
14001248pub fn ensure_signed() {
1401− if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1249+ if std::env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
14021250 return;
14031251 }
1404− let exe = env::current_exe().expect("failed to get current exe path");
1252+ let exe = std::env::current_exe().expect("failed to get current exe path");
14051253 let exe_str = exe.to_str().expect("exe path not valid utf-8");
14061254
14071255 let has_required_entitlements = {
@@ -1423,8 +1271,8 @@ pub fn ensure_signed() {
14231271 }
14241272
14251273 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");
1274+ let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1275+ std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
14281276
14291277 let output = Command::new("codesign")
14301278 .args([
@@ -1437,7 +1285,7 @@ pub fn ensure_signed() {
14371285 ])
14381286 .output();
14391287
1440− let _ = fs::remove_file(&entitlements_path);
1288+ let _ = std::fs::remove_file(&entitlements_path);
14411289
14421290 match output {
14431291 Ok(o) if o.status.success() => {
@@ -1445,7 +1293,7 @@ pub fn ensure_signed() {
14451293 if !stderr.trim().is_empty() {
14461294 tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
14471295 }
1448− let err = Command::new(&exe).args(env::args_os().skip(1)).exec();
1296+ let err = Command::new(&exe).args(std::env::args_os().skip(1)).exec();
14491297 tracing::error!(error = %err, "failed to re-exec after signing");
14501298 std::process::exit(1);
14511299 }