use std::path::PathBuf;
use serde::Deserialize;
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub(crate) struct HerdrContext {
pub(crate) workspace_id: Option<String>,
pub(crate) workspace_cwd: Option<String>,
pub(crate) focused_pane_id: Option<String>,
pub(crate) focused_pane_cwd: Option<String>,
pub(crate) focused_pane_agent: Option<String>,
pub(crate) invocation_source: Option<String>,
pub(crate) clicked_url: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Target {
pub(crate) pane: String,
pub(crate) agent: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct HerdrEnv {
pub(crate) in_herdr: bool,
pub(crate) bin: PathBuf,
pub(crate) pane_id: Option<String>,
pub(crate) context: Option<HerdrContext>,
pub(crate) file: Option<PathBuf>,
pub(crate) deliver_to: Option<String>,
pub(crate) deliver_agent: Option<String>,
pub(crate) placement: Option<String>,
pub(crate) plugin_id: Option<String>,
pub(crate) message_pid: Option<u32>,
pub(crate) host: Option<String>,
pub(crate) session: Option<PathBuf>,
pub(crate) session_id: Option<String>,
pub(crate) newest: bool,
pub(crate) terminal_pane: Option<String>,
pub(crate) terminal_lines: Option<u32>,
pub(crate) gate: bool,
pub(crate) result_file: Option<PathBuf>,
pub(crate) review: Option<String>,
pub(crate) repo: Option<PathBuf>,
}
impl HerdrEnv {
pub(crate) fn from_env() -> Self {
Self::from_lookup(|k| std::env::var(k).ok())
}
pub(crate) fn from_lookup(env: impl Fn(&str) -> Option<String>) -> Self {
let non_empty = |k: &str| env(k).filter(|v| !v.is_empty());
let context =
non_empty("HERDR_PLUGIN_CONTEXT_JSON").and_then(|json| serde_json::from_str(&json).ok());
Self {
in_herdr: env("HERDR_ENV").as_deref() == Some("1"),
bin: non_empty("HERDR_BIN_PATH").map_or_else(|| PathBuf::from("herdr"), PathBuf::from),
pane_id: non_empty("HERDR_PANE_ID"),
context,
file: non_empty("PLANNOTATOR_TUI_FILE").map(PathBuf::from),
deliver_to: non_empty("PLANNOTATOR_TUI_DELIVER_TO"),
deliver_agent: non_empty("PLANNOTATOR_TUI_DELIVER_AGENT"),
placement: non_empty("PLANNOTATOR_TUI_PLACEMENT"),
plugin_id: non_empty("HERDR_PLUGIN_ID"),
message_pid: non_empty("PLANNOTATOR_TUI_MESSAGE_PID").and_then(|v| v.parse().ok()),
host: non_empty("PLANNOTATOR_TUI_HOST"),
session: non_empty("PLANNOTATOR_TUI_SESSION").map(PathBuf::from),
session_id: non_empty("PLANNOTATOR_TUI_SESSION_ID"),
newest: env("PLANNOTATOR_TUI_NEWEST").as_deref() == Some("1"),
terminal_pane: non_empty("PLANNOTATOR_TUI_TERMINAL_PANE"),
terminal_lines: non_empty("PLANNOTATOR_TUI_TERMINAL_LINES").and_then(|v| v.parse().ok()),
gate: env("PLANNOTATOR_TUI_GATE").as_deref() == Some("1"),
result_file: non_empty("PLANNOTATOR_TUI_RESULT_FILE").map(PathBuf::from),
review: non_empty("PLANNOTATOR_TUI_REVIEW"),
repo: non_empty("PLANNOTATOR_TUI_REPO").map(PathBuf::from),
}
}
pub(crate) fn focused_agent_pane(&self) -> Option<Target> {
let context = self.context.as_ref()?;
let agent = context.focused_pane_agent.clone().filter(|agent| !agent.trim().is_empty())?;
Some(Target { pane: context.focused_pane_id.clone()?, agent: Some(agent) })
}
pub(crate) fn delivery_target(&self) -> Option<Target> {
if let Some(pane) = &self.deliver_to {
return Some(Target { pane: pane.clone(), agent: self.deliver_agent.clone() });
}
self.focused_agent_pane()
}
pub(crate) fn has_message_source(&self) -> bool {
self.session.is_some() || self.session_id.is_some() || self.message_pid.is_some()
}
pub(crate) fn reviewed_pane(&self) -> Option<String> {
match &self.context {
Some(context) => context.focused_pane_id.clone(),
None => self.pane_id.clone(),
}
}
pub(crate) fn context_agent_in(&self, pane: &str) -> Option<String> {
let context = self.context.as_ref()?;
(context.focused_pane_id.as_deref() == Some(pane))
.then(|| context.focused_pane_agent.clone())
.flatten()
.filter(|agent| !agent.trim().is_empty())
}
pub(crate) fn agent_in_pane(&self, pane: &str) -> Option<String> {
let output = std::process::Command::new(&self.bin)
.args(["pane", "get", pane])
.stdin(std::process::Stdio::null())
.output()
.ok()
.filter(|o| o.status.success())?;
let json: serde_json::Value = serde_json::from_slice(&output.stdout).ok()?;
json.pointer("/result/pane/agent")?.as_str().map(str::to_owned)
}
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::*;
fn env(vars: &[(&str, &str)]) -> HerdrEnv {
let owned: Vec<(String, String)> =
vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
HerdrEnv::from_lookup(|k| owned.iter().find(|(name, _)| name == k).map(|(_, v)| v.clone()))
}
#[test]
fn context_with_omitted_and_unknown_fields_parses() {
let json = r#"{"focused_pane_id":"w1:p2","focused_pane_agent":"claude","link_handler_id":"x","worktree":{"a":1}}"#;
let context: HerdrContext = serde_json::from_str(json).expect("parses");
assert_eq!(context.focused_pane_id.as_deref(), Some("w1:p2"));
assert_eq!(context.focused_pane_agent.as_deref(), Some("claude"));
assert_eq!(context.workspace_cwd, None);
}
#[test]
fn outside_herdr_nothing_is_set() {
let env = env(&[]);
assert!(!env.in_herdr);
assert_eq!(env.bin, PathBuf::from("herdr"));
assert_eq!(env.delivery_target(), None);
}
#[test]
fn explicit_deliver_to_wins_and_carries_the_agent_label() {
let env = env(&[
("HERDR_ENV", "1"),
("PLANNOTATOR_TUI_DELIVER_TO", "w1:p1"),
("PLANNOTATOR_TUI_DELIVER_AGENT", "claude"),
("HERDR_PLUGIN_CONTEXT_JSON", r#"{"focused_pane_id":"w1:p9","focused_pane_agent":"codex"}"#),
]);
assert_eq!(
env.delivery_target(),
Some(Target { pane: "w1:p1".into(), agent: Some("claude".into()) })
);
}
#[test]
fn context_pane_is_a_target_only_when_an_agent_runs_there() {
let with_agent = env(&[
("HERDR_ENV", "1"),
("HERDR_PLUGIN_CONTEXT_JSON", r#"{"focused_pane_id":"w1:p2","focused_pane_agent":"claude"}"#),
]);
assert_eq!(
with_agent.delivery_target(),
Some(Target { pane: "w1:p2".into(), agent: Some("claude".into()) })
);
let shell =
env(&[("HERDR_ENV", "1"), ("HERDR_PLUGIN_CONTEXT_JSON", r#"{"focused_pane_id":"w1:p2"}"#)]);
assert_eq!(shell.delivery_target(), None);
let mirror_shell =
env(&[("HERDR_PLUGIN_CONTEXT_JSON", r#"{"focused_pane_id":"w1:p2","focused_pane_agent":""}"#)]);
assert_eq!(mirror_shell.delivery_target(), None);
}
#[test]
fn own_pane_id_is_never_a_target() {
let env = env(&[("HERDR_ENV", "1"), ("HERDR_PANE_ID", "w1:p3")]);
assert_eq!(env.pane_id.as_deref(), Some("w1:p3"));
assert_eq!(env.delivery_target(), None);
}
#[test]
fn any_exact_session_or_pid_selects_the_message_entrypoint() {
for vars in [
vec![("PLANNOTATOR_TUI_SESSION", "C:\\sessions\\one.jsonl")],
vec![("PLANNOTATOR_TUI_SESSION_ID", "session-one")],
vec![("PLANNOTATOR_TUI_MESSAGE_PID", "42")],
] {
assert!(env(&vars).has_message_source());
}
assert!(!env(&[]).has_message_source());
}
#[test]
fn only_an_exact_newest_flag_skips_the_picker() {
assert!(env(&[("PLANNOTATOR_TUI_NEWEST", "1")]).newest);
assert!(!env(&[]).newest);
assert!(!env(&[("PLANNOTATOR_TUI_NEWEST", "")]).newest);
assert!(!env(&[("PLANNOTATOR_TUI_NEWEST", "0")]).newest);
}
#[test]
fn the_reviewed_pane_is_the_focused_one_from_an_action_else_the_caller() {
let action = env(&[
("HERDR_PANE_ID", "w1:p9"),
("HERDR_PLUGIN_CONTEXT_JSON", r#"{"focused_pane_id":"w1:p2","focused_pane_agent":"codex"}"#),
]);
assert_eq!(action.reviewed_pane().as_deref(), Some("w1:p2"));
assert_eq!(action.context_agent_in("w1:p2").as_deref(), Some("codex"));
assert_eq!(action.context_agent_in("w1:p3"), None);
assert_eq!(env(&[("HERDR_PANE_ID", "w1:p9")]).reviewed_pane().as_deref(), Some("w1:p9"));
assert_eq!(env(&[("HERDR_PLUGIN_CONTEXT_JSON", "{}")]).reviewed_pane(), None);
}
#[test]
fn the_terminal_pane_and_line_count_come_from_the_launcher() {
let env =
env(&[("PLANNOTATOR_TUI_TERMINAL_PANE", "w1:p2"), ("PLANNOTATOR_TUI_TERMINAL_LINES", "80")]);
assert_eq!(env.terminal_pane.as_deref(), Some("w1:p2"));
assert_eq!(env.terminal_lines, Some(80));
}
#[test]
fn a_code_review_scope_and_repository_come_from_the_launcher() {
let env = env(&[("PLANNOTATOR_TUI_REVIEW", "commit:HEAD"), ("PLANNOTATOR_TUI_REPO", "/work/app")]);
assert_eq!(env.review.as_deref(), Some("commit:HEAD"));
assert_eq!(env.repo, Some(PathBuf::from("/work/app")));
}
#[test]
fn only_an_exact_gate_flag_gates_the_pane() {
let gated = env(&[("PLANNOTATOR_TUI_GATE", "1"), ("PLANNOTATOR_TUI_RESULT_FILE", "/tmp/d.json")]);
assert!(gated.gate);
assert_eq!(gated.result_file, Some(PathBuf::from("/tmp/d.json")));
assert!(!env(&[("PLANNOTATOR_TUI_GATE", "true")]).gate);
assert!(!env(&[]).gate);
}
}