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;
21 session_manager::INSTANCE_DIR_NAME,
22 tui::{self, AppState},
23 vm::{self, LoginAction, VmInput},
26const INSTANCE_TOML: &str = "instance.toml";
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 {
37 #[serde(default = "default_ssh_user")]
40 sudo_password: String,
42 pub(crate) vm_ipv4: Option<String>,
45fn default_ssh_user() -> String {
46 DEFAULT_SSH_USER.to_string()
49pub fn run_with_ssh(manager_conn: UnixStream) -> Result<(), Box<dyn std::error::Error>> {
50 let project_root = env::current_dir()?;
51 tracing::info!(root = %project_root.display(), "starting ssh session");
52 let instance_dir = ensure_instance_dir(&project_root)?;
53 tracing::debug!(instance_dir = %instance_dir.display(), "instance dir ready");
54 let (ssh_key, _ssh_pub) = ensure_ssh_keypair(&instance_dir)?;
56 let config = load_or_create_instance_config(&instance_dir)?;
57 let ssh_user = config.ssh_user.clone();
58 tracing::debug!(ssh_user = %ssh_user, "loaded instance config");
60 let _manager_conn = manager_conn;
61 tracing::debug!("waiting for vm ipv4");
62 wait_for_vm_ipv4(&instance_dir, Duration::from_secs(120))?;
64 let ip = load_or_create_instance_config(&instance_dir)?
66 .ok_or("VM IPv4 not available")?;
67 tracing::info!(ip = %ip, "vm ipv4 ready");
69 run_ssh_session(ssh_key, ssh_user, ip)
72pub(crate) fn ensure_instance_dir(project_root: &Path) -> Result<PathBuf, io::Error> {
73 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
74 fs::create_dir_all(&instance_dir)?;
78pub(crate) fn ensure_ssh_keypair(
80) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
81 let private_key = instance_dir.join(SSH_KEY_NAME);
82 let public_key = instance_dir.join(format!("{SSH_KEY_NAME}.pub"));
84 if private_key.exists() && public_key.exists() {
85 return Ok((private_key, public_key));
88 if private_key.exists() {
89 let _ = fs::remove_file(&private_key);
91 if public_key.exists() {
92 let _ = fs::remove_file(&public_key);
95 let status = Command::new("ssh-keygen")
102 private_key.to_str().ok_or("ssh key path not utf-8")?,
106 .stdin(Stdio::null())
107 .stdout(Stdio::null())
108 .stderr(Stdio::inherit())
111 if !status.success() {
112 return Err("ssh-keygen failed".into());
115 fs::set_permissions(&private_key, fs::Permissions::from_mode(0o600))?;
116 fs::set_permissions(&public_key, fs::Permissions::from_mode(0o644))?;
118 Ok((private_key, public_key))
121pub(crate) fn load_or_create_instance_config(
123) -> Result<InstanceConfig, Box<dyn std::error::Error>> {
124 let config_path = instance_dir.join(INSTANCE_TOML);
125 let mut config = if config_path.exists() {
126 let raw = fs::read_to_string(&config_path)?;
127 toml::from_str::<InstanceConfig>(&raw)?
130 ssh_user: default_ssh_user(),
131 sudo_password: String::new(),
136 let mut changed = false;
137 if config.ssh_user.trim().is_empty() {
138 config.ssh_user = default_ssh_user();
142 if config.sudo_password.trim().is_empty() {
143 config.sudo_password = generate_password();
147 if !config_path.exists() || changed {
148 write_instance_config(&config_path, &config)?;
154pub(crate) fn write_instance_config(
156 config: &InstanceConfig,
157) -> Result<(), Box<dyn std::error::Error>> {
158 let data = toml::to_string_pretty(config)?;
159 fs::write(path, data)?;
160 fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
164fn generate_password() -> String {
165 Uuid::now_v7().simple().to_string()
168pub(crate) fn extract_ipv4(line: &str) -> Option<String> {
169 let mut current = String::new();
170 let mut best: Option<String> = None;
172 for ch in line.chars().chain(std::iter::once(' ')) {
173 if ch.is_ascii_digit() || ch == '.' {
175 } else if !current.is_empty() {
176 if is_ipv4_candidate(¤t) {
177 best = Some(current.clone());
190) -> Result<(), Box<dyn std::error::Error>> {
191 let start = Instant::now();
193 let config = load_or_create_instance_config(instance_dir)?;
194 if config.vm_ipv4.is_some() {
197 if start.elapsed() > timeout {
198 return Err("Timed out waiting for VM IPv4".into());
200 if start.elapsed().as_secs() % 5 == 0 {
201 tracing::debug!("still waiting for vm ipv4");
203 thread::sleep(Duration::from_millis(200));
211) -> Result<(), Box<dyn std::error::Error>> {
212 let mut attempts = 0usize;
215 if !ssh_port_open(&ip) {
216 tracing::debug!(attempts, "ssh port not open yet");
218 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
220 if attempts >= SSH_CONNECT_RETRIES {
222 format!("ssh port not ready after {SSH_CONNECT_RETRIES} attempts").into(),
225 thread::sleep(Duration::from_millis(SSH_CONNECT_DELAY_MS));
230 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
232 tracing::info!(attempts, user = %ssh_user, ip = %ip, "starting ssh");
233 let status = Command::new("ssh")
236 ssh_key.to_str().unwrap_or(".vibebox/ssh_key"),
238 "IdentitiesOnly=yes",
240 "StrictHostKeyChecking=no",
242 "UserKnownHostsFile=/dev/null",
244 "GlobalKnownHostsFile=/dev/null",
246 "PasswordAuthentication=no",
254 .env_remove("LC_CTYPE")
255 .env_remove("LC_ALL")
257 .arg(format!("{ssh_user}@{ip}"))
258 .stdin(Stdio::inherit())
259 .stdout(Stdio::inherit())
260 .stderr(Stdio::inherit())
264 Ok(status) if status.success() => {
265 eprintln!("[vibebox] ssh exited with status: {status}");
268 Ok(status) if status.code() == Some(255) => {
269 eprintln!("[vibebox] ssh connection failed: {status}");
270 if attempts >= SSH_CONNECT_RETRIES {
271 return Err(format!("ssh failed after {SSH_CONNECT_RETRIES} attempts").into());
273 thread::sleep(Duration::from_millis(500));
276 return Err(format!("ssh exited with status: {status}").into());
279 return Err(format!("failed to start ssh: {err}").into());
287fn is_ipv4_candidate(candidate: &str) -> bool {
288 let parts: Vec<&str> = candidate.split('.').collect();
289 if parts.len() != 4 {
293 if part.is_empty() || part.len() > 3 {
296 if part.parse::<u8>().is_err() {
303fn ssh_port_open(ip: &str) -> bool {
304 let addr: SocketAddr = match format!("{ip}:22").parse() {
306 Err(_) => return false,
308 TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(500)).is_ok()
311pub(crate) fn build_ssh_login_actions(
312 config: &Arc<Mutex<InstanceConfig>>,
316) -> Vec<LoginAction> {
317 let config_guard = config.lock().expect("config mutex poisoned");
318 let ssh_user = config_guard.ssh_user.clone();
319 let sudo_password = config_guard.sudo_password.clone();
322 let key_path = format!("{guest_dir}/{key_name}.pub");
324 let setup_script = SSH_SETUP_SCRIPT
325 .replace("__SSH_USER__", &ssh_user)
326 .replace("__SUDO_PASSWORD__", &sudo_password)
327 .replace("__PROJECT_NAME__", project_name)
328 .replace("__KEY_PATH__", &key_path);
329 let setup = vm::script_command_from_content("ssh_setup", &setup_script)
330 .expect("ssh setup script contained invalid marker");
332 vec![LoginAction::Send(setup)]
337 app: Arc<Mutex<AppState>>,
338 config: Arc<Mutex<InstanceConfig>>,
339 instance_dir: PathBuf,
341 output_monitor: Arc<vm::OutputMonitor>,
342 vm_output_fd: OwnedFd,
343 vm_input_fd: OwnedFd,
345 let io_control = vm::IoControl::new();
347 let log_path = instance_dir.join(SERIAL_LOG_NAME);
348 let log_file = fs::OpenOptions::new()
353 .map(|file| Arc::new(Mutex::new(file)));
355 let ssh_connected = Arc::new(AtomicBool::new(false));
356 let ssh_started = Arc::new(AtomicBool::new(false));
357 let ssh_ready = Arc::new(AtomicBool::new(false));
358 let input_tx_holder: Arc<Mutex<Option<Sender<VmInput>>>> = Arc::new(Mutex::new(None));
360 let instance_path = instance_dir.join(INSTANCE_TOML);
361 let config_for_output = config.clone();
362 let log_for_output = log_file.clone();
363 let ssh_connected_for_output = ssh_connected.clone();
364 let ssh_ready_for_output = ssh_ready.clone();
366 let mut line_buf = String::new();
369 let app = app.clone();
372 if let Ok(mut locked) = app.lock() {
373 let _ = tui::render_commands_component(&mut locked);
381 let on_output = move |bytes: &[u8]| {
382 if ssh_connected_for_output.load(Ordering::SeqCst) {
383 if let Some(log) = &log_for_output {
384 if let Ok(mut file) = log.lock() {
385 let _ = file.write_all(bytes);
390 let text = String::from_utf8_lossy(bytes);
391 line_buf.push_str(&text);
393 while let Some(pos) = line_buf.find('\n') {
394 let mut line = line_buf[..pos].to_string();
395 if line.ends_with('\r') {
398 line_buf.drain(..=pos);
400 let cleaned = line.trim_start_matches(|c: char| c == '\r' || c == ' ');
402 if let Some(pos) = cleaned.find("VIBEBOX_IPV4=") {
403 let ip_raw = &cleaned[(pos + "VIBEBOX_IPV4=".len())..];
404 let ip = extract_ipv4(ip_raw).unwrap_or_default();
406 if let Ok(mut cfg) = config_for_output.lock() {
407 if cfg.vm_ipv4.as_deref() != Some(ip.as_str()) {
408 cfg.vm_ipv4 = Some(ip.clone());
409 let _ = write_instance_config(&instance_path, &cfg);
410 eprintln!("[vibebox] detected vm IPv4: {ip}");
416 if cleaned.contains("VIBEBOX_SSH_READY") {
417 ssh_ready_for_output.store(true, Ordering::SeqCst);
418 eprintln!("[vibebox] sshd ready");
423 let io_ctx = vm::spawn_vm_io_with_hooks(
432 *input_tx_holder.lock().unwrap() = Some(io_ctx.input_tx.clone());
434 let ssh_ready_for_thread = ssh_ready.clone();
435 let ssh_started_for_thread = ssh_started.clone();
436 let ssh_connected_for_thread = ssh_connected.clone();
437 let io_control_for_thread = io_control.clone();
438 let ssh_key_for_thread = ssh_key.clone();
439 let config_for_thread = config.clone();
440 let input_tx_holder_for_thread = input_tx_holder.clone();
442 thread::spawn(move || {
444 if ssh_started_for_thread.load(Ordering::SeqCst) {
447 if !ssh_ready_for_thread.load(Ordering::SeqCst) {
448 thread::sleep(std::time::Duration::from_millis(200));
452 let ip = config_for_thread
455 .and_then(|cfg| cfg.vm_ipv4.clone());
456 let ssh_user = config_for_thread
458 .map(|cfg| cfg.ssh_user.clone())
459 .unwrap_or_else(|_| DEFAULT_SSH_USER.to_string());
461 if let Some(ip) = ip {
462 if ssh_started_for_thread
463 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
469 eprintln!("[vibebox] starting ssh to {ssh_user}@{ip}");
470 io_control_for_thread.request_terminal_restore();
471 io_control_for_thread.set_forward_output(false);
472 io_control_for_thread.set_forward_input(false);
473 ssh_connected_for_thread.store(true, Ordering::SeqCst);
475 let mut attempts = 0usize;
478 if !ssh_port_open(&ip) {
480 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
482 if attempts >= SSH_CONNECT_RETRIES {
483 ssh_connected_for_thread.store(false, Ordering::SeqCst);
485 "[vibebox] ssh port not ready after {SSH_CONNECT_RETRIES} attempts"
489 thread::sleep(std::time::Duration::from_millis(SSH_CONNECT_DELAY_MS));
494 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
496 let status = Command::new("ssh")
499 ssh_key_for_thread.to_str().unwrap_or(".vibebox/ssh_key"),
501 "IdentitiesOnly=yes",
503 "StrictHostKeyChecking=no",
505 "UserKnownHostsFile=/dev/null",
507 "GlobalKnownHostsFile=/dev/null",
509 "PasswordAuthentication=no",
517 .env_remove("LC_CTYPE")
518 .env_remove("LC_ALL")
519 // .env_remove("LANG")
520 .arg(format!("{ssh_user}@{ip}"))
521 .stdin(Stdio::inherit())
522 .stdout(Stdio::inherit())
523 .stderr(Stdio::inherit())
527 Ok(status) if status.success() => {
528 ssh_connected_for_thread.store(false, Ordering::SeqCst);
529 eprintln!("[vibebox] ssh exited with status: {status}");
530 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
531 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
535 Ok(status) if status.code() == Some(255) => {
536 eprintln!("[vibebox] ssh connection failed: {status}");
537 if attempts >= SSH_CONNECT_RETRIES {
538 ssh_connected_for_thread.store(false, Ordering::SeqCst);
540 "[vibebox] ssh failed after {SSH_CONNECT_RETRIES} attempts"
544 thread::sleep(std::time::Duration::from_millis(500));
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()));
556 ssh_connected_for_thread.store(false, Ordering::SeqCst);
557 eprintln!("[vibebox] failed to start ssh: {err}");
565 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