use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde_json::Value;
use super::agent::{AGENT_VAR, BLOCK_VAR, PI_SESSION_VAR, PID_VAR, SUBMIT_VAR};
use super::command::Rex;
use crate::config::RexPlacement;
use crate::herdr::launch::known_host;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Review {
Last { newest: bool },
Open(Option<PathBuf>, Option<Gate>),
Terminal { lines: u32 },
Find { lines: u32 },
#[cfg_attr(not(unix), allow(dead_code, reason = "code review is unix only"))]
Code { scope: String, repo: PathBuf },
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Gate {
pub(crate) result_file: Option<PathBuf>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Handoff {
Send,
Paste,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Foreground {
pub(crate) pid: u32,
pub(crate) cwd: Option<PathBuf>,
pub(crate) host: Option<&'static str>,
}
pub(crate) fn foreground(process: &Value) -> Option<Foreground> {
let fg = process.get("foreground")?;
let pid = u32::try_from(fg.get("pid")?.as_u64()?).ok()?;
let host = ["argv0", "invoked_path", "name", "path", "script"]
.iter()
.filter_map(|key| fg.get(*key).and_then(Value::as_str))
.find_map(known_host);
let cwd = fg.get("cwd").and_then(Value::as_str).map(PathBuf::from);
Some(Foreground { pid, cwd, host })
}
pub(crate) fn reported_host(status: &Value, pid: u32) -> Option<&'static str> {
let records = status.get("records")?.as_array()?;
records
.iter()
.filter(|r| r.pointer("/owner/pid").and_then(Value::as_u64) == Some(u64::from(pid)))
.flat_map(|r| ["effective_app", "app"].map(|key| r.get(key).and_then(Value::as_str)))
.flatten()
.find_map(|app| if app == "claude-code" { Some("claude") } else { known_host(app) })
}
pub(crate) fn argv(
exe: &Path,
block: &str,
fg: &Foreground,
review: &Review,
handoff: Handoff,
) -> Result<Vec<String>> {
let mut args = vec!["/usr/bin/env".to_owned()];
if let Some(host) = fg.host {
args.push(format!("{BLOCK_VAR}={block}"));
args.push(format!("{AGENT_VAR}={host}"));
args.push(format!("{PID_VAR}={}", fg.pid));
if handoff == Handoff::Paste {
args.push(format!("{SUBMIT_VAR}=0"));
}
}
args.extend([exe.display().to_string(), "rex".to_owned(), "pane".to_owned()]);
match review {
Review::Last { newest } => {
let host = fg.host.context("no supported agent runs in this block")?;
args.extend(["last".to_owned(), "--pid".to_owned(), fg.pid.to_string()]);
args.extend(["--host".to_owned(), host.to_owned()]);
if *newest {
args.push("--newest".to_owned());
}
}
Review::Open(path, gate) => {
let path = path.clone().or_else(|| fg.cwd.clone()).context("no file or folder to open")?;
args.extend(["open".to_owned(), path.display().to_string()]);
if let Some(gate) = gate {
args.push("--gate".to_owned());
if let Some(file) = &gate.result_file {
args.extend(["--result-file".to_owned(), file.display().to_string()]);
}
}
}
Review::Terminal { lines } => {
args.extend(["terminal", "--block", block, "--lines"].map(str::to_owned));
args.push(lines.to_string());
}
Review::Find { .. } => anyhow::bail!("a find review is resolved to an open before the split"),
Review::Code { scope, repo } => {
args.extend(["review".to_owned(), scope.clone(), repo.display().to_string()]);
}
}
Ok(args)
}
fn newest_markdown(rex: &Rex, block: &str, fg: &Foreground, lines: u32) -> Result<PathBuf> {
let text = super::terminal::read(rex, block, lines)?;
let home = std::env::var_os("HOME").map(PathBuf::from);
super::paths::markdown_files(&text, fg.cwd.as_deref(), home.as_deref())
.into_iter()
.next()
.with_context(|| format!("no Markdown file named in the last {lines} lines of block {block}"))
}
pub(crate) fn agent(rex: &Rex, block: &str) -> Result<Foreground> {
let process = rex.terminal_method(block, "process")?;
let mut fg = foreground(&process).with_context(|| format!("block {block} has no foreground process"))?;
if let Ok(status) = rex.terminal_method(block, "program_status") {
fg.host = reported_host(&status, fg.pid).or(fg.host);
}
Ok(fg)
}
pub(crate) fn run(
rex: &Rex,
block: &str,
review: &Review,
handoff: Handoff,
placement: RexPlacement,
) -> Result<()> {
let fg = agent(rex, block)?;
let review = match review {
Review::Find { lines } => Review::Open(Some(newest_markdown(rex, block, &fg, *lines)?), None),
other => other.clone(),
};
open(rex, block, &fg, &review, handoff, placement)
}
pub(crate) fn open(
rex: &Rex,
block: &str,
fg: &Foreground,
review: &Review,
handoff: Handoff,
placement: RexPlacement,
) -> Result<()> {
let exe = std::env::current_exe().context("finding the plannotator-tui binary")?;
let mut args = argv(&exe, block, fg, review, handoff)?;
if placement == RexPlacement::Tab {
returning_to(&mut args, block);
}
let registry = crate::pi::root();
if let Some(session) = pi_session(fg, review, ®istry) {
args.insert(1, format!("{PI_SESSION_VAR}={session}"));
args.insert(1, format!("{}={}", crate::pi::SESSIONS_DIR_VAR, registry.display()));
}
let cwd = match review {
Review::Code { repo, .. } => Some(repo.as_path()),
_ => fg.cwd.as_deref(),
};
super::place::open(rex, block, placement, cwd, &args, &tab_label(fg, review))
}
fn pi_session(fg: &Foreground, review: &Review, registry: &Path) -> Option<String> {
if fg.host != Some("pi") || !matches!(review, Review::Last { .. }) {
return None;
}
crate::pi::live_entry_for_pid(registry, fg.pid).map(|entry| entry.id)
}
pub(crate) const RETURN_VAR: &str = "PLANNOTATOR_TUI_REX_RETURN";
fn returning_to(args: &mut Vec<String>, block: &str) {
args.insert(1, format!("{RETURN_VAR}={block}"));
}
fn tab_label(fg: &Foreground, review: &Review) -> String {
let name = |path: &Path| path.file_name().map(|n| n.to_string_lossy().into_owned());
let what = match review {
Review::Open(path, _) => path.as_deref().or(fg.cwd.as_deref()).and_then(name),
Review::Code { repo, .. } => fg.host.map(str::to_owned).or_else(|| name(repo)),
_ => fg.host.map(str::to_owned).or_else(|| fg.cwd.as_deref().and_then(name)),
};
what.map_or_else(
|| "Annotate".to_owned(),
|what| format!("Annotate · {what}").chars().take(128).collect(),
)
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::*;
#[test]
fn only_a_last_review_of_a_running_registered_pi_is_pinned_to_its_session() {
let registry = std::env::temp_dir().join(format!("plannotator-tui-rex-pin-{}", std::process::id()));
let _ = std::fs::remove_dir_all(®istry);
crate::pi::write_test_entry(®istry, "session-1", 73139, true);
crate::pi::write_test_entry(®istry, "gone", 73140, false);
let pi = |pid| Foreground { pid, cwd: None, host: Some("pi") };
let last = Review::Last { newest: false };
assert_eq!(pi_session(&pi(73139), &last, ®istry).as_deref(), Some("session-1"));
assert_eq!(pi_session(&pi(73140), &last, ®istry), None, "a Pi that is gone pins nothing");
assert_eq!(pi_session(&pi(73141), &last, ®istry), None, "no extension: no pin");
let open = Review::Open(Some(PathBuf::from("/p/plan.md")), None);
assert_eq!(pi_session(&pi(73139), &open, ®istry), None, "a file review is not pinned");
let claude = Foreground { pid: 73139, cwd: None, host: Some("claude") };
assert_eq!(pi_session(&claude, &last, ®istry), None);
std::fs::remove_dir_all(registry).ok();
}
const CLAUDE: &str = r#"{"last_exit":null,"child":{"pid":59515,"name":"login"},"foreground":{"pid":60223,"name":"2.1.308","path":"/Users/me/.local/share/claude/versions/2.1.308","invoked_path":"/Users/me/.local/bin/claude","argv0":"claude","cwd":"/Users/me/project"}}"#;
const SHELL: &str = r#"{"foreground":{"pid":700,"name":"fish","argv0":"-fish","cwd":"/Users/me"}}"#;
const PI_NODE: &str = r#"{"last_exit":null,"foreground":{"pid":73139,"user_id":501,"user":"me","name":"node","path":"/Users/me/.local/share/fnm/node-versions/v24.15.0/installation/bin/node","invoked_path":"/Users/me/.local/share/fnm/node-versions/v24.15.0/installation/bin/node","argv0":"node","script":"/Users/me/.local/share/fnm/node-versions/v24.15.0/installation/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js","cwd":"/Users/me/project"},"home":"/Users/me"}"#;
const PI_STATUS: &str = r#"{"records":[{"state":"idle","app":"pi","effective_app":"pi","updated_at":"2026-11-10T00:25:21.924601-05:00","owner":{"pid":73139,"name":"node"}}]}"#;
fn parse(json: &str) -> Foreground {
foreground(&serde_json::from_str(json).expect("json")).expect("a foreground process")
}
#[test]
fn claude_code_is_found_by_its_invoked_name_not_its_versioned_binary() {
let fg = parse(CLAUDE);
assert_eq!(fg.pid, 60223);
assert_eq!(fg.host, Some("claude"));
assert_eq!(fg.cwd.as_deref(), Some(Path::new("/Users/me/project")));
assert_eq!(parse(SHELL).host, None);
}
fn status(json: &str) -> Value {
serde_json::from_str(json).expect("json")
}
#[test]
fn an_agent_under_an_interpreter_is_named_by_its_own_status_report() {
let fg = parse(PI_NODE);
assert_eq!(fg.host, None, "node and cli.js name no agent");
assert_eq!(reported_host(&status(PI_STATUS), fg.pid), Some("pi"));
let claude = r#"{"records":[{"state":"working","app":"claude-code","owner":{"pid":60223}}]}"#;
assert_eq!(reported_host(&status(claude), 60223), Some("claude"));
}
#[test]
fn a_status_left_by_another_process_names_no_agent() {
assert_eq!(reported_host(&status(PI_STATUS), 700), None);
let unknown = r#"{"records":[{"state":"working","app":"terraform","owner":{"pid":700}}]}"#;
assert_eq!(reported_host(&status(unknown), 700), None);
assert_eq!(reported_host(&status(r#"{"records":[]}"#), 700), None);
}
#[test]
fn a_script_names_the_agent_when_its_file_is_called_after_it() {
let script = r#"{"foreground":{"pid":9,"name":"node","argv0":"node","script":"/opt/bin/pi"}}"#;
assert_eq!(parse(script).host, Some("pi"));
}
#[test]
fn last_reads_the_agents_pid_and_sends_back_to_its_block() {
let args = argv(
Path::new("/bin/pt"),
"block:b",
&parse(CLAUDE),
&Review::Last { newest: true },
Handoff::Send,
)
.expect("argv");
assert_eq!(
args,
[
"/usr/bin/env",
"PLANNOTATOR_TUI_REX_BLOCK=block:b",
"PLANNOTATOR_TUI_DELIVER_AGENT=claude",
"PLANNOTATOR_TUI_REX_PID=60223",
"/bin/pt",
"rex",
"pane",
"last",
"--pid",
"60223",
"--host",
"claude",
"--newest"
]
);
assert!(
argv(
Path::new("/bin/pt"),
"block:b",
&parse(SHELL),
&Review::Last { newest: false },
Handoff::Send
)
.is_err()
);
}
#[test]
fn open_without_an_agent_reviews_the_blocks_folder_and_copies_to_the_clipboard() {
let args =
argv(Path::new("/bin/pt"), "block:b", &parse(SHELL), &Review::Open(None, None), Handoff::Send)
.expect("argv");
assert_eq!(args, ["/usr/bin/env", "/bin/pt", "rex", "pane", "open", "/Users/me"]);
}
#[test]
fn pasting_is_passed_on_only_where_there_is_an_agent_to_paste_into() {
let paste = |json| {
argv(Path::new("/bin/pt"), "block:b", &parse(json), &Review::Open(None, None), Handoff::Paste)
.expect("argv")
};
assert!(paste(CLAUDE).contains(&"PLANNOTATOR_TUI_REX_SUBMIT=0".to_owned()));
assert!(!paste(SHELL).iter().any(|arg| arg.starts_with("PLANNOTATOR_TUI_REX")));
}
#[test]
fn a_gated_open_hands_the_gate_and_its_result_file_to_the_pane() {
let gated = |gate| {
let review = Review::Open(Some(PathBuf::from("/p/plan.md")), Some(gate));
argv(Path::new("/bin/pt"), "block:b", &parse(CLAUDE), &review, Handoff::Send).expect("argv")
};
let tail = |args: &[String]| args.iter().skip_while(|a| *a != "open").cloned().collect::<Vec<_>>();
assert_eq!(tail(&gated(Gate::default())), ["open", "/p/plan.md", "--gate"]);
let published = gated(Gate { result_file: Some(PathBuf::from("/p/decision.json")) });
assert_eq!(tail(&published), ["open", "/p/plan.md", "--gate", "--result-file", "/p/decision.json"]);
assert!(published.contains(&"PLANNOTATOR_TUI_REX_BLOCK=block:b".to_owned()), "the agent hears it");
}
#[test]
fn a_code_review_names_its_scope_and_repository_and_sends_to_the_blocks_agent() {
let review = Review::Code { scope: "base:origin/main".to_owned(), repo: PathBuf::from("/p/repo") };
let args =
argv(Path::new("/bin/pt"), "block:b", &parse(CLAUDE), &review, Handoff::Send).expect("argv");
assert_eq!(
args,
[
"/usr/bin/env",
"PLANNOTATOR_TUI_REX_BLOCK=block:b",
"PLANNOTATOR_TUI_DELIVER_AGENT=claude",
"PLANNOTATOR_TUI_REX_PID=60223",
"/bin/pt",
"rex",
"pane",
"review",
"base:origin/main",
"/p/repo"
]
);
let shell =
argv(Path::new("/bin/pt"), "block:b", &parse(SHELL), &review, Handoff::Send).expect("argv");
assert_eq!(
shell,
["/usr/bin/env", "/bin/pt", "rex", "pane", "review", "base:origin/main", "/p/repo"]
);
}
#[test]
fn a_terminal_review_reads_the_block_from_inside_the_split() {
let args = argv(
Path::new("/bin/pt"),
"block:b",
&parse(SHELL),
&Review::Terminal { lines: 80 },
Handoff::Send,
)
.expect("argv");
assert_eq!(
args,
["/usr/bin/env", "/bin/pt", "rex", "pane", "terminal", "--block", "block:b", "--lines", "80"]
);
}
#[test]
fn a_review_in_a_tab_knows_the_block_to_show_again_when_it_ends() {
let review = Review::Open(Some(PathBuf::from("/Users/me/project/plan.md")), Some(Gate::default()));
let mut args =
argv(Path::new("/bin/pt"), "block:b", &parse(CLAUDE), &review, Handoff::Send).expect("argv");
returning_to(&mut args, "block:b");
assert_eq!(
args.get(..3),
Some(
&["/usr/bin/env", "PLANNOTATOR_TUI_REX_RETURN=block:b", "PLANNOTATOR_TUI_REX_BLOCK=block:b"]
.map(String::from)[..]
)
);
assert_eq!(args.iter().rev().take(2).collect::<Vec<_>>(), ["--gate", "/Users/me/project/plan.md"]);
}
#[test]
fn a_tab_is_named_for_the_file_it_opens_else_the_agent_else_the_folder() {
let open = |path: Option<&str>| Review::Open(path.map(PathBuf::from), None);
assert_eq!(tab_label(&parse(CLAUDE), &open(Some("/Users/me/project/plan.md"))), "Annotate · plan.md");
assert_eq!(tab_label(&parse(CLAUDE), &open(None)), "Annotate · project");
assert_eq!(tab_label(&parse(CLAUDE), &Review::Last { newest: false }), "Annotate · claude");
let code = Review::Code { scope: "uncommitted".to_owned(), repo: PathBuf::from("/p/repo") };
assert_eq!(tab_label(&parse(CLAUDE), &code), "Annotate · claude");
assert_eq!(tab_label(&parse(SHELL), &code), "Annotate · repo");
assert_eq!(tab_label(&parse(SHELL), &Review::Terminal { lines: 80 }), "Annotate · me");
}
}