fix: the open-in-hx key resumes the session's hx conversation instead of starting a new one
build / version (push) Successful in 18s
build / build (aarch64-apple-darwin) (push) Successful in 2m42s
build / build (x86_64-unknown-linux-musl) (push) Successful in 5m40s
build / release (push) Successful in 28s

hx --session takes a file path, not orch's session id. Resolve the file
hx serve wrote (acp-<id>.jsonl under the sessions dir, following
HX_SESSIONS_DIR and the sessions_dir/sessions_host config keys) with the
session's own profile, and report a missing file instead of starting fresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Johannes KresnerandClaude Opus 5.5 committed 2026-11-17 16:50:53 +01:00
1 parent c59924fc0f
commit 9f6bd32d01
2 files changed
+177 -4

No files matched your search

+151 -1
View File
@@ -7,13 +7,94 @@ use crate::profile::Profile;
use crate::run::hx_env; use crate::run::hx_env;
use anyhow::{Context, Result, anyhow, bail}; use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::collections::HashMap;
use std::io::{BufRead, Write}; use std::io::{BufRead, Write};
use std::os::unix::process::CommandExt; use std::os::unix::process::CommandExt;
use std::path::Path; use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio}; use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc; use std::sync::mpsc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
/// The conversation file `hx serve --cwd <worktree> --session <id>` writes, for `hx --session <file>` 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<String, String> = 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: `<root>/<[host/]cwd slug>/acp-<id>.jsonl`. The root is `$HX_SESSIONS_DIR`, else
/// `sessions_dir` from `$HX_HOME/config.toml` or `<cwd>/.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<String, String>,
cwd: &Path,
id: &str,
hostname: impl Fn() -> Option<String>,
) -> 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::<toml::Table>().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::<Vec<_>>()
.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. /// Receives what hx reports while a step runs.
pub trait Sink { pub trait Sink {
/// Notifications: `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`, `session/update`. /// 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(); let _ = self.child.wait();
} }
} }
#[cfg(test)]
mod tests {
use super::*;
fn env(kv: &[(&str, &str)]) -> HashMap<String, String> {
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();
}
}
+26 -3
View File
@@ -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. /// Opens hx on the session's conversation in the worktree: the TUI steps aside for the time hx runs.
fn open_in_hx( fn open_in_hx(
term: &mut ratatui::DefaultTerminal, term: &mut ratatui::DefaultTerminal,
db: Option<&Db>,
worktree: &str, worktree: &str,
session: &str, session: &str,
) -> Option<String> { ) -> Option<String> {
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 parts = hx.split_whitespace();
let mut cmd = std::process::Command::new(parts.next()?); let mut cmd = std::process::Command::new(parts.next()?);
cmd.args(parts) cmd.args(parts)
.args(["--session", session]) .arg("--session")
.arg(&file)
.current_dir(worktree); .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(); ratatui::restore();
let res = cmd.status(); let res = cmd.status();
*term = ratatui::init(); *term = ratatui::init();
@@ -1082,7 +1104,8 @@ fn on_key(
} }
KeyCode::Char('o') => { KeyCode::Char('o') => {
if let Some(d) = &app.detail 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 { app.pager = Some(Pager {
title: "open worktree".into(), title: "open worktree".into(),