4 net::{SocketAddr, TcpStream},
5 os::unix::{fs::PermissionsExt, io::OwnedFd},
7 process::{Command, Stdio},
10 atomic::{AtomicBool, Ordering},
15use serde::{Deserialize, Serialize};
16use std::sync::mpsc::Sender;
20 session_manager::{GLOBAL_DIR_NAME, INSTANCE_DIR_NAME},
21 tui::{self, AppState},
22 vm::{self, DirectoryShare, LoginAction, VmInput},
25const INSTANCE_TOML: &str = "instance.toml";
26const SSH_KEY_NAME: &str = "ssh_key";
27const SERIAL_LOG_NAME: &str = "serial.log";
28const DEFAULT_SSH_USER: &str = "vibecoder";
29const SSH_CONNECT_RETRIES: usize = 30;
30const SSH_CONNECT_DELAY_MS: u64 = 500;
31const SSH_SETUP_SCRIPT: &str = include_str!("ssh.sh");
33#[derive(Debug, Clone, Serialize, Deserialize)]
34struct InstanceConfig {
35 #[serde(default = "default_ssh_user")]
38 sudo_password: String,
40 vm_ipv4: Option<String>,
43fn default_ssh_user() -> String {
44 DEFAULT_SSH_USER.to_string()
49 app: Arc<Mutex<AppState>>,
50) -> Result<(), Box<dyn std::error::Error>> {
51 let project_root = env::current_dir()?;
52 let project_name = project_root
54 .ok_or("Project directory has no name")?
57 let instance_dir = ensure_instance_dir(&project_root)?;
58 let (ssh_key, _ssh_pub) = ensure_ssh_keypair(&instance_dir)?;
60 let mut config = load_or_create_instance_config(&instance_dir)?;
61 // Clear cached IP to avoid reusing a stale address on startup.
62 if config.vm_ipv4.is_some() {
63 config.vm_ipv4 = None;
64 write_instance_config(&instance_dir.join(INSTANCE_TOML), &config)?;
66 let config = Arc::new(Mutex::new(config));
68 let ssh_guest_dir = format!("/root/{}", GLOBAL_DIR_NAME);
70 let extra_shares = vec![DirectoryShare::new(
72 ssh_guest_dir.clone().into(),
76 let extra_login_actions =
77 build_ssh_login_actions(&config, &project_name, ssh_guest_dir.as_str(), SSH_KEY_NAME);
79 vm::run_with_args_and_extras(
81 |output_monitor, vm_output_fd, vm_input_fd| {
97fn ensure_instance_dir(project_root: &Path) -> Result<PathBuf, io::Error> {
98 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
99 fs::create_dir_all(&instance_dir)?;
103fn ensure_ssh_keypair(
105) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
106 let private_key = instance_dir.join(SSH_KEY_NAME);
107 let public_key = instance_dir.join(format!("{SSH_KEY_NAME}.pub"));
109 if private_key.exists() && public_key.exists() {
110 return Ok((private_key, public_key));
113 if private_key.exists() {
114 let _ = fs::remove_file(&private_key);
116 if public_key.exists() {
117 let _ = fs::remove_file(&public_key);
120 let status = Command::new("ssh-keygen")
127 private_key.to_str().ok_or("ssh key path not utf-8")?,
131 .stdin(Stdio::null())
132 .stdout(Stdio::null())
133 .stderr(Stdio::inherit())
136 if !status.success() {
137 return Err("ssh-keygen failed".into());
140 fs::set_permissions(&private_key, fs::Permissions::from_mode(0o600))?;
141 fs::set_permissions(&public_key, fs::Permissions::from_mode(0o644))?;
143 Ok((private_key, public_key))
146fn load_or_create_instance_config(
148) -> Result<InstanceConfig, Box<dyn std::error::Error>> {
149 let config_path = instance_dir.join(INSTANCE_TOML);
150 let mut config = if config_path.exists() {
151 let raw = fs::read_to_string(&config_path)?;
152 toml::from_str::<InstanceConfig>(&raw)?
155 ssh_user: default_ssh_user(),
156 sudo_password: String::new(),
161 let mut changed = false;
162 if config.ssh_user.trim().is_empty() {
163 config.ssh_user = default_ssh_user();
167 if config.sudo_password.trim().is_empty() {
168 config.sudo_password = generate_password();
172 if !config_path.exists() || changed {
173 write_instance_config(&config_path, &config)?;
179fn write_instance_config(
181 config: &InstanceConfig,
182) -> Result<(), Box<dyn std::error::Error>> {
183 let data = toml::to_string_pretty(config)?;
184 fs::write(path, data)?;
185 fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
189fn generate_password() -> String {
190 Uuid::now_v7().simple().to_string()
193fn extract_ipv4(line: &str) -> Option<String> {
194 let mut current = String::new();
195 let mut best: Option<String> = None;
197 for ch in line.chars().chain(std::iter::once(' ')) {
198 if ch.is_ascii_digit() || ch == '.' {
200 } else if !current.is_empty() {
201 if is_ipv4_candidate(¤t) {
202 best = Some(current.clone());
212fn is_ipv4_candidate(candidate: &str) -> bool {
213 let parts: Vec<&str> = candidate.split('.').collect();
214 if parts.len() != 4 {
218 if part.is_empty() || part.len() > 3 {
221 if part.parse::<u8>().is_err() {
228fn ssh_port_open(ip: &str) -> bool {
229 let addr: SocketAddr = match format!("{ip}:22").parse() {
231 Err(_) => return false,
233 TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(500)).is_ok()
236fn build_ssh_login_actions(
237 config: &Arc<Mutex<InstanceConfig>>,
241) -> Vec<LoginAction> {
242 let config_guard = config.lock().expect("config mutex poisoned");
243 let ssh_user = config_guard.ssh_user.clone();
244 let sudo_password = config_guard.sudo_password.clone();
247 let key_path = format!("{guest_dir}/{key_name}.pub");
249 let setup_script = SSH_SETUP_SCRIPT
250 .replace("__SSH_USER__", &ssh_user)
251 .replace("__SUDO_PASSWORD__", &sudo_password)
252 .replace("__PROJECT_NAME__", project_name)
253 .replace("__KEY_PATH__", &key_path);
254 let setup = vm::script_command_from_content("ssh_setup", &setup_script)
255 .expect("ssh setup script contained invalid marker");
257 vec![LoginAction::Send(setup)]
261 app: Arc<Mutex<AppState>>,
262 config: Arc<Mutex<InstanceConfig>>,
263 instance_dir: PathBuf,
265 output_monitor: Arc<vm::OutputMonitor>,
266 vm_output_fd: OwnedFd,
267 vm_input_fd: OwnedFd,
269 let io_control = vm::IoControl::new();
271 let log_path = instance_dir.join(SERIAL_LOG_NAME);
272 let log_file = fs::OpenOptions::new()
277 .map(|file| Arc::new(Mutex::new(file)));
279 let ssh_connected = Arc::new(AtomicBool::new(false));
280 let ssh_started = Arc::new(AtomicBool::new(false));
281 let ssh_ready = Arc::new(AtomicBool::new(false));
282 let input_tx_holder: Arc<Mutex<Option<Sender<VmInput>>>> = Arc::new(Mutex::new(None));
284 let instance_path = instance_dir.join(INSTANCE_TOML);
285 let config_for_output = config.clone();
286 let log_for_output = log_file.clone();
287 let ssh_connected_for_output = ssh_connected.clone();
288 let ssh_ready_for_output = ssh_ready.clone();
290 let mut line_buf = String::new();
293 let app = app.clone();
296 if let Ok(mut locked) = app.lock() {
297 let _ = tui::render_commands_component(&mut locked);
305 let on_output = move |bytes: &[u8]| {
306 if ssh_connected_for_output.load(Ordering::SeqCst) {
307 if let Some(log) = &log_for_output {
308 if let Ok(mut file) = log.lock() {
309 let _ = file.write_all(bytes);
314 let text = String::from_utf8_lossy(bytes);
315 line_buf.push_str(&text);
317 while let Some(pos) = line_buf.find('\n') {
318 let mut line = line_buf[..pos].to_string();
319 if line.ends_with('\r') {
322 line_buf.drain(..=pos);
324 let cleaned = line.trim_start_matches(|c: char| c == '\r' || c == ' ');
326 if let Some(pos) = cleaned.find("VIBEBOX_IPV4=") {
327 let ip_raw = &cleaned[(pos + "VIBEBOX_IPV4=".len())..];
328 let ip = extract_ipv4(ip_raw).unwrap_or_default();
330 if let Ok(mut cfg) = config_for_output.lock() {
331 if cfg.vm_ipv4.as_deref() != Some(ip.as_str()) {
332 cfg.vm_ipv4 = Some(ip.clone());
333 let _ = write_instance_config(&instance_path, &cfg);
334 eprintln!("[vibebox] detected vm IPv4: {ip}");
340 if cleaned.contains("VIBEBOX_SSH_READY") {
341 ssh_ready_for_output.store(true, Ordering::SeqCst);
342 eprintln!("[vibebox] sshd ready");
347 let io_ctx = vm::spawn_vm_io_with_hooks(
356 *input_tx_holder.lock().unwrap() = Some(io_ctx.input_tx.clone());
358 let ssh_ready_for_thread = ssh_ready.clone();
359 let ssh_started_for_thread = ssh_started.clone();
360 let ssh_connected_for_thread = ssh_connected.clone();
361 let io_control_for_thread = io_control.clone();
362 let ssh_key_for_thread = ssh_key.clone();
363 let config_for_thread = config.clone();
364 let input_tx_holder_for_thread = input_tx_holder.clone();
366 thread::spawn(move || {
368 if ssh_started_for_thread.load(Ordering::SeqCst) {
371 if !ssh_ready_for_thread.load(Ordering::SeqCst) {
372 thread::sleep(std::time::Duration::from_millis(200));
376 let ip = config_for_thread
379 .and_then(|cfg| cfg.vm_ipv4.clone());
380 let ssh_user = config_for_thread
382 .map(|cfg| cfg.ssh_user.clone())
383 .unwrap_or_else(|_| DEFAULT_SSH_USER.to_string());
385 if let Some(ip) = ip {
386 if ssh_started_for_thread
387 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
393 eprintln!("[vibebox] starting ssh to {ssh_user}@{ip}");
394 io_control_for_thread.request_terminal_restore();
395 io_control_for_thread.set_forward_output(false);
396 io_control_for_thread.set_forward_input(false);
397 ssh_connected_for_thread.store(true, Ordering::SeqCst);
399 let mut attempts = 0usize;
402 if !ssh_port_open(&ip) {
404 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
406 if attempts >= SSH_CONNECT_RETRIES {
407 ssh_connected_for_thread.store(false, Ordering::SeqCst);
409 "[vibebox] ssh port not ready after {SSH_CONNECT_RETRIES} attempts"
413 thread::sleep(std::time::Duration::from_millis(SSH_CONNECT_DELAY_MS));
418 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
420 let status = Command::new("ssh")
423 ssh_key_for_thread.to_str().unwrap_or(".vibebox/ssh_key"),
425 "IdentitiesOnly=yes",
427 "StrictHostKeyChecking=no",
429 "UserKnownHostsFile=/dev/null",
431 "GlobalKnownHostsFile=/dev/null",
433 "PasswordAuthentication=no",
441 .env_remove("LC_CTYPE")
442 .env_remove("LC_ALL")
443 // .env_remove("LANG")
444 .arg(format!("{ssh_user}@{ip}"))
445 .stdin(Stdio::inherit())
446 .stdout(Stdio::inherit())
447 .stderr(Stdio::inherit())
451 Ok(status) if status.success() => {
452 ssh_connected_for_thread.store(false, Ordering::SeqCst);
453 eprintln!("[vibebox] ssh exited with status: {status}");
454 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
455 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
459 Ok(status) if status.code() == Some(255) => {
460 eprintln!("[vibebox] ssh connection failed: {status}");
461 if attempts >= SSH_CONNECT_RETRIES {
462 ssh_connected_for_thread.store(false, Ordering::SeqCst);
464 "[vibebox] ssh failed after {SSH_CONNECT_RETRIES} attempts"
468 thread::sleep(std::time::Duration::from_millis(500));
472 ssh_connected_for_thread.store(false, Ordering::SeqCst);
473 eprintln!("[vibebox] ssh exited with status: {status}");
474 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
475 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
480 ssh_connected_for_thread.store(false, Ordering::SeqCst);
481 eprintln!("[vibebox] failed to start ssh: {err}");
489 thread::sleep(std::time::Duration::from_millis(200));
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list