@@ -1,5 +1,5 @@
1−use crate::instance::STATUS_FILE_NAME;
2use crate::session_manager::{GLOBAL_CACHE_DIR_NAME, INSTANCE_DIR_NAME};
1use crate::session_manager::{GLOBAL_CACHE_DIR_NAME, INSTANCE_DIR_NAME};
2+use anyhow::{Context, Error, Result, bail};
5 io::{self, Write},
5 io::{self, Write},
@@ -23,6 +23,7 @@ use std::{
25use block2::RcBlock;
25use block2::RcBlock;
26+use bytesize::ByteSize;
26use dispatch2::DispatchQueue;
27use dispatch2::DispatchQueue;
27use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
28use objc2::{AnyThread, rc::Retained, runtime::ProtocolObject};
28use objc2_foundation::*;
29use objc2_foundation::*;
@@ -34,49 +35,19 @@ const DEBIAN_COMPRESSED_SIZE_BYTES: u64 = 280901576;
34const SHARED_DIRECTORIES_TAG: &str = "shared";
35const SHARED_DIRECTORIES_TAG: &str = "shared";
35pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
36pub const PROJECT_GUEST_BASE: &str = "/usr/local/vibebox-mounts";
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;
41const START_TIMEOUT: Duration = Duration::from_secs(60);
38const START_TIMEOUT: Duration = Duration::from_secs(60);
42const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
39const LOGIN_EXPECT_TIMEOUT: Duration = Duration::from_secs(120);
43const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
40const PROVISION_EXPECT_TIMEOUT: Duration = Duration::from_secs(900);
45−struct StatusFile {
42+const ERROR_REPORT_SCRIPT: &str = include_str!("error_report.sh");
51− fn new(path: PathBuf) -> Self {
54− cleared: AtomicBool::new(false),
58− fn update(&self, message: &str) {
59− let _ = fs::write(&self.path, message);
63−impl Drop for StatusFile {
65− if !self.cleared.load(Ordering::SeqCst) {
66− let _ = fs::remove_file(&self.path);
67− self.cleared.store(true, Ordering::SeqCst);
71const PROVISION_SCRIPT: &str = include_str!("provision.sh");
43const PROVISION_SCRIPT: &str = include_str!("provision.sh");
72−const PROVISION_SCRIPT_NAME: &str = "provision.sh";
73const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
44const RESIZE_DISK_SCRIPT: &str = include_str!("resize_disk.sh");
74const DEFAULT_RAW_NAME: &str = "default.raw";
45const DEFAULT_RAW_NAME: &str = "default.raw";
75const INSTANCE_RAW_NAME: &str = "instance.raw";
46const INSTANCE_RAW_NAME: &str = "instance.raw";
76const BASE_DISK_RAW_NAME: &str = "disk.raw";
47const BASE_DISK_RAW_NAME: &str = "disk.raw";
78#[derive(Clone)]
49#[derive(Clone)]
79−pub(crate) enum LoginAction {
50+pub enum LoginAction {
81 text: String,
52 text: String,
82 timeout: Duration,
53 timeout: Duration,
@@ -88,23 +59,20 @@ pub(crate) enum LoginAction {
89 Send(String),
60 Send(String),
62+use crate::config::BoxConfig;
91use LoginAction::*;
63use LoginAction::*;
93#[derive(Clone)]
65#[derive(Clone)]
94−pub(crate) struct DirectoryShare {
66+pub struct DirectoryShare {
95 host: PathBuf,
67 host: PathBuf,
96 guest: PathBuf,
68 guest: PathBuf,
97 read_only: bool,
69 read_only: bool,
100impl DirectoryShare {
72impl DirectoryShare {
103− mut guest: PathBuf,
73+ pub fn new(host: PathBuf, mut guest: PathBuf, read_only: bool) -> Result<Self> {
105− ) -> Result<Self, Box<dyn std::error::Error>> {
106 if !host.exists() {
74 if !host.exists() {
107− return Err(format!("Host path does not exist: {}", host.display()).into());
75+ bail!(format!("host path does not exist: {}", host.display()));
109 if !guest.is_absolute() {
77 if !guest.is_absolute() {
110 guest = PathBuf::from("/root").join(guest);
78 guest = PathBuf::from("/root").join(guest);
@@ -116,10 +84,10 @@ impl DirectoryShare {
119− pub(crate) fn from_mount_spec(spec: &str) -> Result<Self, Box<dyn std::error::Error>> {
87+ pub fn from_mount_spec(spec: &str) -> Result<Self> {
120 let parts: Vec<&str> = spec.split(':').collect();
88 let parts: Vec<&str> = spec.split(':').collect();
121 if parts.len() < 2 || parts.len() > 3 {
89 if parts.len() < 2 || parts.len() > 3 {
122− return Err(format!("Invalid mount spec: {spec}").into());
90+ bail!(format!("invalid mount spec: {spec}"));
124 let host = expand_tilde_path(parts[0]);
92 let host = expand_tilde_path(parts[0]);
125 let guest = PathBuf::from(parts[1]);
93 let guest = PathBuf::from(parts[1]);
@@ -128,11 +96,10 @@ impl DirectoryShare {
128 "read-only" => true,
96 "read-only" => true,
129 "read-write" => false,
97 "read-write" => false,
131− return Err(format!(
99+ bail!(format!(
132 "Invalid mount mode '{}'; expected read-only or read-write",
100 "Invalid mount mode '{}'; expected read-only or read-write",
@@ -176,19 +143,28 @@ pub struct VmArg {
176 pub mounts: Vec<String>,
143 pub mounts: Vec<String>,
146+type StatusEmitter<'a> = dyn Fn(&str) + std::marker::Send + Sync + 'a;
148+fn emit_status(status: Option<&StatusEmitter<'_>>, message: &str) {
149+ if let Some(status) = status {
179−pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<(), Box<dyn std::error::Error>>
154+pub fn run_with_args<F>(args: VmArg, io_handler: F) -> Result<()>
181 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
156 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
183− run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new())
158+ run_with_args_and_extras(args, io_handler, Vec::new(), Vec::new(), None)
186−pub(crate) fn run_with_args_and_extras<F>(
161+pub fn run_with_args_and_extras<F>(
187 args: VmArg,
162 args: VmArg,
188 io_handler: F,
163 io_handler: F,
189 extra_login_actions: Vec<LoginAction>,
164 extra_login_actions: Vec<LoginAction>,
190 extra_directory_shares: Vec<DirectoryShare>,
165 extra_directory_shares: Vec<DirectoryShare>,
191−) -> Result<(), Box<dyn std::error::Error>>
166+ status: Option<&StatusEmitter<'_>>,
193 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
169 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
@@ -197,7 +173,7 @@ where
197 let project_root = env::current_dir()?;
173 let project_root = env::current_dir()?;
198 let project_name = project_root
174 let project_name = project_root
199 .file_name()
175 .file_name()
200− .ok_or("Project directory has no name")?
176+ .with_context(|| "Project directory has no name")?
201 .to_string_lossy()
177 .to_string_lossy()
202 .into_owned();
178 .into_owned();
@@ -210,8 +186,8 @@ where
211 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
187 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
212 fs::create_dir_all(&instance_dir)?;
188 fs::create_dir_all(&instance_dir)?;
213− let status_file = StatusFile::new(instance_dir.join(STATUS_FILE_NAME));
189+ emit_status(status, "preparing VM image...");
214− status_file.update("preparing VM image...");
190+ tracing::info!("preparing VM image...");
215 let provision_log = instance_dir.join("provision.log");
191 let provision_log = instance_dir.join("provision.log");
217 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
193 let basename_compressed = DEBIAN_COMPRESSED_DISK_URL.rsplit('/').next().unwrap();
@@ -236,14 +212,14 @@ where
236 &base_compressed,
212 &base_compressed,
237 &default_raw,
213 &default_raw,
238 std::slice::from_ref(&mise_directory_share),
214 std::slice::from_ref(&mise_directory_share),
240 Some(&provision_log),
215 Some(&provision_log),
242 let _ = ensure_instance_disk(
218 let _ = ensure_instance_disk(
243 &instance_raw,
219 &instance_raw,
244 &default_raw,
220 &default_raw,
245− args.disk_bytes,
221+ ByteSize(args.disk_bytes),
246− Some(&status_file),
222+ status,
248 let base_size = fs::metadata(&default_raw)?.len();
224 let base_size = fs::metadata(&default_raw)?.len();
249 let instance_size = fs::metadata(&instance_raw)?.len();
225 let instance_size = fs::metadata(&instance_raw)?.len();
@@ -273,7 +249,7 @@ where
275 if needs_resize {
251 if needs_resize {
276− let resize_cmd = script_command_from_content("resize_disk", RESIZE_DISK_SCRIPT)?;
252+ let resize_cmd = script_command_from_content("resize_disk.sh", RESIZE_DISK_SCRIPT)?;
277 login_actions.push(Send(resize_cmd));
253 login_actions.push(Send(resize_cmd));
@@ -289,25 +265,29 @@ where
289 &directory_shares[..],
265 &directory_shares[..],
290 args.cpu_count,
266 args.cpu_count,
291 args.ram_bytes,
267 args.ram_bytes,
292− Some(&status_file),
268+ status,
293 io_handler,
269 io_handler,
297−pub(crate) fn script_command_from_content(
273+pub fn script_command_from_content(label: &str, script: &str) -> Result<String> {
300−) -> Result<String, Box<dyn std::error::Error>> {
301 let marker = "VIBE_SCRIPT_EOF";
274 let marker = "VIBE_SCRIPT_EOF";
302 let guest_dir = "/tmp/vibe-scripts";
275 let guest_dir = "/tmp/vibe-scripts";
303 let guest_path = format!("{guest_dir}/{label}.sh");
276 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,
281+ let wrapped_script = ERROR_REPORT_SCRIPT
282+ .replace("__LABEL__", label)
283+ .replace("__SCRIPT_BODY__", script_body);
304 let command = format!(
284 let command = format!(
305− "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}"
307 if script.contains(marker) {
287 if script.contains(marker) {
308− return Err(
288+ bail!(format!(
309− format!("Script '{label}' contains marker '{marker}', cannot safely upload").into(),
289+ "Script '{label}' contains marker '{marker}', cannot safely upload"
312 Ok(command)
292 Ok(command)
@@ -504,18 +484,16 @@ impl IoControl {
504fn ensure_base_image(
484fn ensure_base_image(
505 base_raw: &Path,
485 base_raw: &Path,
506 base_compressed: &Path,
486 base_compressed: &Path,
507− status: Option<&StatusFile>,
487+ status: Option<&StatusEmitter<'_>>,
508−) -> Result<(), Box<dyn std::error::Error>> {
488+) -> Result<()> {
509 if base_raw.exists() {
489 if base_raw.exists() {
510 return Ok(());
490 return Ok(());
513 if !base_compressed.exists()
493 if !base_compressed.exists()
514− || 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
516− if let Some(status) = status {
517− status.update("downloading base image...");
496+ emit_status(status, "downloading base image...");
519 tracing::info!("downloading base image");
497 tracing::info!("downloading base image");
520 let status = Command::new("curl")
498 let status = Command::new("curl")
@@ -530,15 +508,14 @@ fn ensure_base_image(
531 .status()?;
509 .status()?;
532 if !status.success() {
510 if !status.success() {
533− return Err("Failed to download base image".into());
511+ bail!("failed to download base image");
537 // Check SHA
515 // Check SHA
539− if let Some(status) = status {
517+ emit_status(status, "verifying base image...");
540− status.update("verifying base image...");
518+ tracing::info!("verifying base image...");
542 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
519 let input = format!("{} {}\n", DEBIAN_COMPRESSED_SHA, base_compressed.display());
544 let mut child = Command::new("/usr/bin/shasum")
521 let mut child = Command::new("/usr/bin/shasum")
@@ -556,25 +533,25 @@ fn ensure_base_image(
557 let status = child.wait().expect("failed to wait on child");
534 let status = child.wait().expect("failed to wait on child");
558 if !status.success() {
535 if !status.success() {
559− return Err(format!("SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}").into());
537+ "SHA validation failed for {DEBIAN_COMPRESSED_DISK_URL}"
563− if let Some(status) = status {
564− status.update("decompressing base image...");
542+ emit_status(status, "decompressing base image...");
566− tracing::info!("decompressing base image");
543+ tracing::info!("decompressing base image...");
567 let status = Command::new("tar")
544 let status = Command::new("tar")
570 &base_compressed.to_string_lossy(),
547 &base_compressed.to_string_lossy(),
571 BASE_DISK_RAW_NAME,
548 BASE_DISK_RAW_NAME,
573− .stdout(std::fs::File::create(base_raw)?)
550+ .stdout(fs::File::create(base_raw)?)
574 .status()?;
551 .status()?;
576 if !status.success() {
553 if !status.success() {
577− return Err("Failed to decompress base image".into());
554+ bail!("Failed to decompress base image");
@@ -585,22 +562,20 @@ fn ensure_default_image(
585 base_compressed: &Path,
562 base_compressed: &Path,
586 default_raw: &Path,
563 default_raw: &Path,
587 directory_shares: &[DirectoryShare],
564 directory_shares: &[DirectoryShare],
588− status: Option<&StatusFile>,
589 provision_log: Option<&Path>,
565 provision_log: Option<&Path>,
590−) -> Result<(), Box<dyn std::error::Error>> {
566+ status: Option<&StatusEmitter<'_>>,
591 if default_raw.exists() {
568 if default_raw.exists() {
592 return Ok(());
569 return Ok(());
595 ensure_base_image(base_raw, base_compressed, status)?;
572 ensure_base_image(base_raw, base_compressed, status)?;
597− if let Some(status) = status {
598− status.update("configuring base image...");
574+ emit_status(status, "configuring base image...");
600− tracing::info!("configuring base image");
575+ tracing::info!("configuring base image...");
601 fs::copy(base_raw, default_raw)?;
576 fs::copy(base_raw, default_raw)?;
603− let provision_command = script_command_from_content(PROVISION_SCRIPT_NAME, PROVISION_SCRIPT)?;
578+ let provision_command = script_command_from_content("provision.sh", PROVISION_SCRIPT)?;
604 let provision_actions = [
579 let provision_actions = [
605 Send(provision_command),
580 Send(provision_command),
606 ExpectEither {
581 ExpectEither {
@@ -615,9 +590,9 @@ fn ensure_default_image(
615 default_raw,
590 default_raw,
616 &provision_actions,
591 &provision_actions,
617 directory_shares,
592 directory_shares,
618− DEFAULT_CPU_COUNT,
593+ BoxConfig::default().cpu_count,
619− DEFAULT_RAM_BYTES,
594+ BoxConfig::default().ram_size.as_u64(),
621 move |output_monitor, vm_output_fd, vm_input_fd| {
596 move |output_monitor, vm_output_fd, vm_input_fd| {
622 spawn_vm_io_with_log(output_monitor, vm_output_fd, vm_input_fd, log_path)
597 spawn_vm_io_with_log(output_monitor, vm_output_fd, vm_input_fd, log_path)
@@ -627,9 +602,9 @@ fn ensure_default_image(
627 default_raw,
602 default_raw,
628 &provision_actions,
603 &provision_actions,
629 directory_shares,
604 directory_shares,
630− DEFAULT_CPU_COUNT,
605+ BoxConfig::default().cpu_count,
631− DEFAULT_RAM_BYTES,
606+ BoxConfig::default().ram_size.as_u64(),
@@ -644,18 +619,16 @@ fn ensure_default_image(
644fn ensure_instance_disk(
619fn ensure_instance_disk(
645 instance_raw: &Path,
620 instance_raw: &Path,
646 template_raw: &Path,
621 template_raw: &Path,
647− target_bytes: u64,
622+ target_bytes: ByteSize,
648− status: Option<&StatusFile>,
623+ status: Option<&StatusEmitter<'_>>,
649−) -> Result<bool, Box<dyn std::error::Error>> {
624+) -> Result<bool> {
650 if instance_raw.exists() {
625 if instance_raw.exists() {
651− let current_size = fs::metadata(instance_raw)?.len();
626+ let current_size = ByteSize(fs::metadata(instance_raw)?.len());
652 if current_size != target_bytes {
627 if current_size != target_bytes {
653− let current_gb = current_size as f64 / (1024.0 * 1024.0 * 1024.0);
628+ let current_gb = current_size;
654− let target_gb = target_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
629+ let target_gb = target_bytes;
655 tracing::warn!(
630 tracing::warn!(
656− current_bytes = current_size,
658− "instance disk size does not match config (current {:.2} GB, config {:.2} GB); disk_gb applies only on init. Run `vibebox reset` to recreate or set disk_gb to match; using existing disk.",
631+ "instance disk size does not match config (current {}, config {}); disk_gb applies only on init. Run `vibebox reset` to recreate or set disk_gb to match; using existing disk.",
659 current_gb,
632 current_gb,
660 target_gb
633 target_gb
@@ -663,30 +636,28 @@ fn ensure_instance_disk(
663 return Ok(false);
636 return Ok(false);
666− let template_size = fs::metadata(template_raw)?.len();
639+ let template_size = ByteSize(fs::metadata(template_raw)?.len());
667 if target_bytes < template_size {
640 if target_bytes < template_size {
668− return Err(format!(
641+ bail!(format!(
669− "Requested disk size {} bytes is smaller than base image size {} bytes",
642+ "Requested disk size {} is smaller than base image size {}",
670 target_bytes, template_size
643 target_bytes, template_size
674 let target_size = target_bytes;
646 let target_size = target_bytes;
675 let needs_resize = target_size > template_size;
647 let needs_resize = target_size > template_size;
677− if let Some(status) = status {
649+ emit_status(status, "creating instance disk...");
678− status.update("creating instance disk...");
650+ tracing::info!("creating instance disk...");
680 tracing::info!(path = %template_raw.display(), "creating instance disk");
651 tracing::info!(path = %template_raw.display(), "creating instance disk");
681− std::fs::create_dir_all(instance_raw.parent().unwrap())?;
652+ fs::create_dir_all(instance_raw.parent().unwrap())?;
682 if target_size == template_size {
653 if target_size == template_size {
683 fs::copy(template_raw, instance_raw)?;
654 fs::copy(template_raw, instance_raw)?;
684 return Ok(needs_resize);
655 return Ok(needs_resize);
687− let mut dst = std::fs::File::create(instance_raw)?;
658+ let mut dst = fs::File::create(instance_raw)?;
688− dst.set_len(target_size)?;
659+ dst.set_len(target_size.as_u64())?;
689− let mut src = std::fs::File::open(template_raw)?;
660+ let mut src = fs::File::open(template_raw)?;
690 std::io::copy(&mut src, &mut dst)?;
661 std::io::copy(&mut src, &mut dst)?;
691 Ok(needs_resize)
662 Ok(needs_resize)
@@ -704,18 +675,17 @@ pub fn create_pipe() -> (OwnedFd, OwnedFd) {
704 (read_stream.into(), write_stream.into())
675 (read_stream.into(), write_stream.into())
707−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,
708 output_monitor: Arc<OutputMonitor>,
682 output_monitor: Arc<OutputMonitor>,
709 vm_output_fd: OwnedFd,
683 vm_output_fd: OwnedFd,
710 vm_input_fd: OwnedFd,
684 vm_input_fd: OwnedFd,
711 io_control: Arc<IoControl>,
685 io_control: Arc<IoControl>,
712 mut on_line: F,
686 mut on_line: F,
713 mut on_output: G,
687 mut on_output: G,
714−) -> IoContext
688+) -> IoContext {
716− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
717− G: FnMut(&[u8]) + ::std::marker::Send + 'static,
719 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
689 let (input_tx, input_rx): (Sender<VmInput>, Receiver<VmInput>) = mpsc::channel();
721 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
691 // raw_guard is set when we've put the user's terminal into raw mode because we've attached stdin/stdout to the VM.
@@ -863,14 +833,14 @@ where
863 PollResult::Spurious => continue,
833 PollResult::Spurious => continue,
864 PollResult::Ready(bytes) => {
834 PollResult::Ready(bytes) => {
865 if io_control.forward_output() {
835 if io_control.forward_output() {
866− // enable raw mode, if we haven't already
836+ // enable raw mode if we haven't already
867 if raw_guard.lock().unwrap().is_none()
837 if raw_guard.lock().unwrap().is_none()
868 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
838 && let Ok(guard) = enable_raw_mode(libc::STDIN_FILENO)
870 *raw_guard.lock().unwrap() = Some(guard);
840 *raw_guard.lock().unwrap() = Some(guard);
873− let mut stdout = std::io::stdout().lock();
843+ let mut stdout = io::stdout().lock();
874 if stdout.write_all(bytes).is_err() {
844 if stdout.write_all(bytes).is_err() {
@@ -886,7 +856,7 @@ where
887 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
857 // Copies data from mpsc channel into VM, so vibe can "type" stuff and run scripts.
888 let mux_thread = thread::spawn(move || {
858 let mux_thread = thread::spawn(move || {
889− let mut vm_writer = std::fs::File::from(vm_input_fd);
859+ let mut vm_writer = fs::File::from(vm_input_fd);
891 match input_rx.recv() {
861 match input_rx.recv() {
892 Ok(VmInput::Bytes(data)) => {
862 Ok(VmInput::Bytes(data)) => {
@@ -916,7 +886,7 @@ pub fn spawn_vm_io_with_line_handler<F>(
916 on_line: F,
886 on_line: F,
917) -> IoContext
887) -> IoContext
919− F: FnMut(&str) -> bool + ::std::marker::Send + 'static,
889+ F: FnMut(&str) -> bool + std::marker::Send + 'static,
921 spawn_vm_io_with_hooks(
891 spawn_vm_io_with_hooks(
922 output_monitor,
892 output_monitor,
@@ -983,7 +953,7 @@ fn create_vm_configuration(
983 vm_writes_to_fd: OwnedFd,
953 vm_writes_to_fd: OwnedFd,
984 cpu_count: usize,
954 cpu_count: usize,
985 ram_bytes: u64,
955 ram_bytes: u64,
986−) -> Result<Retained<VZVirtualMachineConfiguration>, Box<dyn std::error::Error>> {
956+) -> Result<Retained<VZVirtualMachineConfiguration>> {
988 let platform =
958 let platform =
989 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
959 VZGenericPlatformConfiguration::init(VZGenericPlatformConfiguration::alloc());
@@ -1017,7 +987,7 @@ fn create_vm_configuration(
1018 VZDiskImageCachingMode::Automatic,
988 VZDiskImageCachingMode::Automatic,
1019 VZDiskImageSynchronizationMode::Full,
989 VZDiskImageSynchronizationMode::Full,
1020− ).unwrap();
990+ )?;
1022 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
992 let disk_device = VZVirtioBlockDeviceConfiguration::initWithAttachment(
1023 VZVirtioBlockDeviceConfiguration::alloc(),
993 VZVirtioBlockDeviceConfiguration::alloc(),
@@ -1104,7 +1074,7 @@ fn create_vm_configuration(
1104 // Validate
1074 // Validate
1105 config.validateWithError().map_err(|e| {
1075 config.validateWithError().map_err(|e| {
1106 io::Error::other(format!(
1076 io::Error::other(format!(
1107− "Invalid VM configuration: {:?}",
1077+ "invalid VM configuration: {:?}",
1108 e.localizedDescription()
1078 e.localizedDescription()
@@ -1113,9 +1083,9 @@ fn create_vm_configuration(
1116−fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std::error::Error>> {
1086+fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>> {
1117 unsafe {
1087 unsafe {
1118− let temp_dir = std::env::temp_dir();
1088+ let temp_dir = env::temp_dir();
1119 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
1089 let temp_path = temp_dir.join(format!("efi_variable_store_{}.efivars", std::process::id()));
1120 let url = nsurl_from_path(&temp_path)?;
1090 let url = nsurl_from_path(&temp_path)?;
1121 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
1091 let options = VZEFIVariableStoreInitializationOptions::AllowOverwrite;
@@ -1131,8 +1101,8 @@ fn load_efi_variable_store() -> Result<Retained<VZEFIVariableStore>, Box<dyn std
1131fn spawn_login_actions_thread(
1101fn spawn_login_actions_thread(
1132 login_actions: Vec<LoginAction>,
1102 login_actions: Vec<LoginAction>,
1133 output_monitor: Arc<OutputMonitor>,
1103 output_monitor: Arc<OutputMonitor>,
1134− input_tx: mpsc::Sender<VmInput>,
1104+ input_tx: Sender<VmInput>,
1135− vm_output_tx: mpsc::Sender<VmOutput>,
1105+ vm_output_tx: Sender<VmOutput>,
1136) -> thread::JoinHandle<()> {
1106) -> thread::JoinHandle<()> {
1137 thread::spawn(move || {
1107 thread::spawn(move || {
1138 for a in login_actions {
1108 for a in login_actions {
@@ -1182,9 +1152,9 @@ fn run_vm_with_io<F>(
1182 directory_shares: &[DirectoryShare],
1152 directory_shares: &[DirectoryShare],
1183 cpu_count: usize,
1153 cpu_count: usize,
1184 ram_bytes: u64,
1154 ram_bytes: u64,
1185− status: Option<&StatusFile>,
1155+ status: Option<&StatusEmitter<'_>>,
1186 io_handler: F,
1156 io_handler: F,
1187−) -> Result<(), Box<dyn std::error::Error>>
1157+) -> Result<()>
1189 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
1159 F: FnOnce(Arc<OutputMonitor>, OwnedFd, OwnedFd) -> IoContext,
@@ -1231,23 +1201,22 @@ where
1232 match rx.try_recv() {
1202 match rx.try_recv() {
1233 Ok(result) => {
1203 Ok(result) => {
1234− result.map_err(|e| format!("Failed to start VM: {}", e))?;
1204+ result.map_err(|e| Error::msg(format!("Failed to start VM: {}", e)))?;
1237 Err(mpsc::TryRecvError::Empty) => continue,
1207 Err(mpsc::TryRecvError::Empty) => continue,
1238 Err(mpsc::TryRecvError::Disconnected) => {
1208 Err(mpsc::TryRecvError::Disconnected) => {
1239− return Err("VM start channel disconnected".into());
1209+ bail!("VM start channel disconnected");
1244 if Instant::now() >= start_deadline {
1214 if Instant::now() >= start_deadline {
1245− return Err("Timed out waiting for VM to start".into());
1215+ bail!("Timed out waiting for VM to start");
1248− if let Some(status) = status {
1218+ emit_status(status, "vm booting... go vibecoder!");
1249− status.update("vm booting... go vibecoder!");
1219+ tracing::info!("vm booting... go vibecoder!");
1251 tracing::info!("vm booting");
1220 tracing::info!("vm booting");
1253 let output_monitor = Arc::new(OutputMonitor::default());
1222 let output_monitor = Arc::new(OutputMonitor::default());
@@ -1293,7 +1262,7 @@ where
1295 let mut last_state = None;
1264 let mut last_state = None;
1296− let mut exit_result = Ok(());
1265+ let mut exit_result: Result<(), String> = Ok(());
1298 unsafe {
1267 unsafe {
1299 NSRunLoop::mainRunLoop().runMode_beforeDate(
1268 NSRunLoop::mainRunLoop().runMode_beforeDate(
@@ -1312,8 +1281,7 @@ where
1312 exit_result = Err(format!(
1281 exit_result = Err(format!(
1313 "Login action ({}) timed out after {:?}; shutting down.",
1282 "Login action ({}) timed out after {:?}; shutting down.",
1314 action, timeout
1283 action, timeout
1317 unsafe {
1285 unsafe {
1318 if vm.canRequestStop() {
1286 if vm.canRequestStop() {
1319 if let Err(err) = vm.requestStopWithError() {
1287 if let Err(err) = vm.requestStopWithError() {
@@ -1330,8 +1298,7 @@ where
1330 exit_result = Err(format!(
1298 exit_result = Err(format!(
1331 "Login action ({}) failed: {}; shutting down.",
1299 "Login action ({}) failed: {}; shutting down.",
1332 action, reason
1300 action, reason
1335 unsafe {
1302 unsafe {
1336 if vm.canRequestStop() {
1303 if vm.canRequestStop() {
1337 if let Err(err) = vm.requestStopWithError() {
1304 if let Err(err) = vm.requestStopWithError() {
@@ -1347,7 +1314,7 @@ where
1347 Err(mpsc::TryRecvError::Empty) => {}
1314 Err(mpsc::TryRecvError::Empty) => {}
1348 Err(mpsc::TryRecvError::Disconnected) => {}
1315 Err(mpsc::TryRecvError::Disconnected) => {}
1350− if state != objc2_virtualization::VZVirtualMachineState::Running {
1317+ if state != VZVirtualMachineState::Running {
1351 //eprintln!("VM stopped with state: {:?}", state);
1318 //eprintln!("VM stopped with state: {:?}", state);
@@ -1357,7 +1324,7 @@ where
1358 io_ctx.shutdown();
1325 io_ctx.shutdown();
1360− exit_result
1327+ exit_result.map_err(Error::msg)
1363fn run_vm(
1330fn run_vm(
@@ -1366,8 +1333,8 @@ fn run_vm(
1366 directory_shares: &[DirectoryShare],
1333 directory_shares: &[DirectoryShare],
1367 cpu_count: usize,
1334 cpu_count: usize,
1368 ram_bytes: u64,
1335 ram_bytes: u64,
1369− status: Option<&StatusFile>,
1336+ status: Option<&StatusEmitter<'_>>,
1370−) -> Result<(), Box<dyn std::error::Error>> {
1337+) -> Result<()> {
1371 run_vm_with_io(
1338 run_vm_with_io(
1372 disk_path,
1339 disk_path,
1373 login_actions,
1340 login_actions,
@@ -1379,7 +1346,7 @@ fn run_vm(
1382−fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::Error>> {
1349+fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>> {
1383 let abs_path = if path.is_absolute() {
1350 let abs_path = if path.is_absolute() {
1384 path.to_path_buf()
1351 path.to_path_buf()
1385 } else {
1352 } else {
@@ -1388,7 +1355,7 @@ fn nsurl_from_path(path: &Path) -> Result<Retained<NSURL>, Box<dyn std::error::E
1388 let ns_path = NSString::from_str(
1355 let ns_path = NSString::from_str(
1389 abs_path
1356 abs_path
1390 .to_str()
1357 .to_str()
1391− .ok_or("Non-UTF8 path encountered while building NSURL")?,
1358+ .with_context(|| "non-UTF8 path encountered while building NSURL")?,
1393 Ok(NSURL::fileURLWithPath(&ns_path))
1360 Ok(NSURL::fileURLWithPath(&ns_path))
@@ -1403,7 +1370,7 @@ fn enable_raw_mode(fd: i32) -> io::Result<RawModeGuard> {
1403 let original = attributes;
1370 let original = attributes;
1405 // Disable translation of carriage return to newline on input
1372 // Disable translation of carriage return to newline on input
1406− attributes.c_iflag &= !(libc::ICRNL);
1373+ attributes.c_iflag &= !libc::ICRNL;
1407 // Disable canonical mode (line buffering), echo, and signal generation
1374 // Disable canonical mode (line buffering), echo, and signal generation
1408 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
1375 attributes.c_lflag &= !(libc::ICANON | libc::ECHO | libc::ISIG);
1409 attributes.c_cc[libc::VMIN] = 0;
1376 attributes.c_cc[libc::VMIN] = 0;
@@ -1431,10 +1398,10 @@ impl Drop for RawModeGuard {
1432// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
1399// Ensure the running binary has com.apple.security.virtualization entitlements by checking and, if not, signing and relaunching.
1433pub fn ensure_signed() {
1400pub fn ensure_signed() {
1434− if std::env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1401+ if env::var("VIBEBOX_SKIP_CODESIGN").as_deref() == Ok("1") {
1437− 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");
1438 let exe_str = exe.to_str().expect("exe path not valid utf-8");
1405 let exe_str = exe.to_str().expect("exe path not valid utf-8");
1440 let has_required_entitlements = {
1407 let has_required_entitlements = {
@@ -1456,8 +1423,8 @@ pub fn ensure_signed() {
1458 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1425 const ENTITLEMENTS: &str = include_str!("entitlements.plist");
1459− let entitlements_path = std::env::temp_dir().join("entitlements.plist");
1426+ let entitlements_path = env::temp_dir().join("entitlements.plist");
1460− std::fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1427+ fs::write(&entitlements_path, ENTITLEMENTS).expect("failed to write entitlements");
1462 let output = Command::new("codesign")
1429 let output = Command::new("codesign")
@@ -1470,7 +1437,7 @@ pub fn ensure_signed() {
1471 .output();
1438 .output();
1473− let _ = std::fs::remove_file(&entitlements_path);
1440+ let _ = fs::remove_file(&entitlements_path);
1475 match output {
1442 match output {
1476 Ok(o) if o.status.success() => {
1443 Ok(o) if o.status.success() => {
@@ -1478,7 +1445,7 @@ pub fn ensure_signed() {
1478 if !stderr.trim().is_empty() {
1445 if !stderr.trim().is_empty() {
1479 tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
1446 tracing::debug!(codesign_stderr = %stderr.trim(), "codesign output");
1481− 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();
1482 tracing::error!(error = %err, "failed to re-exec after signing");
1449 tracing::error!(error = %err, "failed to re-exec after signing");
1483 std::process::exit(1);
1450 std::process::exit(1);