use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result};
use plannotator_tui_hosts::Host;
use super::context::{HerdrEnv, Target};
use crate::config::{Config, Placement, SplitDirection};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct OpenArgs {
pub(crate) path: Option<PathBuf>,
pub(crate) placement: Option<Placement>,
pub(crate) deliver_to: Option<String>,
pub(crate) newest: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Launch {
pub(crate) file: PathBuf,
pub(crate) cwd: PathBuf,
pub(crate) placement: Placement,
pub(crate) direction: SplitDirection,
pub(crate) popup: (String, String),
pub(crate) target_pane: Option<String>,
pub(crate) deliver: Option<Target>,
pub(crate) plugin: String,
pub(crate) message: Option<AgentMessage>,
pub(crate) session: Option<AgentSession>,
pub(crate) newest: bool,
pub(crate) terminal: Option<TerminalRead>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TerminalRead {
pub(crate) pane: String,
pub(crate) lines: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AgentMessage {
pub(crate) host: String,
pub(crate) pid: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AgentSession {
Path(String),
Id(String),
}
pub(crate) fn agent_session(agent_get_json: &str) -> Option<AgentSession> {
let json: serde_json::Value = serde_json::from_str(agent_get_json).ok()?;
let session = json.pointer("/result/agent/agent_session")?;
let value = session.get("value")?.as_str()?;
if value.trim().is_empty() {
return None;
}
match session.get("kind")?.as_str()? {
"path" => Some(AgentSession::Path(value.to_owned())),
"id" => Some(AgentSession::Id(value.to_owned())),
_ => None,
}
}
fn agent_host(agent_get_json: &str) -> Option<&'static str> {
let json: serde_json::Value = serde_json::from_str(agent_get_json).ok()?;
let label = json.pointer("/result/agent/agent")?.as_str()?;
Host::ALL.into_iter().find(|host| host.label() == label).map(Host::label)
}
pub(crate) fn agent_identity(agent_get_json: &str) -> Option<(String, AgentSession)> {
Some((agent_host(agent_get_json)?.to_owned(), agent_session(agent_get_json)?))
}
pub(crate) fn agent_pid(process_info_json: &str) -> Option<(u32, String)> {
let json: serde_json::Value = serde_json::from_str(process_info_json).ok()?;
let info = json.pointer("/result/process_info")?;
let processes = info.get("foreground_processes")?.as_array()?;
let name_of = |p: &serde_json::Value| p.get("name").and_then(|n| n.as_str()).unwrap_or("").to_owned();
let pid_of = |p: &serde_json::Value| p.get("pid").and_then(serde_json::Value::as_u64).map(|n| n as u32);
for process in processes {
let name = name_of(process);
if let Some(host) = known_host(&name) {
return pid_of(process).map(|pid| (pid, host.to_owned()));
}
}
let leader = info.get("foreground_process_group_id").and_then(serde_json::Value::as_u64)?;
let process = processes.iter().find(|p| pid_of(p) == Some(leader as u32))?;
let name = name_of(process);
let host = name.rsplit('/').next().unwrap_or(&name).to_owned();
pid_of(process).map(|pid| (pid, if host.is_empty() { "claude".to_owned() } else { host }))
}
fn known_host(name: &str) -> Option<&'static str> {
match name.rsplit('/').next().unwrap_or(name) {
"claude" => Some("claude"),
"codex" => Some("codex"),
"pi" => Some("pi"),
"opencode" => Some("opencode"),
"agy" => Some("agy"),
_ => None,
}
}
pub(crate) fn plan_last(
env: &HerdrEnv,
config: &Config,
args: OpenArgs,
cwd: &Path,
process_info_json: Option<&str>,
agent_get_json: Option<&str>,
) -> Result<Launch> {
let newest = args.newest;
let mut launch = plan(env, config, OpenArgs { path: None, ..args }, cwd)?;
launch.newest = newest;
let pane = launch.deliver.as_ref().map(|t| t.pane.clone()).or_else(|| launch.target_pane.clone());
let Some(pane) = pane else {
anyhow::bail!("no agent pane to read: not focused on one and no --deliver-to")
};
launch.file.clone_from(&launch.cwd);
if let Some((host, session)) = agent_get_json.and_then(agent_identity) {
launch.message = Some(AgentMessage { host, pid: None });
launch.session = Some(session);
return Ok(launch);
}
let process_info = process_info_json
.with_context(|| format!("no exact agent session or process info for pane {pane}"))?;
let Some((pid, process_host)) = agent_pid(process_info) else {
anyhow::bail!("no agent process found in pane {pane}");
};
let host = agent_get_json.and_then(agent_host).unwrap_or(&process_host).to_owned();
launch.message = Some(AgentMessage { host, pid: Some(pid) });
Ok(launch)
}
pub(crate) fn plan_terminal(
env: &HerdrEnv,
config: &Config,
args: OpenArgs,
cwd: &Path,
read: TerminalRead,
) -> Result<Launch> {
let mut launch = plan(env, config, OpenArgs { path: None, newest: false, ..args }, cwd)?;
launch.file.clone_from(&launch.cwd);
launch.target_pane = Some(read.pane.clone());
launch.terminal = Some(read);
Ok(launch)
}
fn file_url_path(url: &str) -> Option<PathBuf> {
let rest = url.strip_prefix("file://")?;
let path = match rest.find('/') {
Some(0) => rest,
Some(slash) if matches!(&rest[..slash], "" | "localhost") => &rest[slash..],
_ => return None,
};
let decoded = percent_decode(path);
#[cfg(windows)]
let decoded = match decoded.as_bytes() {
[b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => {
decoded.get(1..).unwrap_or_default().to_owned()
}
_ => decoded,
};
Some(PathBuf::from(decoded))
}
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let decoded = (bytes.get(i) == Some(&b'%'))
.then(|| s.get(i + 1..i + 3))
.flatten()
.and_then(|hex| u8::from_str_radix(hex, 16).ok());
if let Some(byte) = decoded {
out.push(byte);
i += 3;
} else {
out.extend(bytes.get(i..=i).unwrap_or_default());
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
pub(crate) fn plan(env: &HerdrEnv, config: &Config, args: OpenArgs, cwd: &Path) -> Result<Launch> {
let context = env.context.as_ref();
let placement = match (args.placement, env.placement.as_deref()) {
(Some(p), _) => p,
(None, Some(text)) => text.parse().context("PLANNOTATOR_TUI_PLACEMENT")?,
(None, None)
if config.herdr.placement == Placement::Overlay
&& context.and_then(|c| c.invocation_source.as_deref()) == Some("mirror") =>
{
Placement::Split
}
(None, None) => config.herdr.placement,
};
let file = args
.path
.or_else(|| context.and_then(|c| c.clicked_url.as_deref()).and_then(file_url_path))
.or_else(|| context.and_then(|c| c.focused_pane_cwd.clone()).map(PathBuf::from))
.or_else(|| context.and_then(|c| c.workspace_cwd.clone()).map(PathBuf::from))
.unwrap_or_else(|| cwd.to_path_buf());
let file = if file.is_absolute() { file } else { cwd.join(file) };
let dir = if file.is_dir() {
file.clone()
} else {
file.parent().map_or_else(|| cwd.to_path_buf(), Path::to_path_buf)
};
let deliver = match args.deliver_to {
Some(pane) => Some(Target { pane, agent: None }),
None if env.context.is_some() => env.focused_agent_pane(),
None => env.pane_id.clone().map(|pane| Target { pane, agent: None }),
};
let target_pane = deliver
.as_ref()
.map(|t| t.pane.clone())
.or_else(|| context.and_then(|c| c.focused_pane_id.clone()))
.or_else(|| env.pane_id.clone());
Ok(Launch {
file,
cwd: dir,
placement,
direction: config.herdr.split_direction,
popup: (config.herdr.popup_width.clone(), config.herdr.popup_height.clone()),
target_pane,
deliver,
plugin: env.plugin_id.clone().unwrap_or_else(|| "annotate".to_owned()),
message: None,
session: None,
newest: false,
terminal: None,
})
}
pub(crate) fn argv(launch: &Launch) -> Vec<String> {
let mut out: Vec<String> = ["plugin", "pane", "open", "--plugin", &launch.plugin, "--entrypoint", "doc"]
.into_iter()
.map(str::to_owned)
.collect();
out.extend(["--placement".to_owned(), launch.placement.to_string()]);
match launch.placement {
Placement::Split => {
out.extend(["--direction".to_owned(), launch.direction.to_string()]);
if let Some(pane) = &launch.target_pane {
out.extend(["--target-pane".to_owned(), pane.clone()]);
}
}
Placement::Popup => {
out.extend(["--width".to_owned(), launch.popup.0.clone()]);
out.extend(["--height".to_owned(), launch.popup.1.clone()]);
}
Placement::Overlay => {}
}
out.push("--focus".to_owned());
out.extend(["--cwd".to_owned(), launch.cwd.display().to_string()]);
match (&launch.message, &launch.terminal) {
(_, Some(terminal)) => {
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_TERMINAL_PANE={}", terminal.pane)]);
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_TERMINAL_LINES={}", terminal.lines)]);
}
(Some(message), None) => {
if let Some(pid) = message.pid {
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_MESSAGE_PID={pid}")]);
}
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_HOST={}", message.host)]);
if launch.newest {
out.extend(["--env".to_owned(), "PLANNOTATOR_TUI_NEWEST=1".to_owned()]);
}
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_CWD={}", launch.cwd.display())]);
match &launch.session {
Some(AgentSession::Path(p)) => {
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_SESSION={p}")]);
}
Some(AgentSession::Id(id)) => {
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_SESSION_ID={id}")]);
}
None => {}
}
}
(None, None) => {
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_FILE={}", launch.file.display())]);
}
}
if let Some(target) = &launch.deliver {
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_DELIVER_TO={}", target.pane)]);
if let Some(agent) = &target.agent {
out.extend(["--env".to_owned(), format!("PLANNOTATOR_TUI_DELIVER_AGENT={agent}")]);
}
}
out
}
pub(crate) fn process_info(env: &HerdrEnv, pane: &str) -> Result<String> {
let output = Command::new(&env.bin)
.args(["pane", "process-info", "--pane", pane])
.output()
.with_context(|| format!("running {} pane process-info", env.bin.display()))?;
if !output.status.success() {
anyhow::bail!("herdr pane process-info {pane}: {}", String::from_utf8_lossy(&output.stderr).trim());
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
pub(crate) fn agent_get(env: &HerdrEnv, pane: &str) -> Option<String> {
let output = Command::new(&env.bin).args(["agent", "get", pane]).output().ok()?;
output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned())
}
pub(crate) fn run(env: &HerdrEnv, launch: &Launch) -> Result<()> {
if !env.in_herdr {
anyhow::bail!("not inside Herdr (HERDR_ENV is not set)");
}
let status = Command::new(&env.bin)
.args(argv(launch))
.status()
.with_context(|| format!("running {}", env.bin.display()))?;
if !status.success() {
anyhow::bail!("herdr plugin pane open failed with {status}");
}
Ok(())
}
#[cfg(test)]
mod tests;