4 net::{SocketAddr, TcpStream},
5 os::unix::{fs::PermissionsExt, io::OwnedFd, net::UnixStream},
7 process::{Command, Stdio},
10 atomic::{AtomicBool, Ordering},
13 time::{Duration, Instant},
16use serde::{Deserialize, Serialize};
17use std::sync::mpsc::Sender;
18use time::{OffsetDateTime, format_description::well_known::Rfc3339};
22 session_manager::{INSTANCE_DIR_NAME, INSTANCE_TOML_FILENAME},
23 tui::{self, AppState},
24 vm::{self, LoginAction, VmInput},
27const SSH_KEY_NAME: &str = "ssh_key";
29const SERIAL_LOG_NAME: &str = "serial.log";
30const DEFAULT_SSH_USER: &str = "vibecoder";
31const SSH_CONNECT_RETRIES: usize = 30;
32const SSH_CONNECT_DELAY_MS: u64 = 500;
33const SSH_SETUP_SCRIPT: &str = include_str!("ssh.sh");
35#[derive(Debug, Clone, Serialize, Deserialize)]
36pub(crate) struct InstanceConfig {
39 #[serde(default = "default_ssh_user")]
42 sudo_password: String,
44 last_active: Option<String>,
46 pub(crate) vm_ipv4: Option<String>,
49fn default_ssh_user() -> String {
50 DEFAULT_SSH_USER.to_string()
53pub fn run_with_ssh(manager_conn: UnixStream) -> Result<(), Box<dyn std::error::Error>> {
54 let project_root = env::current_dir()?;
55 tracing::info!(root = %project_root.display(), "starting ssh session");
56 let instance_dir = ensure_instance_dir(&project_root)?;
57 tracing::debug!(instance_dir = %instance_dir.display(), "instance dir ready");
58 let (ssh_key, _ssh_pub) = ensure_ssh_keypair(&instance_dir)?;
60 let config = load_or_create_instance_config(&instance_dir)?;
61 let ssh_user = config.ssh_user.clone();
62 tracing::debug!(ssh_user = %ssh_user, "loaded instance config");
64 let _manager_conn = manager_conn;
65 tracing::debug!("waiting for vm ipv4");
66 wait_for_vm_ipv4(&instance_dir, Duration::from_secs(120))?;
68 let ip = load_or_create_instance_config(&instance_dir)?
70 .ok_or("VM IPv4 not available")?;
71 tracing::info!(ip = %ip, "vm ipv4 ready");
73 run_ssh_session(ssh_key, ssh_user, ip)
76pub fn ensure_instance_dir(project_root: &Path) -> Result<PathBuf, io::Error> {
77 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
78 fs::create_dir_all(&instance_dir)?;
82pub(crate) fn ensure_ssh_keypair(
84) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
85 let private_key = instance_dir.join(SSH_KEY_NAME);
86 let public_key = instance_dir.join(format!("{SSH_KEY_NAME}.pub"));
88 if private_key.exists() && public_key.exists() {
89 return Ok((private_key, public_key));
92 if private_key.exists() {
93 let _ = fs::remove_file(&private_key);
95 if public_key.exists() {
96 let _ = fs::remove_file(&public_key);
99 let status = Command::new("ssh-keygen")
106 private_key.to_str().ok_or("ssh key path not utf-8")?,
110 .stdin(Stdio::null())
111 .stdout(Stdio::null())
112 .stderr(Stdio::inherit())
115 if !status.success() {
116 return Err("ssh-keygen failed".into());
119 fs::set_permissions(&private_key, fs::Permissions::from_mode(0o600))?;
120 fs::set_permissions(&public_key, fs::Permissions::from_mode(0o644))?;
122 Ok((private_key, public_key))
125pub(crate) fn load_or_create_instance_config(
127) -> Result<InstanceConfig, Box<dyn std::error::Error>> {
128 let config_path = instance_dir.join(INSTANCE_TOML_FILENAME);
129 let mut config = if config_path.exists() {
130 let raw = fs::read_to_string(&config_path)?;
131 toml::from_str::<InstanceConfig>(&raw)?
135 ssh_user: default_ssh_user(),
136 sudo_password: String::new(),
142 let mut changed = false;
143 if config.ssh_user.trim().is_empty() {
144 config.ssh_user = default_ssh_user();
148 if config.id.trim().is_empty() {
149 config.id = Uuid::now_v7().to_string();
153 if config.sudo_password.trim().is_empty() {
154 config.sudo_password = generate_password();
158 if !config_path.exists() || changed {
159 write_instance_config(&config_path, &config)?;
165pub fn touch_last_active(instance_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
166 let mut config = load_or_create_instance_config(instance_dir)?;
167 let now = OffsetDateTime::now_utc().format(&Rfc3339)?;
168 config.last_active = Some(now);
169 write_instance_config(&instance_dir.join(INSTANCE_TOML_FILENAME), &config)?;
173pub(crate) fn write_instance_config(
175 config: &InstanceConfig,
176) -> Result<(), Box<dyn std::error::Error>> {
177 let data = toml::to_string_pretty(config)?;
178 fs::write(path, data)?;
179 fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
183fn generate_password() -> String {
184 Uuid::now_v7().simple().to_string()
187pub(crate) fn extract_ipv4(line: &str) -> Option<String> {
188 let mut current = String::new();
189 let mut best: Option<String> = None;
191 for ch in line.chars().chain(std::iter::once(' ')) {
192 if ch.is_ascii_digit() || ch == '.' {
194 } else if !current.is_empty() {
195 if is_ipv4_candidate(¤t) {
196 best = Some(current.clone());
209) -> Result<(), Box<dyn std::error::Error>> {
210 let start = Instant::now();
212 let config = load_or_create_instance_config(instance_dir)?;
213 if config.vm_ipv4.is_some() {
216 if start.elapsed() > timeout {
217 return Err("Timed out waiting for VM IPv4".into());
219 if start.elapsed().as_secs() % 5 == 0 {
220 tracing::debug!("still waiting for vm ipv4");
222 thread::sleep(Duration::from_millis(200));
230) -> Result<(), Box<dyn std::error::Error>> {
231 let mut attempts = 0usize;
234 if !ssh_port_open(&ip) {
235 tracing::debug!(attempts, "ssh port not open yet");
237 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
239 if attempts >= SSH_CONNECT_RETRIES {
241 format!("ssh port not ready after {SSH_CONNECT_RETRIES} attempts").into(),
244 thread::sleep(Duration::from_millis(SSH_CONNECT_DELAY_MS));
249 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
251 tracing::info!(attempts, user = %ssh_user, ip = %ip, "starting ssh");
252 let status = Command::new("ssh")
255 ssh_key.to_str().unwrap_or(".vibebox/ssh_key"),
257 "IdentitiesOnly=yes",
259 "StrictHostKeyChecking=no",
261 "UserKnownHostsFile=/dev/null",
263 "GlobalKnownHostsFile=/dev/null",
265 "PasswordAuthentication=no",
273 .env_remove("LC_CTYPE")
274 .env_remove("LC_ALL")
276 .arg(format!("{ssh_user}@{ip}"))
277 .stdin(Stdio::inherit())
278 .stdout(Stdio::inherit())
279 .stderr(Stdio::inherit())
283 Ok(status) if status.success() => {
284 eprintln!("[vibebox] ssh exited with status: {status}");
287 Ok(status) if status.code() == Some(255) => {
288 eprintln!("[vibebox] ssh connection failed: {status}");
289 if attempts >= SSH_CONNECT_RETRIES {
290 return Err(format!("ssh failed after {SSH_CONNECT_RETRIES} attempts").into());
292 thread::sleep(Duration::from_millis(500));
295 return Err(format!("ssh exited with status: {status}").into());
298 return Err(format!("failed to start ssh: {err}").into());
306fn is_ipv4_candidate(candidate: &str) -> bool {
307 let parts: Vec<&str> = candidate.split('.').collect();
308 if parts.len() != 4 {
312 if part.is_empty() || part.len() > 3 {
315 if part.parse::<u8>().is_err() {
322fn ssh_port_open(ip: &str) -> bool {
323 let addr: SocketAddr = match format!("{ip}:22").parse() {
325 Err(_) => return false,
327 TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(500)).is_ok()
330pub(crate) fn build_ssh_login_actions(
331 config: &Arc<Mutex<InstanceConfig>>,
335) -> Vec<LoginAction> {
336 let config_guard = config.lock().expect("config mutex poisoned");
337 let ssh_user = config_guard.ssh_user.clone();
338 let sudo_password = config_guard.sudo_password.clone();
341 let key_path = format!("{guest_dir}/{key_name}.pub");
343 let setup_script = SSH_SETUP_SCRIPT
344 .replace("__SSH_USER__", &ssh_user)
345 .replace("__SUDO_PASSWORD__", &sudo_password)
346 .replace("__PROJECT_NAME__", project_name)
347 .replace("__KEY_PATH__", &key_path);
348 let setup = vm::script_command_from_content("ssh_setup", &setup_script)
349 .expect("ssh setup script contained invalid marker");
351 vec![LoginAction::Send(setup)]
356 app: Arc<Mutex<AppState>>,
357 config: Arc<Mutex<InstanceConfig>>,
358 instance_dir: PathBuf,
360 output_monitor: Arc<vm::OutputMonitor>,
361 vm_output_fd: OwnedFd,
362 vm_input_fd: OwnedFd,
364 let io_control = vm::IoControl::new();
366 let log_path = instance_dir.join(SERIAL_LOG_NAME);
367 let log_file = fs::OpenOptions::new()
373 .map(|file| Arc::new(Mutex::new(file)));
375 let ssh_connected = Arc::new(AtomicBool::new(false));
376 let ssh_started = Arc::new(AtomicBool::new(false));
377 let ssh_ready = Arc::new(AtomicBool::new(false));
378 let input_tx_holder: Arc<Mutex<Option<Sender<VmInput>>>> = Arc::new(Mutex::new(None));
380 let instance_path = instance_dir.join(INSTANCE_TOML_FILENAME);
381 let config_for_output = config.clone();
382 let log_for_output = log_file.clone();
383 let ssh_connected_for_output = ssh_connected.clone();
384 let ssh_ready_for_output = ssh_ready.clone();
386 let mut line_buf = String::new();
389 let app = app.clone();
392 if let Ok(mut locked) = app.lock() {
393 let _ = tui::render_commands_component(&mut locked);
401 let on_output = move |bytes: &[u8]| {
402 if ssh_connected_for_output.load(Ordering::SeqCst) {
403 if let Some(log) = &log_for_output {
404 if let Ok(mut file) = log.lock() {
405 let _ = file.write_all(bytes);
410 let text = String::from_utf8_lossy(bytes);
411 line_buf.push_str(&text);
413 while let Some(pos) = line_buf.find('\n') {
414 let mut line = line_buf[..pos].to_string();
415 if line.ends_with('\r') {
418 line_buf.drain(..=pos);
420 let cleaned = line.trim_start_matches(|c: char| c == '\r' || c == ' ');
422 if let Some(pos) = cleaned.find("VIBEBOX_IPV4=") {
423 let ip_raw = &cleaned[(pos + "VIBEBOX_IPV4=".len())..];
424 let ip = extract_ipv4(ip_raw).unwrap_or_default();
426 if let Ok(mut cfg) = config_for_output.lock() {
427 if cfg.vm_ipv4.as_deref() != Some(ip.as_str()) {
428 cfg.vm_ipv4 = Some(ip.clone());
429 let _ = write_instance_config(&instance_path, &cfg);
430 eprintln!("[vibebox] detected vm IPv4: {ip}");
436 if cleaned.contains("VIBEBOX_SSH_READY") {
437 ssh_ready_for_output.store(true, Ordering::SeqCst);
438 eprintln!("[vibebox] sshd ready");
443 let io_ctx = vm::spawn_vm_io_with_hooks(
452 *input_tx_holder.lock().unwrap() = Some(io_ctx.input_tx.clone());
454 let ssh_ready_for_thread = ssh_ready.clone();
455 let ssh_started_for_thread = ssh_started.clone();
456 let ssh_connected_for_thread = ssh_connected.clone();
457 let io_control_for_thread = io_control.clone();
458 let ssh_key_for_thread = ssh_key.clone();
459 let config_for_thread = config.clone();
460 let input_tx_holder_for_thread = input_tx_holder.clone();
462 thread::spawn(move || {
464 if ssh_started_for_thread.load(Ordering::SeqCst) {
467 if !ssh_ready_for_thread.load(Ordering::SeqCst) {
468 thread::sleep(std::time::Duration::from_millis(200));
472 let ip = config_for_thread
475 .and_then(|cfg| cfg.vm_ipv4.clone());
476 let ssh_user = config_for_thread
478 .map(|cfg| cfg.ssh_user.clone())
479 .unwrap_or_else(|_| DEFAULT_SSH_USER.to_string());
481 if let Some(ip) = ip {
482 if ssh_started_for_thread
483 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
489 eprintln!("[vibebox] starting ssh to {ssh_user}@{ip}");
490 io_control_for_thread.request_terminal_restore();
491 io_control_for_thread.set_forward_output(false);
492 io_control_for_thread.set_forward_input(false);
493 ssh_connected_for_thread.store(true, Ordering::SeqCst);
495 let mut attempts = 0usize;
498 if !ssh_port_open(&ip) {
500 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
502 if attempts >= SSH_CONNECT_RETRIES {
503 ssh_connected_for_thread.store(false, Ordering::SeqCst);
505 "[vibebox] ssh port not ready after {SSH_CONNECT_RETRIES} attempts"
509 thread::sleep(std::time::Duration::from_millis(SSH_CONNECT_DELAY_MS));
514 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
516 let status = Command::new("ssh")
519 ssh_key_for_thread.to_str().unwrap_or(".vibebox/ssh_key"),
521 "IdentitiesOnly=yes",
523 "StrictHostKeyChecking=no",
525 "UserKnownHostsFile=/dev/null",
527 "GlobalKnownHostsFile=/dev/null",
529 "PasswordAuthentication=no",
537 .env_remove("LC_CTYPE")
538 .env_remove("LC_ALL")
539 // .env_remove("LANG")
540 .arg(format!("{ssh_user}@{ip}"))
541 .stdin(Stdio::inherit())
542 .stdout(Stdio::inherit())
543 .stderr(Stdio::inherit())
547 Ok(status) if status.success() => {
548 ssh_connected_for_thread.store(false, Ordering::SeqCst);
549 eprintln!("[vibebox] ssh exited with status: {status}");
550 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
551 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
555 Ok(status) if status.code() == Some(255) => {
556 eprintln!("[vibebox] ssh connection failed: {status}");
557 if attempts >= SSH_CONNECT_RETRIES {
558 ssh_connected_for_thread.store(false, Ordering::SeqCst);
560 "[vibebox] ssh failed after {SSH_CONNECT_RETRIES} attempts"
564 thread::sleep(std::time::Duration::from_millis(500));
568 ssh_connected_for_thread.store(false, Ordering::SeqCst);
569 eprintln!("[vibebox] ssh exited with status: {status}");
570 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
571 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
576 ssh_connected_for_thread.store(false, Ordering::SeqCst);
577 eprintln!("[vibebox] failed to start ssh: {err}");
585 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