Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions crates/plannotator-tui/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ fn review_delivery(interactive: bool, path: Option<&Path>) -> Box<dyn Delivery>
if !interactive {
return Box::new(Discard);
}
agent_pane().or_else(|| deliver_command(path)).unwrap_or_else(|| Box::new(Clipboard))
agent_pane(true).or_else(|| deliver_command(path)).unwrap_or_else(|| Box::new(Clipboard))
}

/// `PLANNOTATOR_TUI_DELIVER_CMD`, else `[deliver] command`. A config that does not parse
Expand All @@ -108,14 +108,16 @@ fn deliver_command(path: Option<&Path>) -> Option<Box<dyn Delivery>> {
Some(Box::new(command))
}

/// A gated review sends to the same agent pane; without one its decision goes to the caller.
/// A gated review sends to the same agent pane; without one, or when the pane cannot reach
/// it, its decision goes to the caller.
fn gate_delivery() -> Box<dyn Delivery> {
agent_pane().unwrap_or_else(|| Box::new(Caller))
agent_pane(false).unwrap_or_else(|| Box::new(Caller))
}

/// The Pi that started the review, or the Rex block, hc terminal or Herdr agent pane the
/// environment names, if any.
fn agent_pane() -> Option<Box<dyn Delivery>> {
/// environment names, if any. With `refuse_unreachable`, a Rex launcher's agent that this
/// pane cannot reach is a target that refuses Send and says why.
fn agent_pane(refuse_unreachable: bool) -> Option<Box<dyn Delivery>> {
// Set only by Pi's `/plannotator-review`, for the review it runs in its own terminal. A
// Pi that cannot be found refuses Send: the Rex block, hc terminal or Herdr pane in Pi's
// environment is the one the review now runs in.
Expand All @@ -124,8 +126,10 @@ fn agent_pane() -> Option<Box<dyn Delivery>> {
Some(Err(gone)) => return Some(Box::new(gone)),
None => {}
}
if let Some(agent) = RexAgent::from_lookup(|k| std::env::var(k).ok()) {
return Some(Box::new(agent));
match RexAgent::from_lookup(|k| std::env::var(k).ok()) {
Some(Ok(agent)) => return Some(Box::new(agent)),
Some(Err(unreachable)) if refuse_unreachable => return Some(Box::new(unreachable)),
_ => {}
}
if let Some(agent) = HcAgent::from_lookup(|k| std::env::var(k).ok()) {
return Some(Box::new(agent));
Expand Down
11 changes: 10 additions & 1 deletion crates/plannotator-tui/src/review/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,10 +259,19 @@ impl Screen {
key if key.is_empty() => String::new(),
key => format!(" ({key})"),
};
// Before a send this session, the review's record says where its notes went last, so
// a reopened review whose notes were only copied does not read `Sent ✓`.
let copied = match self.last_send {
LastSend::Clipboard => true,
LastSend::Agent => false,
LastSend::None => {
self.store.deliveries().last().is_some_and(|d| d.target == Clipboard.describe())
}
};
match &self.send_state {
SendState::Blocked(_) => format!("{} at a dialog · retry{key}", self.delivery.describe()),
SendState::Sent if copied => "Copied ✓".to_owned(),
SendState::Sent if self.delivery.is_agent() => format!("Sent ✓{to}"),
SendState::Sent if self.last_send == LastSend::Clipboard => "Copied ✓".to_owned(),
SendState::Sent => "Sent ✓".to_owned(),
SendState::Ready => format!("{verb} {count} new{to}{key}"),
}
Expand Down
33 changes: 33 additions & 0 deletions crates/plannotator-tui/src/review/tests/blocked_send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use super::*;
use crate::delivery::{Clipboard, test_clipboard};
use crate::herdr::agents::{HerdrAgents, fake_herdr};
use crate::review::Mode;
use crate::rex::agent::{AGENT_VAR, BLOCK_VAR, PID_VAR, RexAgent};
use crate::rex::agents::{FIXTURE_OWN_BLOCK, FIXTURE_SESSION, RexAgents, fake_rex};
use crate::ui::agent_picker::{AgentFinder, Reach};
use crate::ui::send_button::SendState;
Expand Down Expand Up @@ -82,3 +83,35 @@ fn a_rex_agent_at_a_dialog_gets_nothing_and_nothing_is_copied() {
assert_waits(&screen, "claude in 63239c");
assert!(!fake.join("pastes").exists());
}

#[test]
fn a_rex_agent_the_review_cannot_reach_is_named_and_the_note_stays_pending() {
let fixture = Fixture::new("unreachable-rex");
let finder = AgentFinder {
pi_root: Some(fixture.dir.join("registry")),
herdr: None,
rex: None,
ask_on_send: true,
};
let mut screen = screen_with(&fixture, finder);
// A launcher named claude's block, but this pane has no Rex session to reach it in.
let env = |k: &str| match k {
BLOCK_VAR => Some("block:01a17dd5-e47c-754f-b72e-ef739ea1d6db".to_owned()),
PID_VAR => Some("7".to_owned()),
AGENT_VAR => Some("claude".to_owned()),
_ => None,
};
screen.delivery = Box::new(RexAgent::from_lookup(env).expect("named").expect_err("unreachable"));
assert_eq!(screen.send_label(), "Send 1 new ▸ claude · not found (E)");
keys(&mut screen, "E");
assert_eq!(
screen.status.as_deref(),
Some(
"no agent to send to (REX_BLOCK is not set, so this pane cannot reach a1d6db) · copied to clipboard · E retry"
)
);
assert_eq!(test_clipboard::copied().len(), 1, "the feedback is copied");
assert_eq!(screen.store.pending().len(), 1, "the note is still pending");
assert_eq!(screen.send_label(), "Send 1 new ▸ claude · not found (E)", "never Sent ✓");
assert!(screen.has_unsent(), "quitting asks first");
}
22 changes: 22 additions & 0 deletions crates/plannotator-tui/src/review/tests/send_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,28 @@ fn send_carries_new_notes_and_resending_after_an_edit_carries_only_the_edit() {
assert!(all.contains("name the total") && all.contains("or missing"), "R resends every note");
}

#[test]
fn a_reopened_review_whose_notes_were_only_copied_says_copied_not_sent() {
let fixture = Fixture::new("reopen-copied");
let mut screen = fixture.open();
screen.delivery = Box::new(crate::delivery::Clipboard);
note(&mut screen, 9, "name the total");
keys(&mut screen, "E");
assert_eq!(screen.send_label(), "Copied ✓");
// Reopened with the agent as target, or again with none: the notes reached no agent.
let reopened = fixture.open();
assert_eq!(reopened.send_state, SendState::Sent);
assert_eq!(reopened.send_label(), "Copied ✓");
let mut reopened = fixture.open();
reopened.delivery = Box::new(crate::delivery::Clipboard);
assert_eq!(reopened.send_label(), "Copied ✓");
// Resent to the agent, they read sent again, then and after the next reopen.
let mut screen = fixture.open();
keys(&mut screen, "R");
assert_eq!(screen.send_label(), "Sent ✓ ▸ test agent");
assert_eq!(fixture.open().send_label(), "Sent ✓ ▸ test agent");
}

#[test]
fn a_blocked_agent_keeps_the_notes_pending_and_says_so() {
let fixture = Fixture::new("blocked");
Expand Down
71 changes: 65 additions & 6 deletions crates/plannotator-tui/src/rex/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,24 @@ pub(crate) struct RexAgent {
}

impl RexAgent {
/// The target `plannotator-tui rex` named in the environment, or `None` outside such a layer.
pub(crate) fn from_lookup(env: impl Fn(&str) -> Option<String>) -> Option<Self> {
/// The target `plannotator-tui rex` named in the environment, or `None` outside such a
/// layer. A launcher names a block only when it found an agent there, so a pane that
/// cannot reach it gets [`RexUnreachable`]: Send says why instead of copying in silence.
pub(crate) fn from_lookup(env: impl Fn(&str) -> Option<String>) -> Option<Result<Self, RexUnreachable>> {
let non_empty = |k: &str| env(k).filter(|v| !v.is_empty());
let block = non_empty(BLOCK_VAR)?;
let pid = non_empty(PID_VAR)?.parse().ok()?;
let rex = Rex::from_lookup(&env, None).ok()?;
let unreachable = |reason: String| RexUnreachable { agent: non_empty(AGENT_VAR), reason };
let Some(pid) = non_empty(PID_VAR).and_then(|pid| pid.parse().ok()) else {
return Some(Err(unreachable(format!("{PID_VAR} names no process"))));
};
let Ok(rex) = Rex::from_lookup(&env, None) else {
return Some(Err(unreachable(format!(
"REX_BLOCK is not set, so this pane cannot reach {}",
short_id(&block)
))));
};
let submit = env(SUBMIT_VAR).as_deref() != Some("0");
Some(Self {
Some(Ok(Self {
rex,
block,
agent: non_empty(AGENT_VAR),
Expand All @@ -70,7 +80,7 @@ impl RexAgent {
),
submit,
notice: RefCell::default(),
})
}))
}

/// The agent `agent` (its host label), process `pid`, that the agent picker found in
Expand All @@ -89,6 +99,33 @@ impl RexAgent {
}
}

/// The Send target of a review a Rex launcher opened for an agent, when the review's pane
/// cannot reach that agent. Send sends nothing and says why, the feedback is copied, and the
/// notes stay unsent, so the button never reads `Sent ✓` for feedback the agent never got.
#[derive(Debug)]
pub(crate) struct RexUnreachable {
agent: Option<String>,
reason: String,
}

impl Delivery for RexUnreachable {
fn agent_host(&self) -> Option<&str> {
self.agent.as_deref()
}

fn describe(&self) -> String {
format!("{} · not found", self.agent.as_deref().unwrap_or("agent"))
}

fn is_agent(&self) -> bool {
true
}

fn deliver(&self, _feedback: &str) -> Result<(), DeliveryError> {
Err(DeliveryError::Unavailable(self.reason.clone()))
}
}

impl Delivery for RexAgent {
fn agent_host(&self) -> Option<&str> {
self.agent.as_deref()
Expand Down Expand Up @@ -211,11 +248,33 @@ mod tests {
use super::*;

fn agent(vars: &[(&str, &str)]) -> Option<RexAgent> {
lookup(vars).and_then(Result::ok)
}

fn lookup(vars: &[(&str, &str)]) -> Option<Result<RexAgent, RexUnreachable>> {
let owned: Vec<(String, String)> =
vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
RexAgent::from_lookup(|k| owned.iter().find(|(name, _)| name == k).map(|(_, v)| v.clone()))
}

#[test]
fn a_launchers_agent_the_pane_cannot_reach_refuses_send_and_says_why() {
let block = "block:01a17dd5-e47c-754f-b72e-ef739ea1d6db";
assert!(lookup(&[("REX_BLOCK", "block:r")]).is_none(), "no launcher named an agent");
let unreachable = |vars: &[(&str, &str)]| lookup(vars).expect("named").expect_err("unreachable");
let no_session = unreachable(&[(BLOCK_VAR, block), (PID_VAR, "7"), (AGENT_VAR, "claude")]);
assert_eq!(no_session.describe(), "claude · not found");
assert!(no_session.is_agent(), "quitting with the notes unsent still asks");
let refused = no_session.deliver("feedback").expect_err("refused");
assert!(refused.wants_copy());
assert_eq!(
refused.status(&no_session.describe(), true, 'E'),
"no agent to send to (REX_BLOCK is not set, so this pane cannot reach a1d6db) · copied to clipboard · E retry"
);
let no_pid = unreachable(&[("REX_BLOCK", "block:r"), (BLOCK_VAR, block), (PID_VAR, "x")]);
assert_eq!(no_pid.describe(), "agent · not found");
}

#[test]
fn a_pi_last_review_sends_only_while_pi_is_in_the_same_session() {
assert_eq!(pi_session_changed("session-1", Some("session-1")), None);
Expand Down
95 changes: 80 additions & 15 deletions crates/plannotator-tui/src/rex/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,20 +88,20 @@ struct Candidate {
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RexAgents {
pub(crate) bin: PathBuf,
/// `REX_SESSION`: its agents come first.
/// The review's session, or a block in that session (see [`command::session_from`]).
/// The picker lists this session's agents first.
pub(crate) session: String,
/// `REX_BLOCK`: never listed, it is the review's own block. Its window comes first.
pub(crate) own_block: Option<String>,
}

impl RexAgents {
/// Inside Rex (`REX_SESSION` set), the agents Rex runs; else `None`. Rex sets
/// `REX_SESSION`, `REX_BLOCK` and `REX_BIN_DIR` in every block, so the review's own pane
/// has them whether a launcher opened it or you ran it there.
/// Inside Rex (`REX_BLOCK` or `REX_SESSION` set), the agents Rex runs; else `None`. Rex
/// sets `REX_BLOCK` and `REX_BIN_DIR` in every block, so the review's own pane has them
/// whether a launcher opened it or you ran it there.
pub(crate) fn from_lookup(env: impl Fn(&str) -> Option<String>) -> Option<Self> {
let non_empty = |k: &str| env(k).filter(|v| !v.is_empty());
let session = non_empty("REX_SESSION")?;
let own_block = non_empty("REX_BLOCK");
let session = command::session_from(&env)?;
let own_block = env("REX_BLOCK").filter(|v| !v.is_empty());
Some(Self { bin: command::bin_from(&env), session, own_block })
}

Expand All @@ -110,16 +110,31 @@ impl RexAgents {
pub(crate) fn list(&self) -> Vec<BlockAgent> {
let listed = self.read(&["ls", "--json"]);
let mut found = listed.as_ref().map(sessions).unwrap_or_default();
if !found.iter().any(|(id, _)| *id == self.session) {
found.push((self.session.clone(), short_id(&self.session).to_owned()));
}
// `rex ls` lists sessions by their session IDs. If `session` is not in that list, it is
// a block's ID, or `rex ls` failed. The window list of `session` gives the real session
// ID. It is also that session's own window list, so the loop below does not read it again.
// When it cannot be read, the other sessions are still listed, as for any unreadable
// session.
let mut own_view = None;
let session = if found.iter().any(|(id, _)| *id == self.session) {
self.session.clone()
} else if let Some((id, view)) = self.own_window_list() {
if !found.iter().any(|(listed, _)| *listed == id) {
found.push((id.clone(), label_or(&view, short_id(&id))));
}
own_view = Some(view);
id
} else {
self.session.clone()
};
// The review's session first; the sort is stable, so the rest keep Rex's order.
found.sort_by_key(|(id, _)| *id != self.session);
found.sort_by_key(|(id, _)| *id != session);
let candidates: Vec<Candidate> = found
.iter()
.enumerate()
.filter_map(|(at, (id, label))| {
let view = self.read(&["window", "ls", "-s", id, "--json"])?;
let own = if *id == session { own_view.take() } else { None };
let view = own.or_else(|| self.read(&["window", "ls", "-s", id, "--json"]))?;
Some(blocks(&view, at, label, self.own_block.as_deref()))
})
.flatten()
Expand All @@ -135,6 +150,13 @@ impl RexAgents {
.collect()
}

/// `rex window ls` of the review's session or block, with the session ID it names.
fn own_window_list(&self) -> Option<(String, Value)> {
let view = self.read(&["window", "ls", "-s", &self.session, "--json"])?;
let id = view.get("session_id").and_then(Value::as_str).filter(|id| !id.is_empty())?.to_owned();
Some((id, view))
}

/// The agent in `candidate`'s block, if one runs there. Only an agent's title is read.
fn agent(&self, candidate: &Candidate) -> Option<BlockAgent> {
let call = |method: &str| {
Expand Down Expand Up @@ -360,7 +382,7 @@ d='{d}'
echo "$*" >> "$d/calls"
case "$1 $2" in
'ls --json') cat "$d/ls.json" ;;
'window ls') f=$(grep -l "\"session_id\": \"$4\"" "$d"/window-ls-*.json | head -1); [ -n "$f" ] || exit 3; cat "$f" ;;
'window ls') f=$(grep -Fl "\"$4\"" "$d"/window-ls-*.json | head -1); [ -n "$f" ] || exit 3; cat "$f" ;;
do\ com.superlogical.terminal.*)
m=${{2#com.superlogical.terminal.}}; b=$4; f="$d/${{b#"${{b%??????}}"}}.$m.json"
[ -f "$f" ] || exit 3; cat "$f" ;;
Expand Down Expand Up @@ -494,8 +516,11 @@ mod tests {
let env = |vars: &'static [(&'static str, &'static str)]| {
move |k: &str| vars.iter().find(|(name, _)| *name == k).map(|(_, v)| (*v).to_owned())
};
assert_eq!(RexAgents::from_lookup(env(&[("REX_BLOCK", "block:b")])), None);
assert_eq!(RexAgents::from_lookup(env(&[("REX_SESSION", "")])), None);
assert_eq!(RexAgents::from_lookup(env(&[])), None);
assert_eq!(RexAgents::from_lookup(env(&[("REX_SESSION", ""), ("REX_BLOCK", "")])), None);
let block_only = RexAgents::from_lookup(env(&[("REX_BLOCK", "block:b")])).expect("rex");
assert_eq!(block_only.session, "block:b");
assert_eq!(block_only.own_block.as_deref(), Some("block:b"));
let inside =
RexAgents::from_lookup(env(&[("REX_SESSION", "session:s"), ("REX_BIN_DIR", "/opt/rex")]))
.expect("rex");
Expand Down Expand Up @@ -541,4 +566,44 @@ mod tests {
assert_eq!(gone.list(), []);
std::fs::remove_dir_all(&dir).expect("cleanup");
}

#[cfg(unix)]
#[test]
fn a_review_known_only_by_its_block_lists_its_own_session_first_and_once() {
let dir =
std::env::temp_dir().join(format!("plannotator-tui-rex-agents-by-block-{}", std::process::id()));
let bin = fake_rex(&dir);
// `rex ls` lists `side` second, so only the sort can put its agent first.
let side_block = "block:01a1f658-9a2c-7d0b-a3ae-7899dcfd82e9";
let rex = RexAgents { bin, session: side_block.into(), own_block: None };
let agents = rex.list();
assert_eq!(agents.len(), 5, "each session once: {agents:?}");
assert_eq!(agents[0].place(), "side › Window 122adf3e · fd82e9");
assert_eq!(agents[0].rank.0, 0, "the review's session comes first");
assert!(agents[1..].iter().all(|a| a.rank.0 == 1));
let calls = std::fs::read_to_string(dir.join("calls")).expect("calls");
let window_reads: Vec<&str> = calls.lines().filter(|l| l.starts_with("window ls")).collect();
assert_eq!(
window_reads,
[
format!("window ls -s {side_block} --json"),
"window ls -s session:01a1f658-7c0a-71ad-8ff6-a1bcbc31504f --json".to_owned(),
],
"the block's window list is the session's, so it is read once"
);
std::fs::remove_dir_all(&dir).expect("cleanup");
}

#[cfg(unix)]
#[test]
fn a_review_whose_own_session_cannot_be_read_still_lists_the_other_sessions() {
let dir =
std::env::temp_dir().join(format!("plannotator-tui-rex-agents-unread-{}", std::process::id()));
let bin = fake_rex(&dir);
// A block Rex no longer knows: its window list fails, `rex ls` still answers.
let rex =
RexAgents { bin, session: "block:01a1f658-0000-0000-0000-000000000000".into(), own_block: None };
assert_eq!(rex.list(), recorded(None), "every listed session, in Rex's order");
std::fs::remove_dir_all(&dir).expect("cleanup");
}
}
Loading
Loading