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};
23 session_manager::{INSTANCE_DIR_NAME, INSTANCE_FILENAME},
25 vm::{self, LoginAction, VmInput},
28const SSH_KEY_NAME: &str = "ssh_key";
29pub(crate) const SERIAL_LOG_NAME: &str = "serial.log";
30pub(crate) const 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>,
50 pub(crate) fn ssh_user_display(&self) -> String {
51 if self.ssh_user.trim().is_empty() {
52 DEFAULT_SSH_USER.to_string()
59fn default_ssh_user() -> String {
60 DEFAULT_SSH_USER.to_string()
63pub fn run_with_ssh(manager_conn: UnixStream) -> Result<(), Box<dyn std::error::Error>> {
64 let project_root = env::current_dir()?;
65 tracing::info!(root = %project_root.display(), "starting ssh session");
66 let instance_dir = ensure_instance_dir(&project_root)?;
67 tracing::debug!(instance_dir = %instance_dir.display(), "instance dir ready");
68 let (ssh_key, _ssh_pub) = ensure_ssh_keypair(&instance_dir)?;
70 let config = load_or_create_instance_config(&instance_dir)?;
71 let ssh_user = config.ssh_user.clone();
72 tracing::debug!(ssh_user = %ssh_user, "loaded instance config");
74 let _manager_conn = manager_conn;
75 tracing::debug!("waiting for vm ipv4");
76 wait_for_vm_ipv4(&instance_dir, Duration::from_secs(120))?;
78 let ip = load_or_create_instance_config(&instance_dir)?
80 .ok_or("VM IPv4 not available")?;
81 tracing::info!(ip = %ip, "vm ipv4 ready");
83 run_ssh_session(ssh_key, ssh_user, ip)
86pub fn ensure_instance_dir(project_root: &Path) -> Result<PathBuf, io::Error> {
87 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
88 fs::create_dir_all(&instance_dir)?;
92pub(crate) fn ensure_ssh_keypair(
94) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
95 let private_key = instance_dir.join(SSH_KEY_NAME);
96 let public_key = instance_dir.join(format!("{SSH_KEY_NAME}.pub"));
98 if private_key.exists() && public_key.exists() {
99 return Ok((private_key, public_key));
102 if private_key.exists() {
103 let _ = fs::remove_file(&private_key);
105 if public_key.exists() {
106 let _ = fs::remove_file(&public_key);
109 let status = Command::new("ssh-keygen")
116 private_key.to_str().ok_or("ssh key path not utf-8")?,
120 .stdin(Stdio::null())
121 .stdout(Stdio::null())
122 .stderr(Stdio::inherit())
125 if !status.success() {
126 return Err("ssh-keygen failed".into());
129 fs::set_permissions(&private_key, fs::Permissions::from_mode(0o600))?;
130 fs::set_permissions(&public_key, fs::Permissions::from_mode(0o644))?;
132 Ok((private_key, public_key))
135pub(crate) fn load_or_create_instance_config(
137) -> Result<InstanceConfig, Box<dyn std::error::Error>> {
138 let config_path = instance_dir.join(INSTANCE_FILENAME);
139 let mut config = if config_path.exists() {
140 let raw = fs::read_to_string(&config_path)?;
141 toml::from_str::<InstanceConfig>(&raw)?
145 ssh_user: default_ssh_user(),
146 sudo_password: String::new(),
152 let mut changed = false;
153 if config.ssh_user.trim().is_empty() {
154 config.ssh_user = default_ssh_user();
158 if config.id.trim().is_empty() {
159 config.id = Uuid::now_v7().to_string();
163 if config.sudo_password.trim().is_empty() {
164 config.sudo_password = generate_password();
168 if !config_path.exists() || changed {
169 write_instance_config(&config_path, &config)?;
175fn read_instance_config(
177) -> Result<Option<InstanceConfig>, Box<dyn std::error::Error>> {
178 let config_path = instance_dir.join(INSTANCE_FILENAME);
179 if !config_path.exists() {
182 let raw = fs::read_to_string(&config_path)?;
183 let config = toml::from_str::<InstanceConfig>(&raw)?;
187pub fn read_instance_vm_ip(
189) -> Result<Option<String>, Box<dyn std::error::Error>> {
190 let config = read_instance_config(instance_dir)?;
191 Ok(config.and_then(|cfg| cfg.vm_ipv4))
194pub fn read_instance_ssh_user(
196) -> Result<Option<String>, Box<dyn std::error::Error>> {
197 let config = read_instance_config(instance_dir)?;
199 .map(|cfg| cfg.ssh_user)
200 .filter(|user| !user.trim().is_empty()))
203pub fn touch_last_active(instance_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
204 let mut config = load_or_create_instance_config(instance_dir)?;
205 let now = OffsetDateTime::now_utc().format(&Rfc3339)?;
206 config.last_active = Some(now);
207 write_instance_config(&instance_dir.join(INSTANCE_FILENAME), &config)?;
211pub(crate) fn write_instance_config(
213 config: &InstanceConfig,
214) -> Result<(), Box<dyn std::error::Error>> {
215 let data = toml::to_string_pretty(config)?;
216 fs::write(path, data)?;
217 fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
221fn generate_password() -> String {
222 Uuid::now_v7().simple().to_string()
225pub(crate) fn extract_ipv4(line: &str) -> Option<String> {
226 let mut current = String::new();
227 let mut best: Option<String> = None;
229 for ch in line.chars().chain(std::iter::once(' ')) {
230 if ch.is_ascii_digit() || ch == '.' {
232 } else if !current.is_empty() {
233 if is_ipv4_candidate(¤t) {
234 best = Some(current.clone());
247) -> Result<(), Box<dyn std::error::Error>> {
248 let start = Instant::now();
250 let config = load_or_create_instance_config(instance_dir)?;
251 if config.vm_ipv4.is_some() {
254 if start.elapsed() > timeout {
255 return Err("Timed out waiting for VM IPv4".into());
257 if start.elapsed().as_secs() % 5 == 0 {
258 tracing::debug!("still waiting for vm ipv4");
260 thread::sleep(Duration::from_millis(200));
268) -> Result<(), Box<dyn std::error::Error>> {
269 let mut attempts = 0usize;
272 if !ssh_port_open(&ip) {
273 tracing::debug!(attempts, "ssh port not open yet");
275 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
277 if attempts >= SSH_CONNECT_RETRIES {
279 format!("ssh port not ready after {SSH_CONNECT_RETRIES} attempts").into(),
282 thread::sleep(Duration::from_millis(SSH_CONNECT_DELAY_MS));
287 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
289 tracing::info!(attempts, user = %ssh_user, ip = %ip, "starting ssh");
290 let status = Command::new("ssh")
293 ssh_key.to_str().unwrap_or(".vibebox/ssh_key"),
295 "IdentitiesOnly=yes",
297 "StrictHostKeyChecking=no",
299 "UserKnownHostsFile=/dev/null",
301 "GlobalKnownHostsFile=/dev/null",
303 "PasswordAuthentication=no",
311 .env_remove("LC_CTYPE")
312 .env_remove("LC_ALL")
314 .arg(format!("{ssh_user}@{ip}"))
315 .stdin(Stdio::inherit())
316 .stdout(Stdio::inherit())
317 .stderr(Stdio::inherit())
321 Ok(status) if status.success() => {
322 eprintln!("[vibebox] ssh exited with status: {status}");
325 Ok(status) if status.code() == Some(255) => {
326 eprintln!("[vibebox] ssh connection failed: {status}");
327 if attempts >= SSH_CONNECT_RETRIES {
328 return Err(format!("ssh failed after {SSH_CONNECT_RETRIES} attempts").into());
330 thread::sleep(Duration::from_millis(500));
333 eprintln!("[vibebox] ssh exited with status: {status}");
337 return Err(format!("failed to start ssh: {err}").into());
345fn is_ipv4_candidate(candidate: &str) -> bool {
346 let parts: Vec<&str> = candidate.split('.').collect();
347 if parts.len() != 4 {
351 if part.is_empty() || part.len() > 3 {
354 if part.parse::<u8>().is_err() {
361fn ssh_port_open(ip: &str) -> bool {
362 let addr: SocketAddr = match format!("{ip}:22").parse() {
364 Err(_) => return false,
366 TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(500)).is_ok()
369pub(crate) fn build_ssh_login_actions(
370 config: &Arc<Mutex<InstanceConfig>>,
374 home_links_script: &str,
375) -> Vec<LoginAction> {
376 let config_guard = config.lock().expect("config mutex poisoned");
377 let ssh_user = config_guard.ssh_user.clone();
378 let sudo_password = config_guard.sudo_password.clone();
381 let key_path = format!("{guest_dir}/{key_name}.pub");
383 let setup_script = SSH_SETUP_SCRIPT
384 .replace("__SSH_USER__", &ssh_user)
385 .replace("__SUDO_PASSWORD__", &sudo_password)
386 .replace("__PROJECT_NAME__", project_name)
387 .replace("__KEY_PATH__", &key_path)
388 .replace("__VIBEBOX_SHELL_SCRIPT__", &commands::render_shell_script())
389 .replace("__VIBEBOX_HOME_LINKS__", home_links_script);
390 let setup = vm::script_command_from_content("ssh_setup", &setup_script)
391 .expect("ssh setup script contained invalid marker");
393 vec![LoginAction::Send(setup)]
397 app: Arc<Mutex<AppState>>,
398 config: Arc<Mutex<InstanceConfig>>,
399 instance_dir: PathBuf,
401 output_monitor: Arc<vm::OutputMonitor>,
402 vm_output_fd: OwnedFd,
403 vm_input_fd: OwnedFd,
405 let io_control = vm::IoControl::new();
407 let log_path = instance_dir.join(SERIAL_LOG_NAME);
408 let log_file = fs::OpenOptions::new()
414 .map(|file| Arc::new(Mutex::new(file)));
416 let ssh_connected = Arc::new(AtomicBool::new(false));
417 let ssh_started = Arc::new(AtomicBool::new(false));
418 let ssh_ready = Arc::new(AtomicBool::new(false));
419 let input_tx_holder: Arc<Mutex<Option<Sender<VmInput>>>> = Arc::new(Mutex::new(None));
421 let instance_path = instance_dir.join(INSTANCE_FILENAME);
422 let config_for_output = config.clone();
423 let log_for_output = log_file.clone();
424 let ssh_connected_for_output = ssh_connected.clone();
425 let ssh_ready_for_output = ssh_ready.clone();
427 let mut line_buf = String::new();
429 let handlers = commands::build_handlers(app.clone(), io_control.clone());
430 let on_line = move |line: &str| handlers.handle(line);
432 let on_output = move |bytes: &[u8]| {
433 if ssh_connected_for_output.load(Ordering::SeqCst) {
434 if let Some(log) = &log_for_output {
435 if let Ok(mut file) = log.lock() {
436 let _ = file.write_all(bytes);
441 let text = String::from_utf8_lossy(bytes);
442 line_buf.push_str(&text);
444 while let Some(pos) = line_buf.find('\n') {
445 let mut line = line_buf[..pos].to_string();
446 if line.ends_with('\r') {
449 line_buf.drain(..=pos);
451 let cleaned = line.trim_start_matches(|c: char| c == '\r' || c == ' ');
453 if let Some(pos) = cleaned.find("VIBEBOX_IPV4=") {
454 let ip_raw = &cleaned[(pos + "VIBEBOX_IPV4=".len())..];
455 let ip = extract_ipv4(ip_raw).unwrap_or_default();
457 if let Ok(mut cfg) = config_for_output.lock() {
458 if cfg.vm_ipv4.as_deref() != Some(ip.as_str()) {
459 cfg.vm_ipv4 = Some(ip.clone());
460 let _ = write_instance_config(&instance_path, &cfg);
461 eprintln!("[vibebox] detected vm IPv4: {ip}");
467 if cleaned.contains("VIBEBOX_SSH_READY") {
468 ssh_ready_for_output.store(true, Ordering::SeqCst);
469 eprintln!("[vibebox] sshd ready");
474 let io_ctx = vm::spawn_vm_io_with_hooks(
483 *input_tx_holder.lock().unwrap() = Some(io_ctx.input_tx.clone());
485 let ssh_ready_for_thread = ssh_ready.clone();
486 let ssh_started_for_thread = ssh_started.clone();
487 let ssh_connected_for_thread = ssh_connected.clone();
488 let io_control_for_thread = io_control.clone();
489 let ssh_key_for_thread = ssh_key.clone();
490 let config_for_thread = config.clone();
491 let input_tx_holder_for_thread = input_tx_holder.clone();
493 thread::spawn(move || {
495 if ssh_started_for_thread.load(Ordering::SeqCst) {
498 if !ssh_ready_for_thread.load(Ordering::SeqCst) {
499 thread::sleep(std::time::Duration::from_millis(200));
503 let ip = config_for_thread
506 .and_then(|cfg| cfg.vm_ipv4.clone());
507 let ssh_user = config_for_thread
509 .map(|cfg| cfg.ssh_user.clone())
510 .unwrap_or_else(|_| DEFAULT_SSH_USER.to_string());
512 if let Some(ip) = ip {
513 if ssh_started_for_thread
514 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
520 eprintln!("[vibebox] starting ssh to {ssh_user}@{ip}");
521 io_control_for_thread.request_terminal_restore();
522 io_control_for_thread.set_forward_output(false);
523 io_control_for_thread.set_forward_input(false);
524 ssh_connected_for_thread.store(true, Ordering::SeqCst);
526 let mut attempts = 0usize;
529 if !ssh_port_open(&ip) {
531 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
533 if attempts >= SSH_CONNECT_RETRIES {
534 ssh_connected_for_thread.store(false, Ordering::SeqCst);
536 "[vibebox] ssh port not ready after {SSH_CONNECT_RETRIES} attempts"
540 thread::sleep(std::time::Duration::from_millis(SSH_CONNECT_DELAY_MS));
545 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
547 let status = Command::new("ssh")
550 ssh_key_for_thread.to_str().unwrap_or(".vibebox/ssh_key"),
552 "IdentitiesOnly=yes",
554 "StrictHostKeyChecking=no",
556 "UserKnownHostsFile=/dev/null",
558 "GlobalKnownHostsFile=/dev/null",
560 "PasswordAuthentication=no",
568 .env_remove("LC_CTYPE")
569 .env_remove("LC_ALL")
570 // .env_remove("LANG")
571 .arg(format!("{ssh_user}@{ip}"))
572 .stdin(Stdio::inherit())
573 .stdout(Stdio::inherit())
574 .stderr(Stdio::inherit())
578 Ok(status) if status.success() => {
579 ssh_connected_for_thread.store(false, Ordering::SeqCst);
580 eprintln!("[vibebox] ssh exited with status: {status}");
581 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
582 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
586 Ok(status) if status.code() == Some(255) => {
587 eprintln!("[vibebox] ssh connection failed: {status}");
588 if attempts >= SSH_CONNECT_RETRIES {
589 ssh_connected_for_thread.store(false, Ordering::SeqCst);
591 "[vibebox] ssh failed after {SSH_CONNECT_RETRIES} attempts"
595 thread::sleep(std::time::Duration::from_millis(500));
599 ssh_connected_for_thread.store(false, Ordering::SeqCst);
600 eprintln!("[vibebox] ssh exited with status: {status}");
601 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
602 let _ = tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
607 ssh_connected_for_thread.store(false, Ordering::SeqCst);
608 eprintln!("[vibebox] failed to start ssh: {err}");
616 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