diff --git a/src/acp.rs b/src/acp.rs index 3e0075f..f833780 100644 --- a/src/acp.rs +++ b/src/acp.rs @@ -7,13 +7,94 @@ use crate::profile::Profile; use crate::run::hx_env; use anyhow::{Context, Result, anyhow, bail}; use serde_json::{Value, json}; +use std::collections::HashMap; use std::io::{BufRead, Write}; use std::os::unix::process::CommandExt; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, Command, Stdio}; use std::sync::mpsc; use std::time::{Duration, Instant}; +/// The conversation file `hx serve --cwd --session ` writes, for `hx --session ` to +/// resume. Resolved from the environment the agent ran with (`hx_env` plus the profile's `HOME`), not orch's own. +pub fn session_file(p: &Profile, worktree: &Path, id: &str) -> PathBuf { + let mut env: HashMap = hx_env(std::env::vars(), p).into_iter().collect(); + if let Some(h) = &p.home { + env.insert("HOME".into(), h.to_string_lossy().into()); + } + // hx runs in the canonical cwd (`/private/tmp`, not `/tmp`), so the slug comes from that + let cwd = worktree + .canonicalize() + .unwrap_or_else(|_| worktree.to_path_buf()); + let hostname = || std::fs::read_to_string("/etc/hostname").ok(); + hx_session_file(&env, &cwd, id, hostname) +} + +/// hx's own path rule: `/<[host/]cwd slug>/acp-.jsonl`. The root is `$HX_SESSIONS_DIR`, else +/// `sessions_dir` from `$HX_HOME/config.toml` or `/.hx/config.toml` (the latter wins, `~` is `$HOME`), +/// else `$HX_HOME/sessions`; `sessions_host = true` puts the host name in front of the slug. +fn hx_session_file( + env: &HashMap, + cwd: &Path, + id: &str, + hostname: impl Fn() -> Option, +) -> PathBuf { + let var = |k: &str| env.get(k).filter(|v| !v.is_empty()); + let home = PathBuf::from(var("HOME").map_or("", String::as_str)); + let hx_home = var("HX_HOME").map_or_else(|| home.join(".hx"), PathBuf::from); + let (mut dir, mut host) = (None, None); + for f in [hx_home.join("config.toml"), cwd.join(".hx/config.toml")] { + let Some(t) = std::fs::read_to_string(f) + .ok() + .and_then(|s| s.parse::().ok()) + else { + continue; + }; + if let Some(d) = t.get("sessions_dir").and_then(|v| v.as_str()) { + dir = Some(d.to_string()); + } + if let Some(h) = t.get("sessions_host").and_then(toml::Value::as_bool) { + host = Some(h); + } + } + let root = match var("HX_SESSIONS_DIR").cloned().or(dir) { + Some(s) if !s.is_empty() => match s.strip_prefix('~') { + Some(r) => home.join(r.trim_start_matches('/')), + None => s.into(), + }, + _ => hx_home.join("sessions"), + }; + let host = host.unwrap_or(false).then(|| { + ["HOSTNAME", "HOST", "COMPUTERNAME"] + .iter() + .find_map(|k| env.get(*k).cloned()) + .or_else(hostname) + .map_or("host".into(), |h| h.trim().to_string()) + }); + let cwd = cwd.to_string_lossy(); + let slug: String = host + .as_deref() + .into_iter() + .chain([cwd.trim_matches('/')]) + .collect::>() + .join("/") + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect(); + let id: String = id + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || "-_.".contains(c) { + c + } else { + '_' + } + }) + .collect(); + root.join(slug.trim_matches('-')) + .join(format!("acp-{id}.jsonl")) +} + /// Receives what hx reports while a step runs. pub trait Sink { /// Notifications: `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`, `session/update`. @@ -256,3 +337,72 @@ impl Drop for Acp { let _ = self.child.wait(); } } + +#[cfg(test)] +mod tests { + use super::*; + + fn env(kv: &[(&str, &str)]) -> HashMap { + kv.iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + } + + #[test] + fn session_file_defaults_to_hx_home_sessions() { + let e = env(&[("HOME", "/nonexistent/h")]); + let f = hx_session_file(&e, Path::new("/w/a.b/s1"), "s1", || None); + assert_eq!( + f, + Path::new("/nonexistent/h/.hx/sessions/w-a-b-s1/acp-s1.jsonl") + ); + } + + #[test] + fn session_file_follows_hx_config_and_env() { + let t = std::env::temp_dir().join(format!("orch-acp-cfg-{}", std::process::id())); + let (home, wt) = (t.join("h"), t.join("wt")); + std::fs::create_dir_all(home.join(".hx")).unwrap(); + std::fs::create_dir_all(wt.join(".hx")).unwrap(); + std::fs::write(home.join(".hx/config.toml"), "sessions_dir = \"~/cloud\"\n").unwrap(); + let e = env(&[("HOME", home.to_str().unwrap())]); + let slug = |p: &Path| -> String { + p.to_string_lossy() + .trim_matches('/') + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect() + }; + let f = hx_session_file(&e, &wt, "s1", || None); + assert_eq!(f, home.join("cloud").join(slug(&wt)).join("acp-s1.jsonl")); + + // the worktree's config wins, and sessions_host prefixes the host name + std::fs::write( + wt.join(".hx/config.toml"), + "sessions_dir = \"/sd\"\nsessions_host = true\n", + ) + .unwrap(); + let f = hx_session_file(&e, &wt, "s1", || Some("box\n".into())); + assert_eq!( + f, + Path::new("/sd") + .join(format!("box-{}", slug(&wt))) + .join("acp-s1.jsonl") + ); + + // HX_SESSIONS_DIR beats both config files + let e = env(&[ + ("HOME", home.to_str().unwrap()), + ("HX_SESSIONS_DIR", "/env"), + ("HOST", "h2"), + ]); + let f = hx_session_file(&e, &wt, "s1", || None); + assert_eq!( + f, + Path::new("/env") + .join(format!("h2-{}", slug(&wt))) + .join("acp-s1.jsonl") + ); + std::fs::remove_dir_all(&t).unwrap(); + } +} diff --git a/src/tui/mod.rs b/src/tui/mod.rs index 83c5205..f30714a 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -837,15 +837,37 @@ fn transcript(app: &App, id: &str) -> Pager { /// Opens hx on the session's conversation in the worktree: the TUI steps aside for the time hx runs. fn open_in_hx( term: &mut ratatui::DefaultTerminal, + db: Option<&Db>, worktree: &str, session: &str, ) -> Option { - let hx = crate::profile::Profile::load("default").map_or_else(|_| "hx".into(), |p| p.hx); + use crate::profile::Profile; + // the session's own profile: its home holds the conversation hx serve wrote + let p = db + .and_then(|db| db.options(session).ok()) + .and_then(|o| o.get("profile")?.as_str().map(PathBuf::from)) + .and_then(|path| Profile::load_path(&path).ok()) + .or_else(|| Profile::load(PROFILE).ok()); + let hx = p.as_ref().map_or_else(|| "hx".into(), |p| p.hx.clone()); + let file = match &p { + Some(p) => crate::acp::session_file(p, Path::new(worktree), session), + None => return Some(format!("could not load profile {PROFILE:?}")), + }; + if !file.exists() { + return Some(format!( + "no hx conversation for {session} at {}", + file.display() + )); + } let mut parts = hx.split_whitespace(); let mut cmd = std::process::Command::new(parts.next()?); cmd.args(parts) - .args(["--session", session]) + .arg("--session") + .arg(&file) .current_dir(worktree); + if let Some(h) = p.as_ref().and_then(|p| p.home.as_ref()) { + cmd.env("HOME", h).env_remove("HX_HOME"); + } ratatui::restore(); let res = cmd.status(); *term = ratatui::init(); @@ -1082,7 +1104,8 @@ fn on_key( } KeyCode::Char('o') => { if let Some(d) = &app.detail - && let Some(err) = open_in_hx(term, &d.worktree.clone(), &d.id.clone()) + && let Some(err) = + open_in_hx(term, app.db.as_ref(), &d.worktree.clone(), &d.id.clone()) { app.pager = Some(Pager { title: "open worktree".into(),