use super::hc_layout::{
terminal_addresses, terminal_layout, valid_id, DesktopLayout, DOCUMENT_NAME, SPACE_PREFIX,
};
use super::hc_shared_terminal::{publish_at, Placement};
use super::{
bindings, snapshot, Action, ActionResult, Layout, NewAgent, OpenedWorkspace, Pane, SessionInfo,
Snapshot, StartedAgent, Tab, Target, Workspace,
};
use crate::core::{
herdr::hc::{local_address, Core},
project_worktrees,
skill_store::SkillStore,
};
use anyhow::{bail, ensure, Context, Result};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::{
collections::{BTreeMap, HashMap, HashSet},
path::{Path, PathBuf},
};
const PREFIX: &str = "hc:";
const CHECKOUT: &str = "agenthub.checkout";
pub(super) fn checkout(path: &str) -> Option<PathBuf> {
let path = Path::new(path).canonicalize().ok()?;
if !path.is_dir() {
return None;
}
Some(
git2::Repository::discover(&path)
.ok()
.and_then(|repo| repo.workdir()?.canonicalize().ok())
.unwrap_or(path),
)
}
fn common_directory(repo: &git2::Repository) -> PathBuf {
if repo.is_worktree() {
if let Ok(relative) = std::fs::read_to_string(repo.path().join("commondir")) {
if let Ok(common) = repo.path().join(relative.trim()).canonicalize() {
return common;
}
}
}
repo.path()
.canonicalize()
.unwrap_or_else(|_| repo.path().to_owned())
}
fn workspace_id(path: &Path) -> String {
format!(
"{PREFIX}{}",
hex::encode(Sha256::digest(path.as_os_str().as_encoded_bytes()))
)
}
fn pane(row: &Value, directory: &Path) -> Option<Pane> {
let address = row["address"]
.as_str()
.filter(|address| local_address(address))?;
let identity = row["identity"]
.as_str()
.filter(|identity| !identity.is_empty())?;
let pane_id = format!("{PREFIX}{address}");
let status = &row["status"];
let app = status["app"].as_str().filter(|app| !app.is_empty());
let kind = match app {
Some("claude-code") => Some("claude"),
Some("opencode") => Some("opencode"),
other => other,
};
let status = match status["state"].as_str() {
Some("error") => "blocked",
Some(state @ ("working" | "idle" | "done" | "blocked")) => state,
_ => "unknown",
};
let revision = row["turn"].as_u64().unwrap_or_default();
let seen_turn = row["labels"]["herdr.seen"]
.as_str()
.and_then(|value| value.parse::<u64>().ok());
let display_status = match (status, seen_turn) {
("idle" | "done", Some(seen)) => {
Some(if revision > seen { "done" } else { "idle" }.to_owned())
}
_ => None,
};
Some(Pane {
tab_id: pane_id.clone(),
pane_id,
workspace_id: workspace_id(directory),
terminal_id: format!("{PREFIX}{identity}"),
cwd: Some(directory.to_string_lossy().into_owned()),
focused: true,
revision,
agent_status: status.to_owned(),
agent: kind.map(str::to_owned),
program: row["foreground"]["name"]
.as_str()
.filter(|name| !name.is_empty())
.map(str::to_owned),
name: [row["name"].as_str(), row["title"].as_str()]
.into_iter()
.flatten()
.find(|name| !name.trim().is_empty())
.map(str::to_owned),
title: row["title"]
.as_str()
.filter(|title| !title.is_empty())
.map(str::to_owned),
display_status,
desktop_owned: row["labels"][super::super::hc::interactive::OWNER]
.as_str()
.is_some(),
status_ms: row["status_ms"].as_u64(),
agent_session: app.map(|app| json!({ "app": app, "identity": identity })),
})
}
fn directory(row: &Value) -> Option<PathBuf> {
row["labels"][CHECKOUT]
.as_str()
.and_then(|path| Path::new(path).canonicalize().ok())
.filter(|path| path.is_dir())
.or_else(|| row["cwd"].as_str().and_then(checkout))
}
pub(super) fn standalone_workspace_id(row: &Value) -> Option<String> {
directory(row).map(|path| workspace_id(&path))
}
pub(super) fn desktop_directory(row: &Value) -> Option<PathBuf> {
row["foreground"]["cwd"]
.as_str()
.and_then(checkout)
.or_else(|| row["cwd"].as_str().and_then(checkout))
.or_else(|| directory(row))
}
fn workspace_row(
id: String,
directory: &Path,
label: Option<&str>,
active_tab_id: String,
) -> Workspace {
let worktree = git2::Repository::discover(directory).ok().map(|repo| {
json!({
"checkout_path": directory,
"repo_key": common_directory(&repo),
"is_linked_worktree": repo.is_worktree(),
})
});
Workspace {
workspace_id: id,
label: label
.filter(|label| !label.is_empty())
.or_else(|| directory.file_name().and_then(|name| name.to_str()))
.unwrap_or("Workspace")
.to_owned(),
active_tab_id,
directory: Some(directory.to_string_lossy().into_owned()),
worktree,
branch: None,
head: None,
detached: false,
repository_icon: None,
ahead: None,
behind: None,
}
}
fn local_folder(path: &str) -> Option<PathBuf> {
let path = Path::new(path);
path.is_absolute()
.then(|| path.canonicalize().ok())
.flatten()
.filter(|path| path.is_dir())
}
fn desktop_space_name(name: &str, folder: &Path, home: Option<&Path>) -> String {
if !name.is_empty() {
return name.to_owned();
}
if home.is_some_and(|home| {
if cfg!(windows) {
folder
.to_string_lossy()
.eq_ignore_ascii_case(&home.to_string_lossy())
} else {
folder == home
}
}) {
return "~".to_owned();
}
folder
.file_name()
.unwrap_or(folder.as_os_str())
.to_string_lossy()
.into_owned()
}
fn desktop_tab_title(name: &str, lead: Option<&Value>) -> String {
let agent = lead.and_then(|row| row["status"]["app"].as_str());
let executable = lead.and_then(|row| row["foreground"]["name"].as_str());
let key = agent.or(executable).unwrap_or_default();
let program = match key {
"" => "Terminal".to_owned(),
"claude" | "claude-code" => "Claude Code".to_owned(),
"opencode" => "OpenCode".to_owned(),
"node" => "Node".to_owned(),
_ => {
let mut chars = key.chars();
chars
.next()
.into_iter()
.flat_map(char::to_uppercase)
.chain(chars)
.collect()
}
};
let base = if name.is_empty() {
program.as_str()
} else {
name
};
if let Some(row) = lead.filter(|_| agent.is_some() && (name.is_empty() || name == program)) {
let title = row["title"].as_str().unwrap_or_default().trim();
let title = title.trim_start_matches(|c: char| {
c.is_whitespace() || matches!(c, '✦' | '✧' | '✳' | '✶' | '✻' | '✽' | '·' | '\u{2800}'..='\u{28ff}' | '\u{25d0}'..='\u{25d3}')
});
if !title.is_empty()
&& !title.starts_with(['~', '/'])
&& !title
.as_bytes()
.get(1..3)
.is_some_and(|prefix| prefix == b":\\")
&& !title.contains('@')
&& !title.eq_ignore_ascii_case(key)
&& title != program
&& row["address"].as_str() != Some(title)
{
return title.to_owned();
}
}
base.to_owned()
}
fn project_snapshot(result: Value, layout: DesktopLayout) -> Result<Snapshot> {
let rows = result["terminals"]
.as_array()
.context("Herdr Core did not return terminals")?;
let live: HashMap<_, _> = rows
.iter()
.filter(|row| row["state"] == "live")
.filter_map(|row| {
row["address"]
.as_str()
.filter(|id| local_address(id))
.map(|id| (id, row))
})
.collect();
let mut workspaces = Vec::new();
let mut panes = Vec::new();
let mut tabs = Vec::new();
let mut placed = HashSet::new();
let mut space_ids = HashSet::new();
let mut folders = HashMap::new();
let home = dirs::home_dir().and_then(|path| path.canonicalize().ok());
for space in layout.spaces {
if !valid_id(&space.id) || !space_ids.insert(space.id.clone()) {
continue;
}
let id = format!("{SPACE_PREFIX}{}", space.id);
let mut folder = local_folder(&space.folder);
let mut first_tab = None;
let mut first_checkout = None;
let mut tab_ids = HashSet::new();
for doc_tab in space.tabs {
if !valid_id(&doc_tab.id) || !tab_ids.insert(doc_tab.id.clone()) {
continue;
}
let tab_id = format!("hc:tab/{}/{}", space.id, doc_tab.id);
let mut addresses = Vec::new();
terminal_addresses(&doc_tab.root, &mut addresses);
let mut lead = None;
for address in addresses {
let Some(row) = live.get(address.as_str()) else {
continue;
};
let Some(directory) = desktop_directory(row).or_else(|| folder.clone()) else {
continue;
};
let Some(mut pane) = pane(row, &directory) else {
continue;
};
if !placed.insert(pane.pane_id.clone()) {
continue;
}
first_checkout.get_or_insert_with(|| directory.clone());
folder.get_or_insert(directory);
first_tab.get_or_insert_with(|| tab_id.clone());
pane.workspace_id.clone_from(&id);
pane.tab_id.clone_from(&tab_id);
if lead.is_none()
|| (pane.agent.is_some()
&& lead.is_some_and(|row: &Value| row["status"]["app"].is_null()))
{
lead = Some(*row);
}
panes.push(pane);
}
tabs.push(Tab {
tab_id,
workspace_id: id.clone(),
label: desktop_tab_title(&doc_tab.name, lead),
pane_layout: terminal_layout(&doc_tab.root, 0),
});
}
if let Some(checkout) = first_checkout.or(folder) {
folders.insert(id.clone(), checkout.to_string_lossy().into_owned());
workspaces.push(workspace_row(
id,
&checkout,
Some(&desktop_space_name(&space.name, &checkout, home.as_deref())),
first_tab.unwrap_or_default(),
));
}
}
let mut unplaced = BTreeMap::new();
for row in rows.iter().filter(|row| row["state"] == "live") {
let Some(directory) = directory(row) else {
continue;
};
let Some(pane) = pane(row, &directory) else {
continue;
};
if !placed.insert(pane.pane_id.clone()) {
continue;
}
unplaced
.entry(pane.workspace_id.clone())
.or_insert_with(|| {
workspace_row(
pane.workspace_id.clone(),
&directory,
None,
pane.tab_id.clone(),
)
});
tabs.push(Tab {
tab_id: pane.tab_id.clone(),
workspace_id: pane.workspace_id.clone(),
label: pane.name.clone().unwrap_or_else(|| "Terminal".to_owned()),
pane_layout: None,
});
panes.push(pane);
}
workspaces.extend(unplaced.into_values());
let mut snapshot = Snapshot {
version: "herdr-core".to_owned(),
workspaces,
tabs,
layouts: Vec::<Layout>::new(),
agents: panes
.iter()
.filter(|pane| pane.agent.is_some())
.cloned()
.collect(),
panes,
};
snapshot::enrich_workspaces(&mut snapshot);
for workspace in &mut snapshot.workspaces {
if let Some(folder) = folders.remove(&workspace.workspace_id) {
workspace.directory = Some(folder);
}
}
Ok(snapshot)
}
impl Core {
fn require_session(&self, session: &str) -> Result<()> {
ensure!(
session == self.session_key(),
"Select the matching Herdr Core session"
);
Ok(())
}
pub(super) fn session_info(&self) -> Result<Vec<SessionInfo>> {
let status = self.status()?;
Ok(vec![SessionInfo {
name: self.session_key(),
running: status["pid"].as_u64().is_some(),
default: self.session_key() == super::super::hc::sessions::DEFAULT,
backend: Some("core".into()),
label: None,
socket_path: None,
}])
}
pub(super) fn prepare_ui(&self) -> Result<String> {
self.call("server.status", json!({}))?;
Ok(self.session_key())
}
pub(super) fn snapshot(&self, session: &str) -> Result<Snapshot> {
self.require_session(session)?;
let terminals = self.call("terminal.list", json!({}))?;
project_snapshot(terminals, self.desktop_layout()?)
}
fn desktop_layout(&self) -> Result<DesktopLayout> {
let document = self.call("doc.get", json!({"name": DOCUMENT_NAME}))?;
match document.get("value").filter(|value| !value.is_null()) {
Some(value) => serde_json::from_value(value.clone())
.context("Unsupported Herdr App workspace layout"),
None => Ok(DesktopLayout::default()),
}
}
pub(super) fn open(
&self,
store: &SkillStore,
session: &str,
workspace: &str,
requested: Option<&str>,
) -> Result<OpenedWorkspace> {
self.require_session(session)?;
super::hc_migration::restore_tabs(self, workspace)?;
let snapshot = self.snapshot(session)?;
let selected = snapshot
.panes
.iter()
.find(|pane| {
pane.workspace_id == workspace && requested.map_or(true, |id| id == pane.pane_id)
})
.context("Herdr Core terminal no longer exists; refresh the sidebar")?;
let directory = Path::new(
selected
.cwd
.as_deref()
.context("Terminal directory is unavailable")?,
);
Ok(OpenedWorkspace {
project_id: bindings::resolve_project(store, directory)?,
path: directory.to_string_lossy().into_owned(),
target: Target::from_pane(session, selected),
})
}
pub(super) fn ensure(
&self,
store: &SkillStore,
session: &str,
project_id: &str,
path: Option<&str>,
) -> Result<OpenedWorkspace> {
let mut snapshot = self.snapshot(session)?;
let directory = project_worktrees::directory(store, project_id, path)?;
let shared = snapshot.workspaces.iter().find(|workspace| {
workspace.workspace_id.starts_with(SPACE_PREFIX)
&& workspace
.directory
.as_deref()
.is_some_and(|path| Path::new(path) == directory)
});
if let Some(workspace) = shared {
let restored = super::hc_migration::restore_tabs(self, &workspace.workspace_id)?;
if restored
|| !snapshot
.panes
.iter()
.any(|pane| pane.workspace_id == workspace.workspace_id)
{
snapshot = self.snapshot(session)?;
}
}
let target = match snapshot.panes.iter().find(|pane| {
pane.cwd
.as_deref()
.is_some_and(|path| Path::new(path) == directory)
}) {
Some(pane) => Target::from_pane(session, pane),
None => self.shell(&directory)?,
};
Ok(OpenedWorkspace {
project_id: project_id.to_owned(),
path: directory.to_string_lossy().into_owned(),
target,
})
}
fn shell(&self, directory: &Path) -> Result<Target> {
self.launch(directory, &[], None, json!({}))
}
fn launch(
&self,
directory: &Path,
argv: &[String],
name: Option<&str>,
env: Value,
) -> Result<Target> {
self.launch_at(directory, argv, name, env, Placement::Checkout)
}
fn launch_at(
&self,
directory: &Path,
argv: &[String],
name: Option<&str>,
env: Value,
placement: Placement<'_>,
) -> Result<Target> {
let address = self.run(
directory,
argv,
name,
json!({(CHECKOUT): directory, "herdr.seen": "0"}),
match env {
Value::Object(mut env) => {
env.entry("TERM_PROGRAM").or_insert_with(|| json!("herdr"));
Value::Object(env)
}
_ => json!({"TERM_PROGRAM": "herdr"}),
},
)?;
let row = self.call("terminal.get", json!({"terminal": address}))?;
let mut pane = pane(&row, directory).context(
"Cannot identify the created Herdr Core terminal; inspect it before retrying",
)?;
let (placement, _) = publish_at(self, directory, &address, name, placement, |candidate| {
candidate["identity"] == row["identity"]
})
.context("The Core terminal was started; check its placement before retrying")?;
pane.workspace_id = placement.workspace_id();
Ok(Target::from_pane(&self.session_key(), &pane))
}
fn verify(&self, target: &Target) -> Result<(String, PathBuf, Pane)> {
self.require_session(&target.session)?;
let address = target
.pane_id
.strip_prefix(PREFIX)
.filter(|address| local_address(address))
.context("This terminal belongs to the previous Herdr backend")?;
let row = self.call("terminal.get", json!({"terminal": address}))?;
let directory = if target.workspace_id.starts_with(SPACE_PREFIX) {
desktop_directory(&row)
} else {
directory(&row)
}
.context("Terminal directory is unavailable")?;
let pane = pane(&row, &directory).context("Herdr Core terminal identity unavailable")?;
ensure!(
row["state"] == "live"
&& pane.terminal_id == target.terminal_id
&& pane.pane_id == target.pane_id,
"Herdr Core terminal changed; refresh before retrying"
);
let same_workspace = if target.workspace_id.starts_with(SPACE_PREFIX) {
self.desktop_layout()?
.contains_terminal(&target.workspace_id, address)
} else {
pane.workspace_id == target.workspace_id
};
ensure!(
same_workspace,
"Herdr Core terminal moved; refresh before retrying"
);
Ok((address.to_owned(), directory, pane))
}
pub(super) fn attach_target(
&self,
store: &SkillStore,
project: &str,
path: &str,
target: &Target,
) -> Result<portable_pty::CommandBuilder> {
let expected = project_worktrees::directory(store, project, Some(path))?;
let (address, actual, _) = self.verify(target)?;
ensure!(
expected == actual,
"Terminal no longer belongs to the selected checkout"
);
self.attach(&address)
}
pub(super) fn action(
&self,
target: &Target,
action: Action,
text: Option<&str>,
) -> Result<ActionResult> {
let (address, directory, pane) = self.verify(target)?;
let mut output = None;
let mut next = None;
match action {
Action::Read => {
let value = self.call("terminal.read", json!({"terminal": address, "lines": 0}))?;
output = Some(
value["text"]
.as_str()
.context("Herdr Core did not return terminal output")?
.to_owned(),
);
}
Action::Prompt => {
let text = text
.filter(|text| !text.trim().is_empty() && text.len() <= 32 * 1024)
.context("Enter a task of up to 32 KiB")?;
ensure!(pane.agent_session.is_some() && pane.agent_session == target.agent_session && pane.revision == target.revision
&& matches!(pane.agent_status.as_str(), "idle" | "done"),
"Agent is not idle or its identity changed; inspect the terminal before sending");
self.call(
"terminal.send",
json!({"terminal": address, "text": text, "if": "idle", "wait": false}),
)?;
}
Action::Interrupt => {
ensure!(
pane.agent_session.is_some()
&& pane.agent_session == target.agent_session
&& pane.revision == target.revision
&& pane.agent_status == "working",
"Agent is no longer working or its identity changed"
);
self.call(
"terminal.interrupt",
json!({"terminal": address, "timeout": 5}),
)?;
}
Action::Close => {
self.stop_terminal(&address)?;
if target.workspace_id.starts_with(SPACE_PREFIX) {
super::hc_shared_terminal::remove_stopped_terminal(
self,
&target.workspace_id,
&address,
)?;
}
}
Action::RenameTab => {
super::hc_shared_terminal::rename_tab(
self,
&target.workspace_id,
&address,
text.context("A tab name is required")?,
)?;
}
Action::NewTab | Action::SplitRight | Action::SplitDown => {
let workspace = target.workspace_id.as_str();
let placement = if !workspace.starts_with(SPACE_PREFIX) {
Placement::Checkout
} else if matches!(action, Action::NewTab) {
Placement::After {
workspace,
terminal: &address,
}
} else {
Placement::Split {
workspace,
terminal: &address,
axis: if matches!(action, Action::SplitRight) {
"row"
} else {
"column"
},
}
};
next = Some(self.launch_at(&directory, &[], None, json!({}), placement)?)
}
Action::Zoom => bail!("Zoom is controlled by the terminal layout"),
}
Ok(ActionResult {
output,
target: next,
})
}
pub(super) fn start_agent(
&self,
target: &Target,
input: NewAgent,
created: impl FnOnce(&Target) -> Result<()>,
) -> Result<StartedAgent> {
let (_, directory, _) = self.verify(target)?;
let launch = crate::core::agent_launch_config::resolve_scheme(
&input.kind,
input.scheme_id.as_deref(),
)?;
let argv = Self::agent_argv(&directory, launch, Some(&input.prompt))?;
let env = if input.teams {
ensure!(input.kind == "claude", "Agent Teams requires Claude");
json!({"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"})
} else {
json!({})
};
let target = self.launch(&directory, &argv, Some(&input.name), env)?;
let warning = created(&target).err().map(|error| error.to_string());
Ok(StartedAgent { target, warning })
}
}
#[cfg(test)]
#[path = "hc_tests.rs"]
mod tests;